mysqli/lib/api.js

130 lines
2.8 KiB
JavaScript
Raw Normal View History

2018-05-29 02:42:12 +08:00
/**
*
2020-11-24 21:11:45 +08:00
* @author yutent<yutent.io@gmail.com>
* @date 2020/11/24 20:04:39
2018-05-29 02:42:12 +08:00
*/
const { SqlErr, parser, fixtable } = require('./utils')
const Method = require('./method')
class Api {
constructor(pool, slave = 'MASTER', db = '') {
this.pool = pool
this.slave = slave
this.db = db ? '`' + db + '`' : null
}
connect() {
let defer = Promise.defer()
this.pool.getConnection(this.slave, (err, conn) => {
if (err) {
return defer.reject(new SqlErr(`MySQL connect ${err}`))
}
if (this.db) {
conn.query('USE ' + this.db, err => {
if (err) {
return defer.reject(new SqlErr('Use DB ' + err))
}
defer.resolve(conn)
})
} else {
defer.resolve(conn)
}
})
return defer.promise
}
table(name) {
if (!name) {
throw new SqlErr('Query Error: empty table')
}
name = fixtable(name)
return new Method(this.pool, this.slave, this.db, name, this.debug)
2018-05-29 02:42:12 +08:00
}
/**
* [query sql语句执行]
* @param {[type]} sql [sql语句]
*/
query(sql) {
if (typeof sql !== 'string') {
return Promise.reject(
new SqlErr(
`Query error, argument sql must be string. ${typeof sql} given`,
sql
)
)
}
return this.connect().then(conn => {
let defer = Promise.defer()
if (this.debug) {
2021-06-30 09:35:39 +08:00
console.log(`[${new Date().format('Y/m/d_H:i:s')}][debug]`, sql)
}
2018-05-29 02:42:12 +08:00
conn.query(sql, (err, result) => {
conn.release()
if (err) {
return defer.reject(new SqlErr(`Query ${err}`, sql))
}
defer.resolve(result)
})
return defer.promise
})
}
drop(db) {
if (!this.db && db) {
return Promise.reject('No database selected.')
}
return this.query(`DROP DATABASE IF EXISTS ${db || this.db}`)
2018-05-29 02:42:12 +08:00
}
dbList() {
return this.query('SHOW DATABASES').then(list =>
list.map(it => it.Database)
)
2018-05-29 02:42:12 +08:00
}
//返回数据表
tableList() {
return this.query('SHOW TABLES').then(list =>
list.map(it => it[Object.keys(it)[0]])
)
2018-05-29 02:42:12 +08:00
}
// 创建新的数据库
2019-09-23 16:07:30 +08:00
dbCreate(name, { charset = 'utf8mb4' } = {}) {
2018-05-29 02:42:12 +08:00
if (!name) {
return Promise.reject('Empty database name.')
}
let sql = `CREATE DATABASE \`${name}\` DEFAULT CHARACTER SET = \`${charset}\``
return this.query(sql)
2018-05-29 02:42:12 +08:00
}
// 创建新的表,
2019-09-23 16:07:30 +08:00
tableCreate(name, fields, { charset = 'utf8mb4', engine = 'InnoDB' } = {}) {
2018-05-29 02:42:12 +08:00
if (!name) {
return Promise.reject('Empty database name.')
}
let sql = `CREATE TABLE \`${name}\` `
try {
sql += parser.field(fields)
} catch (err) {
return Promise.reject(err + '')
}
sql += ` ENGINE=${engine} DEFAULT CHARSET=${charset}`
return this.query(sql)
2018-05-29 02:42:12 +08:00
}
}
module.exports = Api