@maiyunnet/kebab 10.1.1 → 11.0.0
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/doc/kebab-rag.md +385 -199
- package/index.d.ts +1 -1
- package/index.js +1 -1
- package/lib/db/conn.js +22 -0
- package/lib/sql.d.ts +74 -5
- package/lib/sql.js +519 -264
- package/lib/text.d.ts +10 -0
- package/lib/text.js +35 -0
- package/package.json +1 -1
- package/sys/mod.d.ts +9 -5
- package/sys/mod.js +121 -20
- package/www/example/ctr/test.js +18 -10
package/lib/sql.js
CHANGED
|
@@ -34,6 +34,68 @@ export var EJSON;
|
|
|
34
34
|
const columnSymbol = Symbol('kebab.sql.column');
|
|
35
35
|
/** --- value() 内部私有标记,防止通过外部 JSON 伪造值对象 --- */
|
|
36
36
|
const valueSymbol = Symbol('kebab.sql.value');
|
|
37
|
+
/** --- raw() 内部私有标记,防止通过外部 JSON 伪造原始 SQL 表达式 --- */
|
|
38
|
+
const rawSymbol = Symbol('kebab.sql.raw');
|
|
39
|
+
/** --- 允许的 WHERE 运算符白名单 --- */
|
|
40
|
+
const WHERE_OPERATORS = new Set([
|
|
41
|
+
'=', '!=', '<>', '>', '>=', '<', '<=', '<=>',
|
|
42
|
+
'LIKE', 'NOT LIKE', 'ILIKE', 'NOT ILIKE',
|
|
43
|
+
'IN', 'NOT IN', 'IS', 'IS NOT', 'IS DISTINCT FROM', 'IS NOT DISTINCT FROM',
|
|
44
|
+
'REGEXP', 'NOT REGEXP', 'RLIKE', 'NOT RLIKE',
|
|
45
|
+
'~', '~*', '!~', '!~*',
|
|
46
|
+
'@>', '<@', '&&', '?', '?|', '?&',
|
|
47
|
+
'&', '|', '^', '<<', '>>',
|
|
48
|
+
]);
|
|
49
|
+
/** --- 允许的 UPDATE 赋值运算符白名单 --- */
|
|
50
|
+
const UPDATE_OPERATORS = new Set([
|
|
51
|
+
'=', '+', '-', '*', '/', '%', '||', '&', '|', '^', '<<', '>>',
|
|
52
|
+
]);
|
|
53
|
+
/** --- 允许的 JOIN 类型白名单 --- */
|
|
54
|
+
const JOIN_TYPES = new Set([
|
|
55
|
+
'INNER', 'LEFT', 'RIGHT', 'FULL', 'CROSS',
|
|
56
|
+
'LEFT OUTER', 'RIGHT OUTER', 'FULL OUTER',
|
|
57
|
+
'NATURAL', 'NATURAL LEFT', 'NATURAL RIGHT',
|
|
58
|
+
]);
|
|
59
|
+
/** --- 允许的 UNION 类型白名单 --- */
|
|
60
|
+
const UNION_TYPES = new Set(['', 'ALL', 'DISTINCT']);
|
|
61
|
+
/**
|
|
62
|
+
* --- 校验并规范化 ORDER BY 排序方向 ---
|
|
63
|
+
* @param dir 排序方向
|
|
64
|
+
* @returns 大写的 ASC 或 DESC,不合法返回 null
|
|
65
|
+
*/
|
|
66
|
+
function parseOrderDir(dir) {
|
|
67
|
+
if (typeof dir === 'string') {
|
|
68
|
+
const upper = dir.trim().toUpperCase();
|
|
69
|
+
if (upper === 'ASC' || upper === 'DESC') {
|
|
70
|
+
return upper;
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
return null;
|
|
74
|
+
}
|
|
75
|
+
/**
|
|
76
|
+
* --- 校验并规范化 WHERE 运算符 ---
|
|
77
|
+
* @param op 运算符
|
|
78
|
+
* @returns 规范化后的大写运算符,不合法返回 null
|
|
79
|
+
*/
|
|
80
|
+
function parseWhereOp(op) {
|
|
81
|
+
if (typeof op !== 'string') {
|
|
82
|
+
return null;
|
|
83
|
+
}
|
|
84
|
+
const val = op.trim().replace(/\s+/g, ' ').toUpperCase();
|
|
85
|
+
return WHERE_OPERATORS.has(val) ? val : null;
|
|
86
|
+
}
|
|
87
|
+
/**
|
|
88
|
+
* --- 校验并规范化 UPDATE 运算符 ---
|
|
89
|
+
* @param op 运算符
|
|
90
|
+
* @returns 规范化后的运算符,不合法返回 null
|
|
91
|
+
*/
|
|
92
|
+
function parseUpdateOp(op) {
|
|
93
|
+
if (typeof op !== 'string') {
|
|
94
|
+
return null;
|
|
95
|
+
}
|
|
96
|
+
const val = op.trim();
|
|
97
|
+
return UPDATE_OPERATORS.has(val) ? val : null;
|
|
98
|
+
}
|
|
37
99
|
/** --- field 用 token --- */
|
|
38
100
|
let columnToken = '';
|
|
39
101
|
/** --- value 用 token --- */
|
|
@@ -57,6 +119,10 @@ export class Sql {
|
|
|
57
119
|
_ignore = false;
|
|
58
120
|
/** --- MySQL 优化器 Hint,如 INDEX(table idx) --- */
|
|
59
121
|
_hint = '';
|
|
122
|
+
/** --- 当前构建器的粘性错误;非空时 getSql() 返回空串、getData() 返回空数组 --- */
|
|
123
|
+
_error = '';
|
|
124
|
+
/** --- hint() 独立错误,避免先 hint() 再 select() 时被重置覆盖 --- */
|
|
125
|
+
_hintError = '';
|
|
60
126
|
// --- 实例化 ---
|
|
61
127
|
constructor(opt) {
|
|
62
128
|
this._ctr = opt.ctr;
|
|
@@ -73,6 +139,17 @@ export class Sql {
|
|
|
73
139
|
this._alias = opt.alias;
|
|
74
140
|
}
|
|
75
141
|
}
|
|
142
|
+
/** --- 记录构建错误并写入错误日志,保持首个错误不被覆盖 --- */
|
|
143
|
+
_setError(msg) {
|
|
144
|
+
if (!this._error) {
|
|
145
|
+
this._error = msg;
|
|
146
|
+
}
|
|
147
|
+
lCore.log(this._ctr ?? {}, `[SQL] ${msg}`, '-error');
|
|
148
|
+
}
|
|
149
|
+
/** --- 获取当前构建错误,正常时为空字符串 --- */
|
|
150
|
+
getError() {
|
|
151
|
+
return this._error;
|
|
152
|
+
}
|
|
76
153
|
/**
|
|
77
154
|
* --- 设置 MySQL 优化器 Hint ---
|
|
78
155
|
* --- 会以 Optimizer Hint 注释语法注入到 SELECT 关键字后 ---
|
|
@@ -97,6 +174,13 @@ export class Sql {
|
|
|
97
174
|
* // --- 官方文档: https://dev.mysql.com/doc/refman/8.0/en/optimizer-hints.html ---
|
|
98
175
|
*/
|
|
99
176
|
hint(h) {
|
|
177
|
+
if (typeof h !== 'string' || h.includes('/*') || h.includes('*/')) {
|
|
178
|
+
this._hint = '';
|
|
179
|
+
this._hintError = 'Invalid SQL optimizer hint';
|
|
180
|
+
this._setError(this._hintError);
|
|
181
|
+
return this;
|
|
182
|
+
}
|
|
183
|
+
this._hintError = '';
|
|
100
184
|
this._hint = h;
|
|
101
185
|
return this;
|
|
102
186
|
}
|
|
@@ -107,6 +191,7 @@ export class Sql {
|
|
|
107
191
|
* @param ignore 是否忽略错误(MySQL: INSERT IGNORE, PGSQL: ON CONFLICT DO NOTHING)
|
|
108
192
|
*/
|
|
109
193
|
insert(table, ignore = false) {
|
|
194
|
+
this._error = this._hintError;
|
|
110
195
|
this._data = [];
|
|
111
196
|
this._placeholderCounter = 1;
|
|
112
197
|
this._alias.length = 0;
|
|
@@ -138,10 +223,13 @@ export class Sql {
|
|
|
138
223
|
}
|
|
139
224
|
// --- INSERT INTO xx (id, name) VALUES (?, ?) ---
|
|
140
225
|
// --- INSERT INTO xx (id, name) VALUES (?, ?), (?, ?) ---
|
|
226
|
+
let row = 0;
|
|
141
227
|
for (const v of vs) {
|
|
228
|
+
++row;
|
|
142
229
|
sql += '(';
|
|
143
|
-
|
|
144
|
-
|
|
230
|
+
let ci = 0;
|
|
231
|
+
for (const value of v) {
|
|
232
|
+
const result = this._processValue(value, cs[ci++], row);
|
|
145
233
|
sql += result.sql + ', ';
|
|
146
234
|
if (result.data !== undefined) {
|
|
147
235
|
this._data.push(...result.data);
|
|
@@ -158,8 +246,7 @@ export class Sql {
|
|
|
158
246
|
for (const k in cs) {
|
|
159
247
|
const v = cs[k];
|
|
160
248
|
sql += this.field(k) + ', ';
|
|
161
|
-
|
|
162
|
-
const result = this._processValue(v);
|
|
249
|
+
const result = this._processValue(v, k);
|
|
163
250
|
values += result.sql + ', ';
|
|
164
251
|
if (result.data !== undefined) {
|
|
165
252
|
this._data.push(...result.data);
|
|
@@ -217,6 +304,7 @@ export class Sql {
|
|
|
217
304
|
* @param rows 数据行数组,每行顺序为 [keyVal, col1Val, col2Val, ...](与 [key, ...cols] 对应)
|
|
218
305
|
*/
|
|
219
306
|
updateByValues(table, key, cols, rows) {
|
|
307
|
+
this._error = this._hintError;
|
|
220
308
|
this._data = [];
|
|
221
309
|
this._placeholderCounter = 1;
|
|
222
310
|
const allCols = [key, ...cols];
|
|
@@ -233,7 +321,7 @@ export class Sql {
|
|
|
233
321
|
for (let ri = 0; ri < rows.length; ri++) {
|
|
234
322
|
const row = rows[ri];
|
|
235
323
|
const parts = row.map((v, ci) => {
|
|
236
|
-
const result = this._processValue(v);
|
|
324
|
+
const result = this._processValue(v, allCols[ci], ri + 1, quotedTable);
|
|
237
325
|
if (result.data.length > 0) {
|
|
238
326
|
this._data.push(...result.data);
|
|
239
327
|
}
|
|
@@ -250,9 +338,11 @@ export class Sql {
|
|
|
250
338
|
const valueParts = [];
|
|
251
339
|
const typeParts = allCols.map(c => `(NULL::${quotedTable}).${this.field(c)}`);
|
|
252
340
|
valueParts.push(`(${typeParts.join(', ')})`);
|
|
341
|
+
let ri = 0;
|
|
253
342
|
for (const row of rows) {
|
|
254
|
-
|
|
255
|
-
|
|
343
|
+
++ri;
|
|
344
|
+
const parts = row.map((v, ci) => {
|
|
345
|
+
const result = this._processValue(v, allCols[ci], ri, quotedTable);
|
|
256
346
|
if (result.data.length > 0) {
|
|
257
347
|
this._data.push(...result.data);
|
|
258
348
|
}
|
|
@@ -272,6 +362,7 @@ export class Sql {
|
|
|
272
362
|
* @param f 表,允许多张表
|
|
273
363
|
*/
|
|
274
364
|
select(c, f) {
|
|
365
|
+
this._error = this._hintError;
|
|
275
366
|
this._data = [];
|
|
276
367
|
this._placeholderCounter = 1;
|
|
277
368
|
let sql = 'SELECT ';
|
|
@@ -312,20 +403,28 @@ export class Sql {
|
|
|
312
403
|
* @param s 设定 update 的值
|
|
313
404
|
*/
|
|
314
405
|
update(f, s) {
|
|
406
|
+
this._error = this._hintError;
|
|
315
407
|
this._data = [];
|
|
316
408
|
this._placeholderCounter = 1;
|
|
317
|
-
const
|
|
409
|
+
const table = this.field(f, this._pre);
|
|
410
|
+
const sql = `UPDATE ${table} SET ${this._updateSub(s, table)}`;
|
|
318
411
|
this._sql = [sql];
|
|
319
412
|
return this;
|
|
320
413
|
}
|
|
321
|
-
|
|
414
|
+
/**
|
|
415
|
+
* --- 生成更新字段列表及其绑定参数 ---
|
|
416
|
+
* @param s 更新值
|
|
417
|
+
* @param table 已格式化的目标表名,UPSERT 从 INSERT 前导取表名
|
|
418
|
+
* @returns SET 子句中的赋值列表
|
|
419
|
+
*/
|
|
420
|
+
_updateSub(s, table) {
|
|
322
421
|
/*
|
|
323
422
|
[
|
|
324
423
|
['total', '+', '1'],
|
|
325
424
|
{
|
|
326
425
|
'type': '6',
|
|
327
426
|
'type': column('type2'),
|
|
328
|
-
'type':
|
|
427
|
+
'type': raw('(CASE `id` WHEN 1 THEN ? WHEN 2 THEN ? END)', ['val1', 'val2']),
|
|
329
428
|
'point': { 'x': 0, 'y': 0 },
|
|
330
429
|
'polygon': [ [ { 'x': 0, 'y': 0 }, { ... } ], [ ... ] ],
|
|
331
430
|
'json': json({ 'a': 1, 'b': { 'c': 2 }, 'c': [ { 'c': 2 } ] }),
|
|
@@ -333,44 +432,42 @@ export class Sql {
|
|
|
333
432
|
}
|
|
334
433
|
]
|
|
335
434
|
*/
|
|
336
|
-
s = aoMix(s);
|
|
337
435
|
let sql = '';
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
if (
|
|
341
|
-
// --- 数组运算式:[字段, 运算符, 值] ---
|
|
342
|
-
const
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
|
|
436
|
+
const items = Array.isArray(s) ? s : [s];
|
|
437
|
+
for (const item of items) {
|
|
438
|
+
if (Array.isArray(item)) {
|
|
439
|
+
// --- 数组运算式:[字段, 运算符, 值],仅在外层为数组时识别 ---
|
|
440
|
+
const op = parseUpdateOp(item[1]);
|
|
441
|
+
if (op === null) {
|
|
442
|
+
this._setError(`Invalid SQL UPDATE operator: ${String(item[1])}`);
|
|
443
|
+
return '';
|
|
444
|
+
}
|
|
445
|
+
const val = item[2];
|
|
446
|
+
if (this._isField(val)) {
|
|
447
|
+
const col = this.field(item[0]);
|
|
448
|
+
const target = this.field(val.value);
|
|
449
|
+
sql += op === '=' ? `${col} = ${target}, ` : `${col} = ${col} ${op} ${target}, `;
|
|
351
450
|
}
|
|
352
451
|
else {
|
|
353
|
-
|
|
354
|
-
const
|
|
452
|
+
// --- JSON 标记值需要生成 ::jsonb;普通运算值保持原占位符行为 ---
|
|
453
|
+
const res = lSqlValue.isJson(val) ? this._processValue(val) : {
|
|
355
454
|
'sql': this._placeholder(),
|
|
356
|
-
'data': [
|
|
455
|
+
'data': [val],
|
|
357
456
|
};
|
|
358
|
-
|
|
359
|
-
|
|
360
|
-
|
|
361
|
-
else {
|
|
362
|
-
sql += this.field(v[0]) + ' = ' + this.field(v[0]) + ' ' + v[1] + ' ' + result.sql + ', ';
|
|
363
|
-
}
|
|
364
|
-
this._data.push(...result.data);
|
|
457
|
+
const col = this.field(item[0]);
|
|
458
|
+
sql += op === '=' ? `${col} = ${res.sql}, ` : `${col} = ${col} ${op} ${res.sql}, `;
|
|
459
|
+
this._data.push(...res.data);
|
|
365
460
|
}
|
|
366
461
|
}
|
|
367
|
-
else {
|
|
368
|
-
// --- 对象赋值式:{字段: 值} ---
|
|
369
|
-
|
|
370
|
-
const
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
|
|
462
|
+
else if (item && typeof item === 'object') {
|
|
463
|
+
// --- 对象赋值式:{字段: 值};数字键同样按列名处理,避免 JSON 伪造运算式 ---
|
|
464
|
+
const obj = item;
|
|
465
|
+
for (const key in obj) {
|
|
466
|
+
const res = this._processValue(obj[key], key, undefined, table);
|
|
467
|
+
sql += `${this.field(key)} = ${res.sql}, `;
|
|
468
|
+
if (res.data !== undefined) {
|
|
469
|
+
this._data.push(...res.data);
|
|
470
|
+
}
|
|
374
471
|
}
|
|
375
472
|
}
|
|
376
473
|
}
|
|
@@ -382,6 +479,7 @@ export class Sql {
|
|
|
382
479
|
* @param f 表名
|
|
383
480
|
*/
|
|
384
481
|
delete(f) {
|
|
482
|
+
this._error = this._hintError;
|
|
385
483
|
this._data = [];
|
|
386
484
|
this._placeholderCounter = 1;
|
|
387
485
|
this._sql = ['DELETE FROM ' + this.field(f, this._pre)];
|
|
@@ -393,9 +491,22 @@ export class Sql {
|
|
|
393
491
|
* @param type 类型
|
|
394
492
|
*/
|
|
395
493
|
union(lsql, type = '') {
|
|
494
|
+
if (lsql.getError()) {
|
|
495
|
+
this._setError(lsql.getError());
|
|
496
|
+
return this;
|
|
497
|
+
}
|
|
498
|
+
if (typeof type !== 'string') {
|
|
499
|
+
this._setError('Invalid SQL UNION type');
|
|
500
|
+
return this;
|
|
501
|
+
}
|
|
502
|
+
const kind = type.trim().toUpperCase();
|
|
503
|
+
if (!UNION_TYPES.has(kind)) {
|
|
504
|
+
this._setError(`Invalid SQL UNION type: ${type}`);
|
|
505
|
+
return this;
|
|
506
|
+
}
|
|
396
507
|
const offset = this._data.length;
|
|
397
508
|
this._data = this._data.concat(lsql.getData());
|
|
398
|
-
this._sql.push(
|
|
509
|
+
this._sql.push(kind ? ` UNION ${kind} ` : ' UNION ');
|
|
399
510
|
let unionSql = lsql.getSql();
|
|
400
511
|
// --- PGSQL: 偏移 $N 占位符编号 ---
|
|
401
512
|
if (this._service === ESERVICE.PGSQL && offset > 0) {
|
|
@@ -421,7 +532,16 @@ export class Sql {
|
|
|
421
532
|
* @param pre MySQL 时为表前缀,PostgreSQL 时为 Schema 名,仅在 join 非默认前缀时填写
|
|
422
533
|
*/
|
|
423
534
|
join(f, s = [], type = 'INNER', suf = '', pre = '') {
|
|
424
|
-
|
|
535
|
+
if (typeof type !== 'string') {
|
|
536
|
+
this._setError('Invalid SQL JOIN type');
|
|
537
|
+
return this;
|
|
538
|
+
}
|
|
539
|
+
const kind = type.trim().replace(/\s+/g, ' ').toUpperCase();
|
|
540
|
+
if (!JOIN_TYPES.has(kind)) {
|
|
541
|
+
this._setError(`Invalid SQL JOIN type: ${type}`);
|
|
542
|
+
return this;
|
|
543
|
+
}
|
|
544
|
+
let field = this.field(f, pre || this._pre, suf ? `#${suf}` : '');
|
|
425
545
|
if (pre) {
|
|
426
546
|
// --- 处理不同 pre 的 as 前缀问题 ---
|
|
427
547
|
if (this._service === ESERVICE.MYSQL) {
|
|
@@ -431,7 +551,7 @@ export class Sql {
|
|
|
431
551
|
field = field.replace(new RegExp(`AS "${pre}"."(.+?)"`), `AS "${this._pre}"."$1"`);
|
|
432
552
|
}
|
|
433
553
|
}
|
|
434
|
-
let sql =
|
|
554
|
+
let sql = ` ${kind} JOIN ${field}`;
|
|
435
555
|
if (Array.isArray(s) ? s.length : Object.keys(s).length) {
|
|
436
556
|
sql += ' ON ' + this._whereSub(s);
|
|
437
557
|
}
|
|
@@ -557,166 +677,198 @@ export class Sql {
|
|
|
557
677
|
}
|
|
558
678
|
return this;
|
|
559
679
|
}
|
|
560
|
-
|
|
561
|
-
|
|
562
|
-
|
|
563
|
-
|
|
564
|
-
|
|
565
|
-
|
|
566
|
-
|
|
567
|
-
|
|
568
|
-
|
|
569
|
-
|
|
570
|
-
|
|
571
|
-
if (v[1] !== undefined) {
|
|
572
|
-
data.push(...v[1]);
|
|
573
|
-
}
|
|
574
|
-
}
|
|
575
|
-
else if (typeof v[1] === 'string' && ['json', 'json_in', 'json_key', 'json_any', 'json_all', 'json_overlaps'].includes(v[1].toLowerCase())) {
|
|
576
|
-
// --- JSON 操作符条件 ---
|
|
577
|
-
const op = v[1].toLowerCase();
|
|
578
|
-
const nv = lSqlValue.unwrapJson(v[2]);
|
|
579
|
-
if (op === 'json') {
|
|
580
|
-
if (this._service === ESERVICE.MYSQL) {
|
|
581
|
-
sql += `JSON_CONTAINS(${this.field(v[0])}, ${this._placeholder()}) AND `;
|
|
582
|
-
data.push(lText.stringifyJson(nv));
|
|
583
|
-
}
|
|
584
|
-
else {
|
|
585
|
-
sql += `${this.field(v[0])} @> ${this._placeholder()} AND `;
|
|
586
|
-
data.push(lText.stringifyJson(nv));
|
|
587
|
-
}
|
|
588
|
-
}
|
|
589
|
-
else if (op === 'json_in') {
|
|
590
|
-
if (this._service === ESERVICE.MYSQL) {
|
|
591
|
-
sql += `JSON_CONTAINS(${this._placeholder()}, ${this.field(v[0])}) AND `;
|
|
592
|
-
data.push(lText.stringifyJson(nv));
|
|
593
|
-
}
|
|
594
|
-
else {
|
|
595
|
-
sql += `${this.field(v[0])} <@ ${this._placeholder()} AND `;
|
|
596
|
-
data.push(lText.stringifyJson(nv));
|
|
597
|
-
}
|
|
598
|
-
}
|
|
599
|
-
else if (op === 'json_overlaps') {
|
|
600
|
-
if (this._service === ESERVICE.MYSQL) {
|
|
601
|
-
sql += `JSON_OVERLAPS(${this.field(v[0])}, ${this._placeholder()}) AND `;
|
|
602
|
-
data.push(lText.stringifyJson(nv));
|
|
603
|
-
}
|
|
604
|
-
else {
|
|
605
|
-
sql += `${this.field(v[0])} && ${this._placeholder()} AND `;
|
|
606
|
-
data.push(nv);
|
|
607
|
-
}
|
|
608
|
-
}
|
|
609
|
-
else {
|
|
610
|
-
// --- json_key, json_any, json_all ---
|
|
611
|
-
const keys = Array.isArray(nv) ? nv : [nv];
|
|
612
|
-
if (this._service === ESERVICE.MYSQL) {
|
|
613
|
-
const type = op === 'json_all' ? 'all' : 'one';
|
|
614
|
-
let pathSql = '';
|
|
615
|
-
for (const k of keys) {
|
|
616
|
-
pathSql += ', ' + this._placeholder();
|
|
617
|
-
data.push(k.startsWith('$') ? k : `$.${k}`);
|
|
618
|
-
}
|
|
619
|
-
sql += `JSON_CONTAINS_PATH(${this.field(v[0])}, '${type}'${pathSql}) AND `;
|
|
620
|
-
}
|
|
621
|
-
else {
|
|
622
|
-
if (op === 'json_key' && keys.length === 1) {
|
|
623
|
-
sql += `${this.field(v[0])} ? ${this._placeholder()} AND `;
|
|
624
|
-
data.push(keys[0]);
|
|
625
|
-
}
|
|
626
|
-
else {
|
|
627
|
-
const pgOp = op === 'json_all' ? '?&' : '?|';
|
|
628
|
-
sql += `${this.field(v[0])} ${pgOp} ${this._placeholder()} AND `;
|
|
629
|
-
data.push(keys);
|
|
630
|
-
}
|
|
631
|
-
}
|
|
632
|
-
}
|
|
680
|
+
/**
|
|
681
|
+
* --- 统计条件项数量,决定逻辑分组内是否需要外层括号 ---
|
|
682
|
+
* @param cond 条件对象或数组
|
|
683
|
+
* @returns 条件条数
|
|
684
|
+
*/
|
|
685
|
+
_countConditions(cond) {
|
|
686
|
+
if (Array.isArray(cond)) {
|
|
687
|
+
let count = 0;
|
|
688
|
+
for (const item of cond) {
|
|
689
|
+
if (Array.isArray(item)) {
|
|
690
|
+
++count;
|
|
633
691
|
}
|
|
634
|
-
else if (
|
|
635
|
-
|
|
636
|
-
let opera = v[1];
|
|
637
|
-
if (opera === '!=' || opera === '!==' || opera === '<>') {
|
|
638
|
-
opera = 'IS NOT';
|
|
639
|
-
}
|
|
640
|
-
else if (opera === '=' || opera === '==' || opera === '===') {
|
|
641
|
-
opera = 'IS';
|
|
642
|
-
}
|
|
643
|
-
else {
|
|
644
|
-
opera = opera.toUpperCase();
|
|
645
|
-
}
|
|
646
|
-
sql += this.field(v[0]) + ' ' + opera + ' NULL AND ';
|
|
692
|
+
else if (item && typeof item === 'object') {
|
|
693
|
+
count += Object.keys(item).length;
|
|
647
694
|
}
|
|
648
|
-
|
|
649
|
-
|
|
695
|
+
}
|
|
696
|
+
return count;
|
|
697
|
+
}
|
|
698
|
+
if (cond && typeof cond === 'object') {
|
|
699
|
+
return Object.keys(cond).length;
|
|
700
|
+
}
|
|
701
|
+
return 0;
|
|
702
|
+
}
|
|
703
|
+
/**
|
|
704
|
+
* --- 生成单条数组条件 SQL 片段 ---
|
|
705
|
+
* @param item 数组条件项
|
|
706
|
+
* @param data 绑定参数列表
|
|
707
|
+
* @returns 带尾随 AND 的 SQL 片段,校验失败返回空字符串
|
|
708
|
+
*/
|
|
709
|
+
_whereArrayItem(item, data) {
|
|
710
|
+
// --- 原始 SQL 条件及参数 ---
|
|
711
|
+
if (item[2] === undefined) {
|
|
712
|
+
if (item[1] !== undefined) {
|
|
713
|
+
data.push(...item[1]);
|
|
714
|
+
}
|
|
715
|
+
return `${this.field(item[0])} AND `;
|
|
716
|
+
}
|
|
717
|
+
// --- JSON 操作符条件 ---
|
|
718
|
+
if (typeof item[1] === 'string' && ['json', 'json_in', 'json_key', 'json_any', 'json_all', 'json_overlaps'].includes(item[1].toLowerCase())) {
|
|
719
|
+
const op = item[1].toLowerCase();
|
|
720
|
+
const val = lSqlValue.unwrapJson(item[2]);
|
|
721
|
+
if (op === 'json') {
|
|
722
|
+
data.push(lText.stringifyJson(val));
|
|
723
|
+
return this._service === ESERVICE.MYSQL ?
|
|
724
|
+
`JSON_CONTAINS(${this.field(item[0])}, ${this._placeholder()}) AND ` :
|
|
725
|
+
`${this.field(item[0])} @> ${this._placeholder()} AND `;
|
|
726
|
+
}
|
|
727
|
+
if (op === 'json_in') {
|
|
728
|
+
data.push(lText.stringifyJson(val));
|
|
729
|
+
return this._service === ESERVICE.MYSQL ?
|
|
730
|
+
`JSON_CONTAINS(${this._placeholder()}, ${this.field(item[0])}) AND ` :
|
|
731
|
+
`${this.field(item[0])} <@ ${this._placeholder()} AND `;
|
|
732
|
+
}
|
|
733
|
+
if (op === 'json_overlaps') {
|
|
734
|
+
if (this._service === ESERVICE.MYSQL) {
|
|
735
|
+
data.push(lText.stringifyJson(val));
|
|
736
|
+
return `JSON_OVERLAPS(${this.field(item[0])}, ${this._placeholder()}) AND `;
|
|
650
737
|
}
|
|
651
|
-
|
|
652
|
-
|
|
653
|
-
|
|
654
|
-
|
|
655
|
-
|
|
656
|
-
|
|
657
|
-
|
|
658
|
-
|
|
659
|
-
|
|
660
|
-
|
|
661
|
-
|
|
662
|
-
// --- 字段比较 ---
|
|
663
|
-
sql += v0sql + ' ' + v[1] + ' ' + this.field(nv.value) + ' AND ';
|
|
664
|
-
}
|
|
665
|
-
else {
|
|
666
|
-
const result = lSqlValue.isJson(nv) ? this._processValue(nv) : {
|
|
667
|
-
'sql': this._placeholder(),
|
|
668
|
-
'data': [nv],
|
|
669
|
-
};
|
|
670
|
-
sql += v0sql + ' ' + v[1] + ' ' + result.sql + ' AND ';
|
|
671
|
-
data.push(...result.data);
|
|
672
|
-
}
|
|
738
|
+
data.push(val);
|
|
739
|
+
return `${this.field(item[0])} && ${this._placeholder()} AND `;
|
|
740
|
+
}
|
|
741
|
+
// --- json_key, json_any, json_all ---
|
|
742
|
+
const keys = Array.isArray(val) ? val : [val];
|
|
743
|
+
if (this._service === ESERVICE.MYSQL) {
|
|
744
|
+
const mode = op === 'json_all' ? 'all' : 'one';
|
|
745
|
+
let pathSql = '';
|
|
746
|
+
for (const key of keys) {
|
|
747
|
+
pathSql += `, ${this._placeholder()}`;
|
|
748
|
+
data.push(key.startsWith('$') ? key : `$.${key}`);
|
|
673
749
|
}
|
|
750
|
+
return `JSON_CONTAINS_PATH(${this.field(item[0])}, '${mode}'${pathSql}) AND `;
|
|
751
|
+
}
|
|
752
|
+
if (op === 'json_key' && keys.length === 1) {
|
|
753
|
+
data.push(keys[0]);
|
|
754
|
+
return `${this.field(item[0])} ? ${this._placeholder()} AND `;
|
|
755
|
+
}
|
|
756
|
+
const pgOp = op === 'json_all' ? '?&' : '?|';
|
|
757
|
+
data.push(keys);
|
|
758
|
+
return `${this.field(item[0])} ${pgOp} ${this._placeholder()} AND `;
|
|
759
|
+
}
|
|
760
|
+
// --- NULL 比较 ---
|
|
761
|
+
if (item[2] === null) {
|
|
762
|
+
let op;
|
|
763
|
+
if (item[1] === '!=' || item[1] === '!==' || item[1] === '<>') {
|
|
764
|
+
op = 'IS NOT';
|
|
765
|
+
}
|
|
766
|
+
else if (item[1] === '=' || item[1] === '==' || item[1] === '===') {
|
|
767
|
+
op = 'IS';
|
|
674
768
|
}
|
|
675
769
|
else {
|
|
676
|
-
|
|
677
|
-
|
|
678
|
-
|
|
679
|
-
|
|
680
|
-
|
|
681
|
-
|
|
682
|
-
|
|
683
|
-
|
|
684
|
-
|
|
685
|
-
|
|
686
|
-
|
|
687
|
-
|
|
688
|
-
|
|
689
|
-
|
|
690
|
-
|
|
691
|
-
|
|
692
|
-
|
|
693
|
-
|
|
694
|
-
|
|
695
|
-
|
|
696
|
-
|
|
697
|
-
|
|
698
|
-
|
|
699
|
-
|
|
700
|
-
|
|
701
|
-
|
|
702
|
-
|
|
703
|
-
|
|
704
|
-
|
|
705
|
-
|
|
706
|
-
|
|
707
|
-
|
|
708
|
-
|
|
709
|
-
|
|
710
|
-
|
|
711
|
-
|
|
712
|
-
|
|
713
|
-
|
|
714
|
-
|
|
715
|
-
|
|
716
|
-
|
|
717
|
-
|
|
718
|
-
|
|
719
|
-
|
|
770
|
+
op = parseWhereOp(item[1]);
|
|
771
|
+
}
|
|
772
|
+
if (op === null) {
|
|
773
|
+
this._setError(`Invalid SQL WHERE operator: ${String(item[1])}`);
|
|
774
|
+
return '';
|
|
775
|
+
}
|
|
776
|
+
return `${this.field(item[0])} ${op} NULL AND `;
|
|
777
|
+
}
|
|
778
|
+
// --- 集合比较 ---
|
|
779
|
+
if (Array.isArray(item[2]) || (item[2] instanceof Set && typeof item[1] === 'string' && /^(?:NOT )?IN$/i.test(item[1]))) {
|
|
780
|
+
const op = parseWhereOp(item[1]);
|
|
781
|
+
if (op === null) {
|
|
782
|
+
this._setError(`Invalid SQL WHERE operator: ${String(item[1])}`);
|
|
783
|
+
return '';
|
|
784
|
+
}
|
|
785
|
+
return `${this._whereList(item[0], op, item[2], data)} AND `;
|
|
786
|
+
}
|
|
787
|
+
// --- 普通运算符或字段比较 ---
|
|
788
|
+
const op = parseWhereOp(item[1]);
|
|
789
|
+
if (op === null) {
|
|
790
|
+
this._setError(`Invalid SQL WHERE operator: ${String(item[1])}`);
|
|
791
|
+
return '';
|
|
792
|
+
}
|
|
793
|
+
const val = item[2];
|
|
794
|
+
// --- item[0] 也可以是 value() 包裹的字面量值 ---
|
|
795
|
+
const isVal0 = this._isValue(item[0]);
|
|
796
|
+
const leftSql = isVal0 ? this._placeholder() : this.field(item[0]);
|
|
797
|
+
if (isVal0) {
|
|
798
|
+
data.push(item[0].value);
|
|
799
|
+
}
|
|
800
|
+
if (this._isField(val)) {
|
|
801
|
+
return `${leftSql} ${op} ${this.field(val.value)} AND `;
|
|
802
|
+
}
|
|
803
|
+
const res = lSqlValue.isJson(val) ? this._processValue(val) : {
|
|
804
|
+
'sql': this._placeholder(),
|
|
805
|
+
'data': [val],
|
|
806
|
+
};
|
|
807
|
+
data.push(...res.data);
|
|
808
|
+
return `${leftSql} ${op} ${res.sql} AND `;
|
|
809
|
+
}
|
|
810
|
+
/**
|
|
811
|
+
* --- 生成单个对象键的条件 SQL 片段 ---
|
|
812
|
+
* @param key 字段名或 $or/$and 逻辑分组键
|
|
813
|
+
* @param val 条件值
|
|
814
|
+
* @param data 绑定参数列表
|
|
815
|
+
* @returns 带尾随 AND 的 SQL 片段,校验失败或空分组返回空字符串
|
|
816
|
+
*/
|
|
817
|
+
_whereObjectEntry(key, val, data) {
|
|
818
|
+
if (key.startsWith('$')) {
|
|
819
|
+
// --- 逻辑条件分组,仅允许 $or / $and(可带 - 后缀区分多组) ---
|
|
820
|
+
if (!Array.isArray(val) || val.length === 0) {
|
|
821
|
+
return '';
|
|
822
|
+
}
|
|
823
|
+
const logic = key.slice(1).split('-')[0].toUpperCase();
|
|
824
|
+
if (logic !== 'OR' && logic !== 'AND') {
|
|
825
|
+
this._setError(`Invalid SQL logical operator: ${key}`);
|
|
826
|
+
return '';
|
|
827
|
+
}
|
|
828
|
+
const sep = ` ${logic} `;
|
|
829
|
+
let sql = '(';
|
|
830
|
+
for (const sub of val) {
|
|
831
|
+
const subSql = this._whereSub(sub, data);
|
|
832
|
+
sql += this._countConditions(sub) > 1 ? `(${subSql})${sep}` : `${subSql}${sep}`;
|
|
833
|
+
}
|
|
834
|
+
return `${sql.slice(0, -sep.length)}) AND `;
|
|
835
|
+
}
|
|
836
|
+
// --- 单字段条件 ---
|
|
837
|
+
if (val === null) {
|
|
838
|
+
return `${this.field(key)} IS NULL AND `;
|
|
839
|
+
}
|
|
840
|
+
if (lSqlValue.isJson(val)) {
|
|
841
|
+
const res = this._processValue(val);
|
|
842
|
+
data.push(...res.data);
|
|
843
|
+
return `${this.field(key)} = ${res.sql} AND `;
|
|
844
|
+
}
|
|
845
|
+
if (this._isField(val)) {
|
|
846
|
+
return `${this.field(key)} = ${this.field(val.value)} AND `;
|
|
847
|
+
}
|
|
848
|
+
if (Array.isArray(val) || val instanceof Set) {
|
|
849
|
+
return `${this._whereList(key, 'IN', val, data)} AND `;
|
|
850
|
+
}
|
|
851
|
+
data.push(val);
|
|
852
|
+
return `${this.field(key)} = ${this._placeholder()} AND `;
|
|
853
|
+
}
|
|
854
|
+
/**
|
|
855
|
+
* --- 生成 WHERE / HAVING / ON 条件子句 ---
|
|
856
|
+
* @param s 条件对象或条件数组
|
|
857
|
+
* @param data 接收绑定参数的数组,默认使用当前实例的 _data
|
|
858
|
+
* @returns 条件 SQL 片段,无有效条件时返回空字符串
|
|
859
|
+
*/
|
|
860
|
+
_whereSub(s, data) {
|
|
861
|
+
data ??= this._data;
|
|
862
|
+
let sql = '';
|
|
863
|
+
const items = Array.isArray(s) ? s : [s];
|
|
864
|
+
for (const item of items) {
|
|
865
|
+
if (Array.isArray(item)) {
|
|
866
|
+
sql += this._whereArrayItem(item, data);
|
|
867
|
+
}
|
|
868
|
+
else if (item && typeof item === 'object') {
|
|
869
|
+
const obj = item;
|
|
870
|
+
for (const key in obj) {
|
|
871
|
+
sql += this._whereObjectEntry(key, obj[key], data);
|
|
720
872
|
}
|
|
721
873
|
}
|
|
722
874
|
}
|
|
@@ -765,17 +917,27 @@ export class Sql {
|
|
|
765
917
|
* @param d 排序规则
|
|
766
918
|
*/
|
|
767
919
|
by(c, d = 'DESC') {
|
|
920
|
+
const dir = parseOrderDir(d);
|
|
921
|
+
if (dir === null) {
|
|
922
|
+
this._setError('Invalid SQL ORDER BY direction');
|
|
923
|
+
return this;
|
|
924
|
+
}
|
|
768
925
|
let sql = ' ORDER BY ';
|
|
769
926
|
if (typeof c === 'string') {
|
|
770
|
-
sql += this.field(c)
|
|
927
|
+
sql += `${this.field(c)} ${dir}`;
|
|
771
928
|
}
|
|
772
929
|
else {
|
|
773
|
-
for (const
|
|
774
|
-
if (typeof
|
|
775
|
-
sql += this.field(
|
|
930
|
+
for (const item of c) {
|
|
931
|
+
if (typeof item === 'string' || typeof item === 'number') {
|
|
932
|
+
sql += `${this.field(item)} ${dir}, `;
|
|
776
933
|
}
|
|
777
934
|
else {
|
|
778
|
-
|
|
935
|
+
const subDir = parseOrderDir(item[1]);
|
|
936
|
+
if (subDir === null) {
|
|
937
|
+
this._setError('Invalid SQL ORDER BY direction');
|
|
938
|
+
return this;
|
|
939
|
+
}
|
|
940
|
+
sql += `${this.field(item[0])} ${subDir}, `;
|
|
779
941
|
}
|
|
780
942
|
}
|
|
781
943
|
sql = sql.slice(0, -2);
|
|
@@ -789,49 +951,53 @@ export class Sql {
|
|
|
789
951
|
* @param c 排序字段,支持表别名;不支持表达式、GROUP BY 或 UNION
|
|
790
952
|
* @param values 上一页末行的字段值,省略时读取首批
|
|
791
953
|
* @param d 扫描方向;读取前一批时反转方向并在取回后反转列表
|
|
792
|
-
* @returns 当前 SQL
|
|
954
|
+
* @returns 当前 SQL 对象;参数非法时记录构建错误并失败关闭
|
|
793
955
|
*/
|
|
794
956
|
seek(c, values, d = 'DESC') {
|
|
795
957
|
// --- 校验排序字段与现有 SQL 结构 ---
|
|
796
958
|
const fields = typeof c === 'string' ? [c] : c;
|
|
959
|
+
const dir = parseOrderDir(d);
|
|
797
960
|
if (!fields.length || new Set(fields).size !== fields.length ||
|
|
798
961
|
fields.some(field => !/^[a-zA-Z_][a-zA-Z0-9_]*(\.[a-zA-Z_][a-zA-Z0-9_]*)?$/.test(field)) ||
|
|
799
|
-
|
|
800
|
-
|
|
962
|
+
dir === null) {
|
|
963
|
+
this._setError('Invalid cursor ordering');
|
|
964
|
+
return this;
|
|
801
965
|
}
|
|
802
966
|
if (this._sql.some(part => /^ (ORDER BY|LIMIT|GROUP BY|HAVING|UNION|FOR UPDATE)\b/i.test(part))) {
|
|
803
|
-
|
|
967
|
+
this._setError('seek requires an ungrouped query without ordering or pagination');
|
|
968
|
+
return this;
|
|
804
969
|
}
|
|
805
970
|
// --- 传入边界值时追加行比较 WHERE 条件 ---
|
|
806
971
|
if (values !== undefined) {
|
|
807
|
-
if (values.length !== fields.length || values.some(
|
|
808
|
-
(typeof
|
|
809
|
-
|
|
810
|
-
|
|
811
|
-
|
|
812
|
-
const
|
|
813
|
-
const
|
|
814
|
-
const
|
|
815
|
-
|
|
816
|
-
|
|
972
|
+
if (values.length !== fields.length || values.some(val => (typeof val !== 'string' && typeof val !== 'number') ||
|
|
973
|
+
(typeof val === 'number' && (!Number.isFinite(val) || (Number.isInteger(val) && !Number.isSafeInteger(val)))))) {
|
|
974
|
+
this._setError('Invalid cursor values; use strings for large integers');
|
|
975
|
+
return this;
|
|
976
|
+
}
|
|
977
|
+
const cols = fields.map(field => this.field(field));
|
|
978
|
+
const holders = values.map(() => this._placeholder());
|
|
979
|
+
const left = cols.length === 1 ? cols[0] : `(${cols.join(', ')})`;
|
|
980
|
+
const right = holders.length === 1 ? holders[0] : `(${holders.join(', ')})`;
|
|
981
|
+
let cond = `${left} ${dir === 'DESC' ? '<' : '>'} ${right}`;
|
|
982
|
+
if (cols.length > 1) {
|
|
817
983
|
// --- 显式收紧首列边界,避免已有较宽范围条件让 PG 在索引内遍历到行比较边界 ---
|
|
818
|
-
|
|
984
|
+
cond += ` AND ${cols[0]} ${dir === 'DESC' ? '<=' : '>='} ${this._placeholder()}`;
|
|
819
985
|
}
|
|
820
|
-
const
|
|
821
|
-
if (
|
|
986
|
+
const idx = this._sql.findIndex(part => part.startsWith(' WHERE '));
|
|
987
|
+
if (idx === -1) {
|
|
822
988
|
this._whereDataPosition[0] = this._data.length;
|
|
823
|
-
this._sql.push(
|
|
989
|
+
this._sql.push(` WHERE ${cond}`);
|
|
824
990
|
}
|
|
825
991
|
else {
|
|
826
|
-
this._sql[
|
|
992
|
+
this._sql[idx] = ` WHERE (${this._sql[idx].slice(7)}) AND ${cond}`;
|
|
827
993
|
}
|
|
828
994
|
this._data.push(...values);
|
|
829
|
-
if (
|
|
995
|
+
if (cols.length > 1) {
|
|
830
996
|
this._data.push(values[0]);
|
|
831
997
|
}
|
|
832
998
|
this._whereDataPosition[1] = this._data.length;
|
|
833
999
|
}
|
|
834
|
-
return this.by(fields,
|
|
1000
|
+
return this.by(fields, dir);
|
|
835
1001
|
}
|
|
836
1002
|
/**
|
|
837
1003
|
* --- GROUP BY ---
|
|
@@ -853,17 +1019,23 @@ export class Sql {
|
|
|
853
1019
|
}
|
|
854
1020
|
/**
|
|
855
1021
|
* --- LIMIT(limit、offset, limit) ---
|
|
856
|
-
* @param a 起始(offset)
|
|
1022
|
+
* @param a 起始(offset)或仅传单参时的长度(limit)
|
|
857
1023
|
* @param b 长度(limit)
|
|
858
1024
|
*/
|
|
859
1025
|
limit(a, b = 0) {
|
|
860
|
-
|
|
1026
|
+
const first = lText.parseSafeInt(a, { 'min': 0 });
|
|
1027
|
+
const second = lText.parseSafeInt(b, { 'min': 0 });
|
|
1028
|
+
if (first === null || second === null) {
|
|
1029
|
+
this._setError('Invalid SQL limit: must be an integer >= 0');
|
|
1030
|
+
return this;
|
|
1031
|
+
}
|
|
1032
|
+
if (second) {
|
|
861
1033
|
// --- offset, limit ---
|
|
862
|
-
this._sql.push(` LIMIT ${
|
|
1034
|
+
this._sql.push(` LIMIT ${second} OFFSET ${first}`);
|
|
863
1035
|
}
|
|
864
1036
|
else {
|
|
865
1037
|
// --- limit ---
|
|
866
|
-
this._sql.push(` LIMIT ${
|
|
1038
|
+
this._sql.push(` LIMIT ${first}`);
|
|
867
1039
|
}
|
|
868
1040
|
return this;
|
|
869
1041
|
}
|
|
@@ -994,7 +1166,16 @@ export class Sql {
|
|
|
994
1166
|
'data': data,
|
|
995
1167
|
'sql': sql,
|
|
996
1168
|
'alias': lCore.clone(this._alias),
|
|
997
|
-
})
|
|
1169
|
+
});
|
|
1170
|
+
if (this._hint) {
|
|
1171
|
+
result.hint(this._hint);
|
|
1172
|
+
}
|
|
1173
|
+
if (this._hintError) {
|
|
1174
|
+
result._hintError = this._hintError;
|
|
1175
|
+
}
|
|
1176
|
+
if (this._error) {
|
|
1177
|
+
result._error = this._error;
|
|
1178
|
+
}
|
|
998
1179
|
if (opt.where === undefined) {
|
|
999
1180
|
result._whereDataPosition = [...this._whereDataPosition];
|
|
1000
1181
|
}
|
|
@@ -1002,9 +1183,12 @@ export class Sql {
|
|
|
1002
1183
|
}
|
|
1003
1184
|
// --- 操作 ---
|
|
1004
1185
|
/**
|
|
1005
|
-
* --- 获取 sql
|
|
1186
|
+
* --- 获取 sql 语句;存在构建错误时返回空字符串 ---
|
|
1006
1187
|
*/
|
|
1007
1188
|
getSql() {
|
|
1189
|
+
if (this._error) {
|
|
1190
|
+
return '';
|
|
1191
|
+
}
|
|
1008
1192
|
let sql = this._sql.join('');
|
|
1009
1193
|
// --- 注入优化器 Hint 到 SELECT 关键字后 ---
|
|
1010
1194
|
if (this._hint && !sql.includes('/*+')) {
|
|
@@ -1021,9 +1205,12 @@ export class Sql {
|
|
|
1021
1205
|
return sql;
|
|
1022
1206
|
}
|
|
1023
1207
|
/**
|
|
1024
|
-
* --- 获取全部 data ---
|
|
1208
|
+
* --- 获取全部 data;存在构建错误时返回空数组 ---
|
|
1025
1209
|
*/
|
|
1026
1210
|
getData() {
|
|
1211
|
+
if (this._error) {
|
|
1212
|
+
return [];
|
|
1213
|
+
}
|
|
1027
1214
|
return lSqlValue.serializeList(this._data) ?? [];
|
|
1028
1215
|
}
|
|
1029
1216
|
/**
|
|
@@ -1193,18 +1380,48 @@ export class Sql {
|
|
|
1193
1380
|
}
|
|
1194
1381
|
return true;
|
|
1195
1382
|
}
|
|
1383
|
+
/**
|
|
1384
|
+
* --- 判断传入值是否是 raw 表达式对象(由 raw() 函数创建) ---
|
|
1385
|
+
* @param arg 待判断的值
|
|
1386
|
+
*/
|
|
1387
|
+
_isRaw(arg) {
|
|
1388
|
+
return arg !== null &&
|
|
1389
|
+
typeof arg === 'object' &&
|
|
1390
|
+
arg[rawSymbol] === true &&
|
|
1391
|
+
typeof arg.sql === 'string' &&
|
|
1392
|
+
Array.isArray(arg.params);
|
|
1393
|
+
}
|
|
1196
1394
|
/** --- 获取占位符 --- */
|
|
1197
1395
|
_placeholder() {
|
|
1198
1396
|
return this._service === ESERVICE.MYSQL ? '?' : `$${this._placeholderCounter++}`;
|
|
1199
1397
|
}
|
|
1200
1398
|
/**
|
|
1201
|
-
* ---
|
|
1399
|
+
* --- 生成单个值的 SQL 片段和绑定参数 ---
|
|
1202
1400
|
* @param v 要处理的值
|
|
1401
|
+
* @param field 写入字段名
|
|
1402
|
+
* @param row 批量写入行号,从 1 开始
|
|
1403
|
+
* @param table 已格式化的 UPDATE 目标表名,INSERT 从前导取表名
|
|
1404
|
+
* @param parameter SQL 表达式内的参数位置,从 1 开始,嵌套时逐级记录
|
|
1405
|
+
* @returns SQL 片段和绑定参数,异常值沿用空字符串
|
|
1203
1406
|
*/
|
|
1204
|
-
_processValue(v) {
|
|
1407
|
+
_processValue(v, field, row, table, parameter) {
|
|
1205
1408
|
if (v === undefined || Number.isNaN(v)) {
|
|
1206
|
-
// ---
|
|
1207
|
-
|
|
1409
|
+
// --- INSERT 的第一段只有写入前导,后续片段可能包含业务值 ---
|
|
1410
|
+
table ??= /^INSERT (?:IGNORE )?INTO ([\w`".]+)(?: AS [\w`".]+)?$/.exec(this._sql[0] ?? '')?.[1];
|
|
1411
|
+
const route = this._ctr?.getPrototype('_config')?.const;
|
|
1412
|
+
const stack = new Error().stack;
|
|
1413
|
+
const detail = lText.stringifyJson({
|
|
1414
|
+
'value': v === undefined ? 'undefined' : 'NaN',
|
|
1415
|
+
'table': table,
|
|
1416
|
+
'field': field,
|
|
1417
|
+
'row': row,
|
|
1418
|
+
'parameter': parameter,
|
|
1419
|
+
'stack': typeof stack === 'string' ? stack.split('\n').slice(1, 11) : undefined,
|
|
1420
|
+
});
|
|
1421
|
+
lCore.log({
|
|
1422
|
+
'urlFull': route?.urlFull,
|
|
1423
|
+
'path': route?.path,
|
|
1424
|
+
}, `[SQL][_processValue] value error ${detail}`, '-error');
|
|
1208
1425
|
return { 'sql': "''", 'data': [] };
|
|
1209
1426
|
}
|
|
1210
1427
|
else if (v === null) {
|
|
@@ -1219,37 +1436,45 @@ export class Sql {
|
|
|
1219
1436
|
else if (typeof v === 'string' || typeof v === 'number') {
|
|
1220
1437
|
return { 'sql': this._placeholder(), 'data': [v] };
|
|
1221
1438
|
}
|
|
1222
|
-
else if (
|
|
1223
|
-
|
|
1224
|
-
|
|
1225
|
-
|
|
1226
|
-
|
|
1227
|
-
v
|
|
1228
|
-
|
|
1229
|
-
|
|
1230
|
-
|
|
1231
|
-
|
|
1232
|
-
|
|
1233
|
-
const
|
|
1234
|
-
|
|
1235
|
-
|
|
1236
|
-
|
|
1237
|
-
|
|
1238
|
-
|
|
1239
|
-
|
|
1240
|
-
|
|
1241
|
-
|
|
1242
|
-
|
|
1243
|
-
ds.push(...res.data);
|
|
1439
|
+
else if (this._isRaw(v)) {
|
|
1440
|
+
// --- 显式原始 SQL 表达式,对参数按位置分别处理 ---
|
|
1441
|
+
// --- v: raw('POINT(?)', ['20']) ---
|
|
1442
|
+
// --- v: raw('(CASE `id` WHEN 1 THEN ? WHEN 2 THEN ? END)', ['val1', 'val2']) ---
|
|
1443
|
+
if (v.invalid) {
|
|
1444
|
+
this._setError(v.invalid);
|
|
1445
|
+
return { 'sql': 'NULL', 'data': [] };
|
|
1446
|
+
}
|
|
1447
|
+
const sqls = [];
|
|
1448
|
+
const ds = [];
|
|
1449
|
+
for (const p of v.params) {
|
|
1450
|
+
const res = this._processValue(p, field, row, table, `${parameter ?? ''}[${sqls.length + 1}]`);
|
|
1451
|
+
sqls.push(res.sql);
|
|
1452
|
+
ds.push(...res.data);
|
|
1453
|
+
}
|
|
1454
|
+
let i = 0;
|
|
1455
|
+
let overflow = false;
|
|
1456
|
+
const replacedSql = v.sql.replace(/\?/g, () => {
|
|
1457
|
+
if (i >= sqls.length) {
|
|
1458
|
+
overflow = true;
|
|
1459
|
+
return 'NULL';
|
|
1244
1460
|
}
|
|
1245
|
-
|
|
1246
|
-
|
|
1247
|
-
|
|
1248
|
-
|
|
1249
|
-
|
|
1250
|
-
|
|
1461
|
+
return sqls[i++];
|
|
1462
|
+
});
|
|
1463
|
+
if (overflow) {
|
|
1464
|
+
this._setError('Raw SQL placeholder count exceeds parameter count');
|
|
1465
|
+
return { 'sql': 'NULL', 'data': [] };
|
|
1466
|
+
}
|
|
1467
|
+
if (i !== sqls.length) {
|
|
1468
|
+
this._setError('Raw SQL parameter count does not match placeholders');
|
|
1469
|
+
return { 'sql': 'NULL', 'data': [] };
|
|
1251
1470
|
}
|
|
1252
|
-
|
|
1471
|
+
return {
|
|
1472
|
+
'sql': this.field(replacedSql),
|
|
1473
|
+
'data': ds,
|
|
1474
|
+
};
|
|
1475
|
+
}
|
|
1476
|
+
else if (Array.isArray(v)) {
|
|
1477
|
+
if (v[0]?.y !== undefined) {
|
|
1253
1478
|
// --- v: [{'x': 1, 'y': 2}, { ... }, { ... }, ... ]---
|
|
1254
1479
|
if (this._service === ESERVICE.MYSQL) {
|
|
1255
1480
|
// --- MYSQL ---
|
|
@@ -1441,3 +1666,33 @@ export function value(val) {
|
|
|
1441
1666
|
export function json(obj) {
|
|
1442
1667
|
return lSqlValue.json(obj);
|
|
1443
1668
|
}
|
|
1669
|
+
/**
|
|
1670
|
+
* --- 创建显式 SQL 表达式值,用于 INSERT / UPDATE 写入原生 SQL 函数或 CASE 表达式 ---
|
|
1671
|
+
* --- 使用内部私有 Symbol 标记,外部 JSON 无法伪造;普通数组不再自动识别为 SQL 表达式 ---
|
|
1672
|
+
* @param sql 原生 SQL 表达式,参数位置使用 ? 占位
|
|
1673
|
+
* @param params 绑定参数列表
|
|
1674
|
+
* @returns SQL 表达式包装对象
|
|
1675
|
+
*/
|
|
1676
|
+
export function raw(sql, params = []) {
|
|
1677
|
+
if (typeof sql !== 'string' || !sql.trim()) {
|
|
1678
|
+
return {
|
|
1679
|
+
[rawSymbol]: true,
|
|
1680
|
+
'sql': '',
|
|
1681
|
+
'params': [],
|
|
1682
|
+
'invalid': 'Invalid raw SQL expression',
|
|
1683
|
+
};
|
|
1684
|
+
}
|
|
1685
|
+
if (!Array.isArray(params)) {
|
|
1686
|
+
return {
|
|
1687
|
+
[rawSymbol]: true,
|
|
1688
|
+
'sql': '',
|
|
1689
|
+
'params': [],
|
|
1690
|
+
'invalid': 'Invalid raw SQL parameters',
|
|
1691
|
+
};
|
|
1692
|
+
}
|
|
1693
|
+
return {
|
|
1694
|
+
[rawSymbol]: true,
|
|
1695
|
+
'sql': sql,
|
|
1696
|
+
'params': params,
|
|
1697
|
+
};
|
|
1698
|
+
}
|