mm_dao 1.9.1 → 1.9.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (198) hide show
  1. package/index.js +3 -17
  2. package/lib/admin.js +24 -0
  3. package/lib/dao.js +38 -1219
  4. package/lib/dao_crud.js +379 -0
  5. package/lib/dao_fields.js +145 -0
  6. package/lib/dao_query.js +238 -0
  7. package/lib/dao_scope.js +203 -0
  8. package/lib/dao_stats.js +129 -0
  9. package/lib/dao_transfer.js +358 -0
  10. package/lib/manager.js +17 -34
  11. package/lib/script.tpl.js +4 -4
  12. package/package.json +10 -3
  13. package/tool/dao/index.js +173 -4
  14. package/tool/dao/tool.json +56 -5
  15. package/tool/dao_admin/index.js +36 -0
  16. package/tool/dao_admin/tool.json +11 -0
  17. package/db/mm/user_account/_meta.json +0 -54
  18. package/db/mm.db +0 -0
  19. package/eslint.config.js +0 -235
  20. package/example/index.js +0 -78
  21. package/lib/tools/dao/index.js +0 -73
  22. package/lib/tools/index.js +0 -16
  23. package/test_db/dao_test_1785991977965/account/1.json +0 -6
  24. package/test_db/dao_test_1785991977965/account/2.json +0 -6
  25. package/test_db/dao_test_1785991977965/account/_meta.json +0 -18
  26. package/test_db/dao_test_1785991977965/role/1.json +0 -7
  27. package/test_db/dao_test_1785991977965/role/2.json +0 -7
  28. package/test_db/dao_test_1785991977965/role/3.json +0 -7
  29. package/test_db/dao_test_1785991977965/role/_meta.json +0 -18
  30. package/test_db/dao_test_1785991977965/tool/_meta.json +0 -18
  31. package/test_db/dao_test_1785991977965/tool/bow_001.json +0 -8
  32. package/test_db/dao_test_1785991977965/tool/robe_001.json +0 -8
  33. package/test_db/dao_test_1785991977965/tool/shield_001.json +0 -8
  34. package/test_db/dao_test_1785991977965/tool/staff_001.json +0 -8
  35. package/test_db/dao_test_1785991977965/tool/sword_001.json +0 -8
  36. package/test_db/dao_test_1785993793800/account/1.json +0 -58
  37. package/test_db/dao_test_1785993793800/account/2.json +0 -25
  38. package/test_db/dao_test_1785993793800/account/_meta.json +0 -18
  39. package/test_db/dao_test_1785993793800/role/1.json +0 -7
  40. package/test_db/dao_test_1785993793800/role/2.json +0 -7
  41. package/test_db/dao_test_1785993793800/role/3.json +0 -7
  42. package/test_db/dao_test_1785993793800/role/_meta.json +0 -18
  43. package/test_db/dao_test_1785993793800/tool/_meta.json +0 -18
  44. package/test_db/dao_test_1785993793800/tool/bow_001.json +0 -8
  45. package/test_db/dao_test_1785993793800/tool/robe_001.json +0 -8
  46. package/test_db/dao_test_1785993793800/tool/shield_001.json +0 -8
  47. package/test_db/dao_test_1785993793800/tool/staff_001.json +0 -8
  48. package/test_db/dao_test_1785993793800/tool/sword_001.json +0 -8
  49. package/test_db/dao_test_1785993841615/account/1.json +0 -58
  50. package/test_db/dao_test_1785993841615/account/2.json +0 -25
  51. package/test_db/dao_test_1785993841615/account/_meta.json +0 -18
  52. package/test_db/dao_test_1785993841615/role/1.json +0 -7
  53. package/test_db/dao_test_1785993841615/role/2.json +0 -7
  54. package/test_db/dao_test_1785993841615/role/3.json +0 -7
  55. package/test_db/dao_test_1785993841615/role/_meta.json +0 -18
  56. package/test_db/dao_test_1785993841615/tool/_meta.json +0 -18
  57. package/test_db/dao_test_1785993841615/tool/bow_001.json +0 -8
  58. package/test_db/dao_test_1785993841615/tool/robe_001.json +0 -8
  59. package/test_db/dao_test_1785993841615/tool/shield_001.json +0 -8
  60. package/test_db/dao_test_1785993841615/tool/staff_001.json +0 -8
  61. package/test_db/dao_test_1785993841615/tool/sword_001.json +0 -8
  62. package/test_db/dao_test_1785998204124/account/1.json +0 -58
  63. package/test_db/dao_test_1785998204124/account/2.json +0 -25
  64. package/test_db/dao_test_1785998204124/account/_meta.json +0 -18
  65. package/test_db/dao_test_1785998204124/role/1.json +0 -7
  66. package/test_db/dao_test_1785998204124/role/2.json +0 -7
  67. package/test_db/dao_test_1785998204124/role/3.json +0 -7
  68. package/test_db/dao_test_1785998204124/role/_meta.json +0 -18
  69. package/test_db/dao_test_1785998204124/tool/_meta.json +0 -18
  70. package/test_db/dao_test_1785998204124/tool/bow_001.json +0 -8
  71. package/test_db/dao_test_1785998204124/tool/robe_001.json +0 -8
  72. package/test_db/dao_test_1785998204124/tool/shield_001.json +0 -8
  73. package/test_db/dao_test_1785998204124/tool/staff_001.json +0 -8
  74. package/test_db/dao_test_1785998204124/tool/sword_001.json +0 -8
  75. package/test_db/dao_test_1785998207460/account/1.json +0 -58
  76. package/test_db/dao_test_1785998207460/account/2.json +0 -25
  77. package/test_db/dao_test_1785998207460/account/_meta.json +0 -18
  78. package/test_db/dao_test_1785998207460/role/1.json +0 -7
  79. package/test_db/dao_test_1785998207460/role/2.json +0 -7
  80. package/test_db/dao_test_1785998207460/role/3.json +0 -7
  81. package/test_db/dao_test_1785998207460/role/_meta.json +0 -18
  82. package/test_db/dao_test_1785998207460/tool/_meta.json +0 -18
  83. package/test_db/dao_test_1785998207460/tool/bow_001.json +0 -8
  84. package/test_db/dao_test_1785998207460/tool/robe_001.json +0 -8
  85. package/test_db/dao_test_1785998207460/tool/shield_001.json +0 -8
  86. package/test_db/dao_test_1785998207460/tool/staff_001.json +0 -8
  87. package/test_db/dao_test_1785998207460/tool/sword_001.json +0 -8
  88. package/test_db/dao_test_1785998210638/account/1.json +0 -58
  89. package/test_db/dao_test_1785998210638/account/2.json +0 -25
  90. package/test_db/dao_test_1785998210638/account/_meta.json +0 -18
  91. package/test_db/dao_test_1785998210638/role/1.json +0 -7
  92. package/test_db/dao_test_1785998210638/role/2.json +0 -7
  93. package/test_db/dao_test_1785998210638/role/3.json +0 -7
  94. package/test_db/dao_test_1785998210638/role/_meta.json +0 -18
  95. package/test_db/dao_test_1785998210638/tool/_meta.json +0 -18
  96. package/test_db/dao_test_1785998210638/tool/bow_001.json +0 -8
  97. package/test_db/dao_test_1785998210638/tool/robe_001.json +0 -8
  98. package/test_db/dao_test_1785998210638/tool/shield_001.json +0 -8
  99. package/test_db/dao_test_1785998210638/tool/staff_001.json +0 -8
  100. package/test_db/dao_test_1785998210638/tool/sword_001.json +0 -8
  101. package/test_db/dao_test_1785998213852/account/1.json +0 -58
  102. package/test_db/dao_test_1785998213852/account/2.json +0 -25
  103. package/test_db/dao_test_1785998213852/account/_meta.json +0 -18
  104. package/test_db/dao_test_1785998213852/role/1.json +0 -7
  105. package/test_db/dao_test_1785998213852/role/2.json +0 -7
  106. package/test_db/dao_test_1785998213852/role/3.json +0 -7
  107. package/test_db/dao_test_1785998213852/role/_meta.json +0 -18
  108. package/test_db/dao_test_1785998213852/tool/_meta.json +0 -18
  109. package/test_db/dao_test_1785998213852/tool/bow_001.json +0 -8
  110. package/test_db/dao_test_1785998213852/tool/robe_001.json +0 -8
  111. package/test_db/dao_test_1785998213852/tool/shield_001.json +0 -8
  112. package/test_db/dao_test_1785998213852/tool/staff_001.json +0 -8
  113. package/test_db/dao_test_1785998213852/tool/sword_001.json +0 -8
  114. package/test_db/dao_test_1785998217094/account/1.json +0 -58
  115. package/test_db/dao_test_1785998217094/account/2.json +0 -25
  116. package/test_db/dao_test_1785998217094/account/_meta.json +0 -18
  117. package/test_db/dao_test_1785998217094/role/1.json +0 -7
  118. package/test_db/dao_test_1785998217094/role/2.json +0 -7
  119. package/test_db/dao_test_1785998217094/role/3.json +0 -7
  120. package/test_db/dao_test_1785998217094/role/_meta.json +0 -18
  121. package/test_db/dao_test_1785998217094/tool/_meta.json +0 -18
  122. package/test_db/dao_test_1785998217094/tool/bow_001.json +0 -8
  123. package/test_db/dao_test_1785998217094/tool/robe_001.json +0 -8
  124. package/test_db/dao_test_1785998217094/tool/shield_001.json +0 -8
  125. package/test_db/dao_test_1785998217094/tool/staff_001.json +0 -8
  126. package/test_db/dao_test_1785998217094/tool/sword_001.json +0 -8
  127. package/test_db/dao_test_1786000291805/account/1.json +0 -58
  128. package/test_db/dao_test_1786000291805/account/2.json +0 -25
  129. package/test_db/dao_test_1786000291805/account/_meta.json +0 -18
  130. package/test_db/dao_test_1786000291805/role/1.json +0 -7
  131. package/test_db/dao_test_1786000291805/role/2.json +0 -7
  132. package/test_db/dao_test_1786000291805/role/3.json +0 -7
  133. package/test_db/dao_test_1786000291805/role/_meta.json +0 -18
  134. package/test_db/dao_test_1786000291805/tool/_meta.json +0 -18
  135. package/test_db/dao_test_1786000291805/tool/bow_001.json +0 -8
  136. package/test_db/dao_test_1786000291805/tool/robe_001.json +0 -8
  137. package/test_db/dao_test_1786000291805/tool/shield_001.json +0 -8
  138. package/test_db/dao_test_1786000291805/tool/staff_001.json +0 -8
  139. package/test_db/dao_test_1786000291805/tool/sword_001.json +0 -8
  140. package/test_db/dao_test_1786001183999/account/1.json +0 -58
  141. package/test_db/dao_test_1786001183999/account/2.json +0 -25
  142. package/test_db/dao_test_1786001183999/account/_meta.json +0 -18
  143. package/test_db/dao_test_1786001183999/role/1.json +0 -7
  144. package/test_db/dao_test_1786001183999/role/2.json +0 -7
  145. package/test_db/dao_test_1786001183999/role/3.json +0 -7
  146. package/test_db/dao_test_1786001183999/role/_meta.json +0 -18
  147. package/test_db/dao_test_1786001183999/tool/_meta.json +0 -18
  148. package/test_db/dao_test_1786001183999/tool/bow_001.json +0 -8
  149. package/test_db/dao_test_1786001183999/tool/robe_001.json +0 -8
  150. package/test_db/dao_test_1786001183999/tool/shield_001.json +0 -8
  151. package/test_db/dao_test_1786001183999/tool/staff_001.json +0 -8
  152. package/test_db/dao_test_1786001183999/tool/sword_001.json +0 -8
  153. package/test_db/dao_test_1786001297521/account/1.json +0 -58
  154. package/test_db/dao_test_1786001297521/account/2.json +0 -25
  155. package/test_db/dao_test_1786001297521/account/_meta.json +0 -18
  156. package/test_db/dao_test_1786001297521/role/1.json +0 -7
  157. package/test_db/dao_test_1786001297521/role/2.json +0 -7
  158. package/test_db/dao_test_1786001297521/role/3.json +0 -7
  159. package/test_db/dao_test_1786001297521/role/_meta.json +0 -18
  160. package/test_db/dao_test_1786001297521/tool/_meta.json +0 -18
  161. package/test_db/dao_test_1786001297521/tool/bow_001.json +0 -8
  162. package/test_db/dao_test_1786001297521/tool/robe_001.json +0 -8
  163. package/test_db/dao_test_1786001297521/tool/shield_001.json +0 -8
  164. package/test_db/dao_test_1786001297521/tool/staff_001.json +0 -8
  165. package/test_db/dao_test_1786001297521/tool/sword_001.json +0 -8
  166. package/test_db/debug_dao_1785992422444/account/1.json +0 -24
  167. package/test_db/debug_dao_1785992422444/account/_meta.json +0 -18
  168. package/test_db/debug_dao_1785992422444/role/1.json +0 -7
  169. package/test_db/debug_dao_1785992422444/role/2.json +0 -7
  170. package/test_db/debug_dao_1785992422444/role/_meta.json +0 -18
  171. package/test_db/debug_dao_1785992422444/tool/_meta.json +0 -18
  172. package/test_db/debug_dao_1785992422444/tool/shield_001.json +0 -7
  173. package/test_db/debug_dao_1785992422444/tool/staff_001.json +0 -7
  174. package/test_db/debug_dao_1785992422444/tool/sword_001.json +0 -7
  175. package/test_db/debug_dao_1785993785567/account/1.json +0 -47
  176. package/test_db/debug_dao_1785993785567/account/_meta.json +0 -18
  177. package/test_db/debug_dao_1785993785567/role/1.json +0 -7
  178. package/test_db/debug_dao_1785993785567/role/2.json +0 -7
  179. package/test_db/debug_dao_1785993785567/role/_meta.json +0 -18
  180. package/test_db/debug_dao_1785993785567/tool/_meta.json +0 -18
  181. package/test_db/debug_dao_1785993785567/tool/shield_001.json +0 -7
  182. package/test_db/debug_dao_1785993785567/tool/staff_001.json +0 -7
  183. package/test_db/debug_dao_1785993785567/tool/sword_001.json +0 -7
  184. package/test_db/debug_dao_check/tool/_meta.json +0 -18
  185. package/test_db/debug_dao_check/tool/sword_001.json +0 -6
  186. package/test_db/test_1785973671479/users/1.json +0 -5
  187. package/test_db/test_1785973671479/users/_meta.json +0 -20
  188. package/tests/dao_test.js +0 -213
  189. package/tests/debug_error_test.js +0 -165
  190. package/tests/debug_test.js +0 -35
  191. package/tests/debug_test2.js +0 -45
  192. package/tests/debug_test3.js +0 -54
  193. package/tests/detailed_error_test.js +0 -171
  194. package/tests/main.test.js +0 -261
  195. package/tests/query.test.js +0 -142
  196. package/tests/scope.test.js +0 -72
  197. package/tests/test.js +0 -325
  198. package/tests/test2.js +0 -64
package/lib/dao.js CHANGED
@@ -1,12 +1,19 @@
1
- const path = require('path');
2
1
  const Item = require('mm_machine').Mod;
3
- const { string, array, file } = require('mm_helper');
2
+ const { string } = require('mm_helper');
4
3
  const { getRet } = require('mm_ret');
5
- const { getSql, sqlAdmin } = require('mm_sql');
6
- const dbAdmin = require('mm_dbs');
4
+
5
+ const scope_part = require('./dao_scope.js');
6
+ const query_part = require('./dao_query.js');
7
+ const crud_part = require('./dao_crud.js');
8
+ const fields_part = require('./dao_fields.js');
9
+ const transfer_part = require('./dao_transfer.js');
10
+ const stats_part = require('./dao_stats.js');
7
11
 
8
12
  /**
9
13
  * Sql操作驱动类
14
+ * 类本身承载配置、生命周期与请求分发;数据源、查询构建、增删改查、
15
+ * 字段参数、导入导出、分组统计六个职责分片定义在 dao_*.js,
16
+ * 加载时合并挂载到 Dao.prototype,方法内通过 this 访问实例。
10
17
  * @augments {Item}
11
18
  * @class
12
19
  */
@@ -184,7 +191,7 @@ Dao.prototype._preset = function () {
184
191
  * @private
185
192
  */
186
193
  Dao.prototype._getInject = function (key) {
187
- var value = this.config[key];
194
+ let value = this.config[key];
188
195
  if (value !== undefined && value !== null && value !== '') {
189
196
  return value;
190
197
  }
@@ -200,25 +207,13 @@ Dao.prototype._getDict = function () {
200
207
  return this._getInject('dict') || {};
201
208
  };
202
209
 
203
- /**
204
- * 获取当前用户ID(用于默认条件与默认字段的 {user_id} 占位)
205
- * @param {object} db 数据库管理器
206
- * @returns {string|number} 用户ID, 无登录态时为 '0'
207
- * @private
208
- */
209
- Dao.prototype._getUserId = function (db) {
210
- var id = this._getDict().user_id;
211
- var user = db.user;
212
- return user && user[id] ? user[id] : '0';
213
- };
214
-
215
210
  /**
216
211
  * 执行前, 可用于过滤参数
217
212
  * @param {object} params 参数对象 (object) 包含query和body 如{ query, body }
218
213
  * @param {object} db 数据库管理器
219
214
  * @returns {object} 过滤后的参数
220
215
  */
221
- Dao.prototype.before = async function (params, db) {
216
+ Dao.prototype.before = function (params, db) {
222
217
  return params;
223
218
  };
224
219
 
@@ -228,7 +223,7 @@ Dao.prototype.before = async function (params, db) {
228
223
  * @param {object} db 数据管理器
229
224
  * @returns {boolean} 验证通过返回true, 失败返回false
230
225
  */
231
- Dao.prototype.check = async function (params, db) {
226
+ Dao.prototype.check = function (params, db) {
232
227
  return true;
233
228
  };
234
229
 
@@ -238,7 +233,7 @@ Dao.prototype.check = async function (params, db) {
238
233
  * @param {object} db 数据管理器
239
234
  * @returns {object} 最终执行结果
240
235
  */
241
- Dao.prototype.after = async function (params, db) {
236
+ Dao.prototype.after = function (params, db) {
242
237
  return db.ret;
243
238
  };
244
239
 
@@ -249,67 +244,6 @@ Dao.prototype.after = async function (params, db) {
249
244
  */
250
245
  Dao.prototype.updateCache = async function (table, sql) {};
251
246
 
252
- /**
253
- * 获取本驱动绑定的 Sql 实例(数据源由本驱动配置决定)
254
- * 作用域即数据域:os / user / org / project / client / app 各自可独立配置数据库;
255
- * 未单独配置 sql 时复用进程级主库,便于同库分域与后续平滑拆库。
256
- * @returns {object} Sql 实例
257
- * @private
258
- */
259
- Dao.prototype._getSql = function () {
260
- if (!this._sql) {
261
- var name = this.config.scope || 'os';
262
- var sql_config = this.config.sql;
263
- this._sql = sql_config ? sqlAdmin(name, sql_config) : getSql();
264
- }
265
- return this._sql;
266
- };
267
-
268
- /**
269
- * 获取数据库管理器(委托本驱动绑定的 Sql 实例)
270
- * @returns {object} 数据库管理器实例
271
- */
272
- Dao.prototype.db = function () {
273
- return this._getSql().db();
274
- };
275
-
276
- /**
277
- * 读取并执行 .sql 文件脚本(委托本驱动绑定的 Sql 实例)
278
- * @param {string} fpath SQL 文件路径
279
- * @returns {Promise<object>} 执行结果统计对象
280
- */
281
- Dao.prototype.load = function (fpath) {
282
- return this._getSql().load(fpath);
283
- };
284
-
285
- /**
286
- * @ 执行修改
287
- * @param {object} query 查询url参数
288
- * @param {object} body 修改时置入body的参数
289
- * @param {object} [db] 数据库管理器,不传时由本驱动按自身配置选择数据源
290
- * @returns {object} 返回执行结果
291
- */
292
- Dao.prototype.run = async function (query, body, db) {
293
- if (!db) {
294
- db = this.db();
295
- }
296
- var params = {
297
- query,
298
- body,
299
- };
300
- params = await this.before(params, db);
301
- if (await this.check(params, db)) {
302
- var ret = await this.main(params, db);
303
- if (!ret.error) {
304
- db.ret = ret;
305
- return await this.after(params, db);
306
- } else {
307
- return ret;
308
- }
309
- }
310
- return null;
311
- };
312
-
313
247
  /**
314
248
  * 获取参数过滤表(本 dao 配置优先,缺项由默认配置补齐)
315
249
  * @param {object} cg 配置
@@ -329,1041 +263,26 @@ Dao.prototype._getFilter = function (cg) {
329
263
  * @private
330
264
  */
331
265
  Dao.prototype._errMsg = function (db) {
332
- var err = db && db.error;
266
+ let err = db && db.error;
333
267
  if (!err) {
334
268
  return '';
335
269
  }
336
270
  return err.message || err.toString();
337
271
  };
338
272
 
339
- /**
340
- * SQL操作准备
341
- * @param {object} db 数据库操作类
342
- * @param {object} query 查询条件
343
- * @param {object} body 修改项
344
- * @returns {object} 返回准备参数
345
- */
346
- Dao.prototype.ready = function (db, query, body) {
347
- var cg = this.config;
348
- var qy = { ...query };
349
- this._extractQuery(db, qy, cg);
350
- return {
351
- cg,
352
- qy,
353
- };
354
- };
355
-
356
- /**
357
- * 抽取控制参数,确保 qy 中只剩真正的 SQL 查询条件
358
- * 按 filter 清单逐个抽取,与取值真假无关(page=0、size='' 同样会被抽走),
359
- * 只有真值才赋给数据管理器,避免把空值写成 ''
360
- * @param {object} db 数据库操作类
361
- * @param {object} qy 查询条件
362
- * @param {object} cg 配置
363
- * @returns {object} 清理后的查询条件
364
- * @private
365
- */
366
- Dao.prototype._extractQuery = function (db, qy, cg) {
367
- var f = this._getFilter(cg);
368
- for (var k in f) {
369
- var name = f[k] || k;
370
- var value = qy[name];
371
- if (value === undefined) {
372
- continue;
373
- }
374
- if (f[k] && value) {
375
- db[k] = value;
376
- }
377
- delete qy[name];
378
- }
379
- // 空值不作为查询条件,避免被拼成 `field` = 'undefined'
380
- for (var key in qy) {
381
- if (qy[key] === undefined || qy[key] === null) {
382
- delete qy[key];
383
- }
384
- }
385
- return qy;
386
- };
387
-
388
- /**
389
- * 转为查询条件字符串
390
- * @param {object} db 数据库管理器
391
- * @param {object} query 查寻条件
392
- * @param {object} method 方法
393
- * @returns {string} 返回查询条件
394
- */
395
- Dao.prototype.toWhere = function (db, query, method) {
396
- var { cg, qy } = this.ready(db, query, {});
397
- this._setDbConfig(db, cg, query);
398
- qy = this._setQueryField(db, query, cg, method, qy);
399
- qy = this._setOrderBy(db, query, cg, qy);
400
- return this._buildQueryString(db, qy, cg);
401
- };
402
-
403
- /**
404
- * 设置数据库配置
405
- * @param {object} db 数据库管理器
406
- * @param {object} cg 配置
407
- * @param {object} query 查询条件
408
- * @private
409
- */
410
- Dao.prototype._setDbConfig = function (db, cg, query) {
411
- var f = this._getFilter(cg);
412
- // 只有未传 size 时才套用配置的分页大小(显式传 0 表示不分页,不能被覆盖)
413
- var size = query[f.size];
414
- if ((size === undefined || size === null || size === '') && cg.page_size) {
415
- db.size = cg.page_size + 0;
416
- }
417
- if (db.size > 0 && db.page === 0) {
418
- db.page = 1;
419
- }
420
- };
421
-
422
- /**
423
- * 设置查询字段
424
- * @param {object} db 数据库管理器
425
- * @param {object} query 查询条件
426
- * @param {object} cg 配置
427
- * @param {object} method 方法
428
- * @param {object} qy 查询条件对象
429
- * @returns {object} 更新后的查询条件对象
430
- * @private
431
- */
432
- Dao.prototype._setQueryField = function (db, query, cg, method, qy) {
433
- // 取本 dao 的配置(默认 + cg),不读 db.config.filter:后者是共享配置记录,会被其他 dao 覆盖
434
- var f = this._getFilter(cg);
435
- var field = query[f.field];
436
- if (string.has(cg.field, '*{0}*')) {
437
- if (field) {
438
- var safe_field = typeof field === 'string' && string.validate(field, 'username') ? field : '';
439
- if (safe_field) {
440
- db.field = cg.field.replace('{0}', safe_field);
441
- } else {
442
- db.field = cg.field_default || cg.field + '';
443
- }
444
- } else if (method === 'get_obj' && cg.field_obj) {
445
- db.field = cg.field_obj + '';
446
- } else if (cg.field_default) {
447
- db.field = cg.field_default + '';
448
- }
449
- } else {
450
- db.field = cg.field + '';
451
- if (field) {
452
- return { ...qy, [f.field]: field };
453
- }
454
- }
455
- return qy;
456
- };
457
-
458
- /**
459
- * 设置排序方式
460
- * @param {object} db 数据库管理器
461
- * @param {object} query 查询条件
462
- * @param {object} cg 配置
463
- * @param {object} qy 查询条件对象
464
- * @returns {object} 更新后的查询条件对象
465
- * @private
466
- */
467
- Dao.prototype._setOrderBy = function (db, query, cg, qy) {
468
- // 同上:按本 dao 的配置取参数名
469
- var f = this._getFilter(cg);
470
- var orderby = query[f.orderby];
471
- if (string.has(cg.orderby, '*{0}*')) {
472
- if (orderby) {
473
- var safe_orderby = typeof orderby === 'string' && string.validate(orderby, 'username') ? orderby : '';
474
- if (safe_orderby) {
475
- db.orderby = cg.orderby.replace('{0}', safe_orderby);
476
- } else {
477
- db.orderby = cg.orderby_default || cg.orderby + '';
478
- }
479
- } else if (cg.orderby_default) {
480
- db.orderby = cg.orderby_default + '';
481
- }
482
- } else {
483
- db.orderby = cg.orderby + '';
484
- if (orderby) {
485
- return { ...qy, [f.orderby]: orderby };
486
- }
487
- }
488
- return qy;
489
- };
490
-
491
- /**
492
- * 构建查询字符串
493
- * @param {object} db 数据库管理器
494
- * @param {object} qy 查询条件对象
495
- * @param {object} cg 配置
496
- * @returns {string} 查询字符串
497
- * @private
498
- */
499
- Dao.prototype._buildQueryString = function (db, qy, cg) {
500
- return this._appendDefault(this._tplQuery(db, qy, cg), qy, cg.query_default, db);
501
- };
502
-
503
- /**
504
- * 按本 dao 的分隔符拼接查询条件
505
- * 分隔符存放在数据管理器的共享配置记录中,直接赋值会串到同表模型的其它请求,
506
- * 因此仅在本次拼接期间生效,用完立即还原
507
- * @param {object} db 数据库管理器
508
- * @param {object} qy 查询条件对象
509
- * @param {object} cg 配置
510
- * @returns {string} 查询条件字符串
511
- * @private
512
- */
513
- Dao.prototype._tplQuery = function (db, qy, cg) {
514
- var cf = db.config;
515
- if (!cf) {
516
- return db.tplQuery(qy, cg.query);
517
- }
518
- var prev = cf.separator;
519
- var sep = cg.separator;
520
- if (sep === prev) {
521
- return db.tplQuery(qy, cg.query);
522
- }
523
- cf.separator = sep;
524
- try {
525
- return db.tplQuery(qy, cg.query);
526
- } finally {
527
- if (prev === undefined) {
528
- delete cf.separator;
529
- } else {
530
- cf.separator = prev;
531
- }
532
- }
533
- };
534
-
535
- /**
536
- * 追加默认查询条件
537
- * @param {string} query_str 已有查询条件
538
- * @param {object} qy 查询条件对象
539
- * @param {object} qt 默认查询条件模板
540
- * @param {object} db 数据库管理器
541
- * @returns {string} 追加后的查询条件
542
- * @private
543
- */
544
- Dao.prototype._appendDefault = function (query_str, qy, qt, db) {
545
- if (!qt || Object.keys(qt).length === 0) {
546
- return query_str;
547
- }
548
- var id_key = '{' + this._getDict().user_id + '}';
549
- var user_id = this._getUserId(db);
550
- for (var k in qt) {
551
- if (!qy[k]) {
552
- // 用 AND 而非 &&:&& 只有 MySQL 认,SQLite 会当成语法错误,
553
- // 而默认条件通常是用户/机构隔离条件,必须与具体数据库无关
554
- query_str += ' AND ' + string.replaceAll(qt[k], id_key, user_id);
555
- }
556
- }
557
- return query_str.replace(/^ AND /, '');
558
- };
559
-
560
- /**
561
- * 查询(主要)
562
- * @param {object} db 数据库操作类
563
- * @param {object} query 查询条件
564
- * @param {object} method 方法
565
- * @returns {object} 返回查询结果
566
- */
567
- Dao.prototype.getMain = async function (db, query, method) {
568
- var ret;
569
- if (string.has(this.config.field, '*{0}*')) {
570
- var field = query[this._getFilter(this.config).field];
571
- if (field && array.getMatch(this.config.field_hide, field)) {
572
- return getRet().error(70003, '不合法的查询参数');
573
- }
574
- }
575
- var query_str = this.toWhere(db, query, method);
576
-
577
- // 查询
578
- if (db.count_ret === 'true' || db.count_ret === true) {
579
- ret = getRet().body(await db.getCountSql(query_str, db.orderby, db.field), null);
580
- } else {
581
- ret = getRet().list(await db.getSql(query_str, db.orderby, db.field));
582
- }
583
- return ret;
584
- };
585
-
586
- /**
587
- * 查询
588
- * @param {object} db 数据库操作类
589
- * @param {object} query 查询条件
590
- * @param {object} body 修改项
591
- * @returns {object} 返回查询结果
592
- */
593
- Dao.prototype.get = async function (db, query, body) {
594
- return await this.getMain(db, query);
595
- };
596
-
597
- /**
598
- * 查询单条数据
599
- * @param {object} db 数据库操作类
600
- * @param {object} query 查询条件
601
- * @param {object} body 修改项
602
- * @returns {object} 返回查询结果
603
- */
604
- Dao.prototype.getObj = async function (db, query, body) {
605
- var qy = { ...query };
606
- qy.page = 1;
607
- qy.size = 1;
608
- // get_obj 只是「取一条」,它改的是共享表模型上的分页与字段状态,用完必须还原:
609
- // 否则同一实例上的后续列表查询会被截断成 1 条,字段也可能串成 field_obj
610
- var old_page = db.page;
611
- var old_size = db.size;
612
- var old_field = db.field;
613
- try {
614
- var ret = await this.getMain(db, qy, 'get_obj');
615
- if (ret.result) {
616
- var list = ret.result.list;
617
- return getRet().body({ obj: list && list.length > 0 ? list[0] : null });
618
- }
619
- return ret;
620
- } finally {
621
- db.page = old_page;
622
- db.size = old_size;
623
- db.field = old_field;
624
- }
625
- };
626
-
627
- /**
628
- * 修改(主要)
629
- * @param {object} db 数据库操作类
630
- * @param {object} query 查询条件
631
- * @param {object} body 修改项
632
- * @returns {object} 返回修改结果
633
- */
634
- Dao.prototype.setMain = async function (db, query, body) {
635
- var ret;
636
- var { cg, qy } = this.ready(db, query, body);
637
- var key = cg.key;
638
- if (body[key]) {
639
- qy[key] = body[key];
640
- }
641
- var query_str = this._buildQueryString(db, qy, cg);
642
- var n = await db.setSql(query_str, db.tplBody(body, cg.update));
643
-
644
- if (n < 1) {
645
- var msg = this._errMsg(db);
646
- ret = getRet().error(500, msg ? '修改失败!\n' + msg : '修改失败!');
647
- } else {
648
- ret = getRet().bl(true, '修改成功!');
649
- }
650
- return ret;
651
- };
652
-
653
- /**
654
- * 修改
655
- * @param {object} db 数据库操作类
656
- * @param {object} query 查询条件
657
- * @param {object} body 修改项
658
- * @returns {object} 返回查询结果
659
- */
660
- Dao.prototype.set = async function (db, query, body) {
661
- return await this.setMain(db, query, body);
662
- };
663
-
664
- /**
665
- * 填充默认写入值
666
- * body_default 是「字段 = 值」模板,常用于补 user_id、org_id 这类隔离字段;
667
- * 查询条件里的 query_default 会校验同样的字段,写入侧必须把值补齐,否则
668
- * 新增的记录缺少隔离字段,按同一用户再也查不到(表现为反复新增重复数据)
669
- * @param {object} db 数据库管理器
670
- * @param {object} body 待写入数据
671
- * @param {object} cg 配置
672
- * @returns {object} 补充默认值后的数据副本
673
- * @private
674
- */
675
- Dao.prototype._fillBodyDefault = function (db, body, cg) {
676
- // 复制一份,默认值只补进本 dao 的数据,不改调用方的参数对象
677
- var dt = { ...body };
678
- var bt = cg.body_default;
679
- if (!bt || Object.keys(bt).length === 0) {
680
- return dt;
681
- }
682
- var id_key = '{' + this._getDict().user_id + '}';
683
- var user_id = this._getUserId(db);
684
- for (var k in bt) {
685
- var tpl = String(string.replaceAll(bt[k], id_key, user_id));
686
- // 模板格式:`字段` = 值(空格、反引号、引号可省略)
687
- // 不能用 left/right/trim 按单字符截取:值里带空格时会残留成 `user_id`` 这种非法字段名
688
- var arr = tpl.split('=');
689
- if (arr.length < 2) {
690
- continue;
691
- }
692
- var fkey = arr[0].replace(/`/g, '').trim();
693
- var fval = arr.slice(1).join('=').trim().replace(/^'(.*)'$/, '$1');
694
- // 已有值的字段不覆盖
695
- if (!fkey || dt[fkey]) {
696
- continue;
697
- }
698
- dt[fkey] = fval;
699
- }
700
- return dt;
701
- };
702
-
703
- /**
704
- * 添加(主要)
705
- * @param {object} db 数据库操作类
706
- * @param {object} body 添加项
707
- * @returns {object} 返回查询结果
708
- */
709
- Dao.prototype.addMain = async function (db, body) {
710
- var ret;
711
- var cg = this.config;
712
- if (Object.keys(body).length > 0) {
713
- var dt = this._fillBodyDefault(db, body, cg);
714
- var n = await db.add(dt);
715
- if (n < 1) {
716
- var msg = this._errMsg(db);
717
- ret = getRet().error(500, msg ? '添加失败!\n' + msg : '添加失败!');
718
- } else {
719
- ret = getRet().bl(true, '添加成功!');
720
- }
721
- } else {
722
- ret = getRet().error(30001, '参数不能为空');
723
- }
724
- if (cg.log) {
725
- this.log('debug', '添加SQL语句', db.sql);
726
- }
727
- return ret;
728
- };
729
-
730
- /**
731
- * 添加
732
- * @param {object} db 数据库操作类
733
- * @param {object} query 查询条件
734
- * @param {object} body 修改项
735
- * @returns {object} 返回添加结果
736
- */
737
- Dao.prototype.add = async function (db, query, body) {
738
- return await this.addMain(db, body);
739
- };
740
-
741
- /**
742
- * 批量添加(主要)
743
- * @param {object} db 数据库操作类
744
- * @param {Array} list 添加项列表
745
- * @returns {object} 返回批量添加结果
746
- */
747
- Dao.prototype.addListMain = async function (db, list) {
748
- if (!Array.isArray(list) || list.length === 0) {
749
- return getRet().error(30001, '参数不能为空');
750
- }
751
- var success_num = 0;
752
- var error_num = 0;
753
- var errors = [];
754
- var list_error = [];
755
- for (var i = 0; i < list.length; i++) {
756
- var ret = await this.addMain(db, list[i]);
757
- if (ret.error) {
758
- error_num++;
759
- errors.push(ret.error.message);
760
- list_error.push(list[i]);
761
- } else {
762
- success_num++;
763
- }
764
- }
765
- var done = getRet().bl(success_num > 0, success_num > 0 ? '批量添加成功!' : '批量添加失败!');
766
- Object.assign(done.result, {
767
- total: list.length,
768
- success: success_num,
769
- error: error_num,
770
- list_error: list_error,
771
- errors: errors
772
- });
773
- return done;
774
- };
775
-
776
- /**
777
- * 批量添加
778
- * @param {object} db 数据库操作类
779
- * @param {Array} list 添加项列表
780
- * @returns {object} 返回批量添加结果
781
- */
782
- Dao.prototype.addList = async function (db, list) {
783
- return await this.addListMain(db, list);
784
- };
785
-
786
- /**
787
- * 删除(主要)
788
- * @param {object} db 数据库操作类
789
- * @param {object} query 查询条件
790
- * @returns {object} 返回查询结果
791
- */
792
- Dao.prototype.delMain = async function (db, query) {
793
- var ret;
794
- var { cg, qy } = this.ready(db, query, {});
795
- // 与 get / set 保持一致:删除同样追加 query_default,
796
- // 否则“查到的范围”与“删掉的范围”不一致(默认条件常用于用户/机构隔离,缺失会删到别人数据)
797
- var query_str = this._buildQueryString(db, qy, cg);
798
- // 拒绝空条件删除:部分适配器会把空 where 当成“全删”,不能靠它们兜底
799
- if (!query_str) {
800
- return getRet().error(30001, '删除条件不能为空');
801
- }
802
- var bl = await db.delSql(query_str);
803
- if (bl < 1) {
804
- var msg = this._errMsg(db);
805
- ret = getRet().error(500, msg ? '删除失败!\n' + msg : '删除失败!');
806
- } else {
807
- ret = getRet().bl(true, '删除成功!');
808
- }
809
- if (cg.log) {
810
- this.log('debug', '删除SQL语句', db.sql);
811
- }
812
- return ret;
813
- };
814
-
815
- /**
816
- * 删除
817
- * @param {object} db 数据库操作类
818
- * @param {object} query 查询条件
819
- * @param {object} body 修改项
820
- * @returns {object} 返回删除结果
821
- */
822
- Dao.prototype.del = async function (db, query, body = {}) {
823
- return await this.delMain(db, { ...query, ...body });
824
- };
825
-
826
- /**
827
- * 添加或修改(主要)
828
- * @param {object} db 数据库操作类
829
- * @param {object} query 查询条件
830
- * @param {object} body 修改项
831
- * @returns {object} 返回修改结果
832
- */
833
- Dao.prototype.addOrSetMain = async function (db, query, body) {
834
- var ret;
835
- var { cg, qy } = this.ready(db, query, body);
836
- if (Object.keys(body).length > 0 && Object.keys(qy).length > 0) {
837
- // 与 get / set / del 同源:判断「是否已存在」同样带上 query_default,
838
- // 否则会命中他人的记录并直接改掉(默认条件通常是用户/机构隔离条件)
839
- var where = this._buildQueryString(db, qy, cg);
840
- if (!where) {
841
- return getRet().error(30001, '条件不能为空');
842
- }
843
- // 新增分支不会用到 where 里的隔离字段,需把 body_default 补进写入数据,
844
- // 否则插入的记录缺少隔离字段,后续按同一用户再也查不到(反复新增重复数据)
845
- var dt = this._fillBodyDefault(db, body, cg);
846
- var n;
847
- if (typeof db.countSql === 'function') {
848
- // 自行判断存在性再分派:部分适配器的 addOrSet 在新增分支只写 set 的数据,
849
- // 不会把条件字段写进新记录,导致新记录不满足条件,下次调用又新增一条(重复数据)
850
- var count = await db.countSql(where);
851
- if (count > 0) {
852
- n = await db.setSql(where, db.tplBody(body, cg.update));
853
- } else {
854
- n = await db.add({ ...qy, ...dt });
855
- }
856
- } else {
857
- n = await db.addOrSet(where, dt);
858
- }
859
- if (n < 1) {
860
- var msg = this._errMsg(db);
861
- ret = getRet().error(500, msg ? '操作失败!\n' + msg : '操作失败!');
862
- } else {
863
- ret = getRet().bl(true, '操作成功!');
864
- }
865
- } else {
866
- ret = getRet().error(30001, '参数不能为空');
867
- }
868
- if (cg.log) {
869
- this.log('debug', '添加或修改SQL语句', db.sql);
870
- }
871
- return ret;
872
- };
873
-
874
- /**
875
- * 添加或修改
876
- * @param {object} db 数据库操作类
877
- * @param {object} query 查询条件
878
- * @param {object} body 修改项
879
- * @returns {object} 返回查询结果
880
- */
881
- Dao.prototype.addOrSet = async function (db, query, body) {
882
- return await this.addOrSetMain(db, query, body);
883
- };
884
-
885
- // 历史命名(全小写)保留为别名,避免既有调用方失效
886
- Dao.prototype.addorsetMain = Dao.prototype.addOrSetMain;
887
-
888
- /**
889
- * 获取数据类型
890
- * @param {string} data_type 数据类型
891
- * @returns {string} 返回数据类型
892
- */
893
- Dao.prototype.getType = function (data_type) {
894
- if (!data_type) {
895
- return 'string';
896
- }
897
- return String(data_type).indexOf('int') !== -1 ? 'number' : 'string';
898
- };
899
-
900
- /**
901
- * 获取数据
902
- * @param {object} db 数据库操作类
903
- * @param {string} field 要获取的字段
904
- * @returns {Array} 返回参数信息列表
905
- */
906
- Dao.prototype.getParam = async function (db, field) {
907
- var cg = this.config;
908
- if (cg.params) {
909
- return cg.params;
910
- }
911
- if (this.params) {
912
- return this.params;
913
- }
914
- var lt = await this._getFieldsFromCache(cg);
915
- if (!lt.length) {
916
- lt = await this._getFieldsFromDb(db, cg);
917
- }
918
- return this._filterFields(lt, field, cg);
919
- };
920
-
921
- /**
922
- * 从缓存获取字段列表
923
- * @param {object} cg 配置
924
- * @returns {Array} 字段列表
925
- * @private
926
- */
927
- Dao.prototype._getFieldsFromCache = function (cg) {
928
- var lt = [];
929
- var pool = dbAdmin('os');
930
- if (pool) {
931
- var dt = pool.get(cg.table);
932
- if (dt && dt.config) {
933
- var list = dt.config.fields;
934
- for (var i = 0; i < list.length; i++) {
935
- var name = list[i].replace(/`/g, '');
936
- lt.push({ name, title: name });
937
- }
938
- }
939
- }
940
- return lt;
941
- };
942
-
943
- /**
944
- * 从数据库获取字段列表
945
- * @param {object} db 数据库操作类
946
- * @param {object} cg 配置
947
- * @returns {Array} 字段列表
948
- * @private
949
- */
950
- Dao.prototype._getFieldsFromDb = async function (db, cg) {
951
- var lt = [];
952
- db.table = cg.table;
953
- var list = await db.fields();
954
- for (var i = 0; i < list.length; i++) {
955
- var o = list[i];
956
- var name = o.name;
957
- var note = o.note ? o.note.replace(':', ':') : name;
958
- lt.push({
959
- name,
960
- title: string.left(note, ':', true),
961
- type: this.getType(o.type),
962
- });
963
- }
964
- return lt;
965
- };
966
-
967
- /**
968
- * 过滤字段
969
- * @param {Array} lt 字段列表
970
- * @param {string} field 字段筛选
971
- * @param {object} cg 配置
972
- * @returns {Array} 过滤后的字段列表
973
- * @private
974
- */
975
- Dao.prototype._filterFields = function (lt, field, cg) {
976
- var fields = field || cg.field_default;
977
- if (fields && fields !== '*') {
978
- var arr = fields.replace(/`/g, '').split(',');
979
- return arr.map((name) => array.getObj(lt, { name })).filter((obj) => obj);
980
- }
981
- return lt;
982
- };
983
-
984
- /**
985
- * 获取导入导出格式
986
- * @param {object} db 数据库操作类
987
- * @returns {Array} 格式列表
988
- */
989
- Dao.prototype.getFormat = async function (db) {
990
- // 用原型继承派生一个“不分页”的视图:直接 {...db} 只复制自有属性,
991
- // getSql 等原型方法会丢失,取格式数据时会报 dbs.getSql is not a function
992
- var dbs = Object.create(db);
993
- dbs.size = 0;
994
- var fmt = this.config.format;
995
- for (var i = 0; i < fmt.length; i++) {
996
- var o = fmt[i];
997
- if (o.table) {
998
- if (!o.list || o.list.length == 0) {
999
- dbs.table = o.table;
1000
- if (!o.id) {
1001
- o.id = o.key;
1002
- }
1003
- o.list = await dbs.getSql(o.where, null, o.id + ',' + o.name);
1004
- if (o.id !== o.key) {
1005
- for (var j = 0; j < o.list.length; j++) {
1006
- var m = o.list[j];
1007
- m[o.key] = m[o.name];
1008
- }
1009
- }
1010
- }
1011
- }
1012
- }
1013
- return fmt;
1014
- };
1015
-
1016
- /**
1017
- * 导入数据(主要)
1018
- * @param {object} db 数据库操作类
1019
- * @param {string} filename 文件名
1020
- * @returns {object} 返回导入结果
1021
- */
1022
- Dao.prototype.importMain = async function (db, filename) {
1023
- var params = await this.getParam(db);
1024
- var format = await this.getFormat(db);
1025
- var fpath = this._processFilePath(filename);
1026
- if (!file.hasFile(fpath)) {
1027
- return getRet().error(30001, fpath + '文件不存在!');
1028
- }
1029
- var jarr = await this._loadImport(fpath, params, format);
1030
- if (!jarr || !jarr.length) {
1031
- return getRet().error(10000, '要导入的数据不能为空!');
1032
- }
1033
- var result = await this._importToDb(db, jarr);
1034
- return this._buildImport(result);
1035
- };
1036
-
1037
- /**
1038
- * 处理文件路径
1039
- * @param {string} filename 文件名
1040
- * @returns {string} 处理后的文件路径
1041
- * @private
1042
- */
1043
- Dao.prototype._processFilePath = function (filename) {
1044
- // 局部变量不能叫 file,否则会遮蔽 mm_helper 的 file 助手(hasFile/fullname 会变 undefined)
1045
- var fpath = filename || '';
1046
- var run_path = this._getInject('run_path') || '';
1047
- // 未配置 run_path 时 indexOf('') 恒为 0,不能据此判断“已在运行目录下”
1048
- if (!run_path || fpath.indexOf(run_path) !== 0) {
1049
- // save_dir 是相对运行目录的,基准也必须是运行目录(原来用 _getPath 会拼出 static/static/file)
1050
- var base_path = run_path || process.cwd();
1051
- fpath = file.fullname(fpath.replace(this.url_path, this.save_dir), base_path);
1052
- }
1053
- return fpath;
1054
- };
1055
-
1056
- /**
1057
- * 加载导入数据
1058
- * @param {string} fpath 文件路径
1059
- * @param {Array} params 参数列表
1060
- * @param {Array} format 格式列表
1061
- * @returns {Array} 数据数组
1062
- * @private
1063
- */
1064
- Dao.prototype._loadImport = async function (fpath, params, format) {
1065
- if (fpath.endsWith('.json')) {
1066
- return file.loadJson(fpath);
1067
- }
1068
- if (fpath.endsWith('.xml')) {
1069
- return file.loadXml(fpath);
1070
- }
1071
- const Excel = require('mm_excel');
1072
- var excel = new Excel({ file: fpath, params, format });
1073
- try {
1074
- return await excel.load();
1075
- } catch (e) {
1076
- this.log('error', '导入文件', e);
1077
- } finally {
1078
- excel.clear();
1079
- excel = null;
1080
- }
1081
- return [];
1082
- };
1083
-
1084
- /**
1085
- * 导入数据到数据库
1086
- * @param {object} db 数据库操作类
1087
- * @param {Array} jarr 数据数组
1088
- * @returns {object} 导入结果
1089
- * @private
1090
- */
1091
- Dao.prototype._importToDb = async function (db, jarr) {
1092
- var list = [];
1093
- var errors = [];
1094
- var list_error = [];
1095
- db.table = db.table || this.config.table;
1096
- var key = this.config.key;
1097
- if (jarr[0][key]) {
1098
- for (var i = 0; i < jarr.length; i++) {
1099
- var o = jarr[i];
1100
- var qy = {};
1101
- qy[key] = o[key];
1102
- var n = await db.addOrSet(qy, o);
1103
- if (n < 1) {
1104
- errors.push(db.error);
1105
- list_error.push(o);
1106
- } else {
1107
- list.push(o);
1108
- }
1109
- }
1110
- } else {
1111
- for (var i = 0; i < jarr.length; i++) {
1112
- var o = jarr[i];
1113
- var n = await db.add(o);
1114
- if (n < 1) {
1115
- errors.push(db.error);
1116
- list_error.push(o);
1117
- } else {
1118
- list.push(o);
1119
- }
1120
- }
1121
- }
1122
- return { list, errors, list_error, total: jarr.length };
1123
- };
1124
-
1125
- /**
1126
- * 构建导入结果
1127
- * @param {object} result 导入结果数据
1128
- * @returns {object} 返回结果对象
1129
- * @private
1130
- */
1131
- Dao.prototype._buildImport = function (result) {
1132
- var bl = result.list.length === result.total;
1133
- var body = getRet().bl(bl, bl ? '导入成功!' : '导入失败!');
1134
- body.result.list = result.list;
1135
- if (result.errors.length) {
1136
- body.result.list_error = result.list_error;
1137
- body.result.errors = result.errors;
1138
- }
1139
- return body;
1140
- };
1141
-
1142
- /**
1143
- * 导入数据
1144
- * @param {object} db 数据库操作类
1145
- * @param {object} query 查询条件
1146
- * @param {object} body 导入设置
1147
- * @returns {object} 返回执行结果
1148
- */
1149
- Dao.prototype.import = async function (db, query, body) {
1150
- var params = { ...query, ...body };
1151
- if (!params.file) {
1152
- return getRet().error(60000, '文件名(file)参数不能为空');
1153
- }
1154
- return await this.importMain(db, params.file);
1155
- };
1156
-
1157
- /**
1158
- * 导出数据(主要)
1159
- * @param {object} db 数据库操作类
1160
- * @param {object} query 查询参数
1161
- * @param {object} body 正文参数(导出设置)
1162
- * @property {string} body.fields 需要导出的字段 例如: `username`,`gm`,`vip`
1163
- * @property {string} body.file 文件名 例如: 用户名.xlsx 、用户信息.csv 、用户账户.xls
1164
- * @property {string} body.path 文件路径 例如: /static/download, 可不填写
1165
- * @returns {object} 返回执行结果
1166
- */
1167
- Dao.prototype.exportMain = async function (db, query, body) {
1168
- var by = await this.getMain(db, query);
1169
- if (by.error) {
1170
- return by;
1171
- }
1172
- var err = this._errMsg(db);
1173
- if (err) {
1174
- return getRet().error(10000, err);
1175
- }
1176
- var config = this._prepareExportConfig(query, body);
1177
- var params = await this.getParam(db, config.fields);
1178
- var format = await this.getFormat(db);
1179
- // 统计模式下 getMain 返回的是条数而非列表,此处兜底避免取 list 报错
1180
- var list = (by.result && by.result.list) || [];
1181
- var fpath = await this._saveExportFile(config.file, params, format, list);
1182
- return this._buildExport(fpath, config.name);
1183
- };
1184
-
1185
- /**
1186
- * 准备导出配置
1187
- * @param {object} query 查询参数
1188
- * @param {object} body 正文参数
1189
- * @returns {object} 导出配置
1190
- * @private
1191
- */
1192
- Dao.prototype._prepareExportConfig = function (query, body) {
1193
- var path = body.path || this._getPath();
1194
- var file_name = body.file;
1195
- var fields = body.fields;
1196
- var table = this._getDict().table || this.config.table;
1197
- if (!file_name) {
1198
- file_name = this.save_dir + table + '_' + new Date().stamp() + '.xlsx';
1199
- }
1200
- if (!fields) {
1201
- fields =
1202
- query[this._getFilter(this.config).field] ||
1203
- (this.config.field_default !== '*' ? this.config.field_default : '');
1204
- }
1205
- return { path, file: file_name, fields, name: file_name.split('/').pop() };
1206
- };
1207
-
1208
- /**
1209
- * 获取路径
1210
- * @returns {string} 导出路径
1211
- * @private
1212
- */
1213
- Dao.prototype._getPath = function () {
1214
- return (
1215
- this._getInject('user_path') ||
1216
- this._getInject('static_path') ||
1217
- './static/'
1218
- );
1219
- };
1220
-
1221
- /**
1222
- * 保存导出文件
1223
- * @param {string} fpath 文件路径
1224
- * @param {Array} params 参数列表
1225
- * @param {Array} format 格式列表
1226
- * @param {Array} list 数据列表
1227
- * @returns {string} 保存后的文件路径
1228
- * @private
1229
- */
1230
- Dao.prototype._saveExportFile = async function (fpath, params, format, list) {
1231
- var save_file = file.fullname(fpath, this._getPath());
1232
- file.addDir(save_file);
1233
- const Excel = require('mm_excel');
1234
- var excel = new Excel({ file: save_file, params, format });
1235
- try {
1236
- return await excel.save(list);
1237
- } catch (e) {
1238
- this.log('error', '导出保存文件失败!', e);
1239
- } finally {
1240
- excel.clear();
1241
- excel = null;
1242
- }
1243
- return '';
1244
- };
1245
-
1246
- /**
1247
- * 构建导出结果
1248
- * @param {string} fpath 文件路径
1249
- * @param {string} name 文件名
1250
- * @returns {object} 导出结果
1251
- * @private
1252
- */
1253
- Dao.prototype._buildExport = function (fpath, name) {
1254
- var body = getRet().bl(!!fpath, fpath ? '导出成功!' : '导出失败!');
1255
- body.result.file = fpath;
1256
- body.result.url = this.url_path + name;
1257
- return body;
1258
- };
1259
-
1260
- /**
1261
- * 导出数据
1262
- * @param {object} db 数据库操作类
1263
- * @param {object} query 查询条件
1264
- * @param {object} body 修改项
1265
- * @returns {object} 返回执行结果
1266
- */
1267
- Dao.prototype.export = async function (db, query, body) {
1268
- return await this.exportMain(db, query, body);
1269
- };
1270
-
1271
- /**
1272
- * 删除重复项(主要)
1273
- * @param {object} db 数据库管理器
1274
- * @param {object} params 查询参数
1275
- * @returns {object} 返回执行结果
1276
- */
1277
- Dao.prototype.delRepeatMain = async function (db, params) {
1278
- var pm = { ...params };
1279
- var msg = '';
1280
- var cg = this.config.del_repeat;
1281
- var f = this._getFilter(this.config);
1282
- var order_by = pm[f.orderby] || cg.orderby;
1283
- var group_by_val = pm[f.groupby] || cg.groupby;
1284
- var group_by =
1285
- (typeof group_by_val === 'string' && string.validate(group_by_val, 'username') ? group_by_val : '') ||
1286
- cg.groupby ||
1287
- '';
1288
- var field_val = pm[f.field];
1289
- var field =
1290
- (typeof field_val === 'string' && string.validate(field_val, 'username') ? field_val : '') || group_by;
1291
- // 去重过程会改动分页与字段设置(扫全表 -> 逐条取单条),先记下原值,结束后还原
1292
- var old_page = db.page;
1293
- var old_size = db.size;
1294
- var old_field = db.field;
1295
- // 抽走 page、size、table、method、org_id 等控制参数,只留真正的查询条件,
1296
- // 否则会被拼成 `page` = '1' 之类的条件,导致去重查不到数据
1297
- var qy = this.ready(db, pm, {}).qy;
1298
- // 分组与取行都要带 query_default(用户/机构隔离),否则会跨用户分组并删掉别人的记录
1299
- var where = this._buildQueryString(db, qy, this.config);
1300
- var list = [];
1301
- try {
1302
- // 去重要扫全表,不能带分页(LIMIT 拼到 GROUP BY 前面会直接语法错误)
1303
- db.page = 0;
1304
- db.size = 0;
1305
- db.field = field;
1306
- // 用 toQuery 而不是 toGetSql:view 固定为 *,替换分组字段时不受适配器默认字段影响
1307
- var sql = db
1308
- .toQuery(where, '', '*')
1309
- .replace(' * ', ' `' + field + '`, count(*) as len ');
1310
- sql += ` GROUP BY ${group_by}`;
1311
- sql = 'SELECT * FROM (' + sql + ') a WHERE len > 1';
1312
- list = (await db.run(sql)) || [];
1313
- if (list.length) {
1314
- db.page = 1;
1315
- db.size = 1;
1316
- var key = this.config.key;
1317
- for (var i = 0; i < list.length; i++) {
1318
- var o = list[i];
1319
- var len = o.len - 1;
1320
- delete o.len;
1321
- // 取行同样叠加隔离条件:只按分组字段取第一条会取到他人的记录
1322
- var owhere = this._buildQueryString(db, o, this.config);
1323
- for (var n = 0; n < len; n++) {
1324
- var rows = (await db.getSql(owhere, order_by, key)) || [];
1325
- if (!rows.length) {
1326
- break;
1327
- }
1328
- await db.del(rows[0]);
1329
- }
1330
- }
1331
- } else {
1332
- msg = '没有重复项。';
1333
- }
1334
- } finally {
1335
- db.page = old_page;
1336
- db.size = old_size;
1337
- db.field = old_field;
1338
- }
1339
- return getRet().bl(!msg, msg ? '去重失败!原因:' + msg : '去重成功!');
1340
- };
1341
-
1342
- /**
1343
- * 删除重复项
1344
- * @param {object} db 数据库管理器
1345
- * @param {object} query 查询条件
1346
- * @param {object} body 正文参数
1347
- * @returns {object} 返回执行结果
1348
- */
1349
- Dao.prototype.delRepeat = async function (db, query, body) {
1350
- var pm = { ...query, ...body };
1351
- return await this.delRepeatMain(db, pm);
1352
- };
1353
-
1354
273
  /**
1355
274
  * 执行模板操作
1356
275
  * @param {object} params 参数对象 (object) 包含query和body
1357
276
  * @param {object} db 数据管理器
1358
- * @returns {object} 返回执行结果
277
+ * @returns {Promise<object>} 返回执行结果
1359
278
  */
1360
279
  Dao.prototype.main = async function (params, db) {
1361
- var { query, body } = params;
280
+ let { query, body } = params;
1362
281
 
1363
- var cg = this.config;
282
+ let cg = this.config;
1364
283
  // 参数名统一按本 dao 的 filter 配置取,支持 dao.json 重命名控制参数
1365
- var f = this._getFilter(cg);
1366
- var method = query[f.method];
284
+ let f = this._getFilter(cg);
285
+ let method = query[f.method];
1367
286
 
1368
287
  if (!method) {
1369
288
  method = 'get';
@@ -1372,17 +291,15 @@ Dao.prototype.main = async function (params, db) {
1372
291
  return getRet().error(50001, '不支持的操作方式');
1373
292
  }
1374
293
  method = this._getMethodName(method);
1375
- var qy = { ...query };
294
+ let qy = { ...query };
1376
295
  delete qy[f.method];
1377
296
  if (this[method]) {
1378
297
  db.method = method;
1379
298
 
1380
- // 取数据表名
1381
- var table = query[f.table];
1382
- var safe_table = typeof table === 'string' && string.validate(table, 'username') ? table : '';
299
+ let table = query[f.table];
300
+ let safe_table = typeof table === 'string' && string.validate(table, 'username') ? table : '';
1383
301
 
1384
- // 设置操作的数据表
1385
- var table_name;
302
+ let table_name;
1386
303
  if (string.has(cg.table, '*{0}*')) {
1387
304
  if (table) {
1388
305
  if (!safe_table) {
@@ -1397,17 +314,19 @@ Dao.prototype.main = async function (params, db) {
1397
314
  }
1398
315
  db.table = table_name;
1399
316
 
1400
- // 兼容传入数据管理器(无 config,只有 new/getSql 等方法)的场景:
317
+ // 数据源形态归一:传入的是库级管理器(无 config,只有 new/getSql 等方法)时,
1401
318
  // 派生一张绑定表名的表模型,使 getSql/getCountSql/groupCountSql 等表级方法可用;
1402
- // 传入的已是表模型时保持不变
319
+ // 传入的已是表模型时保持不变。
1403
320
  if (db && db.config === undefined && typeof db.new === 'function') {
1404
321
  db = db.new(table_name, cg.key);
1405
322
  }
323
+ // 占位符取值挂在本次调用的表模型上(每次 new 出来的独立对象),
324
+ // 默认条件、默认字段都从这里取 {user_id} 之类的值,不再读 db.user
325
+ db.context = params.context || {};
1406
326
 
1407
- return await this[method](db, qy, { ...body });
1408
- } else {
1409
- return getRet().error(50001, '不支持的操作方式');
327
+ return this[method](db, qy, { ...body });
1410
328
  }
329
+ return getRet().error(50001, '不支持的操作方式');
1411
330
  };
1412
331
 
1413
332
  /**
@@ -1420,7 +339,7 @@ Dao.prototype._getMethodName = function (method) {
1420
339
  if (!method) {
1421
340
  return '';
1422
341
  }
1423
- if (method.indexOf('_') == -1) {
342
+ if (method.indexOf('_') === -1) {
1424
343
  return method;
1425
344
  }
1426
345
  // 将小写蛇形改为小驼峰
@@ -1434,111 +353,11 @@ Dao.prototype._getMethodName = function (method) {
1434
353
  };
1435
354
 
1436
355
  /**
1437
- * 分组统计(sum、avg、count 共用)
1438
- * @param {object} db 数据库管理器
1439
- * @param {object} param 查询条件
1440
- * @param {string} method 统计方法名 groupSumSql / groupAvgSql / groupCountSql
1441
- * @returns {object} 返回执行结果
1442
- * @private
1443
- */
1444
- Dao.prototype._statMain = async function (db, param, method) {
1445
- var pm = { ...param };
1446
- var f = this._getFilter(this.config);
1447
- var orderby = pm[f.orderby] || '';
1448
- var groupby = pm[f.groupby];
1449
- var field = pm[f.field];
1450
- delete pm[f.orderby];
1451
- delete pm[f.groupby];
1452
- delete pm[f.field];
1453
- if (!groupby || !field) {
1454
- return getRet().error(30000, '参数groupby、field是必须的,且值不能为空!');
1455
- }
1456
- var query_str = this.toWhere(db, pm, 'get_list');
1457
- var list = await db[method](query_str, groupby, field, orderby);
1458
- if (!list.length && db.error) {
1459
- return getRet().body(db.error);
1460
- }
1461
- return getRet().list(list);
1462
- };
1463
-
1464
- /**
1465
- * 总计
1466
- * @param {object} db 数据库管理器
1467
- * @param {object} param 查询条件
1468
- * @returns {object} 返回执行结果
1469
- */
1470
- Dao.prototype.sumMain = async function (db, param) {
1471
- return await this._statMain(db, param, 'groupSumSql');
1472
- };
1473
-
1474
- /**
1475
- * 总计
1476
- * @param {object} db 数据库管理器
1477
- * @param {object} query 查询条件
1478
- * @param {object} body 正文参数
1479
- * @returns {object} 返回执行结果
356
+ * 合并职责分片到原型:各分片导出方法集合,this 指向 Dao 实例
1480
357
  */
1481
- Dao.prototype.sum = async function (db, query, body) {
1482
- return await this.sumMain(db, { ...query, ...body });
1483
- };
1484
-
1485
- /**
1486
- * 平均值
1487
- * @param {object} db 数据库管理器
1488
- * @param {object} param 查询条件
1489
- * @returns {object} 返回执行结果
1490
- */
1491
- Dao.prototype.avgMain = async function (db, param) {
1492
- return await this._statMain(db, param, 'groupAvgSql');
1493
- };
1494
-
1495
- /**
1496
- * 平均值
1497
- * @param {object} db 数据库管理器
1498
- * @param {object} query 查询条件
1499
- * @param {object} body 正文参数
1500
- * @returns {object} 返回执行结果
1501
- */
1502
- Dao.prototype.avg = async function (db, query, body) {
1503
- return await this.avgMain(db, { ...query, ...body });
1504
- };
1505
-
1506
- /**
1507
- * 计数
1508
- * @param {object} db 数据库管理器
1509
- * @param {object} param 查询条件
1510
- * @returns {object} 返回执行结果
1511
- */
1512
- Dao.prototype.countMain = async function (db, param) {
1513
- return await this._statMain(db, param, 'groupCountSql');
1514
- };
1515
-
1516
- /**
1517
- * 计数
1518
- * @param {object} db 数据库管理器
1519
- * @param {object} query 查询条件
1520
- * @param {object} body 正文参数
1521
- * @returns {object} 返回执行结果
1522
- */
1523
- Dao.prototype.count = async function (db, query, body) {
1524
- return await this.countMain(db, { ...query, ...body });
1525
- };
358
+ let parts = [scope_part, query_part, crud_part, fields_part, transfer_part, stats_part];
359
+ for (let part of parts) {
360
+ Object.assign(Dao.prototype, part);
361
+ }
1526
362
 
1527
- /**
1528
- * 获取模型
1529
- * @param {string} type 模型类型
1530
- * @returns {object} 返回获取到的模型
1531
- */
1532
- Dao.prototype.getModel = function (type) {
1533
- let model = { ...this.config };
1534
- let dir = this.config.dir || '';
1535
- let l = path.sep;
1536
- let app_name = string.between(dir, 'app' + l, l);
1537
- let plugin_name = string.between(dir, 'plugin' + l, l);
1538
- let name = path.basename(dir);
1539
- model.app = app_name;
1540
- model.plugin = plugin_name;
1541
- model.name = model.name || app_name + '_' + name;
1542
- return model;
1543
- };
1544
363
  module.exports = Dao;