"use strict"; var Mysql = require('mysql'); var configs = require('../../conf/config.inc.js'); var AppErrors = require('./AppErrors.js'); var objPools = {}; /** * 基本类,提供增删改查 * @param {string} dbKey */ class OujMySql { constructor(dbKey) { this.dbKey = dbKey || 'default'; } getPool() { if (!objPools[this.dbKey]) { var config = configs.dbInfo[this.dbKey]; if (config) { objPools[this.dbKey] = Mysql.createPool(config); } else { throw new AppErrors.DbError("数据库:" + this.dbKey + "没有配置"); } } return objPools[this.dbKey]; } query(sql, values) { let that = this; return new Promise(function(resolve, reject) { that.getPool().query(sql, values, function(err, result) { if (err) { reject(err); throw new AppErrors.DbError(err); } else { resolve(result); } }); }); }; /** * 更新数据 * @param {string} sql */ update(sql) { return this.query(sql, []); }; /** * 获取一个值 * @param {string} sql * @return Promise */ getOne(sql) { var that = this; return new Promise(function(resolve, reject) { var p1 = that.getAll(sql, 1); p1.then(function(rows) { var row = rows[0]; var val = null; if (row) { var keys = Object.keys(row); val = keys && row[keys[0]]; } resolve(val); }, reject); }); }; /** * 获取一列数据 * @param sql * @param limit 行数 */ getCol(sql, limit) { let that = this; return new Promise(function(resolve, reject) { var p1 = that.getAll(sql, limit); p1.then(function(rows) { var cols = []; if (rows[0] && rows.length) { var keys = Object.keys(rows[0]); let key = keys[0]; for (var i = 0; i < rows.length; i++) { cols.push(rows[i][key]); } } resolve(cols); }, reject); }); }; /** * 获取一行数据 * @param sql */ getRow(sql) { let that = this; return new Promise(function(resolve, reject) { var p1 = that.getAll(sql, 1); p1.then(function(rows) { resolve(rows[0] || null); }, reject); }); }; /** * 获取所有行数据 * @param sql * @param limit 行数 */ getAll(sql, limit) { if (typeof limit == 'number' && limit > 0) { sql += " LIMIT " + limit; } return this.query(sql, []); }; /** * 关闭连接池 */ close() { return new Promise(function(resolve, reject) { this.getPool().end(function(err) { if (err) { reject(err); } else { resolve(); } }); }); }; } module.exports = OujMySql;