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.
- package/.qoder/skills/midway-fatcms/01-quick-start.md +231 -0
- package/.qoder/skills/midway-fatcms/02-crud-quick.md +337 -0
- package/.qoder/skills/midway-fatcms/03-crud-sharding.md +488 -0
- package/.qoder/skills/midway-fatcms/04-condition-operators.md +93 -0
- package/.qoder/skills/midway-fatcms/05-configuration.md +290 -0
- package/.qoder/skills/midway-fatcms/06-builtin-functions.md +241 -0
- package/.qoder/skills/midway-fatcms/07-examples.md +500 -0
- package/.qoder/skills/midway-fatcms/SKILL.md +96 -0
- package/README.md +9 -9
- package/dist/controller/base/BaseApiController.d.ts +1 -2
- package/dist/controller/base/BaseApiController.js +0 -4
- package/dist/controller/gateway/DocGatewayController.js +1 -1
- package/dist/controller/manage/FlowConfigManageApi.js +4 -2
- package/dist/controller/manage/SysConfigMangeApi.js +6 -1
- package/dist/controller/manage/UserAccountManageApi.js +7 -2
- package/dist/index.d.ts +2 -2
- package/dist/index.js +2 -2
- package/dist/libs/crud-pro/CrudPro.d.ts +23 -2
- package/dist/libs/crud-pro/CrudPro.js +53 -2
- package/dist/libs/crud-pro/interfaces.d.ts +82 -12
- package/dist/libs/crud-pro/models/CrudResult.d.ts +115 -0
- package/dist/libs/crud-pro/models/CrudResult.js +126 -0
- package/dist/libs/crud-pro/models/RequestModel.d.ts +2 -38
- package/dist/libs/crud-pro/models/RequestModel.js +2 -99
- package/dist/libs/crud-pro/services/CrudProExecuteSqlService.js +36 -2
- package/dist/libs/crud-pro/services/CrudProGenSqlCondition.js +8 -4
- package/dist/libs/crud-pro/services/CrudProTableMetaService.js +1 -2
- package/dist/libs/crud-pro/utils/OrderByUtils.d.ts +70 -0
- package/dist/libs/crud-pro/utils/OrderByUtils.js +158 -0
- package/dist/libs/crud-pro-quick/CrudProQuick.d.ts +295 -0
- package/dist/libs/crud-pro-quick/CrudProQuick.js +529 -0
- package/dist/libs/crud-pro-quick/fixSoftDelete.d.ts +30 -0
- package/dist/{service/curd → libs/crud-pro-quick}/fixSoftDelete.js +3 -6
- package/dist/libs/crud-pro-quick/index.d.ts +36 -0
- package/dist/libs/crud-pro-quick/index.js +49 -0
- package/dist/libs/crud-pro-quick/models.d.ts +33 -0
- package/dist/libs/crud-pro-quick/models.js +2 -0
- package/dist/libs/crud-sharding/ShardingConfig.d.ts +15 -2
- package/dist/libs/crud-sharding/ShardingConfig.js +2 -2
- package/dist/libs/crud-sharding/ShardingCrudPro.d.ts +119 -274
- package/dist/libs/crud-sharding/ShardingCrudPro.js +559 -379
- package/dist/libs/crud-sharding/ShardingMerger.d.ts +12 -20
- package/dist/libs/crud-sharding/ShardingMerger.js +36 -51
- package/dist/libs/crud-sharding/ShardingResult.d.ts +33 -0
- package/dist/libs/crud-sharding/ShardingResult.js +16 -0
- package/dist/libs/crud-sharding/ShardingRouter.d.ts +1 -0
- package/dist/libs/crud-sharding/ShardingRouter.js +25 -6
- package/dist/libs/crud-sharding/ShardingTableCreator.d.ts +21 -4
- package/dist/libs/crud-sharding/ShardingTableCreator.js +193 -59
- package/dist/libs/crud-sharding/ShardingUtils.d.ts +48 -0
- package/dist/libs/crud-sharding/ShardingUtils.js +122 -1
- package/dist/libs/crud-sharding/TIME_COLUMN_CLEAN_SPEC.md +488 -0
- package/dist/libs/crud-sharding/index.d.ts +4 -3
- package/dist/libs/crud-sharding/index.js +14 -2
- package/dist/models/bizmodels.d.ts +2 -6
- package/dist/service/SysAppService.d.ts +2 -2
- package/dist/service/SysAppService.js +16 -5
- package/dist/service/SysConfigService.d.ts +1 -1
- package/dist/service/SysConfigService.js +7 -2
- package/dist/service/SysDictDataService.js +14 -4
- package/dist/service/SysMenuService.js +7 -2
- package/dist/service/curd/CurdMixService.d.ts +6 -4
- package/dist/service/curd/CurdMixService.js +16 -2
- package/dist/service/curd/CurdProService.d.ts +43 -27
- package/dist/service/curd/CurdProService.js +32 -33
- package/dist/service/flow/FlowConfigService.js +7 -2
- package/dist/service/flow/FlowInstanceCrudService.js +22 -19
- package/package.json +2 -1
- package/src/controller/base/BaseApiController.ts +0 -5
- package/src/controller/gateway/DocGatewayController.ts +1 -1
- package/src/controller/manage/CrudStandardDesignApi.ts +4 -3
- package/src/controller/manage/FlowConfigManageApi.ts +4 -2
- package/src/controller/manage/SysConfigMangeApi.ts +6 -1
- package/src/controller/manage/UserAccountManageApi.ts +7 -2
- package/src/index.ts +2 -2
- package/src/libs/crud-pro/CrudPro.ts +62 -4
- package/src/libs/crud-pro/interfaces.ts +110 -15
- package/src/libs/crud-pro/models/CrudResult.ts +178 -0
- package/src/libs/crud-pro/models/RequestModel.ts +4 -110
- package/src/libs/crud-pro/services/CrudProExecuteSqlService.ts +41 -2
- package/src/libs/crud-pro/services/CrudProGenSqlCondition.ts +11 -7
- package/src/libs/crud-pro/services/CrudProTableMetaService.ts +1 -2
- package/src/libs/crud-pro/utils/OrderByUtils.ts +169 -0
- package/src/libs/crud-pro-quick/CrudProQuick.ts +594 -0
- package/src/{service/curd → libs/crud-pro-quick}/fixSoftDelete.ts +23 -13
- package/src/libs/crud-pro-quick/index.ts +52 -0
- package/src/libs/crud-pro-quick/models.ts +35 -0
- package/src/libs/crud-sharding/ShardingConfig.ts +18 -2
- package/src/libs/crud-sharding/ShardingCrudPro.ts +689 -440
- package/src/libs/crud-sharding/ShardingMerger.ts +47 -73
- package/src/libs/crud-sharding/ShardingResult.ts +29 -0
- package/src/libs/crud-sharding/ShardingRouter.ts +27 -6
- package/src/libs/crud-sharding/ShardingTableCreator.ts +214 -71
- package/src/libs/crud-sharding/ShardingUtils.ts +137 -0
- package/src/libs/crud-sharding/TIME_COLUMN_CLEAN_SPEC.md +488 -0
- package/src/libs/crud-sharding/index.ts +14 -3
- package/src/models/bizmodels.ts +4 -7
- package/src/service/SysAppService.ts +18 -7
- package/src/service/SysConfigService.ts +8 -3
- package/src/service/SysDictDataService.ts +14 -4
- package/src/service/SysMenuService.ts +7 -2
- package/src/service/crudstd/CrudStdService.ts +2 -2
- package/src/service/curd/CurdMixService.ts +26 -5
- package/src/service/curd/CurdProService.ts +58 -39
- package/src/service/flow/FlowConfigService.ts +7 -2
- package/src/service/flow/FlowInstanceCrudService.ts +23 -20
- package/dist/libs/crud-pro/README.md +0 -809
- package/dist/libs/crud-pro/README_FUNC.md +0 -193
- package/dist/libs/crud-sharding/ROUTING_LOGIC.md +0 -944
- package/dist/models/StandardColumns.d.ts +0 -71
- package/dist/models/StandardColumns.js +0 -28
- package/dist/service/curd/CrudProQuick.d.ts +0 -190
- package/dist/service/curd/CrudProQuick.js +0 -319
- package/dist/service/curd/README.md +0 -1001
- package/dist/service/curd/fixSoftDelete.d.ts +0 -20
- package/src/libs/crud-pro/README.md +0 -809
- package/src/libs/crud-pro/README_FUNC.md +0 -193
- package/src/libs/crud-sharding/ROUTING_LOGIC.md +0 -944
- package/src/models/StandardColumns.ts +0 -76
- package/src/service/curd/CrudProQuick.ts +0 -360
- package/src/service/curd/README.md +0 -1001
|
@@ -1,12 +1,17 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
3
|
exports.ShardingCrudPro = void 0;
|
|
4
|
+
const OrderByUtils_1 = require("../../libs/crud-pro/utils/OrderByUtils");
|
|
4
5
|
const keys_1 = require("../../libs/crud-pro/models/keys");
|
|
5
6
|
const ShardingConfig_1 = require("./ShardingConfig");
|
|
7
|
+
const fixSoftDelete_1 = require("../../libs/crud-pro-quick/fixSoftDelete");
|
|
6
8
|
const ShardingRouter_1 = require("./ShardingRouter");
|
|
7
9
|
const ShardingMerger_1 = require("./ShardingMerger");
|
|
8
10
|
const ShardingTableCreator_1 = require("./ShardingTableCreator");
|
|
9
11
|
const ShardingCountCache_1 = require("./ShardingCountCache");
|
|
12
|
+
const CrudResult_1 = require("../../libs/crud-pro/models/CrudResult");
|
|
13
|
+
const ShardingResult_1 = require("./ShardingResult");
|
|
14
|
+
const ShardingUtils_1 = require("./ShardingUtils");
|
|
10
15
|
/**
|
|
11
16
|
* 分表 CRUD 操作封装器
|
|
12
17
|
*
|
|
@@ -33,17 +38,24 @@ const ShardingCountCache_1 = require("./ShardingCountCache");
|
|
|
33
38
|
* await sharding.insert({ data: { order_id: '001', amount: 100, created_at: '2024-03-15' } });
|
|
34
39
|
*
|
|
35
40
|
* // 分页查询(自动合并多表结果)
|
|
36
|
-
* const result = await sharding.
|
|
41
|
+
* const result = await sharding.findPage({
|
|
37
42
|
* condition: { created_at: { $gte: '2024-01-01', $lte: '2024-03-31' } },
|
|
38
43
|
* pageNo: 1,
|
|
39
44
|
* pageSize: 10,
|
|
40
45
|
* });
|
|
41
46
|
*/
|
|
42
47
|
class ShardingCrudPro {
|
|
43
|
-
constructor(
|
|
48
|
+
constructor(crudProFactory, config) {
|
|
44
49
|
this.baseCfg = {};
|
|
45
|
-
this.
|
|
50
|
+
this.enableSoftDelete = false;
|
|
46
51
|
this.config = config;
|
|
52
|
+
// 兼容旧的 CrudPro 实例方式和新的工厂函数方式
|
|
53
|
+
if (typeof crudProFactory === 'function') {
|
|
54
|
+
this.crudProFactory = crudProFactory;
|
|
55
|
+
}
|
|
56
|
+
else {
|
|
57
|
+
throw new Error('[ShardingCrudPro] 请使用 CrudProFactory 工厂函数模式');
|
|
58
|
+
}
|
|
47
59
|
// 时间分表必须显式指定 timeColumn
|
|
48
60
|
if ([ShardingConfig_1.ShardingType.YEAR, ShardingConfig_1.ShardingType.MONTH, ShardingConfig_1.ShardingType.DAY].includes(config.type)) {
|
|
49
61
|
if (!config.timeColumn) {
|
|
@@ -52,7 +64,7 @@ class ShardingCrudPro {
|
|
|
52
64
|
}
|
|
53
65
|
this.router = new ShardingRouter_1.ShardingRouter();
|
|
54
66
|
this.merger = new ShardingMerger_1.ShardingMerger();
|
|
55
|
-
this.tableCreator = new ShardingTableCreator_1.ShardingTableCreator(
|
|
67
|
+
this.tableCreator = new ShardingTableCreator_1.ShardingTableCreator(this.crudProFactory, config);
|
|
56
68
|
// 初始化 COUNT 缓存(如果配置了)
|
|
57
69
|
if (config.countCache) {
|
|
58
70
|
const countCache = new ShardingCountCache_1.ShardingCountCache(config.type, config.baseTable, config.countCache.ttlSeconds, config.countCache.maxSize);
|
|
@@ -60,101 +72,44 @@ class ShardingCrudPro {
|
|
|
60
72
|
}
|
|
61
73
|
}
|
|
62
74
|
// ============ 配置方法 ============
|
|
63
|
-
/**
|
|
64
|
-
* 设置基础配置(会应用到所有操作)
|
|
65
|
-
*
|
|
66
|
-
* @param cfg 配置项,如 sqlDatabase、sqlDbType 等
|
|
67
|
-
* @returns this,支持链式调用
|
|
68
|
-
*
|
|
69
|
-
* @example
|
|
70
|
-
* sharding.setBaseCfg({
|
|
71
|
-
* sqlDatabase: 'mydb',
|
|
72
|
-
* sqlDbType: SqlDbType.mysql,
|
|
73
|
-
* });
|
|
74
|
-
*/
|
|
75
75
|
setBaseCfg(cfg) {
|
|
76
76
|
this.baseCfg = { ...this.baseCfg, ...cfg };
|
|
77
77
|
return this;
|
|
78
78
|
}
|
|
79
|
-
/**
|
|
80
|
-
* 获取分表配置
|
|
81
|
-
*/
|
|
82
79
|
getConfig() {
|
|
83
80
|
return this.config;
|
|
84
81
|
}
|
|
85
|
-
// ============ 写操作(单表路由) ============
|
|
86
82
|
/**
|
|
87
|
-
*
|
|
88
|
-
*
|
|
89
|
-
* 根据分表规则自动路由到目标分表。
|
|
90
|
-
* 对于时间分表,需要确保 data 中包含时间字段。
|
|
91
|
-
* 对于哈希/范围分表,需要确保 data 中包含分表字段。
|
|
92
|
-
*
|
|
93
|
-
* 如果目标分表不存在且配置了 autoCreateTable,会自动创建分表。
|
|
94
|
-
*
|
|
95
|
-
* @param reqJson 请求参数,data 为要插入的数据
|
|
96
|
-
* @returns 执行上下文
|
|
97
|
-
*
|
|
98
|
-
* @example
|
|
99
|
-
* await sharding.insert({
|
|
100
|
-
* data: {
|
|
101
|
-
* order_id: 'ORD001',
|
|
102
|
-
* amount: 100,
|
|
103
|
-
* created_at: '2024-03-15 10:00:00',
|
|
104
|
-
* },
|
|
105
|
-
* });
|
|
83
|
+
* 设置是否启用软删除
|
|
84
|
+
* @param enable 是否启用软删除
|
|
106
85
|
*/
|
|
86
|
+
setEnableSoftDelete(enable) {
|
|
87
|
+
this.enableSoftDelete = enable;
|
|
88
|
+
return this;
|
|
89
|
+
}
|
|
90
|
+
// ============ 写操作(单表路由) ============
|
|
107
91
|
async insert(reqJson) {
|
|
92
|
+
// 时间分表校验:data 必须包含 timeColumn
|
|
93
|
+
this.validateTimeColumnForData(reqJson, 'insert');
|
|
108
94
|
const targetTable = this.resolveSingleTable(reqJson, 'insert');
|
|
109
95
|
// 确保分表存在(根据配置决定是否自动创建)
|
|
110
96
|
await this.createShardingTableIfNeeded(targetTable);
|
|
111
|
-
|
|
97
|
+
const ctx = await this.executeOnTable(targetTable, reqJson, keys_1.KeysOfSimpleSQL.SIMPLE_INSERT);
|
|
98
|
+
const affected = ctx.getResModel().affected || { affectedRows: 0 };
|
|
99
|
+
return new CrudResult_1.CrudWriteResult({
|
|
100
|
+
affectedRows: affected.affectedRows,
|
|
101
|
+
insertId: affected.insertId,
|
|
102
|
+
rawContext: ctx,
|
|
103
|
+
});
|
|
112
104
|
}
|
|
113
|
-
/**
|
|
114
|
-
* 批量插入数据(支持跨分表)
|
|
115
|
-
*
|
|
116
|
-
* 自动将数据按分表分组,并行插入到对应的分表。
|
|
117
|
-
*
|
|
118
|
-
* @param reqJson 请求参数,data 为要插入的数据数组
|
|
119
|
-
* @returns 批量插入结果
|
|
120
|
-
*
|
|
121
|
-
* 执行流程:
|
|
122
|
-
* 1. 遍历所有数据,根据分表字段计算目标分表
|
|
123
|
-
* 2. 将数据按分表分组
|
|
124
|
-
* 3. 并行执行各分表的批量插入
|
|
125
|
-
* 4. 汇总结果返回
|
|
126
|
-
*
|
|
127
|
-
* @example
|
|
128
|
-
* // 数据分布在不同月份的分表
|
|
129
|
-
* const result = await sharding.batchInsert({
|
|
130
|
-
* data: [
|
|
131
|
-
* { order_id: '001', amount: 100, created_at: '2024-01-15' }, // -> t_order_202401
|
|
132
|
-
* { order_id: '002', amount: 200, created_at: '2024-01-20' }, // -> t_order_202401
|
|
133
|
-
* { order_id: '003', amount: 150, created_at: '2024-02-10' }, // -> t_order_202402
|
|
134
|
-
* { order_id: '004', amount: 300, created_at: '2024-03-05' }, // -> t_order_202403
|
|
135
|
-
* ],
|
|
136
|
-
* });
|
|
137
|
-
*
|
|
138
|
-
* console.log(result.totalAffected); // 4
|
|
139
|
-
* console.log(result.tableCount); // 3
|
|
140
|
-
* console.log(result.tableResults);
|
|
141
|
-
* // [
|
|
142
|
-
* // { table: 't_order_202401', affected: 2, rowCount: 2 },
|
|
143
|
-
* // { table: 't_order_202402', affected: 1, rowCount: 1 },
|
|
144
|
-
* // { table: 't_order_202403', affected: 1, rowCount: 1 },
|
|
145
|
-
* // ]
|
|
146
|
-
*/
|
|
147
105
|
async batchInsert(reqJson) {
|
|
106
|
+
var _a, _b;
|
|
148
107
|
const dataArray = reqJson.data;
|
|
149
108
|
if (!Array.isArray(dataArray) || dataArray.length === 0) {
|
|
150
|
-
|
|
151
|
-
totalAffected: 0,
|
|
152
|
-
tableResults: [],
|
|
153
|
-
tableCount: 0,
|
|
154
|
-
success: true,
|
|
155
|
-
errors: [],
|
|
156
|
-
};
|
|
109
|
+
throw new Error('[ShardingCrudPro] batchInsert requires non-empty data array');
|
|
157
110
|
}
|
|
111
|
+
// 时间分表校验:每条 data 必须包含 timeColumn
|
|
112
|
+
this.validateTimeColumnForBatchData(dataArray, 'batchInsert');
|
|
158
113
|
// 按分表分组
|
|
159
114
|
const groupedData = this.batchInsertGroupDataByTable(dataArray);
|
|
160
115
|
// 确保所有目标分表存在(根据配置决定是否自动创建)
|
|
@@ -162,27 +117,31 @@ class ShardingCrudPro {
|
|
|
162
117
|
for (let i = 0; i < tableNames.length; i++) {
|
|
163
118
|
await this.createShardingTableIfNeeded(tableNames[i]);
|
|
164
119
|
}
|
|
165
|
-
//
|
|
166
|
-
const
|
|
120
|
+
// 串行执行各分表的批量插入
|
|
121
|
+
const results = [];
|
|
122
|
+
let lastContext = null;
|
|
123
|
+
for (const [table, items] of groupedData.entries()) {
|
|
167
124
|
try {
|
|
168
125
|
const ctx = await this.executeOnTable(table, { data: items }, keys_1.KeysOfSimpleSQL.SIMPLE_BATCH_INSERT);
|
|
169
|
-
|
|
126
|
+
lastContext = ctx;
|
|
127
|
+
results.push({
|
|
170
128
|
table,
|
|
171
|
-
affected: ctx.getResModelItem('affected') || items.length,
|
|
129
|
+
affected: ((_a = ctx.getResModelItem('affected')) === null || _a === void 0 ? void 0 : _a.affectedRows) || items.length,
|
|
172
130
|
rowCount: items.length,
|
|
173
131
|
error: null,
|
|
174
|
-
|
|
132
|
+
context: ctx,
|
|
133
|
+
});
|
|
175
134
|
}
|
|
176
135
|
catch (e) {
|
|
177
|
-
|
|
136
|
+
results.push({
|
|
178
137
|
table,
|
|
179
138
|
affected: 0,
|
|
180
139
|
rowCount: items.length,
|
|
181
140
|
error: e,
|
|
182
|
-
|
|
141
|
+
context: null,
|
|
142
|
+
});
|
|
183
143
|
}
|
|
184
|
-
}
|
|
185
|
-
const results = await Promise.all(insertPromises);
|
|
144
|
+
}
|
|
186
145
|
// 汇总结果
|
|
187
146
|
const tableResults = results.map(r => ({
|
|
188
147
|
table: r.table,
|
|
@@ -193,223 +152,312 @@ class ShardingCrudPro {
|
|
|
193
152
|
.filter(r => r.error !== null)
|
|
194
153
|
.map(r => ({ table: r.table, error: r.error }));
|
|
195
154
|
const totalAffected = results.reduce((sum, r) => sum + r.affected, 0);
|
|
196
|
-
|
|
155
|
+
// Use last successful context, or create a minimal one
|
|
156
|
+
const finalContext = lastContext || ((_b = results.find(r => r.context)) === null || _b === void 0 ? void 0 : _b.context);
|
|
157
|
+
if (!finalContext) {
|
|
158
|
+
throw new Error('[ShardingCrudPro] batchInsert failed - no successful inserts');
|
|
159
|
+
}
|
|
160
|
+
return new ShardingResult_1.ShardingBatchInsertResult({
|
|
197
161
|
totalAffected,
|
|
198
162
|
tableResults,
|
|
199
163
|
tableCount: groupedData.size,
|
|
200
164
|
success: errors.length === 0,
|
|
201
165
|
errors,
|
|
202
|
-
|
|
166
|
+
lastContext: finalContext,
|
|
167
|
+
});
|
|
203
168
|
}
|
|
204
|
-
/**
|
|
205
|
-
* 更新数据
|
|
206
|
-
*
|
|
207
|
-
* 根据条件中的分表字段自动路由到目标分表。
|
|
208
|
-
*
|
|
209
|
-
* @param reqJson 请求参数,condition 为更新条件,data 为更新数据
|
|
210
|
-
* @returns 执行上下文
|
|
211
|
-
*
|
|
212
|
-
* @example
|
|
213
|
-
* await sharding.update({
|
|
214
|
-
* condition: { order_id: 'ORD001', created_at: '2024-03-15' },
|
|
215
|
-
* data: { amount: 200 },
|
|
216
|
-
* });
|
|
217
|
-
*/
|
|
218
169
|
async update(reqJson) {
|
|
170
|
+
// 时间分表校验:condition 必须包含路由字段
|
|
171
|
+
this.validateRoutingFieldForCondition(reqJson, 'update');
|
|
219
172
|
const targetTable = this.resolveSingleTable(reqJson, 'update');
|
|
220
|
-
|
|
173
|
+
// 清理 condition 中的时间字段(如果能确定单一分表)
|
|
174
|
+
const cleanedReqJson = this.cleanTimeColumnForSingleTableQuery(reqJson);
|
|
175
|
+
const ctx = await this.executeOnTable(targetTable, cleanedReqJson, keys_1.KeysOfSimpleSQL.SIMPLE_UPDATE);
|
|
176
|
+
const affected = ctx.getResModel().affected || { affectedRows: 0 };
|
|
177
|
+
return new CrudResult_1.CrudWriteResult({
|
|
178
|
+
affectedRows: affected.affectedRows,
|
|
179
|
+
insertId: affected.insertId,
|
|
180
|
+
rawContext: ctx,
|
|
181
|
+
});
|
|
221
182
|
}
|
|
222
|
-
/**
|
|
223
|
-
* 删除数据
|
|
224
|
-
*
|
|
225
|
-
* 根据条件中的分表字段自动路由到目标分表。
|
|
226
|
-
*
|
|
227
|
-
* @param reqJson 请求参数,condition 为删除条件
|
|
228
|
-
* @returns 执行上下文
|
|
229
|
-
*/
|
|
230
183
|
async delete(reqJson) {
|
|
184
|
+
// 时间分表校验:condition 必须包含路由字段
|
|
185
|
+
this.validateRoutingFieldForCondition(reqJson, 'delete');
|
|
231
186
|
const targetTable = this.resolveSingleTable(reqJson, 'delete');
|
|
232
|
-
|
|
187
|
+
// 清理 condition 中的时间字段(如果能确定单一分表)
|
|
188
|
+
const cleanedReqJson = this.cleanTimeColumnForSingleTableQuery(reqJson);
|
|
189
|
+
const ctx = await this.executeOnTable(targetTable, cleanedReqJson, keys_1.KeysOfSimpleSQL.SIMPLE_DELETE);
|
|
190
|
+
const affected = ctx.getResModel().affected || { affectedRows: 0 };
|
|
191
|
+
return new CrudResult_1.CrudWriteResult({
|
|
192
|
+
affectedRows: affected.affectedRows,
|
|
193
|
+
insertId: affected.insertId,
|
|
194
|
+
rawContext: ctx,
|
|
195
|
+
});
|
|
233
196
|
}
|
|
234
197
|
/**
|
|
235
|
-
*
|
|
198
|
+
* 恢复软删除的记录
|
|
199
|
+
* 将 deleted_at 字段重置为 0,deleted_by 重置为空字符串
|
|
236
200
|
*
|
|
237
|
-
*
|
|
201
|
+
* @param reqJson 请求参数,通过 condition 指定要恢复的记录
|
|
202
|
+
* @returns CrudWriteResult 包含 affectedRows 和 getRawContext()
|
|
238
203
|
*
|
|
239
|
-
* @
|
|
240
|
-
*
|
|
204
|
+
* @example
|
|
205
|
+
* // 恢复指定 ID 的记录
|
|
206
|
+
* await sharding.restore({ condition: { id: 1 } });
|
|
207
|
+
*
|
|
208
|
+
* // 恢复多条记录(使用 $in 操作符)
|
|
209
|
+
* await sharding.restore({ condition: { id: { $in: [1, 2, 3] } } });
|
|
210
|
+
*
|
|
211
|
+
* // 按条件批量恢复记录
|
|
212
|
+
* await sharding.restore({ condition: { status: 'deleted' } });
|
|
241
213
|
*/
|
|
214
|
+
async restore(reqJson) {
|
|
215
|
+
// 时间分表校验:condition 必须包含路由字段
|
|
216
|
+
this.validateRoutingFieldForCondition(reqJson, 'restore');
|
|
217
|
+
const targetTable = this.resolveSingleTable(reqJson, 'restore');
|
|
218
|
+
if (!reqJson.condition || Object.keys(reqJson.condition).length === 0) {
|
|
219
|
+
throw new Error('[ShardingCrudPro] restore 操作必须指定恢复条件');
|
|
220
|
+
}
|
|
221
|
+
// 清理 condition 中的时间字段(如果能确定单一分表)
|
|
222
|
+
const cleanedReqJson = this.cleanTimeColumnForSingleTableQuery(reqJson);
|
|
223
|
+
// 构建恢复数据:重置软删除字段
|
|
224
|
+
const restoreReqJson = {
|
|
225
|
+
...cleanedReqJson,
|
|
226
|
+
data: {
|
|
227
|
+
...cleanedReqJson.data,
|
|
228
|
+
deleted_at: 0,
|
|
229
|
+
deleted_by: '',
|
|
230
|
+
},
|
|
231
|
+
};
|
|
232
|
+
const ctx = await this.executeOnTable(targetTable, restoreReqJson, keys_1.KeysOfSimpleSQL.SIMPLE_UPDATE);
|
|
233
|
+
const affected = ctx.getResModel().affected || { affectedRows: 0 };
|
|
234
|
+
return new CrudResult_1.CrudWriteResult({
|
|
235
|
+
affectedRows: affected.affectedRows,
|
|
236
|
+
insertId: affected.insertId,
|
|
237
|
+
rawContext: ctx,
|
|
238
|
+
});
|
|
239
|
+
}
|
|
242
240
|
async insertOrUpdate(reqJson) {
|
|
241
|
+
var _a;
|
|
242
|
+
// 时间分表校验:data 必须包含 timeColumn,condition 必须包含路由字段
|
|
243
|
+
this.validateTimeColumnForData(reqJson, 'insertOrUpdate');
|
|
244
|
+
this.validateRoutingFieldForCondition(reqJson, 'insertOrUpdate');
|
|
243
245
|
const targetTable = this.resolveSingleTable(reqJson, 'update'); // 使用 condition 路由
|
|
244
|
-
|
|
246
|
+
const ctx = await this.executeOnTable(targetTable, reqJson, keys_1.KeysOfSimpleSQL.SIMPLE_INSERT_OR_UPDATE);
|
|
247
|
+
const resModel = ctx.getResModel();
|
|
248
|
+
return new CrudResult_1.CrudUpsertResult({
|
|
249
|
+
affected: resModel.affected,
|
|
250
|
+
insertAffected: resModel.insert_affected,
|
|
251
|
+
updateAffected: resModel.update_affected,
|
|
252
|
+
isExist: (_a = resModel.is_exist) !== null && _a !== void 0 ? _a : false,
|
|
253
|
+
rawContext: ctx,
|
|
254
|
+
});
|
|
245
255
|
}
|
|
246
|
-
/**
|
|
247
|
-
* 插入或更新(ON DUPLICATE KEY UPDATE)
|
|
248
|
-
*
|
|
249
|
-
* 路由逻辑:根据 condition 路由(先查询是否存在)
|
|
250
|
-
*
|
|
251
|
-
* @param reqJson 请求参数
|
|
252
|
-
* @returns 执行上下文
|
|
253
|
-
*/
|
|
254
256
|
async insertOnDuplicateUpdate(reqJson) {
|
|
257
|
+
// 时间分表校验:data 必须包含 timeColumn,condition 必须包含路由字段
|
|
258
|
+
this.validateTimeColumnForData(reqJson, 'insertOnDuplicateUpdate');
|
|
259
|
+
this.validateRoutingFieldForCondition(reqJson, 'insertOnDuplicateUpdate');
|
|
255
260
|
const targetTable = this.resolveSingleTable(reqJson, 'update'); // 使用 condition 路由
|
|
256
|
-
|
|
261
|
+
const ctx = await this.executeOnTable(targetTable, reqJson, keys_1.KeysOfSimpleSQL.SIMPLE_INSERT_ON_DUPLICATE_UPDATE);
|
|
262
|
+
const affected = ctx.getResModel().affected || { affectedRows: 0 };
|
|
263
|
+
return new CrudResult_1.CrudWriteResult({
|
|
264
|
+
affectedRows: affected.affectedRows,
|
|
265
|
+
insertId: affected.insertId,
|
|
266
|
+
rawContext: ctx,
|
|
267
|
+
});
|
|
257
268
|
}
|
|
258
269
|
// ============ 查询操作(可能多表) ============
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
* 否则按顺序查询各分表,返回第一条匹配记录。
|
|
264
|
-
*
|
|
265
|
-
* @param reqJson 请求参数,condition 为查询条件
|
|
266
|
-
* @returns 单条记录,未找到返回 null
|
|
267
|
-
*
|
|
268
|
-
* @example
|
|
269
|
-
* const order = await sharding.queryOne({
|
|
270
|
-
* condition: { order_id: 'ORD001' },
|
|
271
|
-
* });
|
|
272
|
-
*/
|
|
273
|
-
async queryOne(reqJson) {
|
|
274
|
-
const targetTables = await this.resolveQueryTables(reqJson);
|
|
270
|
+
async findOne(reqJson) {
|
|
271
|
+
// 清理 condition 中的时间字段(如果能确定单一分表)
|
|
272
|
+
const cleanedReqJson = this.cleanTimeColumnForSingleTableQuery(reqJson);
|
|
273
|
+
const targetTables = await this.resolveFindTables(reqJson);
|
|
275
274
|
if (targetTables.length === 0) {
|
|
276
|
-
|
|
275
|
+
// Return a result with null row - we need a context for this
|
|
276
|
+
// Since there are no tables to query, we throw an error for now
|
|
277
|
+
throw new Error('[ShardingCrudPro] findOne: no matching tables found');
|
|
277
278
|
}
|
|
278
279
|
// 多表:顺序查询,找到即返回
|
|
280
|
+
let lastCtx = null;
|
|
279
281
|
for (const table of targetTables) {
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
282
|
+
try {
|
|
283
|
+
const ctx = await this.executeOnTable(table, cleanedReqJson, keys_1.KeysOfSimpleSQL.SIMPLE_QUERY_ONE);
|
|
284
|
+
lastCtx = ctx;
|
|
285
|
+
const row = ctx.getOneObj();
|
|
286
|
+
if (row) {
|
|
287
|
+
return new CrudResult_1.CrudQueryOneResult({ row: row, rawContext: ctx, debugInfo: this.buildDebugInfo(table, reqJson.condition) });
|
|
288
|
+
}
|
|
289
|
+
}
|
|
290
|
+
catch (e) {
|
|
291
|
+
// 表不存在时跳过,继续查下一张表
|
|
292
|
+
}
|
|
283
293
|
}
|
|
284
|
-
|
|
294
|
+
// 未找到,使用最后一次查询的 ctx
|
|
295
|
+
return new CrudResult_1.CrudQueryOneResult({ row: null, rawContext: lastCtx, debugInfo: this.buildDebugInfo(targetTables[0], reqJson.condition) });
|
|
285
296
|
}
|
|
286
297
|
/**
|
|
287
|
-
*
|
|
298
|
+
* 查询唯一单条记录(期望结果为 0 条或 1 条)
|
|
288
299
|
*
|
|
289
|
-
*
|
|
300
|
+
* 与 findOne 不同,此方法会校验查询结果的唯一性:
|
|
301
|
+
* - 如果查到 0 条:返回 row = null
|
|
302
|
+
* - 如果查到 1 条:正常返回
|
|
303
|
+
* - 如果查到多条:抛出异常,包含详细的定位信息(含分表名列表)
|
|
290
304
|
*
|
|
291
|
-
*
|
|
292
|
-
* -
|
|
293
|
-
* -
|
|
305
|
+
* 分表场景的特殊处理:
|
|
306
|
+
* - 单分表:直接查询并校验唯一性
|
|
307
|
+
* - 多分表:顺序查询各分表,累计找到的数量,超过 1 条立即抛异常
|
|
294
308
|
*
|
|
295
309
|
* @param reqJson 请求参数
|
|
296
|
-
* @returns
|
|
310
|
+
* @returns CrudQueryOneResult 包含 row、found 和 getRawContext()
|
|
311
|
+
* @throws Error 如果查询到多条记录
|
|
297
312
|
*
|
|
298
313
|
* @example
|
|
299
|
-
*
|
|
300
|
-
*
|
|
301
|
-
*
|
|
302
|
-
*
|
|
314
|
+
* // 根据唯一索引查询单条
|
|
315
|
+
* const result = await sharding.findUniqueOne({ condition: { order_id: 'ORD001' } });
|
|
316
|
+
* if (result.found) {
|
|
317
|
+
* console.log(result.row);
|
|
318
|
+
* }
|
|
303
319
|
*/
|
|
304
|
-
async
|
|
305
|
-
|
|
320
|
+
async findUniqueOne(reqJson) {
|
|
321
|
+
// 清理 condition 中的时间字段(如果能确定单一分表)
|
|
322
|
+
const cleanedReqJson = this.cleanTimeColumnForSingleTableQuery(reqJson);
|
|
323
|
+
const targetTables = await this.resolveFindTables(reqJson);
|
|
324
|
+
if (targetTables.length === 0) {
|
|
325
|
+
// 无匹配表,返回空结果
|
|
326
|
+
return new CrudResult_1.CrudQueryOneResult({ row: null, rawContext: null, debugInfo: this.buildDebugInfo(undefined, reqJson.condition) });
|
|
327
|
+
}
|
|
328
|
+
// 统一逻辑:每个表查 maxLimit: 2,收集所有结果
|
|
329
|
+
const allRows = [];
|
|
330
|
+
const foundTables = [];
|
|
331
|
+
let firstCtx = null;
|
|
332
|
+
for (const table of targetTables) {
|
|
333
|
+
try {
|
|
334
|
+
const ctx = await this.executeOnTable(table, cleanedReqJson, keys_1.KeysOfSimpleSQL.SIMPLE_QUERY, { maxLimit: 2 });
|
|
335
|
+
if (!firstCtx) {
|
|
336
|
+
firstCtx = ctx;
|
|
337
|
+
}
|
|
338
|
+
const rows = ctx.getResRows();
|
|
339
|
+
if (rows.length > 0) {
|
|
340
|
+
allRows.push(...rows);
|
|
341
|
+
foundTables.push(table);
|
|
342
|
+
// 超过 1 条,立即抛异常,不再查询后续分表
|
|
343
|
+
if (allRows.length > 1) {
|
|
344
|
+
throw new Error(this.formatUniqueError(allRows.length, foundTables, reqJson.condition, foundTables.length > 1));
|
|
345
|
+
}
|
|
346
|
+
}
|
|
347
|
+
}
|
|
348
|
+
catch (e) {
|
|
349
|
+
// 非 formatUniqueError 的异常(如表不存在),继续查询下一张表
|
|
350
|
+
if (e instanceof Error && e.message.startsWith('[ShardingCrudPro] findUniqueOne')) {
|
|
351
|
+
throw e;
|
|
352
|
+
}
|
|
353
|
+
}
|
|
354
|
+
}
|
|
355
|
+
// 返回结果
|
|
356
|
+
return new CrudResult_1.CrudQueryOneResult({
|
|
357
|
+
row: allRows[0] || null,
|
|
358
|
+
rawContext: firstCtx,
|
|
359
|
+
debugInfo: this.buildDebugInfo(foundTables[0] || targetTables[0], reqJson.condition),
|
|
360
|
+
});
|
|
361
|
+
}
|
|
362
|
+
async findList(reqJson) {
|
|
363
|
+
// 清理 condition 中的时间字段(粒度字符串自动转范围、有主键时清理)
|
|
364
|
+
const cleanedReqJson = this.cleanTimeColumnForSingleTableQuery(reqJson);
|
|
365
|
+
const targetTables = await this.resolveFindTables(reqJson);
|
|
306
366
|
if (targetTables.length === 0) {
|
|
307
|
-
return []
|
|
367
|
+
return new CrudResult_1.CrudQueryListResult({ rows: [], rawContext: null });
|
|
308
368
|
}
|
|
309
369
|
if (targetTables.length === 1) {
|
|
310
|
-
const ctx = await this.executeOnTable(targetTables[0],
|
|
311
|
-
|
|
370
|
+
const ctx = await this.executeOnTable(targetTables[0], cleanedReqJson, keys_1.KeysOfSimpleSQL.SIMPLE_QUERY);
|
|
371
|
+
const rows = ctx.getResRows();
|
|
372
|
+
return new CrudResult_1.CrudQueryListResult({ rows, rawContext: ctx });
|
|
312
373
|
}
|
|
313
374
|
// 多表查询时,需要参数校验
|
|
314
|
-
this.
|
|
375
|
+
this.validateFindOrderBy(reqJson);
|
|
315
376
|
// 根据排序方向确定表顺序:DESC 新→旧,ASC 旧→新
|
|
316
377
|
const tablesForMerge = this.sortTablesForOrderBy(targetTables, reqJson);
|
|
317
378
|
// 多表查询合并
|
|
318
|
-
|
|
379
|
+
const mergeResult = await this.merger.mergeQuery(this.crudProFactory(), tablesForMerge, cleanedReqJson, this.buildCfg(keys_1.KeysOfSimpleSQL.SIMPLE_QUERY));
|
|
380
|
+
return new CrudResult_1.CrudQueryListResult({ rows: mergeResult.rows, rawContext: mergeResult.lastCtx });
|
|
319
381
|
}
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
* 1. 顺序累计查询各分表
|
|
325
|
-
* 2. 截取目标数据(无需排序)
|
|
326
|
-
*
|
|
327
|
-
* 使用约束:
|
|
328
|
-
* - 必须传 orderBy 参数
|
|
329
|
-
* - orderBy 必须为 timeColumn DESC 或 timeColumn ASC(如 'created_at DESC' / 'created_at ASC')
|
|
330
|
-
*
|
|
331
|
-
* @param reqJson 请求参数,包含 pageNo、pageSize 和 orderBy
|
|
332
|
-
* @returns 分页结果,包含 rows 和 total_count
|
|
333
|
-
*
|
|
334
|
-
* @example
|
|
335
|
-
* const result = await sharding.queryPage({
|
|
336
|
-
* condition: { created_at: { $gte: '2024-01-01', $lte: '2024-03-31' } },
|
|
337
|
-
* pageNo: 1,
|
|
338
|
-
* pageSize: 10,
|
|
339
|
-
* orderBy: 'created_at DESC', // 或 'created_at ASC'
|
|
340
|
-
* });
|
|
341
|
-
* console.log(result.rows, result.total_count);
|
|
342
|
-
*/
|
|
343
|
-
async queryPage(reqJson) {
|
|
344
|
-
const targetTables = await this.resolveQueryTables(reqJson);
|
|
382
|
+
async findPage(reqJson) {
|
|
383
|
+
// 清理 condition 中的时间字段(粒度字符串自动转范围、有主键时清理)
|
|
384
|
+
const cleanedReqJson = this.cleanTimeColumnForSingleTableQuery(reqJson);
|
|
385
|
+
const targetTables = await this.resolveFindTables(reqJson);
|
|
345
386
|
if (targetTables.length === 0) {
|
|
346
|
-
|
|
387
|
+
throw new Error('[ShardingCrudPro] findPage: no matching tables found');
|
|
347
388
|
}
|
|
348
389
|
if (targetTables.length === 1) {
|
|
349
|
-
const ctx = await this.executeOnTable(targetTables[0],
|
|
350
|
-
|
|
390
|
+
const ctx = await this.executeOnTable(targetTables[0], cleanedReqJson, keys_1.KeysOfSimpleSQL.SIMPLE_QUERY_PAGE);
|
|
391
|
+
const pageResult = ctx.getResModelForQueryPage();
|
|
392
|
+
return new CrudResult_1.CrudQueryPageResult({
|
|
393
|
+
rows: pageResult.rows,
|
|
394
|
+
totalCount: pageResult.total_count,
|
|
395
|
+
rawContext: ctx,
|
|
396
|
+
});
|
|
351
397
|
}
|
|
352
398
|
// 多表查询时,需要参数校验
|
|
353
|
-
this.
|
|
399
|
+
this.validateFindOrderBy(reqJson);
|
|
354
400
|
// 根据排序方向确定表顺序:DESC 新→旧,ASC 旧→新
|
|
355
401
|
const tablesForMerge = this.sortTablesForOrderBy(targetTables, reqJson);
|
|
356
402
|
// 多表分页查询:顺序累计
|
|
357
|
-
|
|
403
|
+
const pageResult = await this.merger.mergePageQuery(this.crudProFactory(), tablesForMerge, cleanedReqJson, this.buildCfg(keys_1.KeysOfSimpleSQL.SIMPLE_QUERY_PAGE));
|
|
404
|
+
return new CrudResult_1.CrudQueryPageResult({
|
|
405
|
+
rows: pageResult.rows,
|
|
406
|
+
totalCount: pageResult.total_count,
|
|
407
|
+
rawContext: pageResult.lastCtx,
|
|
408
|
+
});
|
|
358
409
|
}
|
|
359
|
-
|
|
360
|
-
|
|
361
|
-
|
|
362
|
-
|
|
363
|
-
|
|
364
|
-
* @param reqJson 请求参数
|
|
365
|
-
* @returns 记录总数
|
|
366
|
-
*/
|
|
367
|
-
async queryCount(reqJson) {
|
|
368
|
-
const targetTables = await this.resolveQueryTables(reqJson);
|
|
410
|
+
async findCount(reqJson) {
|
|
411
|
+
var _a;
|
|
412
|
+
// 清理 condition 中的时间字段(粒度字符串自动转范围、有主键时清理)
|
|
413
|
+
const cleanedReqJson = this.cleanTimeColumnForSingleTableQuery(reqJson);
|
|
414
|
+
const targetTables = await this.resolveFindTables(reqJson);
|
|
369
415
|
if (targetTables.length === 0) {
|
|
370
|
-
|
|
416
|
+
throw new Error('[ShardingCrudPro] findCount: no matching tables found');
|
|
371
417
|
}
|
|
372
418
|
if (targetTables.length === 1) {
|
|
373
|
-
const ctx = await this.executeOnTable(targetTables[0],
|
|
374
|
-
|
|
419
|
+
const ctx = await this.executeOnTable(targetTables[0], cleanedReqJson, keys_1.KeysOfSimpleSQL.SIMPLE_QUERY_COUNT);
|
|
420
|
+
const count = ctx.getResModelItem('total_count') || 0;
|
|
421
|
+
return new CrudResult_1.CrudCountResult({ count, rawContext: ctx });
|
|
422
|
+
}
|
|
423
|
+
// 多表统计:串行查询后求和
|
|
424
|
+
const countResults = [];
|
|
425
|
+
for (const table of targetTables) {
|
|
426
|
+
const result = await this.findCountFromTable(table, cleanedReqJson);
|
|
427
|
+
countResults.push(result);
|
|
375
428
|
}
|
|
376
|
-
|
|
377
|
-
const
|
|
378
|
-
|
|
379
|
-
return counts.reduce((sum, c) => sum + c, 0);
|
|
429
|
+
const totalCount = countResults.reduce((sum, r) => sum + r.count, 0);
|
|
430
|
+
const firstCtx = ((_a = countResults.find(r => r.ctx !== null)) === null || _a === void 0 ? void 0 : _a.ctx) || null;
|
|
431
|
+
return new CrudResult_1.CrudCountResult({ count: totalCount, rawContext: firstCtx });
|
|
380
432
|
}
|
|
381
|
-
/**
|
|
382
|
-
* 判断记录是否存在
|
|
383
|
-
*
|
|
384
|
-
* 如果涉及多个分表,会并行查询,任一分表存在即返回 true。
|
|
385
|
-
*
|
|
386
|
-
* @param reqJson 请求参数
|
|
387
|
-
* @returns 是否存在
|
|
388
|
-
*/
|
|
389
433
|
async isExist(reqJson) {
|
|
390
|
-
|
|
434
|
+
// 清理 condition 中的时间字段(粒度字符串自动转范围、有主键时清理)
|
|
435
|
+
const cleanedReqJson = this.cleanTimeColumnForSingleTableQuery(reqJson);
|
|
436
|
+
const targetTables = await this.resolveFindTables(reqJson);
|
|
391
437
|
if (targetTables.length === 0) {
|
|
392
|
-
|
|
438
|
+
throw new Error('[ShardingCrudPro] isExist: no matching tables found');
|
|
393
439
|
}
|
|
394
440
|
if (targetTables.length === 1) {
|
|
395
|
-
const ctx = await this.executeOnTable(targetTables[0],
|
|
396
|
-
|
|
441
|
+
const ctx = await this.executeOnTable(targetTables[0], cleanedReqJson, keys_1.KeysOfSimpleSQL.SIMPLE_QUERY_EXIST);
|
|
442
|
+
const exists = ctx.getResModelItem('is_exist') === true;
|
|
443
|
+
return new CrudResult_1.CrudExistResult({ exists, rawContext: ctx });
|
|
444
|
+
}
|
|
445
|
+
// 多表判断:串行查询,任一表存在即返回 true
|
|
446
|
+
let exists = false;
|
|
447
|
+
let firstCtx = null;
|
|
448
|
+
for (const table of targetTables) {
|
|
449
|
+
const result = await this.isExistInTable(table, cleanedReqJson);
|
|
450
|
+
if (!firstCtx && result.ctx) {
|
|
451
|
+
firstCtx = result.ctx;
|
|
452
|
+
}
|
|
453
|
+
if (result.exists) {
|
|
454
|
+
exists = true;
|
|
455
|
+
break;
|
|
456
|
+
}
|
|
397
457
|
}
|
|
398
|
-
|
|
399
|
-
const promises = targetTables.map(table => this.isExistInTable(table, reqJson));
|
|
400
|
-
const results = await Promise.all(promises);
|
|
401
|
-
return results.some(exists => exists);
|
|
458
|
+
return new CrudResult_1.CrudExistResult({ exists, rawContext: firstCtx });
|
|
402
459
|
}
|
|
403
460
|
// ============ 私有方法:分表路由 ============
|
|
404
|
-
/**
|
|
405
|
-
* 【batchInsert 专用】按分表对数据进行分组
|
|
406
|
-
*
|
|
407
|
-
* 仅用于 batchInsert 方法,遍历所有数据项,
|
|
408
|
-
* 根据分表规则计算每条数据的目标分表,将相同分表的数据归为一组。
|
|
409
|
-
*
|
|
410
|
-
* @param dataArray 数据数组
|
|
411
|
-
* @returns 分表 -> 数据列表 的映射
|
|
412
|
-
*/
|
|
413
461
|
batchInsertGroupDataByTable(dataArray) {
|
|
414
462
|
const groupedData = new Map();
|
|
415
463
|
for (const item of dataArray) {
|
|
@@ -429,11 +477,6 @@ class ShardingCrudPro {
|
|
|
429
477
|
// 批量插入使用 resolveForInsert,确保返回单一表名
|
|
430
478
|
return this.router.resolveForInsert(this.config, context);
|
|
431
479
|
}
|
|
432
|
-
/**
|
|
433
|
-
* 解析单个目标表
|
|
434
|
-
*
|
|
435
|
-
* 写操作必须确定单一目标表,否则抛出异常。
|
|
436
|
-
*/
|
|
437
480
|
resolveSingleTable(reqJson, operation) {
|
|
438
481
|
// insert 操作使用 resolveForInsert(从 data 提取字段)
|
|
439
482
|
if (operation === 'insert') {
|
|
@@ -456,9 +499,6 @@ class ShardingCrudPro {
|
|
|
456
499
|
}
|
|
457
500
|
return result;
|
|
458
501
|
}
|
|
459
|
-
/**
|
|
460
|
-
* 获取分表字段提示
|
|
461
|
-
*/
|
|
462
502
|
getShardingColumnHint() {
|
|
463
503
|
if (this.config.type === ShardingConfig_1.ShardingType.RANGE || this.config.type === ShardingConfig_1.ShardingType.HASH) {
|
|
464
504
|
return this.config.shardingColumn || '分表字段';
|
|
@@ -469,110 +509,78 @@ class ShardingCrudPro {
|
|
|
469
509
|
return '分表字段';
|
|
470
510
|
}
|
|
471
511
|
// ============ 私有方法:配置构建 ============
|
|
472
|
-
/**
|
|
473
|
-
* 构建配置
|
|
474
|
-
*/
|
|
475
512
|
buildCfg(sqlSimpleName) {
|
|
476
513
|
return {
|
|
514
|
+
method: `ShardingCrudProAnonymous_${sqlSimpleName}`,
|
|
477
515
|
...this.baseCfg,
|
|
478
516
|
sqlTable: this.config.baseTable,
|
|
479
517
|
sqlSimpleName,
|
|
480
518
|
};
|
|
481
519
|
}
|
|
482
520
|
// ============ 私有方法:执行操作 ============
|
|
483
|
-
|
|
484
|
-
* 在指定表上执行操作
|
|
485
|
-
*/
|
|
486
|
-
async executeOnTable(table, reqJson, sqlSimpleName) {
|
|
521
|
+
async executeOnTable(table, reqJson, sqlSimpleName, extraCfg) {
|
|
487
522
|
const cfg = this.buildCfg(sqlSimpleName);
|
|
488
523
|
cfg.sqlTable = table; // 替换为实际分表名
|
|
489
|
-
|
|
524
|
+
cfg.enableSoftDelete = this.enableSoftDelete;
|
|
525
|
+
if (extraCfg) {
|
|
526
|
+
Object.assign(cfg, extraCfg);
|
|
527
|
+
}
|
|
528
|
+
// 创建 CrudPro 实例并设置 visitor
|
|
529
|
+
const crudPro = this.crudProFactory();
|
|
530
|
+
// 应用软删除处理
|
|
531
|
+
(0, fixSoftDelete_1.fixSoftDelete)(sqlSimpleName, cfg, reqJson, crudPro.getVisitor());
|
|
532
|
+
return crudPro.executeCrudByCfg(reqJson, cfg);
|
|
490
533
|
}
|
|
491
|
-
|
|
492
|
-
* 从指定表查询单条
|
|
493
|
-
*/
|
|
494
|
-
async queryOneFromTable(table, reqJson) {
|
|
495
|
-
try {
|
|
496
|
-
const ctx = await this.executeOnTable(table, reqJson, keys_1.KeysOfSimpleSQL.SIMPLE_QUERY_ONE);
|
|
497
|
-
return ctx.getOneObj();
|
|
498
|
-
}
|
|
499
|
-
catch (e) {
|
|
500
|
-
// 表不存在时返回 null
|
|
501
|
-
return null;
|
|
502
|
-
}
|
|
503
|
-
}
|
|
504
|
-
/**
|
|
505
|
-
* 从指定表查询数量
|
|
506
|
-
*/
|
|
507
|
-
async queryCountFromTable(table, reqJson) {
|
|
534
|
+
async findCountFromTable(table, reqJson) {
|
|
508
535
|
try {
|
|
509
536
|
const ctx = await this.executeOnTable(table, reqJson, keys_1.KeysOfSimpleSQL.SIMPLE_QUERY_COUNT);
|
|
510
|
-
return ctx.getResModelItem('total_count') || 0;
|
|
537
|
+
return { count: ctx.getResModelItem('total_count') || 0, ctx };
|
|
511
538
|
}
|
|
512
539
|
catch (e) {
|
|
513
540
|
// 表不存在时返回 0
|
|
514
|
-
return 0;
|
|
541
|
+
return { count: 0, ctx: null };
|
|
515
542
|
}
|
|
516
543
|
}
|
|
517
|
-
/**
|
|
518
|
-
* 判断指定表中是否存在记录
|
|
519
|
-
*/
|
|
520
544
|
async isExistInTable(table, reqJson) {
|
|
521
545
|
try {
|
|
522
546
|
const ctx = await this.executeOnTable(table, reqJson, keys_1.KeysOfSimpleSQL.SIMPLE_QUERY_EXIST);
|
|
523
|
-
return ctx.getResModelItem('is_exist') === true;
|
|
547
|
+
return { exists: ctx.getResModelItem('is_exist') === true, ctx };
|
|
524
548
|
}
|
|
525
549
|
catch (e) {
|
|
526
550
|
// 表不存在时返回 false
|
|
527
|
-
return false;
|
|
551
|
+
return { exists: false, ctx: null };
|
|
528
552
|
}
|
|
529
553
|
}
|
|
530
554
|
// ============ 表存在性检查和自动创建 ============
|
|
531
|
-
|
|
532
|
-
* 获取数据库中真实存在的表名集合
|
|
533
|
-
*/
|
|
534
|
-
async getExistingTablesSet() {
|
|
555
|
+
async getExistingTablesSet(skipCache = false) {
|
|
535
556
|
const { sqlDatabase, sqlDbType } = this.baseCfg;
|
|
536
557
|
if (!sqlDatabase || !sqlDbType) {
|
|
537
558
|
throw new Error('[ShardingCrudPro] 未配置 sqlDatabase 或 sqlDbType');
|
|
538
559
|
}
|
|
539
|
-
const { tables } = await this.
|
|
560
|
+
const { tables } = await this.crudProFactory().getAllTableInfos({
|
|
540
561
|
sqlDatabase,
|
|
541
562
|
sqlDbType: sqlDbType,
|
|
542
|
-
});
|
|
563
|
+
}, { skipCache });
|
|
543
564
|
return new Set(tables.map(t => t.name));
|
|
544
565
|
}
|
|
545
|
-
/**
|
|
546
|
-
* 检查表是否存在
|
|
547
|
-
*/
|
|
548
566
|
async isTableExists(tableName) {
|
|
549
|
-
const existingSet = await this.getExistingTablesSet();
|
|
567
|
+
const existingSet = await this.getExistingTablesSet(); // 使用缓存
|
|
550
568
|
return existingSet.has(tableName);
|
|
551
569
|
}
|
|
552
|
-
/**
|
|
553
|
-
* 创建分表(如果需要)
|
|
554
|
-
*
|
|
555
|
-
* 根据配置检查分表是否存在:
|
|
556
|
-
* - 如果分表已存在,直接返回
|
|
557
|
-
* - 如果分表不存在且 autoCreateTable=true,自动创建
|
|
558
|
-
* - 如果分表不存在且 autoCreateTable=false,抛出异常
|
|
559
|
-
*
|
|
560
|
-
* @param tableName 目标分表名
|
|
561
|
-
*/
|
|
562
570
|
async createShardingTableIfNeeded(tableName) {
|
|
563
|
-
// 检查表是否已存在
|
|
564
|
-
if (await this.isTableExists(tableName)) {
|
|
565
|
-
return;
|
|
566
|
-
}
|
|
567
571
|
// 根据配置决定是否自动创建
|
|
568
572
|
if (!this.config.autoCreateTable) {
|
|
569
|
-
|
|
573
|
+
// 使用缓存检查表是否存在,不存在则抛异常
|
|
574
|
+
if (!(await this.isTableExists(tableName))) {
|
|
575
|
+
throw new Error(`[ShardingCrudPro] 分表 ${tableName} 不存在。请先创建分表,或设置 autoCreateTable: true 自动创建`);
|
|
576
|
+
}
|
|
577
|
+
return;
|
|
570
578
|
}
|
|
571
579
|
// 检查数据库配置
|
|
572
580
|
if (!this.baseCfg.sqlDatabase || !this.baseCfg.sqlDbType) {
|
|
573
581
|
throw new Error('[ShardingCrudPro] 请先调用 setBaseCfg 设置数据库配置');
|
|
574
582
|
}
|
|
575
|
-
//
|
|
583
|
+
// 执行创建(内部有 checkTableExists + 建表 + 刷新缓存)
|
|
576
584
|
const result = await this.tableCreator.createTableIfNeeded(tableName, {
|
|
577
585
|
sqlDatabase: this.baseCfg.sqlDatabase,
|
|
578
586
|
sqlDbType: this.baseCfg.sqlDbType,
|
|
@@ -580,110 +588,282 @@ class ShardingCrudPro {
|
|
|
580
588
|
if (!result.success) {
|
|
581
589
|
throw result.error || new Error(`[ShardingCrudPro] 创建分表 ${tableName} 失败`);
|
|
582
590
|
}
|
|
591
|
+
// 建表成功后刷新缓存,确保后续请求命中新表
|
|
592
|
+
if (result.createSql) {
|
|
593
|
+
await this.getExistingTablesSet(true);
|
|
594
|
+
}
|
|
583
595
|
}
|
|
584
596
|
// ============ 参数校验 ============
|
|
585
597
|
/**
|
|
586
|
-
*
|
|
598
|
+
* 判断是否为时间分表类型
|
|
599
|
+
*/
|
|
600
|
+
isTimeSharding() {
|
|
601
|
+
return [ShardingConfig_1.ShardingType.YEAR, ShardingConfig_1.ShardingType.MONTH, ShardingConfig_1.ShardingType.DAY].includes(this.config.type);
|
|
602
|
+
}
|
|
603
|
+
/**
|
|
604
|
+
* 校验时间分表插入操作的 data 必须包含 timeColumn
|
|
605
|
+
*
|
|
606
|
+
* 时间分表需要根据时间字段路由到正确的分表,
|
|
607
|
+
* 如果 data 中缺少时间字段,将无法确定数据应插入哪个分表。
|
|
608
|
+
*
|
|
609
|
+
* @param reqJson 请求参数
|
|
610
|
+
* @param operation 操作名称(用于错误提示)
|
|
611
|
+
* @throws Error 如果 data 中缺少时间字段
|
|
612
|
+
*/
|
|
613
|
+
validateTimeColumnForData(reqJson, operation) {
|
|
614
|
+
if (!this.isTimeSharding())
|
|
615
|
+
return;
|
|
616
|
+
const timeColumn = this.config.timeColumn;
|
|
617
|
+
const data = reqJson.data;
|
|
618
|
+
if (!data || data[timeColumn] === undefined) {
|
|
619
|
+
throw new Error(`[ShardingCrudPro] ${operation} 操作的 data 必须包含时间字段 '${timeColumn}',用于路由到正确的分表。`);
|
|
620
|
+
}
|
|
621
|
+
}
|
|
622
|
+
/**
|
|
623
|
+
* 校验时间分表批量插入操作的每条 data 必须包含 timeColumn
|
|
587
624
|
*
|
|
588
|
-
*
|
|
589
|
-
*
|
|
590
|
-
*
|
|
625
|
+
* @param dataArray 数据数组
|
|
626
|
+
* @param operation 操作名称(用于错误提示)
|
|
627
|
+
* @throws Error 如果任一条 data 中缺少时间字段
|
|
628
|
+
*/
|
|
629
|
+
validateTimeColumnForBatchData(dataArray, operation) {
|
|
630
|
+
if (!this.isTimeSharding())
|
|
631
|
+
return;
|
|
632
|
+
const timeColumn = this.config.timeColumn;
|
|
633
|
+
for (let i = 0; i < dataArray.length; i++) {
|
|
634
|
+
if (!dataArray[i] || dataArray[i][timeColumn] === undefined) {
|
|
635
|
+
throw new Error(`[ShardingCrudPro] ${operation} 操作的 data[${i}] 必须包含时间字段 '${timeColumn}',用于路由到正确的分表。`);
|
|
636
|
+
}
|
|
637
|
+
}
|
|
638
|
+
}
|
|
639
|
+
/**
|
|
640
|
+
* 校验时间分表写操作的 condition 必须包含路由字段(timeColumn)
|
|
591
641
|
*
|
|
592
|
-
*
|
|
593
|
-
*
|
|
594
|
-
* - DESC 时表顺序为 新→旧,ASC 时表顺序为 旧→新(由调用方反转)
|
|
595
|
-
* - 这样无需内存排序,直接按表顺序拼接即可
|
|
642
|
+
* 时间分表需要根据时间字段路由到正确的分表,
|
|
643
|
+
* 如果 condition 中缺少时间字段,将无法确定操作哪个分表。
|
|
596
644
|
*
|
|
597
645
|
* @param reqJson 请求参数
|
|
646
|
+
* @param operation 操作名称(用于错误提示)
|
|
647
|
+
* @throws Error 如果 condition 中缺少时间字段
|
|
598
648
|
*/
|
|
599
|
-
|
|
649
|
+
validateRoutingFieldForCondition(reqJson, operation) {
|
|
650
|
+
if (!this.isTimeSharding())
|
|
651
|
+
return;
|
|
652
|
+
const timeColumn = this.config.timeColumn;
|
|
653
|
+
const condition = reqJson.condition;
|
|
654
|
+
if (!condition || !condition[timeColumn]) {
|
|
655
|
+
throw new Error(`[ShardingCrudPro] ${operation} 操作的 condition 必须包含时间字段 '${timeColumn}',用于路由到正确的分表。` +
|
|
656
|
+
`请提供 '${timeColumn}' 字段(如 { ${timeColumn}: '2026-03-15' })或时间范围(如 { ${timeColumn}: { $gte: '2024-01-01', $lte: '2024-03-31' } })。`);
|
|
657
|
+
}
|
|
658
|
+
}
|
|
659
|
+
/**
|
|
660
|
+
* 智能处理时间分表场景下的时间字段
|
|
661
|
+
*
|
|
662
|
+
* **问题背景**:
|
|
663
|
+
* 在时间分表(YEAR/MONTH/DAY)场景中,timeColumn 既是路由键也是查询条件。
|
|
664
|
+
* 用户传入的时间值可能精度不一致(如传 '2024-01-15' 但数据库存的是毫秒时间戳),
|
|
665
|
+
* 直接作为 WHERE 条件可能导致匹配失败。
|
|
666
|
+
*
|
|
667
|
+
* **处理规则**(详见 TIME_COLUMN_CLEAN_SPEC.md):
|
|
668
|
+
* 1. 操作符表达式($gte/$lte/$range/$in/$null 等)→ 始终保留,不做处理
|
|
669
|
+
* 2. 精确值 + 有 primaryKey → 清理(从 WHERE 移除,仅用于路由)
|
|
670
|
+
* 3. 精确值 + 无 primaryKey + 日期粒度字符串(年/月/日)→ 转换为 $gte/$lte 范围
|
|
671
|
+
* 4. 精确值 + 无 primaryKey + 其他(时间戳/datetime/null等)→ 保留原值
|
|
672
|
+
*
|
|
673
|
+
* **示例**:
|
|
674
|
+
* ```typescript
|
|
675
|
+
* // 有主键 + 精确值 → 清理
|
|
676
|
+
* { order_id: 'ORD001', created_at: '2024-01-15' }
|
|
677
|
+
* → { order_id: 'ORD001' }
|
|
678
|
+
*
|
|
679
|
+
* // 无主键 + 日期粒度字符串 → 转换为范围
|
|
680
|
+
* { status: 'paid', created_at: '2024-01' }
|
|
681
|
+
* → { status: 'paid', created_at: { $gte: '2024-01-01 00:00:00', $lte: '2024-01-31 23:59:59' } }
|
|
682
|
+
*
|
|
683
|
+
* // 操作符表达式 → 保留
|
|
684
|
+
* { order_id: 'ORD001', created_at: { $gte: '2024-01', $lte: '2024-06' } }
|
|
685
|
+
* → 不做任何处理
|
|
686
|
+
* ```
|
|
687
|
+
*
|
|
688
|
+
* @param reqJson 请求参数
|
|
689
|
+
* @returns 处理后的请求参数
|
|
690
|
+
*/
|
|
691
|
+
cleanTimeColumnForSingleTableQuery(reqJson) {
|
|
692
|
+
const { primaryKey, timeColumn, type } = this.config;
|
|
693
|
+
// 只有时间分表且配置了时间字段才需要处理
|
|
694
|
+
if (!timeColumn || ![ShardingConfig_1.ShardingType.YEAR, ShardingConfig_1.ShardingType.MONTH, ShardingConfig_1.ShardingType.DAY].includes(type)) {
|
|
695
|
+
return reqJson;
|
|
696
|
+
}
|
|
697
|
+
const condition = reqJson.condition;
|
|
698
|
+
if (!condition || typeof condition !== 'object') {
|
|
699
|
+
return reqJson;
|
|
700
|
+
}
|
|
701
|
+
const timeValue = condition[timeColumn];
|
|
702
|
+
// timeColumn 不存在 → 不处理
|
|
703
|
+
if (timeValue === undefined) {
|
|
704
|
+
return reqJson;
|
|
705
|
+
}
|
|
706
|
+
// 操作符表达式($gte/$lte/$range/$in/$null 等)→ 始终保留,但校验时间精度
|
|
707
|
+
if ((0, ShardingUtils_1.isOperatorExpression)(timeValue)) {
|
|
708
|
+
this.validateTimeOperatorPrecision(timeValue, timeColumn);
|
|
709
|
+
return reqJson;
|
|
710
|
+
}
|
|
711
|
+
// 判断是否有主键
|
|
712
|
+
const hasPrimaryKey = primaryKey && condition[primaryKey] !== undefined;
|
|
713
|
+
// ---- 精确值处理 ----
|
|
714
|
+
// Date 对象:精确到毫秒,视为精确值
|
|
715
|
+
// number:时间戳,无法推断粒度,视为精确值
|
|
716
|
+
// boolean:视为精确值
|
|
717
|
+
// string:需要检测日期粒度
|
|
718
|
+
if (typeof timeValue === 'string') {
|
|
719
|
+
// 检测日期字符串粒度
|
|
720
|
+
const range = (0, ShardingUtils_1.expandDateToRange)(timeValue);
|
|
721
|
+
if (hasPrimaryKey) {
|
|
722
|
+
// 有主键 → 无论什么粒度的字符串,都清理
|
|
723
|
+
const { [timeColumn]: _, ...cleanedCondition } = condition;
|
|
724
|
+
return { ...reqJson, condition: cleanedCondition };
|
|
725
|
+
}
|
|
726
|
+
// 无主键 + 年/月/日粒度 → 转换为 $gte/$lte 范围
|
|
727
|
+
if (range) {
|
|
728
|
+
return {
|
|
729
|
+
...reqJson,
|
|
730
|
+
condition: { ...condition, [timeColumn]: range },
|
|
731
|
+
};
|
|
732
|
+
}
|
|
733
|
+
// 无主键 + datetime 粒度或无法识别的格式 → 保留原值
|
|
734
|
+
return reqJson;
|
|
735
|
+
}
|
|
736
|
+
// Date / number / boolean / null 等其他精确值
|
|
737
|
+
if (hasPrimaryKey) {
|
|
738
|
+
// 有主键 → 清理
|
|
739
|
+
const { [timeColumn]: _, ...cleanedCondition } = condition;
|
|
740
|
+
return { ...reqJson, condition: cleanedCondition };
|
|
741
|
+
}
|
|
742
|
+
// 无主键 → 保留原值
|
|
743
|
+
return reqJson;
|
|
744
|
+
}
|
|
745
|
+
/**
|
|
746
|
+
* 校验时间操作符的值必须精确到秒
|
|
747
|
+
*
|
|
748
|
+
* MySQL 中 '2026-04-30' 等价于 '2026-04-30 00:00:00',
|
|
749
|
+
* 导致 $lte: '2026-04-30' 会丢失当天所有数据。
|
|
750
|
+
* 如果用户需要查整月/整天数据,应传粒度字符串由系统自动转换,而非手动写 $gte/$lte。
|
|
751
|
+
*
|
|
752
|
+
* @param operatorValue 操作符表达式的值
|
|
753
|
+
* @param timeColumn 时间字段名
|
|
754
|
+
* @throws Error 如果操作符值缺少时间部分
|
|
755
|
+
*/
|
|
756
|
+
validateTimeOperatorPrecision(operatorValue, timeColumn) {
|
|
757
|
+
// 需要校验精度的操作符
|
|
758
|
+
const PRECISION_OPERATORS = ['$gte', '$lte', '$gt', '$lt'];
|
|
759
|
+
for (const op of PRECISION_OPERATORS) {
|
|
760
|
+
const value = operatorValue[op];
|
|
761
|
+
if (value !== undefined && typeof value === 'string') {
|
|
762
|
+
// 匹配日期格式但缺少时间部分:'2026-04-30'
|
|
763
|
+
// datetime 格式 '2026-04-30 00:00:00' 不应被拦截
|
|
764
|
+
const dateOnlyPattern = /^\d{4}-\d{1,2}-\d{1,2}$/;
|
|
765
|
+
if (dateOnlyPattern.test(value)) {
|
|
766
|
+
throw new Error(`[ShardingCrudPro] 时间字段 '${timeColumn}' 的 ${op} 值必须精确到秒,` +
|
|
767
|
+
`当前值: '${value}'。` +
|
|
768
|
+
`请使用 '${value} 23:59:59'($lte/$lt)或 '${value} 00:00:00'($gte/$gt),` +
|
|
769
|
+
`或直接传粒度字符串(如 '${value.substring(0, 7)}' 或 '${value}')由系统自动转换范围。`);
|
|
770
|
+
}
|
|
771
|
+
}
|
|
772
|
+
}
|
|
773
|
+
// $range 操作符校验:[start, end] 两个值都必须精确到秒
|
|
774
|
+
const rangeValue = operatorValue.$range;
|
|
775
|
+
if (Array.isArray(rangeValue) && rangeValue.length >= 2) {
|
|
776
|
+
const dateOnlyPattern = /^\d{4}-\d{1,2}-\d{1,2}$/;
|
|
777
|
+
for (let i = 0; i < rangeValue.length; i++) {
|
|
778
|
+
const val = rangeValue[i];
|
|
779
|
+
if (typeof val === 'string' && dateOnlyPattern.test(val)) {
|
|
780
|
+
throw new Error(`[ShardingCrudPro] 时间字段 '${timeColumn}' 的 $range[${i}] 值必须精确到秒,` +
|
|
781
|
+
`当前值: '${val}'。` +
|
|
782
|
+
`请使用 '${val} ${i === 0 ? '00:00:00' : '23:59:59'}',` +
|
|
783
|
+
`或直接传粒度字符串由系统自动转换范围。`);
|
|
784
|
+
}
|
|
785
|
+
}
|
|
786
|
+
}
|
|
787
|
+
}
|
|
788
|
+
validateFindOrderBy(reqJson) {
|
|
600
789
|
// 非时间分表不强制 orderBy 约束(多表合并排序由调用方自行保证)
|
|
601
790
|
const timeColumn = this.config.timeColumn;
|
|
602
791
|
if (!timeColumn) {
|
|
603
792
|
return;
|
|
604
793
|
}
|
|
605
794
|
const orderBy = reqJson.orderBy;
|
|
606
|
-
const expectedDesc = `${timeColumn} DESC`;
|
|
607
|
-
const expectedAsc = `${timeColumn} ASC`;
|
|
608
795
|
// 1. 必须传 orderBy
|
|
609
796
|
if (!orderBy) {
|
|
610
797
|
throw new Error(`[ShardingCrudPro] 查询操作必须传 orderBy 参数。` +
|
|
611
798
|
`期望值: '${timeColumn} DESC' 或 '${timeColumn} ASC'`);
|
|
612
799
|
}
|
|
613
|
-
// 2.
|
|
614
|
-
|
|
615
|
-
|
|
616
|
-
|
|
617
|
-
|
|
618
|
-
`当前值: '${orderBy}'`);
|
|
619
|
-
}
|
|
800
|
+
// 2. 使用工具类解析并校验首个排序字段是否为 timeColumn
|
|
801
|
+
const firstOrderBy = OrderByUtils_1.OrderByUtils.getFirstOrderBy(orderBy);
|
|
802
|
+
if (!firstOrderBy) {
|
|
803
|
+
throw new Error(`[ShardingCrudPro] orderBy 参数格式错误,无法解析。` +
|
|
804
|
+
`期望值: '${timeColumn} DESC' 或 '${timeColumn} ASC'`);
|
|
620
805
|
}
|
|
621
|
-
|
|
622
|
-
|
|
623
|
-
|
|
624
|
-
throw new Error(`[ShardingCrudPro] orderBy 数组不能为空,首个排序字段必须为 '${timeColumn} DESC' 或 '${timeColumn} ASC'`);
|
|
625
|
-
}
|
|
626
|
-
const firstItem = orderBy[0];
|
|
627
|
-
const firstItemStr = typeof firstItem === 'string'
|
|
628
|
-
? firstItem
|
|
629
|
-
: `${firstItem.fieldName} ${firstItem.orderType || 'ASC'}`;
|
|
630
|
-
const upper = firstItemStr.trim().toUpperCase();
|
|
631
|
-
if (upper !== expectedDesc.toUpperCase() && upper !== expectedAsc.toUpperCase()) {
|
|
632
|
-
throw new Error(`[ShardingCrudPro] orderBy 数组首个排序字段必须为 '${timeColumn} DESC' 或 '${timeColumn} ASC',` +
|
|
633
|
-
`当前值: '${firstItemStr}'`);
|
|
634
|
-
}
|
|
806
|
+
if (firstOrderBy.fieldName !== timeColumn) {
|
|
807
|
+
throw new Error(`[ShardingCrudPro] orderBy 首个排序字段必须为 '${timeColumn}',` +
|
|
808
|
+
`当前值: '${firstOrderBy.fieldName}'`);
|
|
635
809
|
}
|
|
636
|
-
|
|
637
|
-
|
|
810
|
+
// 校验排序方向是否为 ASC 或 DESC
|
|
811
|
+
const orderType = firstOrderBy.orderType.toUpperCase();
|
|
812
|
+
if (orderType !== 'ASC' && orderType !== 'DESC') {
|
|
813
|
+
throw new Error(`[ShardingCrudPro] orderBy 排序方向必须是 'ASC' 或 'DESC',` +
|
|
814
|
+
`当前值: '${firstOrderBy.orderType}'`);
|
|
638
815
|
}
|
|
639
816
|
}
|
|
640
|
-
/**
|
|
641
|
-
* 判断 orderBy 是否为 ASC 方向
|
|
642
|
-
*
|
|
643
|
-
* 前提:validateQueryOrderBy 已通过校验,orderBy 格式合法
|
|
644
|
-
*
|
|
645
|
-
* @param reqJson 请求参数
|
|
646
|
-
* @returns true 表示 ASC,false 表示 DESC
|
|
647
|
-
*/
|
|
648
817
|
isAscOrderBy(reqJson) {
|
|
649
|
-
|
|
650
|
-
if (!orderBy)
|
|
651
|
-
return false;
|
|
652
|
-
if (typeof orderBy === 'string') {
|
|
653
|
-
return orderBy.trim().toUpperCase().endsWith('ASC');
|
|
654
|
-
}
|
|
655
|
-
if (Array.isArray(orderBy) && orderBy.length > 0) {
|
|
656
|
-
const firstItem = orderBy[0];
|
|
657
|
-
const firstItemStr = typeof firstItem === 'string'
|
|
658
|
-
? firstItem
|
|
659
|
-
: `${firstItem.fieldName} ${firstItem.orderType || 'ASC'}`;
|
|
660
|
-
return firstItemStr.trim().toUpperCase().endsWith('ASC');
|
|
661
|
-
}
|
|
662
|
-
return false;
|
|
818
|
+
return OrderByUtils_1.OrderByUtils.isFirstOrderByAsc(reqJson.orderBy);
|
|
663
819
|
}
|
|
664
|
-
/**
|
|
665
|
-
* 根据排序方向对分表列表进行排序
|
|
666
|
-
*
|
|
667
|
-
* 分表名后缀为时间格式(如 202403、20240101),字典序即时间序。
|
|
668
|
-
* - DESC:降序排列(新→旧)
|
|
669
|
-
* - ASC:升序排列(旧→新)
|
|
670
|
-
*
|
|
671
|
-
* @param tables 分表列表
|
|
672
|
-
* @param reqJson 请求参数
|
|
673
|
-
* @returns 排序后的分表列表(新数组,不修改原数组)
|
|
674
|
-
*/
|
|
675
820
|
sortTablesForOrderBy(tables, reqJson) {
|
|
676
821
|
const isAsc = this.isAscOrderBy(reqJson);
|
|
677
822
|
return [...tables].sort((a, b) => isAsc ? a.localeCompare(b) : b.localeCompare(a));
|
|
678
823
|
}
|
|
679
|
-
// ============
|
|
824
|
+
// ============ 辅助方法 ============
|
|
680
825
|
/**
|
|
681
|
-
*
|
|
682
|
-
|
|
683
|
-
|
|
684
|
-
|
|
826
|
+
* 构建辅助定位信息
|
|
827
|
+
*/
|
|
828
|
+
buildDebugInfo(sqlTable, condition) {
|
|
829
|
+
const info = {
|
|
830
|
+
sqlDatabase: this.baseCfg.sqlDatabase || 'unknown',
|
|
831
|
+
sqlTable: sqlTable || this.config.baseTable,
|
|
832
|
+
};
|
|
833
|
+
if (condition) {
|
|
834
|
+
info.condition = condition;
|
|
835
|
+
}
|
|
836
|
+
return info;
|
|
837
|
+
}
|
|
838
|
+
/**
|
|
839
|
+
* 格式化唯一性错误消息
|
|
685
840
|
*/
|
|
686
|
-
|
|
841
|
+
formatUniqueError(foundCount, tables, condition, isMultiTable = false) {
|
|
842
|
+
const parts = [
|
|
843
|
+
`[ShardingCrudPro] findUniqueOne 期望唯一一条记录,但查询到 ${foundCount} 条`,
|
|
844
|
+
];
|
|
845
|
+
if (this.baseCfg.sqlDatabase) {
|
|
846
|
+
parts.push(`数据库: ${this.baseCfg.sqlDatabase}`);
|
|
847
|
+
}
|
|
848
|
+
if (isMultiTable && Array.isArray(tables)) {
|
|
849
|
+
parts.push(`基表: ${this.config.baseTable}`);
|
|
850
|
+
parts.push(`分表: [${tables.join(', ')}]`);
|
|
851
|
+
}
|
|
852
|
+
else {
|
|
853
|
+
parts.push(`表: ${typeof tables === 'string' ? tables : tables[0]}`);
|
|
854
|
+
}
|
|
855
|
+
if (condition) {
|
|
856
|
+
try {
|
|
857
|
+
parts.push(`条件: ${JSON.stringify(condition)}`);
|
|
858
|
+
}
|
|
859
|
+
catch (_a) {
|
|
860
|
+
parts.push(`条件: [无法序列化]`);
|
|
861
|
+
}
|
|
862
|
+
}
|
|
863
|
+
return parts.join(' | ');
|
|
864
|
+
}
|
|
865
|
+
// ============ 查询表解析(委托给 ShardingRouter) ============
|
|
866
|
+
async resolveFindTables(reqJson) {
|
|
687
867
|
const context = {
|
|
688
868
|
config: this.config,
|
|
689
869
|
condition: reqJson.condition,
|