mysqli/lib/method.js

426 lines
9.1 KiB
JavaScript
Raw Permalink Normal View History

/**
*
* @authors yutent (yutent@doui.cc)
* @date 2017-12-14 14:01:03
* @version $Id$
*/
2018-05-29 02:42:12 +08:00
const { SqlErr, parser, escape, fixtable } = require('./utils')
class Method {
2018-05-29 02:42:12 +08:00
constructor(pool, slave, db, table) {
this.pool = pool
this.slave = slave
this.db = db
this.cache = { table }
}
2018-05-29 02:42:12 +08:00
connect() {
let defer = Promise.defer()
this.pool.getConnection(this.slave, (err, conn) => {
if (err) {
2018-05-29 02:42:12 +08:00
return defer.reject(new SqlErr(`MySQL connect ${err}`))
}
if (this.db) {
2018-05-29 02:42:12 +08:00
conn.query('USE ' + this.db, err => {
if (err) {
2018-05-29 02:42:12 +08:00
return defer.reject(new SqlErr('Use DB ' + err))
}
2018-05-29 02:42:12 +08:00
defer.resolve(conn)
})
} else {
2018-05-29 02:42:12 +08:00
defer.resolve(conn)
}
})
2018-05-29 02:42:12 +08:00
return defer.promise
}
2018-05-29 02:42:12 +08:00
leftJoin(tables) {
this.cache.leftJoin = tables
return this
}
2018-05-29 02:42:12 +08:00
rightJoin(tables) {
this.cache.rightJoin = tables
return this
}
2018-05-29 02:42:12 +08:00
join(tables) {
this.cache.join = tables
return this
}
/**
* [filter 过滤条件]
* @param {any} val [支持多种形式的过滤]
* sql: .filter('name like "foo%" and age > 18')
* func: .filter(function(){return 'name = "xiaoming"'})
* obj: .filter({
2019-09-23 16:07:30 +08:00
* name: {$like: 'foo%'}
* age: {$gt: 18}
* })
* obj形式的过滤, 支持多种多样, 详细请看Readme介绍
*/
2018-05-29 02:42:12 +08:00
filter(val) {
this.cache.filter = val
return this
}
/**
* [sort 对记录按指定字段排序]
* @param {number }} keys [以对象形式传入值]
* : {name: 1, age: -1} 1代表顺序, -1代表逆序
*/
2018-05-29 02:42:12 +08:00
sort(keys) {
this.cache.sort = keys
return this
}
// 从第几条记录开始返回, 必须搭配limit使用,否则会被忽略
2018-05-29 02:42:12 +08:00
skip(skip) {
this.cache.skip = skip
return this
}
// 返回指定数量的记录
2018-05-29 02:42:12 +08:00
limit(size) {
this.cache.size = size
return this
}
// 截取指定范围内的记录
2018-05-29 02:42:12 +08:00
slice(start, end) {
this.cache.limit = [start, end - start]
return this
}
/**
* [withFields 选取指定的字段]
* @param {string[]} fields [以数组形式传入]
*/
2018-05-29 02:42:12 +08:00
withFields(fields) {
this.cache.fields = fields
return this
}
// ================================================================
// ====================== 以下方法,才是sql执行 =======================
// ================================================================
/**
* [getAll 获取所有记录]
* @param {any[]} ids [description]
*/
2018-05-29 02:42:12 +08:00
getAll(ids) {
if (!this.cache.filter && ids) {
2018-05-29 02:42:12 +08:00
if (ids.length === 1) {
this.cache.filter = { id: ids[0] }
} else {
this.cache.filter = { id: { $in: ids } }
}
}
let {
table,
leftJoin,
rightJoin,
join,
filter,
fields,
sort,
skip,
size,
limit
} = this.cache
// 没有使用 slice方法的前提下, 通过skip/limit补全
if (!limit) {
if (size && size > 0) {
limit = [size]
if (skip !== undefined) {
limit.unshift(skip)
}
}
}
2018-05-29 02:42:12 +08:00
let sql = parser.select(fields)
sql += `FROM ${table} `
if (leftJoin) {
sql += parser.leftJoin(leftJoin)
}
if (rightJoin) {
sql += parser.rightJoin(rightJoin)
}
if (join) {
sql += parser.join(join)
}
if (filter) {
sql += parser.filter(filter)
}
if (sort) {
sql += parser.sort(sort)
}
if (limit) {
sql += parser.limit(limit)
}
2018-05-29 02:42:12 +08:00
return this.connect().then(conn => {
let defer = Promise.defer()
2018-05-29 02:42:12 +08:00
conn.query(sql, (err, result) => {
conn.release()
if (err) {
2018-05-29 02:42:12 +08:00
return defer.reject(new SqlErr(`Find ${err}`, sql))
}
2018-05-29 02:42:12 +08:00
defer.resolve(result)
})
2018-05-29 02:42:12 +08:00
return defer.promise
})
}
/**
* [get 获取单条记录详细]
* @param {any} id [取主键值为id的记录, 当且仅当没设置过滤条件时有效]
*/
2018-05-29 02:42:12 +08:00
get(id) {
return this.getAll(id ? [id] : null).then(list => {
return list[0]
})
}
/**
* [count 获取记录总数]
* @return {number} [description]
*/
2018-05-29 02:42:12 +08:00
count() {
return this.getAll().then(list => {
return list.length
})
}
/**
* [insert 插入单条文档, 返回当前插入的文档的ID(如果是自增)]
* @param {any }} doc [文档object]
*/
2018-05-29 02:42:12 +08:00
insert(doc) {
if (!doc) {
return Promise.reject(new SqlErr('Insert Error: empty document'))
}
let { table } = this.cache
let sql = `INSERT INTO ${table} `
let keys = []
let vals = []
for (let i in doc) {
keys.push(i)
vals.push(escape(doc[i]))
}
sql += `(${keys.join(',')}) VALUES (${vals.join(',')})`
2018-05-29 02:42:12 +08:00
return this.connect().then(conn => {
const defer = Promise.defer()
2018-05-29 02:42:12 +08:00
conn.query(sql, (err, result) => {
conn.release()
if (err) {
2018-05-29 02:42:12 +08:00
return defer.reject(new SqlErr(`Insert ${err}`, sql))
}
2018-05-29 02:42:12 +08:00
defer.resolve(result.insertId)
})
2018-05-29 02:42:12 +08:00
return defer.promise
})
}
/**
* [update 更新文档, 返回更新成功的文档数量]
* 可以使用filter过滤条件
* @param {any }} doc [要更新的字段]
*/
2018-05-29 02:42:12 +08:00
update(doc) {
if (!doc) {
return Promise.reject(new SqlErr('Update Error: empty document'))
}
let { table, filter } = this.cache
let sql = `UPDATE ${table} SET `
let fields = [] //要更新的字段
for (let i in doc) {
let val = doc[i]
if (typeof val === 'object' && val.$sql) {
val = `(${val.$sql})`
} else {
val = escape(val)
}
fields.push(i + ' = ' + val)
}
sql += fields.join(',')
sql += parser.filter(filter)
2018-05-29 02:42:12 +08:00
return this.connect().then(conn => {
const defer = Promise.defer()
2018-05-29 02:42:12 +08:00
conn.query(sql, (err, result) => {
conn.release()
if (err) {
2018-05-29 02:42:12 +08:00
return defer.reject(new SqlErr(`Update ${err}`, sql))
}
2018-05-29 02:42:12 +08:00
defer.resolve(result.affectedRows)
})
2018-05-29 02:42:12 +08:00
return defer.promise
})
}
/**
* [remove 删除文档, 返回删除成功的文档数量]
* 可以使用filter过滤条件
*/
remove() {
let { table, filter } = this.cache
let sql = `DELETE FROM ${table} `
sql += parser.filter(filter)
2018-05-29 02:42:12 +08:00
return this.connect().then(conn => {
const defer = Promise.defer()
conn.query(sql, (err, result) => {
conn.release()
if (err) {
return defer.reject(new SqlErr(`Remove ${err}`, sql))
}
defer.resolve(result.affectedRows)
})
return defer.promise
})
}
2018-05-29 19:02:33 +08:00
drop() {
let sql = `DROP TABLE ${this.cache.table} `
return this.connect().then(conn => {
const defer = Promise.defer()
conn.query(sql, (err, result) => {
conn.release()
if (err) {
return defer.reject(new SqlErr(`Drop table ${err}`, sql))
}
defer.resolve(true)
})
return defer.promise
})
}
2018-05-29 02:42:12 +08:00
// 重命名表
renameTo(name) {
return this.connect().then(conn => {
const defer = Promise.defer()
let sql = `RENAME TABLE ${this.cache.table} TO ${fixtable(name)}`
conn.query(sql, (err, result) => {
conn.release()
if (err) {
return defer.reject(new SqlErr(`List index ${err}`, sql))
}
defer.resolve(true)
})
return defer.promise
})
}
// 返回索引列表
indexList() {
return this.connect().then(conn => {
const defer = Promise.defer()
let sql = `SHOW INDEX FROM ${this.cache.table}`
conn.query(sql, (err, result) => {
conn.release()
if (err) {
return defer.reject(new SqlErr(`List index ${err}`, sql))
}
let list = result.map(it => {
return {
name: it.Key_name,
column: it.Column_name,
unique: !it.Non_unique,
cardinality: it.Cardinality,
2018-05-29 19:02:33 +08:00
collation: it.Collation
2018-05-29 02:42:12 +08:00
}
})
defer.resolve(list)
})
return defer.promise
})
}
// 删除指定索引
indexDrop(name) {
if (!name) {
return Promise.reject('Empty index name')
}
return this.connect().then(conn => {
const defer = Promise.defer()
let sql = `ALTER TABLE ${this.cache.table} DROP INDEX \`${name}\``
conn.query(sql, (err, result) => {
conn.release()
if (err) {
return defer.reject(new SqlErr(`Drop index ${err}`, sql))
}
defer.resolve(true)
})
return defer.promise
})
}
// 删除指定索引
indexCreate(name, opt = {}) {
if (!name) {
return Promise.reject('Empty index name')
}
if (!opt.field) {
return Promise.reject('Empty field name')
}
let unique = ''
opt.field = '`' + opt.field + '`'
if (opt.unique) {
unique = 'UNIQUE'
}
return this.connect().then(conn => {
const defer = Promise.defer()
2019-09-23 16:07:30 +08:00
let sql = `ALTER TABLE ${this.cache.table} ADD ${unique} INDEX \`${name}\` (${opt.field})`
2018-05-29 02:42:12 +08:00
conn.query(sql, (err, result) => {
conn.release()
if (err) {
2018-05-29 02:42:12 +08:00
return defer.reject(new SqlErr(`Drop index ${err}`, sql))
}
2018-05-29 02:42:12 +08:00
defer.resolve(true)
})
2018-05-29 02:42:12 +08:00
return defer.promise
})
}
}
2018-05-29 02:42:12 +08:00
module.exports = Method