jsql-neo 6.8.1 → 6.8.3

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.
@@ -155,8 +155,15 @@ function match(doc, query) {
155
155
  return true;
156
156
  }
157
157
 
158
- function applyModifier(doc, update) {
159
- for (const [op, payload] of Object.entries(update)) {
158
+ function applyModifier(doc, update, opts = {}) {
159
+ const allowed = new Set(['$set', '$unset', '$inc', '$mul', '$min', '$max',
160
+ '$push', '$addToSet', '$pop', '$pull', '$rename', '$currentDate', '$bit']);
161
+ for (const [op, payload] of Object.entries(update || {})) {
162
+ if (!op.startsWith('$')) continue;
163
+ if (!allowed.has(op)) {
164
+ if (opts.strict) throw new Error(`unknown modifier: ${op}`);
165
+ continue;
166
+ }
160
167
  if (op === '$set') {
161
168
  for (const [k, v] of Object.entries(payload)) setPath(doc, k, v);
162
169
  } else if (op === '$unset') {
@@ -214,6 +221,25 @@ function applyModifier(doc, update) {
214
221
  // 对象元素按字段匹配。这里用 elementMatch 统一处理,真正把匹配元素移除。
215
222
  if (Array.isArray(arr)) setPath(doc, k, arr.filter(el => !elementMatch(el, v)));
216
223
  }
224
+ } else if (op === '$rename') {
225
+ for (const [from, to] of Object.entries(payload)) {
226
+ const v = getPath(doc, from);
227
+ if (v !== undefined) { setPath(doc, to, v); unsetPath(doc, from); }
228
+ }
229
+ } else if (op === '$currentDate') {
230
+ const now = new Date().toISOString();
231
+ for (const [k, v] of Object.entries(payload)) {
232
+ if (v === true || (v && typeof v === 'object') || v === '$type') setPath(doc, k, now);
233
+ }
234
+ } else if (op === '$bit') {
235
+ for (const [k, bits] of Object.entries(payload)) {
236
+ const cur = Number(getPath(doc, k)) || 0;
237
+ let v = cur;
238
+ if (bits && bits.and !== undefined) v = v & Number(bits.and);
239
+ if (bits && bits.or !== undefined) v = v | Number(bits.or);
240
+ if (bits && bits.xor !== undefined) v = v ^ Number(bits.xor);
241
+ setPath(doc, k, v);
242
+ }
217
243
  }
218
244
  }
219
245
  return doc;
@@ -525,4 +551,4 @@ function rowId(row, all) {
525
551
  return idx === -1 ? undefined : idx + 1;
526
552
  }
527
553
 
528
- module.exports = { Datastore, Cursor };
554
+ module.exports = { Datastore, Cursor, getPath, setPath, unsetPath, applyModifier };
package/lib/sql.js CHANGED
@@ -210,6 +210,29 @@ function jsonPathGet(data, path, notFound) {
210
210
  return current === undefined ? miss : current;
211
211
  }
212
212
 
213
+ /**
214
+ * 解析 JSONPath,返回 { parent, key } 供 JSON_ARRAY_APPEND / JSON_ARRAY_INSERT 就地修改。
215
+ * 支持 $.a.b 与 $.a[1](末尾带下标时 parent 就是数组、key 是数值下标)。
216
+ */
217
+ function jsonPathParent(data, path) {
218
+ const p = String(path == null ? '' : path).replace(/^\$\.?/, '');
219
+ if (!p) return null;
220
+ const arr = p.match(/^(.*)\[(\d+)\]$/);
221
+ if (arr) {
222
+ const base = arr[1].replace(/\.$/, '');
223
+ const owner = base ? jsonPathGet(data, '$.' + base) : data;
224
+ return (owner && typeof owner === 'object') ? { parent: owner, key: parseInt(arr[2], 10) } : null;
225
+ }
226
+ const segs = p.split('.');
227
+ const key = segs.pop();
228
+ let parent = data;
229
+ for (const s of segs) {
230
+ if (parent == null || typeof parent !== 'object') return null;
231
+ parent = parent[s];
232
+ }
233
+ return (parent && typeof parent === 'object') ? { parent, key } : null;
234
+ }
235
+
213
236
  /**
214
237
  * 16 进制整数字面量(0x?? / X'??')的精确解析(Issue #38)。
215
238
  *
@@ -346,6 +369,18 @@ function tokenize(sql) {
346
369
  }
347
370
  }
348
371
 
372
+ // 2 进制字面量:0b1010 / 0B1010(MySQL 8.0)
373
+ if (c === '0' && (sql[i + 1] === 'b' || sql[i + 1] === 'B')) {
374
+ let j = i + 2;
375
+ while (j < n && (sql[j] === '0' || sql[j] === '1')) j++;
376
+ if (j === i + 2) throw new Error(`Invalid binary literal at position ${i}`);
377
+ const bits = sql.slice(i + 2, j);
378
+ const b = BigInt('0b' + bits);
379
+ tokens.push(new SQLToken('number', b <= BigInt(Number.MAX_SAFE_INTEGER) ? Number(b) : b, i));
380
+ i = j;
381
+ continue;
382
+ }
383
+
349
384
  if (/[0-9]/.test(c) || (c === '.' && /[0-9]/.test(sql[i + 1] || ''))) {
350
385
  let j = i;
351
386
  let isFloat = false;
@@ -491,7 +526,8 @@ function tokenize(sql) {
491
526
  // 聚合函数集合:这些必须走 aggregate 节点,否则会被当成逐行标量函数(返回 null 且不折叠行)
492
527
  const AGG_FUNCS = new Set(['SUM', 'AVG', 'MIN', 'MAX', 'COUNT',
493
528
  'GROUP_CONCAT', 'STDDEV', 'STD', 'STDDEV_POP', 'STDDEV_SAMP',
494
- 'VARIANCE', 'VAR_POP', 'VAR_SAMP', 'FIRST', 'LAST']);
529
+ 'VARIANCE', 'VAR_POP', 'VAR_SAMP', 'FIRST', 'LAST',
530
+ 'BIT_AND', 'BIT_OR', 'BIT_XOR']);
495
531
 
496
532
  // 方差/标准差族(Issue #114):MySQL 里无后缀的 VARIANCE / STDDEV / STD
497
533
  // 都是**总体**口径(= VAR_POP / STDDEV_POP),不是样本。
@@ -1306,10 +1342,12 @@ class Parser {
1306
1342
  const ops = ['+', '-', '*', '/', '%', '<<', '>>', '&', '|', '^'];
1307
1343
  for (;;) {
1308
1344
  const opTok = this.peek();
1309
- if (opTok.type !== 'op' || !ops.includes(opTok.value)) break;
1345
+ // MySQL 允许中缀 MOD(SELECT 5 MOD 2),与 % 同一优先级/语义
1346
+ const isModWord = this.isWord('MOD');
1347
+ if (!isModWord && (opTok.type !== 'op' || !ops.includes(opTok.value))) break;
1310
1348
  this.next();
1311
1349
  const right = this.parseValueAtom();
1312
- left = { type: 'binary', op: opTok.value, left, right };
1350
+ left = { type: 'binary', op: isModWord ? '%' : opTok.value, left, right };
1313
1351
  }
1314
1352
  return left;
1315
1353
  }
@@ -2807,6 +2845,13 @@ class Parser {
2807
2845
  if (this.isWord('LEADING') || this.isWord('TRAILING') || this.isWord('BOTH')) {
2808
2846
  spec = String(this.next().value).toUpperCase();
2809
2847
  }
2848
+ // TRIM({BOTH|LEADING|TRAILING} FROM str):省略 remstr,默认裁剪空格
2849
+ if (spec && this.isWord('FROM')) {
2850
+ this.next();
2851
+ const target = this.parseOperand();
2852
+ this.expect('op', ')');
2853
+ return { type: 'func', name: 'TRIM', args: [target, { type: 'value', value: null }, { type: 'value', value: spec }] };
2854
+ }
2810
2855
  const first = this.parseOperand();
2811
2856
  let target = null;
2812
2857
  if (this.isWord('FROM')) {
@@ -3053,6 +3098,13 @@ class Parser {
3053
3098
  node = { type: 'arith', op: 'DIV', left: node, right };
3054
3099
  continue;
3055
3100
  }
3101
+ // MySQL 中缀取模:5 MOD 2(与 % 同优先级,复用 % 的求值路径)
3102
+ if (this.isWord('MOD')) {
3103
+ this.next();
3104
+ const right = this.parsePostfix(this.parseOperand());
3105
+ node = { type: 'arith', op: '%', left: node, right };
3106
+ continue;
3107
+ }
3056
3108
  break;
3057
3109
  }
3058
3110
  return node;
@@ -4016,7 +4068,7 @@ function strftime(d, fmt) {
4016
4068
  '%M': MONTH_NAMES[d.getUTCMonth()], '%b': MONTH_NAMES[d.getUTCMonth()].slice(0, 3),
4017
4069
  '%W': DAY_NAMES[d.getUTCDay()], '%a': DAY_NAMES[d.getUTCDay()].slice(0, 3),
4018
4070
  '%w': String(d.getUTCDay()),
4019
- '%j': String(Math.round((d - Date.UTC(d.getUTCFullYear(), 0, 0)) / 86400000)),
4071
+ '%j': String(Math.round((d - Date.UTC(d.getUTCFullYear(), 0, 0)) / 86400000)).padStart(3, '0'),
4020
4072
  '%%': '%',
4021
4073
  };
4022
4074
  return String(fmt).replace(/%[A-Za-z%]/g, (m) => (m in map ? map[m] : m));
@@ -4067,33 +4119,42 @@ function strToDate(s, fmt) {
4067
4119
  const m = new RegExp('^' + pattern + '$').exec(String(s));
4068
4120
  if (!m) return null;
4069
4121
  let year = 1970, month = 0, day = 1, hour = 0, min = 0, sec = 0;
4122
+ let invalid = false;
4123
+ const inRange = (v, lo, hi) => Number.isFinite(v) && v >= lo && v <= hi;
4070
4124
  order.forEach((c, idx) => {
4071
4125
  const v = m[idx + 1];
4072
4126
  if (v === undefined) return;
4127
+ const num = Number(v);
4073
4128
  switch (c) {
4074
- case 'Y': year = Number(v); break;
4075
- case 'y': year = Number(v) < 70 ? 2000 + Number(v) : 1900 + Number(v); break;
4076
- case 'm': case 'c': month = Number(v) - 1; break;
4129
+ case 'Y': year = num; if (!inRange(year, 0, 9999)) invalid = true; break;
4130
+ case 'y': year = num < 70 ? 2000 + num : 1900 + num; break;
4131
+ case 'm': case 'c': month = num - 1; if (!inRange(num, 1, 12)) invalid = true; break;
4077
4132
  case 'M': case 'b': {
4078
4133
  const mi = MONTH_NAMES.findIndex((x) => x.toLowerCase().startsWith(String(v).toLowerCase().slice(0, 3)));
4079
4134
  if (mi >= 0) month = mi;
4080
4135
  break;
4081
4136
  }
4082
- case 'd': case 'e': day = Number(v); break;
4083
- case 'H': case 'k': hour = Number(v); break;
4137
+ case 'd': case 'e': day = num; if (!inRange(num, 1, 31)) invalid = true; break;
4138
+ case 'H': case 'k': hour = num; if (!inRange(num, 0, 23)) invalid = true; break;
4084
4139
  case 'h': case 'I': case 'l': {
4085
- const hh = Number(v) % 12;
4140
+ if (!inRange(num, 1, 12)) { invalid = true; break; }
4141
+ const hh = num % 12;
4086
4142
  hour = /pm/i.test(String(s)) ? hh + 12 : hh;
4087
4143
  break;
4088
4144
  }
4089
- case 'i': min = Number(v); break;
4090
- case 'S': case 's': sec = Number(v); break;
4145
+ case 'i': min = num; if (!inRange(num, 0, 59)) invalid = true; break;
4146
+ case 'S': case 's': sec = num; if (!inRange(num, 0, 59)) invalid = true; break;
4091
4147
  default: break;
4092
4148
  }
4093
4149
  });
4150
+ if (invalid) return null;
4094
4151
  // 无时区 → UTC 墙上时间(与 parseSqlDate 一致)
4095
4152
  const d = new Date(Date.UTC(year, month, day, hour, min, sec));
4096
- return Number.isNaN(d.getTime()) ? null : d;
4153
+ if (Number.isNaN(d.getTime())) return null;
4154
+ // 回读校验:JS 会把 2 月 30 日归一到 3 月 1 日;MySQL 对非法日历日期返回 NULL
4155
+ if (d.getUTCFullYear() !== year || d.getUTCMonth() !== month || d.getUTCDate() !== day ||
4156
+ d.getUTCHours() !== hour || d.getUTCMinutes() !== min || d.getUTCSeconds() !== sec) return null;
4157
+ return d;
4097
4158
  }
4098
4159
 
4099
4160
  /** PG DATE_PART / EXTRACT 的部件取值(UTC 部件) */
@@ -4176,6 +4237,31 @@ const MATH_SCALAR_FNS = new Set([
4176
4237
  'SIN', 'COS', 'TAN', 'ASIN', 'ACOS', 'ATAN', 'ATAN2',
4177
4238
  'DEGREES', 'RADIANS', 'COT',
4178
4239
  ]);
4240
+ // NULLIF 等场景需要 SQL 风格的等值比较:数字与数字字符串按数值比较,
4241
+ // 不能用 JS 的 ===(1 === '1' 为 false,而 MySQL 里 1 = '1' 为真)。
4242
+ function sqlValuesEqual(a, b) {
4243
+ if (a === b) return true;
4244
+ if (a == null || b == null) return false;
4245
+ const numeric = v => typeof v === 'number' || typeof v === 'bigint'
4246
+ || (typeof v === 'string' && v.trim() !== '' && Number.isFinite(Number(v)));
4247
+ const hasNumericOperand = typeof a === 'number' || typeof a === 'bigint'
4248
+ || typeof b === 'number' || typeof b === 'bigint';
4249
+ if (hasNumericOperand && numeric(a) && numeric(b)) return Number(a) === Number(b);
4250
+ return String(a) === String(b);
4251
+ }
4252
+
4253
+ // 判断表达式节点是否带有 BINARY 语义(BINARY x / CAST(x AS BINARY));
4254
+ // LIKE / REGEXP 默认大小写不敏感,带 BINARY 时必须按字节大小写敏感比较。
4255
+ function isBinaryNode(node) {
4256
+ if (!node || typeof node !== 'object') return false;
4257
+ if (node.type === 'binary') return true;
4258
+ if (node.type === 'cast') {
4259
+ const dt = typeof node.dataType === 'string' ? node.dataType : '';
4260
+ return /\b(BINARY|VARBINARY|BLOB)\b/i.test(dt);
4261
+ }
4262
+ return false;
4263
+ }
4264
+
4179
4265
  function applyScalarFunction(fnNode, row, ctx) {
4180
4266
  const name = (fnNode.name || '').toUpperCase();
4181
4267
  const rawArgs = fnNode.args || [];
@@ -4196,12 +4282,37 @@ function applyScalarFunction(fnNode, row, ctx) {
4196
4282
  switch (name) {
4197
4283
  case 'ABS': return v < 0n ? -v : v;
4198
4284
  case 'SIGN': return v > 0n ? 1 : (v < 0n ? -1 : 0);
4199
- case 'FLOOR': case 'CEIL': case 'CEILING': case 'ROUND': case 'TRUNCATE':
4285
+ case 'FLOOR': case 'CEIL': case 'CEILING':
4200
4286
  return v; // 整数本身就是它的 floor/ceil/round
4287
+ case 'ROUND': case 'TRUNCATE': {
4288
+ const d = args[1];
4289
+ if (d == null || d === 0 || d === 0n) return v;
4290
+ const di = typeof d === 'bigint' ? Number(d) : Math.trunc(Number(d));
4291
+ if (!Number.isFinite(di) || di >= 0) return v;
4292
+ const factor = 10n ** BigInt(-di);
4293
+ const q = v / factor;
4294
+ if (name === 'TRUNCATE') return q * factor;
4295
+ const r = v % factor;
4296
+ const ar = r < 0n ? -r : r;
4297
+ let rounded = q;
4298
+ if (ar * 2n >= factor) rounded += (v < 0n ? -1n : 1n);
4299
+ return rounded * factor;
4300
+ }
4201
4301
  case 'MOD': {
4202
4302
  const d = args[1];
4203
4303
  if (d == null || d === 0 || d === 0n) return null;
4204
- return v % (typeof d === 'bigint' ? d : BigInt(Math.trunc(Number(d))));
4304
+ if (typeof d === 'bigint') return v % d;
4305
+ const dn = Number(d);
4306
+ if (!Number.isFinite(dn)) return null;
4307
+ if (Number.isInteger(dn)) return v % BigInt(dn);
4308
+ // 小数除数:MySQL 按浮点语义求值,避免 BigInt(Math.trunc(...)) 截断为 0
4309
+ // 以及大整数经 Number() 丢失精度。用整数缩放保持精确余数。
4310
+ const decimals = (String(dn).split('.')[1] || '').length;
4311
+ const scale = 10 ** decimals;
4312
+ const dInt = BigInt(Math.round(dn * scale));
4313
+ if (dInt === 0n) return null;
4314
+ const remScaled = (v * BigInt(scale)) % dInt;
4315
+ return Number(remScaled) / scale;
4205
4316
  }
4206
4317
  case 'POWER': case 'POW': {
4207
4318
  const e = args[1];
@@ -4224,6 +4335,7 @@ function applyScalarFunction(fnNode, row, ctx) {
4224
4335
  }
4225
4336
  switch (name) {
4226
4337
  case 'VERSION': return '8.0.0-jsql-neo';
4338
+ case 'PI': return Math.PI;
4227
4339
  case 'LAST_INSERT_ID':
4228
4340
  case 'LAST_INSERT_ROWID': {
4229
4341
  if (args.length > 0) {
@@ -4280,10 +4392,14 @@ function applyScalarFunction(fnNode, row, ctx) {
4280
4392
  case 'TRIM': {
4281
4393
  if (args[0] == null) return null;
4282
4394
  const s = String(args[0]);
4395
+ const spec = args[2] ? String(args[2]).toUpperCase() : 'BOTH';
4283
4396
  if (args.length === 1) return s.trim();
4284
4397
  const chars = args[1] == null ? '' : String(args[1]);
4285
- if (!chars) return s.trim();
4286
- const spec = args[2] ? String(args[2]).toUpperCase() : 'BOTH';
4398
+ if (!chars) {
4399
+ if (spec === 'LEADING') return s.replace(/^\s+/, '');
4400
+ if (spec === 'TRAILING') return s.replace(/\s+$/, '');
4401
+ return s.trim();
4402
+ }
4287
4403
  const esc = chars.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
4288
4404
  const head = new RegExp('^[' + esc + ']+');
4289
4405
  const tail = new RegExp('[' + esc + ']+$');
@@ -4318,8 +4434,16 @@ function applyScalarFunction(fnNode, row, ctx) {
4318
4434
  const base = parseSqlDate(args[0]);
4319
4435
  if (!base) return null;
4320
4436
  const iv = args[1];
4321
- if (!iv || !iv.__interval) return fmtSqlDate(String(args[0]).length <= 10, base);
4322
4437
  const isDateOnly = String(args[0]).trim().length <= 10;
4438
+ // MySQL 两参数形式:ADDDATE(date, N) = DATE_ADD(date, INTERVAL N DAY)
4439
+ if (iv && !iv.__interval && typeof iv !== 'object') {
4440
+ const days = Number(iv);
4441
+ if (!Number.isFinite(days)) return null;
4442
+ const d = new Date(base.getTime());
4443
+ d.setUTCDate(d.getUTCDate() + sign * Math.trunc(days));
4444
+ return fmtSqlDate(isDateOnly, d);
4445
+ }
4446
+ if (!iv || !iv.__interval) return fmtSqlDate(isDateOnly, base);
4323
4447
  const d = new Date(base.getTime());
4324
4448
  const n = sign * Number(iv.value || 0);
4325
4449
  switch (String(iv.unit || '').toUpperCase()) {
@@ -4415,16 +4539,17 @@ function applyScalarFunction(fnNode, row, ctx) {
4415
4539
  // TIMESTAMPDIFF(MONTH,'2026-01-31','2026-03-01') = 1(1/31+1月=2/28,2/28+1月=3/28,够不到 3/1)
4416
4540
  let months = (a.getUTCFullYear() - b.getUTCFullYear()) * 12 + (a.getUTCMonth() - b.getUTCMonth());
4417
4541
  if (a.getUTCDate() < b.getUTCDate()) months--;
4542
+ // MySQL 对负差值按「向零截断」取整;Math.floor 会向 -∞ 多减 1。
4418
4543
  switch (unit) {
4419
- case 'MICROSECOND': return Math.floor(ms * 1000);
4420
- case 'SECOND': return Math.floor(ms / 1000);
4421
- case 'MINUTE': return Math.floor(ms / 60000);
4422
- case 'HOUR': return Math.floor(ms / 3600000);
4423
- case 'DAY': return Math.floor(ms / 86400000);
4424
- case 'WEEK': return Math.floor(ms / (86400000 * 7));
4544
+ case 'MICROSECOND': return Math.trunc(ms * 1000);
4545
+ case 'SECOND': return Math.trunc(ms / 1000);
4546
+ case 'MINUTE': return Math.trunc(ms / 60000);
4547
+ case 'HOUR': return Math.trunc(ms / 3600000);
4548
+ case 'DAY': return Math.trunc(ms / 86400000);
4549
+ case 'WEEK': return Math.trunc(ms / (86400000 * 7));
4425
4550
  case 'MONTH': return months;
4426
- case 'QUARTER': return Math.floor(months / 3);
4427
- case 'YEAR': return Math.floor(months / 12);
4551
+ case 'QUARTER': return Math.trunc(months / 3);
4552
+ case 'YEAR': return Math.trunc(months / 12);
4428
4553
  default: return null;
4429
4554
  }
4430
4555
  }
@@ -4482,7 +4607,7 @@ function applyScalarFunction(fnNode, row, ctx) {
4482
4607
  case 'MAKEDATE': {
4483
4608
  const y = Number(args[0]);
4484
4609
  const doy = Number(args[1]);
4485
- if (!Number.isFinite(y) || !Number.isFinite(doy)) return null;
4610
+ if (!Number.isFinite(y) || !Number.isFinite(doy) || doy < 1) return null;
4486
4611
  const d = new Date(Date.UTC(y, 0, 1));
4487
4612
  d.setUTCDate(doy);
4488
4613
  return fmtSqlDate(true, d);
@@ -4591,11 +4716,24 @@ function applyScalarFunction(fnNode, row, ctx) {
4591
4716
  const from = Math.trunc(Number(args[1])), to = Math.trunc(Number(args[2]));
4592
4717
  if (from < 2 || from > 36 || to < 2 || to > 36) return null;
4593
4718
  const digits = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ';
4594
- let n = 0n;
4595
- for (const ch of String(args[0]).trim().toUpperCase()) {
4596
- const d = digits.indexOf(ch);
4597
- if (d < 0 || d >= from) return null;
4598
- n = n * BigInt(from) + BigInt(d);
4719
+ let n;
4720
+ if (typeof args[0] === 'number' || typeof args[0] === 'bigint') {
4721
+ // 数值参数本身就是十进制整数;负数按 64 位无符号(补码)处理
4722
+ const num = typeof args[0] === 'bigint' ? args[0] : BigInt(Math.trunc(Number(args[0])));
4723
+ n = BigInt.asUintN(64, num);
4724
+ } else {
4725
+ let raw = String(args[0]).trim().toUpperCase();
4726
+ let neg = false;
4727
+ if (raw[0] === '-') { neg = true; raw = raw.slice(1); }
4728
+ else if (raw[0] === '+') raw = raw.slice(1);
4729
+ if (!raw) return null;
4730
+ n = 0n;
4731
+ for (const ch of raw) {
4732
+ const d = digits.indexOf(ch);
4733
+ if (d < 0 || d >= from) return null;
4734
+ n = n * BigInt(from) + BigInt(d);
4735
+ }
4736
+ if (neg) n = BigInt.asUintN(64, -n);
4599
4737
  }
4600
4738
  if (n === 0n) return '0';
4601
4739
  let out = '';
@@ -4621,6 +4759,40 @@ function applyScalarFunction(fnNode, row, ctx) {
4621
4759
  if (p < 1 || p > str.length + 1 || l < 0) return str;
4622
4760
  return str.slice(0, p - 1) + String(ins) + str.slice(p - 1 + l);
4623
4761
  }
4762
+ case 'STRCMP': {
4763
+ if (args[0] == null || args[1] == null) return null;
4764
+ const a = String(args[0]), b = String(args[1]);
4765
+ return a < b ? -1 : (a > b ? 1 : 0);
4766
+ }
4767
+ case 'JSON_ARRAY_APPEND': {
4768
+ // JSON_ARRAY_APPEND(json, path, val, ...):把值追加到 path 指向的数组
4769
+ if (args[0] == null) return null;
4770
+ let data = args[0];
4771
+ if (typeof data === 'string') { try { data = JSON.parse(data); } catch (e) { return null; } }
4772
+ data = JSON.parse(JSON.stringify(data));
4773
+ for (let i = 1; i + 1 < args.length; i += 2) {
4774
+ const loc = jsonPathParent(data, args[i]);
4775
+ if (!loc) continue;
4776
+ const cur = loc.parent[loc.key];
4777
+ const arr = Array.isArray(cur) ? cur : [];
4778
+ arr.push(args[i + 1]);
4779
+ loc.parent[loc.key] = arr;
4780
+ }
4781
+ return data;
4782
+ }
4783
+ case 'JSON_ARRAY_INSERT': {
4784
+ // JSON_ARRAY_INSERT(json, path, val, ...):在 path 的数值下标处插入
4785
+ if (args[0] == null) return null;
4786
+ let data = args[0];
4787
+ if (typeof data === 'string') { try { data = JSON.parse(data); } catch (e) { return null; } }
4788
+ data = JSON.parse(JSON.stringify(data));
4789
+ for (let i = 1; i + 1 < args.length; i += 2) {
4790
+ const loc = jsonPathParent(data, args[i]);
4791
+ if (!loc || !Number.isInteger(loc.key) || !Array.isArray(loc.parent)) continue;
4792
+ loc.parent.splice(Math.max(0, loc.key), 0, args[i + 1]);
4793
+ }
4794
+ return data;
4795
+ }
4624
4796
  case 'INET_ATON': {
4625
4797
  if (args[0] == null) return null;
4626
4798
  const m = String(args[0]).match(/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/);
@@ -4631,7 +4803,9 @@ function applyScalarFunction(fnNode, row, ctx) {
4631
4803
  }
4632
4804
  case 'INET_NTOA': {
4633
4805
  if (args[0] == null) return null;
4634
- const n = Number(args[0]) >>> 0;
4806
+ const n = Number(args[0]);
4807
+ // MySQL:越界(负数 / > 2^32-1 / 非整数)返回 NULL,`>>> 0` 的静默截断会伪造合法 IP
4808
+ if (!Number.isFinite(n) || !Number.isInteger(n) || n < 0 || n > 4294967295) return null;
4635
4809
  return [(n >>> 24) & 255, (n >>> 16) & 255, (n >>> 8) & 255, n & 255].join('.');
4636
4810
  }
4637
4811
  case 'FORMAT': {
@@ -4779,7 +4953,7 @@ function applyScalarFunction(fnNode, row, ctx) {
4779
4953
  const hit = args.find(a => a != null);
4780
4954
  return hit === undefined ? null : hit;
4781
4955
  }
4782
- case 'NULLIF': return args[0] === args[1] ? null : args[0];
4956
+ case 'NULLIF': return sqlValuesEqual(args[0], args[1]) ? null : args[0];
4783
4957
  case 'IF': return args[0] ? args[1] : args[2];
4784
4958
  case 'REPLACE': return args[0] == null ? null : String(args[0]).split(args[1]).join(args[2]);
4785
4959
  case 'REPEAT': {
@@ -5817,7 +5991,8 @@ function evaluateExpr(expr, row, ctx) {
5817
5991
  const v = resolveOperand(expr.operand, row, ctx);
5818
5992
  // MySQL 的 LIKE 默认不区分大小写;只有显式 BINARY / ci=false 才敏感。
5819
5993
  // 此前写成 !!expr.ci,把 likeMatch 的 ci 默认值 true 覆盖成了 false。
5820
- const r = likeMatch(v, expr.pattern, expr.ci !== false, expr.escape);
5994
+ const binaryCmp = isBinaryNode(expr.operand) || isBinaryNode(expr.pattern);
5995
+ const r = likeMatch(v, expr.pattern, expr.ci !== false && !binaryCmp, expr.escape);
5821
5996
  // #94:NULL LIKE → UNKNOWN(null);NOT (NULL LIKE) 仍为 UNKNOWN(null)。
5822
5997
  if (r === null) return null;
5823
5998
  return expr.not ? !r : r;
@@ -5830,7 +6005,8 @@ function evaluateExpr(expr, row, ctx) {
5830
6005
  const v = resolveOperand(expr.operand, row, ctx);
5831
6006
  if (v === null || v === undefined) return false;
5832
6007
  // REGEXP / RLIKE 历史上就是大小写不敏感的;`~` 敏感、`~*` 不敏感
5833
- const re = new RegExp(String(expr.pattern), expr.ci === false ? '' : 'i');
6008
+ const binaryCmp = isBinaryNode(expr.operand) || isBinaryNode(expr.pattern);
6009
+ const re = new RegExp(String(expr.pattern), (expr.ci === false || binaryCmp) ? '' : 'i');
5834
6010
  const r = re.test(String(v));
5835
6011
  return expr.not ? !r : r;
5836
6012
  }
@@ -6635,8 +6811,8 @@ class SQLExecutor {
6635
6811
  } else if (typeof this.engine._ensureTable === 'function') {
6636
6812
  const tbl = this.engine._ensureTable(tName) || (this.engine._tables && this.engine._tables[tName]);
6637
6813
  if (tbl && typeof tbl.createIndex === 'function') {
6638
- // Table.createIndex 目前是单字段接口,复合索引按逐列建
6639
- for (const col of statement.columns) tbl.createIndex(col);
6814
+ // 把 UNIQUE 与复合列一起传给 Table,使其注册唯一约束(不只是加速索引)
6815
+ tbl.createIndex(statement.columns.slice(), { unique: !!statement.unique, name: statement.name });
6640
6816
  handled = true;
6641
6817
  }
6642
6818
  }
@@ -7758,6 +7934,21 @@ class SQLExecutor {
7758
7934
  }
7759
7935
  return best;
7760
7936
  }
7937
+ if (fn === 'BIT_AND' || fn === 'BIT_OR' || fn === 'BIT_XOR') {
7938
+ // MySQL:64 位无符号按位聚合;空集 BIT_AND 为全 1,BIT_OR/BIT_XOR 为 0
7939
+ let acc = fn === 'BIT_AND' ? (1n << 64n) - 1n : 0n;
7940
+ for (const v of values) {
7941
+ let n;
7942
+ if (typeof v === 'bigint') n = v;
7943
+ else if (typeof v === 'number' && Number.isFinite(v)) n = BigInt(Math.trunc(v));
7944
+ else if (typeof v === 'string' && /^[-+]?\d+$/.test(v.trim())) n = BigInt(v.trim());
7945
+ else continue;
7946
+ if (fn === 'BIT_AND') acc &= n;
7947
+ else if (fn === 'BIT_OR') acc |= n;
7948
+ else acc ^= n;
7949
+ }
7950
+ return (acc >= SAFE_MIN && acc <= SAFE_MAX) ? Number(acc) : acc;
7951
+ }
7761
7952
  if (fn === 'FIRST') return values.length ? values[0] : null;
7762
7953
  if (fn === 'LAST') return values.length ? values[values.length - 1] : null;
7763
7954
  if (fn === 'GROUP_CONCAT') {
@@ -290,8 +290,19 @@ class Statement {
290
290
  return { changes: r && typeof r.changes === 'number' ? parseInt(r.changes, 10) : 0, lastInsertRowid: r && (r.lastInsertRowid !== undefined && r.lastInsertRowid !== null) ? r.lastInsertRowid : 0, _stmt: this };
291
291
  }
292
292
 
293
+ // better-sqlite3 的 raw()/pluck() 对 get/all/iterate 一致生效
294
+ _shapeOne(row) {
295
+ if (row == null) return row;
296
+ if (this._rawMode && typeof row === 'object' && !Array.isArray(row)) row = Object.values(row);
297
+ if (this._pluck) {
298
+ if (Array.isArray(row)) return row[0];
299
+ if (typeof row === 'object') { const k = Object.keys(row)[0]; return k === undefined ? undefined : row[k]; }
300
+ }
301
+ return row;
302
+ }
303
+
293
304
  get(...params) {
294
- return this._call('get', params.length > 0 ? params : undefined);
305
+ return this._shapeOne(this._call('get', params.length > 0 ? params : undefined));
295
306
  }
296
307
 
297
308
  all(...params) {
package/lib/table.js CHANGED
@@ -208,6 +208,7 @@ class Table {
208
208
  this.__rows = [];
209
209
  this._indexes = {}; // 旧版 hash 索引(兼容)
210
210
  this._btrees = {}; // B-Tree 索引 { fieldName: BTree }
211
+ this._uniqueIndexes = []; // CREATE UNIQUE INDEX 注册的(复合)唯一索引
211
212
  this._autoIncrement = 0;
212
213
  this._dirty = false;
213
214
  this._hooks = {
@@ -537,6 +538,7 @@ class Table {
537
538
  if (row[field] !== undefined && row[field] !== null) uniqueTracker[field].add(row[field]);
538
539
  }
539
540
  }
541
+ const compositeUniqueSets = this._compositeUniqueSets();
540
542
  const autoIncField = this._autoIncrementField;
541
543
  const defaults = this._defaults;
542
544
  const computedFields = this._computedFields;
@@ -594,6 +596,7 @@ class Table {
594
596
  }
595
597
  // CHECK 约束统一在列循环外整体校验(支持跨列/表级约束)
596
598
  this._enforceChecks(data);
599
+ this._checkCompositeUnique(data, -1, compositeUniqueSets);
597
600
  // 主键唯一性检查(主键可能不在 _cachedUniqueFields 中)
598
601
  if (this._primaryKey && data[this._primaryKey] !== undefined && data[this._primaryKey] !== null) {
599
602
  const pkVal = data[this._primaryKey];
@@ -1209,7 +1212,24 @@ class Table {
1209
1212
  // 索引
1210
1213
  // ============================================================
1211
1214
 
1212
- createIndex(field) {
1215
+ createIndex(field, opts) {
1216
+ // CREATE [UNIQUE] INDEX:支持复合列与唯一约束注册
1217
+ if (Array.isArray(field) || (opts && (opts.unique || opts.name))) {
1218
+ const columns = Array.isArray(field) ? field.slice() : [field];
1219
+ if (opts && opts.unique) {
1220
+ const key = columns.join('\u001f');
1221
+ if (!this._uniqueIndexes.some(u => u.key === key)) {
1222
+ this._uniqueIndexes.push({ name: opts.name, columns, key });
1223
+ }
1224
+ // 单列唯一索引复用 schema.unique 的成熟校验路径(insert/update 全覆盖)
1225
+ if (columns.length === 1 && this._schema[columns[0]]) {
1226
+ this._schema[columns[0]].unique = true;
1227
+ if (!this._cachedUniqueFields.includes(columns[0])) this._cachedUniqueFields.push(columns[0]);
1228
+ }
1229
+ }
1230
+ for (const col of columns) if (!this._indexes[col]) this.createIndex(col);
1231
+ return this._uniqueIndexes;
1232
+ }
1213
1233
  this._indexes[field] = new Map();
1214
1234
  for (let i = 0; i < this._rows.length; i++) {
1215
1235
  const value = this._rows[i][field];
@@ -1223,6 +1243,41 @@ class Table {
1223
1243
  return this._indexes[field];
1224
1244
  }
1225
1245
 
1246
+ // 复合唯一索引校验:NULL 不参与唯一性;excludeIndex 供 UPDATE 跳过自身
1247
+ _checkCompositeUnique(data, excludeIndex, existingSets) {
1248
+ const uniques = this._uniqueIndexes || [];
1249
+ for (let j = 0; j < uniques.length; j++) {
1250
+ const u = uniques[j];
1251
+ if (u.columns.length < 2) continue;
1252
+ if (u.columns.some(c => data[c] === undefined || data[c] === null)) continue;
1253
+ const k = u.columns.map(c => String(data[c])).join('\u001f');
1254
+ if (existingSets) {
1255
+ if (existingSets[j].has(k)) throw createError('ER_DUP_ENTRY', k, u.columns.join(','));
1256
+ existingSets[j].add(k);
1257
+ } else {
1258
+ for (let i = 0; i < this._rows.length; i++) {
1259
+ if (i === excludeIndex) continue;
1260
+ const row = this._rows[i];
1261
+ if (u.columns.some(c => row[c] === undefined || row[c] === null)) continue;
1262
+ if (u.columns.map(c => String(row[c])).join('\u001f') === k) {
1263
+ throw createError('ER_DUP_ENTRY', k, u.columns.join(','));
1264
+ }
1265
+ }
1266
+ }
1267
+ }
1268
+ }
1269
+
1270
+ _compositeUniqueSets() {
1271
+ return (this._uniqueIndexes || []).map(u => {
1272
+ const set = new Set();
1273
+ for (const row of this._rows) {
1274
+ if (u.columns.some(c => row[c] === undefined || row[c] === null)) continue;
1275
+ set.add(u.columns.map(c => String(row[c])).join('\u001f'));
1276
+ }
1277
+ return set;
1278
+ });
1279
+ }
1280
+
1226
1281
  dropIndex(field) {
1227
1282
  delete this._indexes[field];
1228
1283
  delete this._btrees[field];
@@ -1889,6 +1944,8 @@ class Table {
1889
1944
  }
1890
1945
  }
1891
1946
 
1947
+ // 复合唯一索引校验(NULL 不参与唯一性)
1948
+ this._checkCompositeUnique(data, excludeIndex);
1892
1949
  // FOREIGN KEY 校验
1893
1950
  // skipForeignKeys:父表主键 CASCADE 传播时,子表的新值尚未在父表生效,
1894
1951
  // 此时跳过本表 FK 复查(否则合法的 CASCADE 会被自己拦住)。
Binary file
@@ -453,6 +453,13 @@ impl Engine for HybridEngine {
453
453
  r
454
454
  }
455
455
 
456
+ fn aggregate(&self, table: &str, op: &str, field: &str) -> Result<String, String> {
457
+ self.ensure_table(table);
458
+ let r = self.mem.borrow().aggregate(table, op, field);
459
+ if r.is_ok() { self.touch(table); }
460
+ r
461
+ }
462
+
456
463
  fn update_by_id(&mut self, table: &str, id: u64, data: HashMap<String, serde_json::Value>) -> Result<bool, String> {
457
464
  self.ensure_table(table);
458
465
  let r = self.mem.borrow_mut().update_by_id(table, id, data)?;
@@ -107,6 +107,11 @@ impl Engine for MemoryEngine {
107
107
  Ok(t.count())
108
108
  }
109
109
 
110
+ fn aggregate(&self, table: &str, op: &str, field: &str) -> Result<String, String> {
111
+ let t = self.tables.get(table).ok_or_else(|| format!("table '{}' not found", table))?;
112
+ Ok(t.aggregate_json(op, field))
113
+ }
114
+
110
115
  fn update_by_id(&mut self, table: &str, id: u64, data: HashMap<String, serde_json::Value>) -> Result<bool, String> {
111
116
  let t = self.tables.get_mut(table).ok_or_else(|| format!("table '{}' not found", table))?;
112
117
  t.update_row(id, data)
@@ -68,6 +68,8 @@ pub trait Engine {
68
68
  Ok((json, cursor, has_more))
69
69
  }
70
70
  fn count(&self, table: &str) -> Result<usize, String>;
71
+ /// 按列聚合(#126),返回 JSON 数值字符串。
72
+ fn aggregate(&self, table: &str, op: &str, field: &str) -> Result<String, String>;
71
73
  fn update_by_id(&mut self, table: &str, id: u64, data: HashMap<String, serde_json::Value>) -> Result<bool, String>;
72
74
  fn update_by_ids(&mut self, table: &str, batch: Vec<(u64, HashMap<String, serde_json::Value>)>) -> Result<usize, String>;
73
75
  fn remove_by_id(&mut self, table: &str, id: u64) -> Result<bool, String>;