midway-fatcms 0.0.6 → 0.0.8

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 (121) hide show
  1. package/.qoder/skills/midway-fatcms/01-quick-start.md +231 -0
  2. package/.qoder/skills/midway-fatcms/02-crud-quick.md +337 -0
  3. package/.qoder/skills/midway-fatcms/03-crud-sharding.md +488 -0
  4. package/.qoder/skills/midway-fatcms/04-condition-operators.md +93 -0
  5. package/.qoder/skills/midway-fatcms/05-configuration.md +290 -0
  6. package/.qoder/skills/midway-fatcms/06-builtin-functions.md +241 -0
  7. package/.qoder/skills/midway-fatcms/07-examples.md +500 -0
  8. package/.qoder/skills/midway-fatcms/SKILL.md +96 -0
  9. package/README.md +9 -9
  10. package/dist/controller/base/BaseApiController.d.ts +1 -2
  11. package/dist/controller/base/BaseApiController.js +0 -4
  12. package/dist/controller/gateway/DocGatewayController.js +1 -1
  13. package/dist/controller/manage/FlowConfigManageApi.js +4 -2
  14. package/dist/controller/manage/SysConfigMangeApi.js +6 -1
  15. package/dist/controller/manage/UserAccountManageApi.js +7 -2
  16. package/dist/index.d.ts +2 -2
  17. package/dist/index.js +2 -2
  18. package/dist/libs/crud-pro/CrudPro.d.ts +23 -2
  19. package/dist/libs/crud-pro/CrudPro.js +53 -2
  20. package/dist/libs/crud-pro/interfaces.d.ts +82 -12
  21. package/dist/libs/crud-pro/models/CrudResult.d.ts +115 -0
  22. package/dist/libs/crud-pro/models/CrudResult.js +126 -0
  23. package/dist/libs/crud-pro/models/RequestModel.d.ts +2 -38
  24. package/dist/libs/crud-pro/models/RequestModel.js +2 -99
  25. package/dist/libs/crud-pro/services/CrudProExecuteSqlService.js +36 -2
  26. package/dist/libs/crud-pro/services/CrudProGenSqlCondition.js +8 -4
  27. package/dist/libs/crud-pro/services/CrudProTableMetaService.js +1 -2
  28. package/dist/libs/crud-pro/utils/OrderByUtils.d.ts +70 -0
  29. package/dist/libs/crud-pro/utils/OrderByUtils.js +158 -0
  30. package/dist/libs/crud-pro-quick/CrudProQuick.d.ts +295 -0
  31. package/dist/libs/crud-pro-quick/CrudProQuick.js +529 -0
  32. package/dist/libs/crud-pro-quick/fixSoftDelete.d.ts +30 -0
  33. package/dist/{service/curd → libs/crud-pro-quick}/fixSoftDelete.js +3 -6
  34. package/dist/libs/crud-pro-quick/index.d.ts +36 -0
  35. package/dist/libs/crud-pro-quick/index.js +49 -0
  36. package/dist/libs/crud-pro-quick/models.d.ts +33 -0
  37. package/dist/libs/crud-pro-quick/models.js +2 -0
  38. package/dist/libs/crud-sharding/ShardingConfig.d.ts +15 -2
  39. package/dist/libs/crud-sharding/ShardingConfig.js +2 -2
  40. package/dist/libs/crud-sharding/ShardingCrudPro.d.ts +119 -274
  41. package/dist/libs/crud-sharding/ShardingCrudPro.js +559 -379
  42. package/dist/libs/crud-sharding/ShardingMerger.d.ts +12 -20
  43. package/dist/libs/crud-sharding/ShardingMerger.js +36 -51
  44. package/dist/libs/crud-sharding/ShardingResult.d.ts +33 -0
  45. package/dist/libs/crud-sharding/ShardingResult.js +16 -0
  46. package/dist/libs/crud-sharding/ShardingRouter.d.ts +1 -0
  47. package/dist/libs/crud-sharding/ShardingRouter.js +25 -6
  48. package/dist/libs/crud-sharding/ShardingTableCreator.d.ts +21 -4
  49. package/dist/libs/crud-sharding/ShardingTableCreator.js +193 -59
  50. package/dist/libs/crud-sharding/ShardingUtils.d.ts +48 -0
  51. package/dist/libs/crud-sharding/ShardingUtils.js +122 -1
  52. package/dist/libs/crud-sharding/TIME_COLUMN_CLEAN_SPEC.md +488 -0
  53. package/dist/libs/crud-sharding/index.d.ts +4 -3
  54. package/dist/libs/crud-sharding/index.js +14 -2
  55. package/dist/models/bizmodels.d.ts +2 -6
  56. package/dist/service/SysAppService.d.ts +2 -2
  57. package/dist/service/SysAppService.js +16 -5
  58. package/dist/service/SysConfigService.d.ts +1 -1
  59. package/dist/service/SysConfigService.js +7 -2
  60. package/dist/service/SysDictDataService.js +14 -4
  61. package/dist/service/SysMenuService.js +7 -2
  62. package/dist/service/curd/CurdMixService.d.ts +6 -4
  63. package/dist/service/curd/CurdMixService.js +16 -2
  64. package/dist/service/curd/CurdProService.d.ts +43 -27
  65. package/dist/service/curd/CurdProService.js +32 -33
  66. package/dist/service/flow/FlowConfigService.js +7 -2
  67. package/dist/service/flow/FlowInstanceCrudService.js +22 -19
  68. package/package.json +2 -1
  69. package/src/controller/base/BaseApiController.ts +0 -5
  70. package/src/controller/gateway/DocGatewayController.ts +1 -1
  71. package/src/controller/manage/CrudStandardDesignApi.ts +4 -3
  72. package/src/controller/manage/FlowConfigManageApi.ts +4 -2
  73. package/src/controller/manage/SysConfigMangeApi.ts +6 -1
  74. package/src/controller/manage/UserAccountManageApi.ts +7 -2
  75. package/src/index.ts +2 -2
  76. package/src/libs/crud-pro/CrudPro.ts +62 -4
  77. package/src/libs/crud-pro/interfaces.ts +110 -15
  78. package/src/libs/crud-pro/models/CrudResult.ts +178 -0
  79. package/src/libs/crud-pro/models/RequestModel.ts +4 -110
  80. package/src/libs/crud-pro/services/CrudProExecuteSqlService.ts +41 -2
  81. package/src/libs/crud-pro/services/CrudProGenSqlCondition.ts +11 -7
  82. package/src/libs/crud-pro/services/CrudProTableMetaService.ts +1 -2
  83. package/src/libs/crud-pro/utils/OrderByUtils.ts +169 -0
  84. package/src/libs/crud-pro-quick/CrudProQuick.ts +594 -0
  85. package/src/{service/curd → libs/crud-pro-quick}/fixSoftDelete.ts +23 -13
  86. package/src/libs/crud-pro-quick/index.ts +52 -0
  87. package/src/libs/crud-pro-quick/models.ts +35 -0
  88. package/src/libs/crud-sharding/ShardingConfig.ts +18 -2
  89. package/src/libs/crud-sharding/ShardingCrudPro.ts +689 -440
  90. package/src/libs/crud-sharding/ShardingMerger.ts +47 -73
  91. package/src/libs/crud-sharding/ShardingResult.ts +29 -0
  92. package/src/libs/crud-sharding/ShardingRouter.ts +27 -6
  93. package/src/libs/crud-sharding/ShardingTableCreator.ts +214 -71
  94. package/src/libs/crud-sharding/ShardingUtils.ts +137 -0
  95. package/src/libs/crud-sharding/TIME_COLUMN_CLEAN_SPEC.md +488 -0
  96. package/src/libs/crud-sharding/index.ts +14 -3
  97. package/src/models/bizmodels.ts +4 -7
  98. package/src/service/SysAppService.ts +18 -7
  99. package/src/service/SysConfigService.ts +8 -3
  100. package/src/service/SysDictDataService.ts +14 -4
  101. package/src/service/SysMenuService.ts +7 -2
  102. package/src/service/crudstd/CrudStdService.ts +2 -2
  103. package/src/service/curd/CurdMixService.ts +26 -5
  104. package/src/service/curd/CurdProService.ts +58 -39
  105. package/src/service/flow/FlowConfigService.ts +7 -2
  106. package/src/service/flow/FlowInstanceCrudService.ts +23 -20
  107. package/dist/libs/crud-pro/README.md +0 -809
  108. package/dist/libs/crud-pro/README_FUNC.md +0 -193
  109. package/dist/libs/crud-sharding/ROUTING_LOGIC.md +0 -944
  110. package/dist/models/StandardColumns.d.ts +0 -71
  111. package/dist/models/StandardColumns.js +0 -28
  112. package/dist/service/curd/CrudProQuick.d.ts +0 -190
  113. package/dist/service/curd/CrudProQuick.js +0 -319
  114. package/dist/service/curd/README.md +0 -1001
  115. package/dist/service/curd/fixSoftDelete.d.ts +0 -20
  116. package/src/libs/crud-pro/README.md +0 -809
  117. package/src/libs/crud-pro/README_FUNC.md +0 -193
  118. package/src/libs/crud-sharding/ROUTING_LOGIC.md +0 -944
  119. package/src/models/StandardColumns.ts +0 -76
  120. package/src/service/curd/CrudProQuick.ts +0 -360
  121. package/src/service/curd/README.md +0 -1001
@@ -0,0 +1,594 @@
1
+ import { KeysOfSimpleSQL, SqlDbType } from '@/libs/crud-pro/models/keys';
2
+ import { IRequestCfgModel, IRequestModel, ISqlCfgModel, ExecuteSQLResult } from '@/libs/crud-pro/interfaces';
3
+ import { CrudPro } from '@/libs/crud-pro/CrudPro';
4
+ import { fixSoftDelete } from "./fixSoftDelete";
5
+ import {
6
+ CrudWriteResult,
7
+ CrudQueryOneResult,
8
+ CrudQueryListResult,
9
+ CrudQueryPageResult,
10
+ CrudExistResult,
11
+ CrudCountResult,
12
+ CrudUpsertResult,
13
+ } from '@/libs/crud-pro/models/CrudResult';
14
+
15
+ const DEFAULT_MAX_LIMIT = 10 * 10000;
16
+
17
+ /**
18
+ * CrudProQuick 构造参数(工厂函数模式)
19
+ */
20
+ export interface ICrudProQuickFactory {
21
+ crudProFactory: () => CrudPro;
22
+ sqlDatabase: string;
23
+ sqlDbType: SqlDbType;
24
+ sqlTable?: string;
25
+ }
26
+
27
+ /**
28
+ * 快捷 CRUD 操作封装器
29
+ *
30
+ * 在 CrudPro 之上封装便捷方法,提供简洁的 API 进行单表 CRUD 操作。
31
+ * 内部使用工厂函数模式,每次操作都会获取新的 CrudPro 实例,因此**可以安全复用**。
32
+ *
33
+ * **使用限制:**
34
+ * - CrudProQuick 可以安全复用(内部每次获取新 CrudPro)
35
+ * - 必须通过 CurdProService.getQuickCrud() 获取实例
36
+ * - sqlTable 必填(构造时或每次调用时传入)
37
+ *
38
+ * @example
39
+ * // 通过 CurdProService 获取实例
40
+ * const quick = curdProService.getQuickCrud('mydb', SqlDbType.mysql, 't_user');
41
+ *
42
+ * // 查询列表
43
+ * const result = await quick.findList({ condition: { status: 1 } });
44
+ * console.log(result.rows, result.count);
45
+ *
46
+ * // 插入数据
47
+ * const insertResult = await quick.insert({ data: { name: '张三', age: 20 } });
48
+ * console.log(insertResult.affectedRows, insertResult.insertId);
49
+ *
50
+ * // 可以安全复用
51
+ * const updateResult = await quick.update({ condition: { id: 1 }, data: { age: 21 } });
52
+ */
53
+ export class CrudProQuick {
54
+ private readonly crudProFactory: () => CrudPro;
55
+ private readonly sqlDbType: SqlDbType;
56
+ private readonly sqlDatabase: string;
57
+ private readonly sqlTable?: string;
58
+ private baseCfgModel: {
59
+ maxLimit?: number;
60
+ enableSoftDelete?: boolean;
61
+ enableStandardUpdateCfg?: boolean;
62
+ enableStandardUpdateCfgCondition?: string[];
63
+ [key: string]: any;
64
+ } = {
65
+ maxLimit: DEFAULT_MAX_LIMIT,
66
+ };
67
+
68
+ /**
69
+ * 构造函数(工厂函数模式)
70
+ * @param args 工厂函数参数
71
+ */
72
+ constructor(args: ICrudProQuickFactory) {
73
+ this.sqlDatabase = args.sqlDatabase;
74
+ this.sqlDbType = args.sqlDbType;
75
+ this.sqlTable = args.sqlTable;
76
+ this.crudProFactory = args.crudProFactory;
77
+ }
78
+
79
+ /**
80
+ * 设置基础配置模型,合并到实例的 baseCfgModel 中,后续所有 CRUD 操作都会携带这些配置
81
+ * 例如可以统一设置 maxLimit、enableSoftDelete 等公共参数,避免每次调用都重复传入
82
+ * @param baseCfgModel 要合并的配置项
83
+ */
84
+ public setBaseCfgModel(baseCfgModel: Record<string, any>) {
85
+ Object.assign(this.baseCfgModel, baseCfgModel);
86
+ }
87
+
88
+ private async executeCrudByCfg(reqJson: IRequestModel, cfgModel2: Record<string, any>) {
89
+ const cfgModel = { ...this.baseCfgModel };
90
+ Object.assign(cfgModel, cfgModel2);
91
+
92
+ cfgModel.method = 'CrudProQuickAnonymous';
93
+ cfgModel.updateCfg = {};
94
+ cfgModel.sqlDatabase = this.sqlDatabase;
95
+ cfgModel.sqlDbType = this.sqlDbType;
96
+
97
+ if (!cfgModel.sqlTable) {
98
+ cfgModel.sqlTable = this.sqlTable;
99
+ }
100
+
101
+ if (!cfgModel.sqlTable) {
102
+ throw new Error('[CrudProQuick] sqlTable not found');
103
+ }
104
+
105
+ // 创建 CrudPro 实例并设置 visitor
106
+ const crudPro = this.crudProFactory();
107
+
108
+ // 应用软删除动作。
109
+ fixSoftDelete(cfgModel.sqlSimpleName, cfgModel, reqJson, crudPro.getVisitor());
110
+
111
+ return await crudPro.executeCrudByCfg(reqJson, cfgModel);
112
+ }
113
+
114
+ /**
115
+ * 查询单条记录
116
+ * @param reqJson 请求参数
117
+ * @param sqlTable 数据库表名称
118
+ * @returns CrudQueryOneResult 包含 row、found 和 getRawContext()
119
+ */
120
+ public async findOne<T = Record<string, any>>(reqJson: IRequestModel, sqlTable?: string): Promise<CrudQueryOneResult<T>> {
121
+ const cfgModel: IRequestCfgModel = {
122
+ sqlTable,
123
+ sqlSimpleName: KeysOfSimpleSQL.SIMPLE_QUERY_ONE,
124
+ };
125
+ const ctx = await this.executeCrudByCfg(reqJson, cfgModel);
126
+ const row = ctx.getOneObj() as T | null;
127
+ return new CrudQueryOneResult<T>({ row, rawContext: ctx, debugInfo: this.buildDebugInfo(sqlTable, reqJson.condition) });
128
+ }
129
+
130
+ /**
131
+ * 查询唯一单条记录(期望结果为 0 条或 1 条)
132
+ *
133
+ * 与 findOne 不同,此方法会校验查询结果的唯一性:
134
+ * - 如果查到 0 条:返回 row = null
135
+ * - 如果查到 1 条:正常返回
136
+ * - 如果查到多条:抛出异常,包含详细的定位信息
137
+ *
138
+ * @param reqJson 请求参数
139
+ * @param sqlTable 数据库表名称
140
+ * @returns CrudQueryOneResult 包含 row、found 和 getRawContext()
141
+ * @throws Error 如果查询到多条记录
142
+ *
143
+ * @example
144
+ * // 根据唯一索引查询单条
145
+ * const result = await quick.findUniqueOne({ condition: { email: 'user@example.com' } });
146
+ * if (result.found) {
147
+ * console.log(result.row);
148
+ * }
149
+ */
150
+ public async findUniqueOne<T = Record<string, any>>(reqJson: IRequestModel, sqlTable?: string): Promise<CrudQueryOneResult<T>> {
151
+ const effectiveTable = sqlTable || this.sqlTable;
152
+
153
+ // 使用 maxLimit: 2 查询,判断是否有多条
154
+ const cfgModel: IRequestCfgModel = {
155
+ sqlTable: effectiveTable,
156
+ sqlSimpleName: KeysOfSimpleSQL.SIMPLE_QUERY,
157
+ maxLimit: 2,
158
+ };
159
+ const ctx = await this.executeCrudByCfg(reqJson, cfgModel);
160
+ const rows = ctx.getResRows() as T[];
161
+
162
+ if (rows.length > 1) {
163
+ const debugInfo = this.buildDebugInfo(effectiveTable, reqJson.condition);
164
+ const errorMsg = this.formatUniqueError(rows.length, debugInfo);
165
+ throw new Error(errorMsg);
166
+ }
167
+
168
+ return new CrudQueryOneResult<T>({
169
+ row: rows[0] || null,
170
+ rawContext: ctx,
171
+ debugInfo: this.buildDebugInfo(effectiveTable, reqJson.condition),
172
+ });
173
+ }
174
+
175
+ /**
176
+ * 构建辅助定位信息
177
+ */
178
+ private buildDebugInfo(sqlTable: string | undefined, condition: Record<string, any> | undefined): { sqlDatabase: string; sqlTable: string; condition?: Record<string, any> } {
179
+ const info: { sqlDatabase: string; sqlTable: string; condition?: Record<string, any> } = {
180
+ sqlDatabase: this.sqlDatabase,
181
+ sqlTable: sqlTable || this.sqlTable || 'unknown',
182
+ };
183
+ if (condition) {
184
+ info.condition = condition;
185
+ }
186
+ return info;
187
+ }
188
+
189
+ /**
190
+ * 格式化唯一性错误消息
191
+ */
192
+ private formatUniqueError(foundCount: number, debugInfo: { sqlDatabase: string; sqlTable: string; condition?: Record<string, any> }): string {
193
+ const parts = [
194
+ `[CrudProQuick] findUniqueOne 期望唯一一条记录,但查询到 ${foundCount} 条`,
195
+ ];
196
+
197
+ if (debugInfo.sqlDatabase) {
198
+ parts.push(`数据库: ${debugInfo.sqlDatabase}`);
199
+ }
200
+ if (debugInfo.sqlTable) {
201
+ parts.push(`表: ${debugInfo.sqlTable}`);
202
+ }
203
+ if (debugInfo.condition) {
204
+ try {
205
+ parts.push(`条件: ${JSON.stringify(debugInfo.condition)}`);
206
+ } catch {
207
+ parts.push(`条件: [无法序列化]`);
208
+ }
209
+ }
210
+
211
+ return parts.join(' | ');
212
+ }
213
+
214
+ /**
215
+ * 查询数据列表
216
+ * @param reqJson 请求参数
217
+ * @param sqlTable 数据库表名称
218
+ * @returns CrudQueryListResult 包含 rows、count 和 getRawContext()
219
+ */
220
+ public async findList<T = Record<string, any>>(reqJson: IRequestModel, sqlTable?: string): Promise<CrudQueryListResult<T>> {
221
+ const cfgModel: IRequestCfgModel = {
222
+ sqlTable,
223
+ sqlSimpleName: KeysOfSimpleSQL.SIMPLE_QUERY,
224
+ };
225
+ const ctx = await this.executeCrudByCfg(reqJson, cfgModel);
226
+ const rows = ctx.getResRows() as T[];
227
+ return new CrudQueryListResult<T>({ rows, rawContext: ctx });
228
+ }
229
+
230
+ /**
231
+ * 分页查询数据列表
232
+ * 内部使用 SIMPLE_QUERY_PAGE 模式,reqJson 中可传入 pageNo、pageSize 控制分页
233
+ * @param reqJson 请求参数,支持 condition(查询条件)、pageNo、pageSize 等
234
+ * @param sqlTable 数据库表名,若构造实例时已设置全局 sqlTable 则可省略
235
+ * @returns CrudQueryPageResult 包含 rows、totalCount、count 和 getRawContext()
236
+ */
237
+ public async findPage<T = Record<string, any>>(reqJson: IRequestModel, sqlTable?: string): Promise<CrudQueryPageResult<T>> {
238
+ const cfgModel: IRequestCfgModel = {
239
+ sqlTable,
240
+ sqlSimpleName: KeysOfSimpleSQL.SIMPLE_QUERY_PAGE,
241
+ };
242
+ const ctx = await this.executeCrudByCfg(reqJson, cfgModel);
243
+ const pageResult = ctx.getResModelForQueryPage();
244
+ return new CrudQueryPageResult<T>({
245
+ rows: pageResult.rows as T[],
246
+ totalCount: pageResult.total_count,
247
+ rawContext: ctx,
248
+ });
249
+ }
250
+
251
+ /**
252
+ * 判断满足条件的记录是否存在
253
+ * 内部使用 SIMPLE_QUERY_EXIST 模式,通过 SELECT EXISTS 子查询实现,找到首条匹配即返回,比 COUNT(*) 更高效
254
+ * @param reqJson 请求参数,通过 condition 指定查询条件
255
+ * @param sqlTable 数据库表名,若构造实例时已设置全局 sqlTable 则可省略
256
+ * @returns CrudExistResult 包含 exists 和 getRawContext()
257
+ */
258
+ public async isExist(reqJson: IRequestModel, sqlTable?: string): Promise<CrudExistResult> {
259
+ const cfgModel: IRequestCfgModel = {
260
+ sqlTable,
261
+ sqlSimpleName: KeysOfSimpleSQL.SIMPLE_QUERY_EXIST,
262
+ };
263
+ const ctx = await this.executeCrudByCfg(reqJson, cfgModel);
264
+ const exists = ctx.getResModel().is_exist;
265
+ return new CrudExistResult({ exists, rawContext: ctx });
266
+ }
267
+
268
+ /**
269
+ * 查询满足条件的记录总数
270
+ * 内部使用 SIMPLE_QUERY_COUNT 模式,仅返回 count 结果
271
+ * @param reqJson 请求参数,通过 condition 指定查询条件
272
+ * @param sqlTable 数据库表名,若构造实例时已设置全局 sqlTable 则可省略
273
+ * @returns CrudCountResult 包含 count 和 getRawContext()
274
+ */
275
+ public async findCount(reqJson: IRequestModel, sqlTable?: string): Promise<CrudCountResult> {
276
+ const cfgModel: IRequestCfgModel = {
277
+ sqlTable,
278
+ sqlSimpleName: KeysOfSimpleSQL.SIMPLE_QUERY_COUNT,
279
+ };
280
+ const ctx = await this.executeCrudByCfg(reqJson, cfgModel);
281
+ const count = ctx.getResModel().total_count || 0;
282
+ return new CrudCountResult({ count, rawContext: ctx });
283
+ }
284
+
285
+ /**
286
+ * 插入一条数据记录
287
+ * 内部使用 SIMPLE_INSERT 模式,通过 reqJson.data 传入要插入的字段和值
288
+ * @param reqJson 请求参数,data 字段中包含要插入的键值对
289
+ * @param sqlTable 数据库表名,若构造实例时已设置全局 sqlTable 则可省略
290
+ * @returns CrudWriteResult 包含 affectedRows、insertId 和 getRawContext()
291
+ */
292
+ public async insert(reqJson: IRequestModel, sqlTable?: string): Promise<CrudWriteResult> {
293
+ const cfgModel: IRequestCfgModel = {
294
+ sqlTable,
295
+ sqlSimpleName: KeysOfSimpleSQL.SIMPLE_INSERT,
296
+ };
297
+ const ctx = await this.executeCrudByCfg(reqJson, cfgModel);
298
+ const affected = ctx.getResModel().affected || { affectedRows: 0 };
299
+ return new CrudWriteResult({
300
+ affectedRows: affected.affectedRows,
301
+ insertId: affected.insertId,
302
+ rawContext: ctx,
303
+ });
304
+ }
305
+
306
+ /**
307
+ * 批量插入数据记录
308
+ * 内部使用 SIMPLE_BATCH_INSERT 模式,单条 SQL 插入多行数据,效率远高于循环单条插入
309
+ *
310
+ * @param reqJson 请求参数,data 为对象数组 [{name:'a'},{name:'b'}]
311
+ * @param sqlTable 数据库表名,若构造实例时已设置全局 sqlTable 则可省略
312
+ * @returns CrudWriteResult 包含 affectedRows、insertId 和 getRawContext()
313
+ *
314
+ * 注意事项:
315
+ * - affectedRows: 返回实际插入的行数,所有数据库均正确返回
316
+ * - insertId: 仅返回第一条记录的自增ID,后续记录的ID需通过 insertId + index 推算
317
+ * - MySQL: 返回第一条的 insertId
318
+ * - PostgreSQL: RETURNING * 返回所有行,但仅取第一条的 id
319
+ * - SQL Server: OUTPUT 返回所有行,但仅取第一条的 id
320
+ */
321
+ public async batchInsert(reqJson: IRequestModel, sqlTable?: string): Promise<CrudWriteResult> {
322
+ const cfgModel: IRequestCfgModel = {
323
+ sqlTable,
324
+ sqlSimpleName: KeysOfSimpleSQL.SIMPLE_BATCH_INSERT,
325
+ };
326
+ const ctx = await this.executeCrudByCfg(reqJson, cfgModel);
327
+ const affected = ctx.getResModel().affected || { affectedRows: 0 };
328
+ return new CrudWriteResult({
329
+ affectedRows: affected.affectedRows,
330
+ insertId: affected.insertId,
331
+ rawContext: ctx,
332
+ });
333
+ }
334
+
335
+ /**
336
+ * 更新数据记录
337
+ * 内部使用 SIMPLE_UPDATE 模式,通过 reqJson.data 传入要更新的字段和值,通过 reqJson.condition 指定更新条件
338
+ * @param reqJson 请求参数,data 为更新内容,condition 为更新条件
339
+ * @param sqlTable 数据库表名,若构造实例时已设置全局 sqlTable 则可省略
340
+ * @returns CrudWriteResult 包含 affectedRows 和 getRawContext()
341
+ */
342
+ public async update(reqJson: IRequestModel, sqlTable?: string): Promise<CrudWriteResult> {
343
+ const cfgModel: IRequestCfgModel = {
344
+ sqlTable,
345
+ sqlSimpleName: KeysOfSimpleSQL.SIMPLE_UPDATE,
346
+ };
347
+ const ctx = await this.executeCrudByCfg(reqJson, cfgModel);
348
+ const affected = ctx.getResModel().affected || { affectedRows: 0 };
349
+ return new CrudWriteResult({
350
+ affectedRows: affected.affectedRows,
351
+ insertId: affected.insertId,
352
+ rawContext: ctx,
353
+ });
354
+ }
355
+
356
+ /**
357
+ * 插入或更新数据记录(upsert)
358
+ * 内部使用 SIMPLE_INSERT_OR_UPDATE 模式,若记录已存在则更新,不存在则插入
359
+ * @param reqJson 请求参数,data 为要插入/更新的内容,condition 为判断条件
360
+ * @param sqlTable 数据库表名,若构造实例时已设置全局 sqlTable 则可省略
361
+ * @returns CrudUpsertResult 包含 affected、insertAffected、updateAffected、isExist 和 getRawContext()
362
+ */
363
+ public async insertOrUpdate(reqJson: IRequestModel, sqlTable?: string): Promise<CrudUpsertResult> {
364
+ const cfgModel: IRequestCfgModel = {
365
+ sqlTable,
366
+ sqlSimpleName: KeysOfSimpleSQL.SIMPLE_INSERT_OR_UPDATE,
367
+ };
368
+ const ctx = await this.executeCrudByCfg(reqJson, cfgModel);
369
+ const resModel = ctx.getResModel();
370
+ return new CrudUpsertResult({
371
+ affected: resModel.affected,
372
+ insertAffected: resModel.insert_affected,
373
+ updateAffected: resModel.update_affected,
374
+ isExist: resModel.is_exist ?? false,
375
+ rawContext: ctx,
376
+ });
377
+ }
378
+
379
+ /**
380
+ * 使用数据库原生 upsert 语法插入或更新(ON DUPLICATE KEY UPDATE / ON CONFLICT / MERGE)
381
+ * 内部使用 SIMPLE_INSERT_ON_DUPLICATE_UPDATE 模式,单条 SQL 完成 upsert,效率更高
382
+ *
383
+ * 数据库差异:
384
+ * - MySQL: ON DUPLICATE KEY UPDATE(依赖唯一索引/主键)
385
+ * - PostgreSQL: ON CONFLICT (...) DO UPDATE(需配置 uniqueColumn)
386
+ * - SQL Server: IF EXISTS ... ELSE ...(需配置 uniqueColumn,仅支持单列)
387
+ *
388
+ * @param reqJson 请求参数,data 为要插入/更新的内容
389
+ * @param uniqueColumn 唯一列名(PostgreSQL/SQL Server 必需),PostgreSQL 支持多列,SQL Server 仅支持单列
390
+ * @param sqlTable 数据库表名,若构造实例时已设置全局 sqlTable 则可省略
391
+ * @returns CrudWriteResult 包含 affectedRows、insertId 和 getRawContext()
392
+ */
393
+ public async insertOnDuplicateUpdate(reqJson: IRequestModel, uniqueColumn?: string[], sqlTable?: string): Promise<CrudWriteResult> {
394
+ const cfgModel: IRequestCfgModel = {
395
+ sqlTable,
396
+ sqlSimpleName: KeysOfSimpleSQL.SIMPLE_INSERT_ON_DUPLICATE_UPDATE,
397
+ uniqueColumn,
398
+ };
399
+ const ctx = await this.executeCrudByCfg(reqJson, cfgModel);
400
+ const affected = ctx.getResModel().affected || { affectedRows: 0 };
401
+ return new CrudWriteResult({
402
+ affectedRows: affected.affectedRows,
403
+ insertId: affected.insertId,
404
+ rawContext: ctx,
405
+ });
406
+ }
407
+
408
+ /**
409
+ * 删除数据记录
410
+ * 内部使用 SIMPLE_DELETE 模式,通过 reqJson.condition 指定删除条件
411
+ * 注意:如果启用了软删除,实际执行的是更新操作而非物理删除
412
+ * @param reqJson 请求参数,condition 为删除条件
413
+ * @param sqlTable 数据库表名,若构造实例时已设置全局 sqlTable 则可省略
414
+ * @returns CrudWriteResult 包含 affectedRows 和 getRawContext()
415
+ */
416
+ public async delete(reqJson: IRequestModel, sqlTable?: string): Promise<CrudWriteResult> {
417
+ const cfgModel: IRequestCfgModel = {
418
+ sqlTable,
419
+ sqlSimpleName: KeysOfSimpleSQL.SIMPLE_DELETE,
420
+ };
421
+ const ctx = await this.executeCrudByCfg(reqJson, cfgModel);
422
+ const affected = ctx.getResModel().affected || { affectedRows: 0 };
423
+ return new CrudWriteResult({
424
+ affectedRows: affected.affectedRows,
425
+ insertId: affected.insertId,
426
+ rawContext: ctx,
427
+ });
428
+ }
429
+
430
+ /**
431
+ * 恢复软删除的记录
432
+ * 将 deleted_at 字段重置为 0,deleted_by 重置为空字符串
433
+ *
434
+ * @param reqJson 请求参数,通过 condition 指定要恢复的记录
435
+ * @param sqlTable 数据库表名,若构造实例时已设置全局 sqlTable 则可省略
436
+ * @returns CrudWriteResult 包含 affectedRows 和 getRawContext()
437
+ *
438
+ * @example
439
+ * // 恢复指定 ID 的记录
440
+ * await quick.restore({ condition: { id: 1 } });
441
+ *
442
+ * // 恢复多条记录(使用 $in 操作符)
443
+ * await quick.restore({ condition: { id: { $in: [1, 2, 3] } } });
444
+ *
445
+ * // 按条件批量恢复记录
446
+ * await quick.restore({ condition: { status: 'deleted' } });
447
+ */
448
+ public async restore(reqJson: IRequestModel, sqlTable?: string): Promise<CrudWriteResult> {
449
+ const effectiveTable = sqlTable || this.sqlTable;
450
+
451
+ if (!reqJson.condition || Object.keys(reqJson.condition).length === 0) {
452
+ throw new Error('[CrudProQuick] restore 操作必须指定恢复条件');
453
+ }
454
+
455
+ // 构建恢复数据:重置软删除字段
456
+ const restoreReqJson: IRequestModel = {
457
+ ...reqJson,
458
+ data: {
459
+ ...reqJson.data,
460
+ deleted_at: 0,
461
+ deleted_by: '',
462
+ },
463
+ };
464
+
465
+ const cfgModel: IRequestCfgModel = {
466
+ sqlTable: effectiveTable,
467
+ sqlSimpleName: KeysOfSimpleSQL.SIMPLE_UPDATE,
468
+ };
469
+
470
+ const ctx = await this.executeCrudByCfg(restoreReqJson, cfgModel);
471
+ const affected = ctx.getResModel().affected || { affectedRows: 0 };
472
+ return new CrudWriteResult({
473
+ affectedRows: affected.affectedRows,
474
+ insertId: affected.insertId,
475
+ rawContext: ctx,
476
+ });
477
+ }
478
+
479
+ /**
480
+ * 根据主键 ID 查询单条记录
481
+ *
482
+ * 等价于 `findUniqueOne({ condition: { id } })`,但更简洁。
483
+ * 使用 findUniqueOne 确保结果唯一性,如果查询到多条记录会抛出异常。
484
+ *
485
+ * @param id 主键值
486
+ * @param sqlTable 数据库表名,若构造实例时已设置全局 sqlTable 则可省略
487
+ * @returns CrudQueryOneResult 包含 row、found 和 getRawContext()
488
+ *
489
+ * @example
490
+ * // 根据 ID 查询单条
491
+ * const result = await quick.findOneById(1);
492
+ * if (result.found) {
493
+ * console.log(result.row);
494
+ * }
495
+ *
496
+ * // 指定表名
497
+ * const result = await quick.findOneById('ORD001', 't_order');
498
+ */
499
+ public async findOneById<T = Record<string, any>>(id: number | string, sqlTable?: string): Promise<CrudQueryOneResult<T>> {
500
+ return this.findUniqueOne<T>({ condition: { id } }, sqlTable);
501
+ }
502
+
503
+ /**
504
+ * 根据主键 ID 列表查询多条记录
505
+ *
506
+ * 等价于 `findList({ condition: { id: { $in: ids } } })`,但更简洁。
507
+ *
508
+ * @param ids 主键值数组
509
+ * @param sqlTable 数据库表名,若构造实例时已设置全局 sqlTable 则可省略
510
+ * @returns CrudQueryListResult 包含 rows、count 和 getRawContext()
511
+ *
512
+ * @example
513
+ * // 根据 ID 列表查询
514
+ * const result = await quick.findListByIds([1, 2, 3]);
515
+ * console.log(result.rows, result.count);
516
+ *
517
+ * // 指定表名
518
+ * const result = await quick.findListByIds(['ORD001', 'ORD002'], 't_order');
519
+ */
520
+ public async findListByIds<T = Record<string, any>>(ids: (number | string)[], sqlTable?: string): Promise<CrudQueryListResult<T>> {
521
+ return this.findList<T>({ condition: { id: { $in: ids } } }, sqlTable);
522
+ }
523
+
524
+ /**
525
+ * 执行自定义 SQL 语句(经 CrudPro 框架封装处理)
526
+ * 与 executeNativeSQL 不同,此方法执行的 SQL 会经过框架的参数绑定等安全处理
527
+ * @param executeSql 要执行的 SQL 语句,支持参数占位符
528
+ * @param args SQL 参数数组,与占位符一一对应
529
+ * @returns 返回未被包装的数据库原始结果(根据 resPicker 配置返回不同类型,无 {code, data, message} 包装层)
530
+ */
531
+ public async executeSQL(executeSql: string, args?: any[]): Promise<ExecuteSQLResult> {
532
+ const sqlCfgModel: ISqlCfgModel = {
533
+ executeSql: executeSql,
534
+ executeSqlArgs: args,
535
+ sqlDatabase: this.sqlDatabase,
536
+ sqlDbType: this.sqlDbType,
537
+ maxLimit: this.baseCfgModel.maxLimit || DEFAULT_MAX_LIMIT,
538
+ };
539
+ return await this.crudProFactory().executeSQL(sqlCfgModel);
540
+ }
541
+
542
+
543
+ /**
544
+ * 执行数据库的原生SQL语句,不做任何封装
545
+ *
546
+ * 返回值结构取决于 SQL 类型和数据库类型:
547
+ *
548
+ * **SELECT 查询**: 返回行数据数组
549
+ *
550
+ * **INSERT/UPDATE/DELETE**: 返回数据库驱动的原始结果
551
+ * - MySQL: `NativeSqlResultMySQL` - 包含 insertId、affectedRows、changedRows 等
552
+ * - PostgreSQL: 空数组(pg 驱动返回 rows 为空)
553
+ * - SQL Server: 空数组(mssql 驱动返回 recordset 为空)
554
+ *
555
+ * **注意**:
556
+ * - 使用 `?` 作为占位符,框架会自动转换为对应数据库的占位符
557
+ * - PostgreSQL/SQL Server 会将 `?` 转换为 `$1, $2, ...` 或 `@fatcms_ms1, @fatcms_ms2, ...`
558
+ *
559
+ * @typeParam T 行数据的类型,默认 Record<string, any>。
560
+ * 影响的是 ExecuteSQLRowsResult 和 ExecuteSQLSingleResult 中的行类型
561
+ *
562
+ * @param executeNativeSql 原生 SQL 语句,使用 `?` 作为参数占位符
563
+ * @param args 参数数组,与 SQL 中的 `?` 一一对应
564
+ * @returns 根据 SQL 类型返回对应结果(ExecuteSQLResult 联合类型)
565
+ *
566
+ * @example
567
+ * // SELECT 查询 - 使用自定义行类型,返回 ExecuteSQLRowsResult
568
+ * const rows = await crudProQuick.executeNativeSQL<{id: number, name: string}>(
569
+ * 'SELECT id, name FROM user WHERE age > ?',
570
+ * [18]
571
+ * );
572
+ * // rows 类型为 ExecuteSQLResult<{id: number, name: string}>
573
+ * // 实际运行时如果是 SELECT 查询,返回的是 ExecuteSQLRowsResult<{id: number, name: string}>
574
+ *
575
+ * // INSERT - MySQL
576
+ * const result = await crudProQuick.executeNativeSQL(
577
+ * 'INSERT INTO user (name, age) VALUES (?, ?)',
578
+ * ['张三', 20]
579
+ * );
580
+ * // result 类型为 ExecuteSQLResult,实际运行时返回 ExecuteSQLUpdateResult
581
+ */
582
+ public async executeNativeSQL<T = Record<string, any>>(executeNativeSql: string, args?: any[]): Promise<ExecuteSQLResult<T>> {
583
+ const sqlCfgModel: ISqlCfgModel = {
584
+ isNativeSQL: true,
585
+ executeSql: executeNativeSql,
586
+ executeSqlArgs: args,
587
+ sqlDatabase: this.sqlDatabase,
588
+ sqlDbType: this.sqlDbType,
589
+ maxLimit: this.baseCfgModel.maxLimit || DEFAULT_MAX_LIMIT,
590
+ };
591
+ return await this.crudProFactory().executeSQL(sqlCfgModel) as ExecuteSQLResult<T>;
592
+ }
593
+
594
+ }
@@ -1,28 +1,38 @@
1
1
  import { KeysOfSimpleSQL } from "@/libs/crud-pro/models/keys";
2
- import { IRequestModel } from "@/libs/crud-pro/interfaces";
3
- import { IRequestCfgModel2 } from "@/models/bizmodels";
4
- import { Context } from "@midwayjs/koa";
5
- import type { ICommonStandardColumns } from "@/models/StandardColumns";
2
+ import { IRequestModel, IVisitor } from "@/libs/crud-pro/interfaces";
3
+ import { IRequestCfgModel2, ICommonStandardColumns } from "./models";
4
+
5
+ /**
6
+ * 软删除需要的用户信息(最小子集)
7
+ */
8
+ interface ISoftDeleteUserInfo {
9
+ accountId: string;
10
+ }
11
+
12
+ /**
13
+ * 获取当前用户信息的函数类型
14
+ */
15
+ type GetCurrentUserFunc = () => ISoftDeleteUserInfo | null | undefined;
6
16
 
7
17
  /**
8
18
  * 软删除处理函数
9
- *
19
+ *
10
20
  * 当 cfgModel.enableSoftDelete === true 时,自动处理软删除逻辑:
11
- *
21
+ *
12
22
  * 1. INSERT 操作:自动设置 deleted_at = 0
13
23
  * 2. DELETE 操作:转为 UPDATE,设置 deleted_at = 时间戳, deleted_by = 当前用户
14
24
  * 3. QUERY 操作:自动添加 deleted_at = 0 条件
15
- *
25
+ *
16
26
  * @param oldSqlSimpleName 原始 SQL 类型
17
27
  * @param cfgModel 配置模型
18
28
  * @param params 请求参数(会被修改)
19
- * @param ctx 请求上下文(用于获取当前用户信息)
29
+ * @param visitor 获取当前用户信息的函数(用于软删除时记录删除人)
20
30
  */
21
31
  function fixSoftDelete(
22
32
  oldSqlSimpleName: KeysOfSimpleSQL,
23
33
  cfgModel: IRequestCfgModel2,
24
34
  params: IRequestModel,
25
- ctx?: Context
35
+ visitor?: IVisitor
26
36
  ): void {
27
37
 
28
38
  // 没有开启软删除,不做处理,直接物理删除
@@ -47,8 +57,6 @@ function fixSoftDelete(
47
57
  throw new Error('执行删除操作,必须指定删除条件');
48
58
  }
49
59
 
50
- // 获取当前用户信息
51
- const sessionInfo = ctx?.userSession?.getSessionInfo();
52
60
 
53
61
  // 在原有 data 对象上添加软删除字段
54
62
  if (!params.data) {
@@ -56,7 +64,7 @@ function fixSoftDelete(
56
64
  }
57
65
  const dataObj = params.data as ICommonStandardColumns;
58
66
  dataObj.deleted_at = Date.now();
59
- dataObj.deleted_by = sessionInfo?.accountId || '';
67
+ dataObj.deleted_by = visitor?.accountId || '';
60
68
 
61
69
  // 改为执行 UPDATE 操作
62
70
  cfgModel.sqlSimpleName = KeysOfSimpleSQL.SIMPLE_UPDATE;
@@ -77,4 +85,6 @@ function fixSoftDelete(
77
85
 
78
86
  export {
79
87
  fixSoftDelete,
80
- }
88
+ };
89
+
90
+ export type { ISoftDeleteUserInfo, GetCurrentUserFunc };