base_service.js 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290
  1. 'use strict';
  2. /**
  3. * 业务逻辑基类
  4. *
  5. * @author CaiAoLin
  6. * @date 2017/10/11
  7. * @version
  8. */
  9. const Service = require('egg').Service;
  10. // sql拼装器
  11. const SqlBuilder = require('../lib/sql_builder');
  12. class BaseService extends Service {
  13. /**
  14. * 构造函数
  15. *
  16. * @param {Object} ctx - egg全局context
  17. * @return {void}
  18. */
  19. constructor(ctx) {
  20. super(ctx);
  21. this.db = this.app.mysql;
  22. this.cache = this.app.redis;
  23. this.uuid = this.app.uuid;
  24. this.transaction = null;
  25. this.sqlBuilder = null;
  26. this._ = this.app._;
  27. this.depart = 0;
  28. }
  29. /**
  30. * 设置表名
  31. *
  32. * @param {String} table - 表名
  33. * @return {void}
  34. */
  35. set tableName(table) {
  36. this._table = this.app.config.tablePrefix + table;
  37. }
  38. /**
  39. * 获取表名
  40. *
  41. * @return {String} - 返回表名
  42. */
  43. get tableName() {
  44. if (this.depart <= 0) return this._table;
  45. if (!this.ctx.tender) throw new TypeError('tableName error: Without Tender');
  46. return this._table + '_' + (this.ctx.tender.id % this.depart);
  47. }
  48. departTableName(key) {
  49. if (this.depart <= 0) return this._table;
  50. if (!key) throw new TypeError('tableName error: Without DepartKey');
  51. return this._table + '_' + (key % this.depart);
  52. }
  53. /**
  54. * 初始化sqlBuilder
  55. *
  56. * @return {void}
  57. */
  58. initSqlBuilder() {
  59. if (this.sqlBuilder === null) {
  60. this.sqlBuilder = new SqlBuilder();
  61. }
  62. }
  63. /**
  64. * 根据id查找数据
  65. *
  66. * @param {Number} id - 数据库中的id
  67. * @return {Object} - 返回单条数据
  68. */
  69. async getDataById(id) {
  70. return await this.db.get(this.tableName, { id });
  71. }
  72. /**
  73. * 根据条件查找单条数据
  74. *
  75. * @param {Object} condition - 筛选条件
  76. * @return {Object} - 返回单条数据
  77. */
  78. async getDataByCondition(condition) {
  79. return await this.db.get(this.tableName, condition);
  80. }
  81. /**
  82. * 根据条件查找列表数据
  83. *
  84. * @param {Object} condition - 筛选条件
  85. * @return {Array} - 返回数据
  86. */
  87. async getAllDataByCondition(condition, transaction = false) {
  88. if (!condition.where && !condition.limit) throw '缺少查询条件,如查询全表,请自建sql';
  89. const conn = transaction || this.db;
  90. return await conn.select(this.tableName, condition);
  91. }
  92. /**
  93. * 主动分隔插入数据
  94. *
  95. * @param transaction 事务
  96. * @param tableName 表名
  97. * @param datas 插入数据
  98. * @param split 分隔条数,默认5000
  99. * @returns {Promise<void>}
  100. */
  101. async insertDatasSplit(transaction, tableName, datas, split = 5000) {
  102. const conn = transaction || this.db;
  103. for (let i = 0; i < datas.length; i += split) {
  104. await conn.insert(tableName, datas.slice(i, i + split));
  105. }
  106. }
  107. /**
  108. * 根据id删除数据
  109. *
  110. * @param {Number} id - 数据库中的id
  111. * @return {boolean} - 返回是否删除成功
  112. */
  113. async deleteById(id) {
  114. const result = await this.db.delete(this.tableName, { id });
  115. return result.affectedRows > 0;
  116. }
  117. /**
  118. * 获取总数
  119. *
  120. * @param {Object} option - 过滤条件(参考select方法中的condition)
  121. * @return {Number} - 返回查找的总数
  122. */
  123. async count(option = {}) {
  124. const result = await this.db.count(this.tableName, option);
  125. return result;
  126. }
  127. async defaultUpdate(data, options, transaction = false) {
  128. const conn = transaction || this.db;
  129. const result = await conn.update(this.tableName, data, options);
  130. return result;
  131. }
  132. async defaultUpdateRows(data, transaction = false) {
  133. const conn = transaction || this.db;
  134. const result = await conn.updateRows(this.tableName, data);
  135. return result;
  136. }
  137. /**
  138. * 更新数据
  139. *
  140. * @param {Object} data - 需要更新的数据
  141. * @param {Object} condition - 更新的条件筛选
  142. * @return {Boolean} - 返回更新结果
  143. */
  144. async update(data, condition, transaction = false) {
  145. if (Object.keys(data).length <= 0 || Object.keys(condition).length <= 0) {
  146. return false;
  147. }
  148. const sqlParam = [];
  149. const param = [];
  150. for (const key in data) {
  151. param.push(key + ' = ?');
  152. sqlParam.push(data[key]);
  153. }
  154. const paramString = param.join(',');
  155. const where = [];
  156. for (const key in condition) {
  157. where.push(key + ' = ?');
  158. sqlParam.push(condition[key]);
  159. }
  160. const whereString = where.join(' AND ');
  161. const sql = 'UPDATE ' + this.tableName + ' SET ' + paramString + ' WHERE ' + whereString;
  162. const result = transaction ? await transaction.query(sql, sqlParam) : await this.db.query(sql, sqlParam);
  163. return result.affectedRows > 0;
  164. }
  165. /**
  166. * 获取分页数据(SqlBuilder版本)
  167. *
  168. * @return {Array} - 返回分页数据
  169. */
  170. async getListWithBuilder() {
  171. // 由于egg-mysql不提供like、不等于操作,所以需要自己组sql
  172. if (this.sqlBuilder === null) {
  173. return [];
  174. }
  175. // 分页相关
  176. this.sqlBuilder.limit = this.ctx.pageSize ? this.ctx.pageSize : this.app.config.pageSize;
  177. this.sqlBuilder.offset = this.sqlBuilder.limit * (this.ctx.page - 1);
  178. // 数据筛选
  179. if (this.ctx.sort !== undefined && this.ctx.sort.length > 0) {
  180. this.sqlBuilder.orderBy = [this.ctx.sort];
  181. }
  182. const [sql, sqlParam] = this.sqlBuilder.build(this.tableName);
  183. const list = await this.db.query(sql, sqlParam);
  184. return list;
  185. }
  186. /**
  187. * 获取数据条数(SqlBuilder版本)
  188. *
  189. * @return {Array} - 返回分页数据
  190. */
  191. async getCountWithBuilder() {
  192. // 由于egg-mysql不提供like、不等于操作,所以需要自己组sql
  193. if (this.sqlBuilder === null) {
  194. return [];
  195. }
  196. const [sql, sqlParam] = this.sqlBuilder.buildCount(this.tableName);
  197. const result = await this.db.query(sql, sqlParam);
  198. return result ? result.length : 0;
  199. }
  200. /**
  201. * 获取分页数据
  202. *
  203. * @param {Object} condition - 搜索条件
  204. * @return {Array} - 返回分页数据
  205. */
  206. async getList(condition) {
  207. const page = this.ctx.page;
  208. // 分页设置
  209. condition.limit = condition.limit === undefined ? this.app.config.pageSize : condition.limit;
  210. condition.offset = condition.offset === undefined ? this.app.config.pageSize * (page - 1) : condition.offset;
  211. if (this.ctx.sort !== undefined && this.ctx.sort.length > 0) {
  212. condition.orders = [this.ctx.sort];
  213. }
  214. const list = await this.db.select(this.tableName, condition);
  215. return list;
  216. }
  217. round(value, decimal) {
  218. return this.ctx.helper.round(value, this._.isNumber(decimal) ? decimal : 8);
  219. }
  220. // 针对大批量数据插入,优化插入datas,按50条为分隔
  221. async insertBigDatas(transaction, insertDatas) {
  222. const batchSize = 50;
  223. for (let i = 0; i < insertDatas.length; i += batchSize) {
  224. const batchDatas = insertDatas.slice(i, i + batchSize);
  225. await transaction.insert(this.tableName, batchDatas);
  226. }
  227. }
  228. /**
  229. * 开启数据库事务。
  230. */
  231. async beginTransaction() {
  232. return await this.db.beginTransaction();
  233. }
  234. /**
  235. * 在事务中锁定符合非空标量等值条件的数据,可按指定字段升序排列。
  236. */
  237. async getAllDataForUpdate(condition, transaction, orderBy) {
  238. if (!transaction) throw '锁定查询必须使用事务';
  239. if (!condition || typeof condition !== 'object' || Array.isArray(condition) || !Object.keys(condition).length) {
  240. throw '锁定查询缺少等值条件';
  241. }
  242. const where = [];
  243. const sqlParam = [this.tableName];
  244. for (const key of Object.keys(condition)) {
  245. if (condition[key] === null || !['string', 'number', 'boolean'].includes(typeof condition[key])) {
  246. throw '锁定查询仅支持非空标量等值条件';
  247. }
  248. where.push('?? = ?');
  249. sqlParam.push(key, condition[key]);
  250. }
  251. if (orderBy) sqlParam.push(orderBy);
  252. const sql = 'SELECT * FROM ?? WHERE ' + where.join(' AND ') + (orderBy ? ' ORDER BY ?? ASC' : '') + ' FOR UPDATE';
  253. return await transaction.query(sql, sqlParam);
  254. }
  255. }
  256. module.exports = BaseService;