jsql-neo 6.8.10 → 6.8.12

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/README.md CHANGED
@@ -3,7 +3,7 @@
3
3
  > **One engine to rule them all** — a Rust-powered embedded database that speaks your language:
4
4
  > MySQL, PostgreSQL, MongoDB, Redis, SQL, TypeScript, **and the browser**.
5
5
 
6
- > **v6.8.10** — stable release · [github.com/vexify-org/JSQL-neo](https://github.com/vexify-org/JSQL-neo) · [jsql.vexify.top](https://jsql.vexify.top)
6
+ > **v6.8.12** — stable release · [github.com/vexify-org/JSQL-neo](https://github.com/vexify-org/JSQL-neo) · [jsql.vexify.top](https://jsql.vexify.top)
7
7
 
8
8
  ![Engines](https://img.shields.io/badge/engines-Native%20%7C%20WASM%20%7C%20Pure%20JS-7ee787)
9
9
  ![MySQL](https://img.shields.io/badge/protocol-MySQL%20compatible-1f6feb)
package/index.js CHANGED
@@ -1,5 +1,5 @@
1
1
  /**
2
- * JSQL-NEO v6.8.10 — Rust-Powered Embedded Database (WASM + HTTP)
2
+ * JSQL-NEO v6.8.12 — Rust-Powered Embedded Database (WASM + HTTP)
3
3
  *
4
4
  * @example
5
5
  * const jsql = require('jsql-neo');
package/lib/database.js CHANGED
@@ -1056,6 +1056,22 @@ class Database {
1056
1056
  await this._runHooks('afterDropTable', [name]);
1057
1057
  }
1058
1058
 
1059
+ /**
1060
+ * 表改名后重写所有子表的外键引用(Issue #246)。
1061
+ * 把 fk.table 从旧表名改成新表名,并同步 _indexRegistry 里的登记。
1062
+ */
1063
+ _rewriteForeignKeyRefs(oldName, newName) {
1064
+ const oldKey = String(oldName).toLowerCase();
1065
+ for (const table of Object.values(this._tables)) {
1066
+ if (!table || !Array.isArray(table._foreignKeys)) continue;
1067
+ for (const fk of table._foreignKeys) {
1068
+ if (String(fk.table).toLowerCase() === oldKey) {
1069
+ fk.table = newName;
1070
+ }
1071
+ }
1072
+ }
1073
+ }
1074
+
1059
1075
  /**
1060
1076
  * 找出所有引用指定父表的子表外键,且子表中至少有一行非空引用值。
1061
1077
  * 用于 DROP TABLE / TRUNCATE 的引用完整性检查。
@@ -1125,6 +1141,13 @@ class Database {
1125
1141
  table._name = newName;
1126
1142
  this._tables[newName] = table;
1127
1143
 
1144
+ // #246:改名后必须同步重写所有子表的外键引用。
1145
+ // 此前只改 _tables 的键,子表 _foreignKeys 里的 fk.table 仍是旧名 →
1146
+ // 悬空引用让外键校验与 ON DELETE CASCADE 全部静默失效:
1147
+ // 坏引用能写进表,删父行也不级联。
1148
+ // MySQL 8.0 的 RENAME TABLE 同样会更新数据字典里的外键引用。
1149
+ this._rewriteForeignKeyRefs(oldName, newName);
1150
+
1128
1151
  this._tableNames.delete(oldName);
1129
1152
  this._tableNames.add(newName);
1130
1153
 
@@ -2307,7 +2330,12 @@ class Database {
2307
2330
  if (!field || !Object.prototype.hasOwnProperty.call(validated, field)) continue;
2308
2331
  const nv = validated[field];
2309
2332
  if (nv === row[field]) continue; // 值没变,不算冲突
2310
- const clash = table._rows.find(r => r !== row && r[field] === nv);
2333
+ // #245:唯一性判定必须与等值比较同一口径(默认大小写不敏感)。
2334
+ // 此处此前用严格 ===,于是 'a' 与 'A' 能共存 —— 与 WHERE e='a'
2335
+ // 的折叠比较互相拆台。改用 Table 层的折叠键判定。
2336
+ const clash = typeof table._uniqueConflictRow === 'function'
2337
+ ? table._uniqueConflictRow(field, nv, row)
2338
+ : table._rows.find(r => r !== row && r[field] === nv);
2311
2339
  if (clash) throw createError('ER_DUP_ENTRY', `Duplicate entry '${nv}' for key '${field}'`);
2312
2340
  }
2313
2341
  // 外键:改主键时按 ON UPDATE 传播到引用它的子表;改自身外键列时校验引用存在。
@@ -42,6 +42,26 @@ function bsonDocument(obj) {
42
42
  continue;
43
43
  }
44
44
  if (typeof v === 'number') {
45
+ // #284:整数按 BSON 规范编 Int32(0x10) / Int64(0x12),只有真正的浮点
46
+ // 才用 Double(0x01)。此前一律编 double,导致线上类型与驱动预期不符
47
+ // ($type:'int' 永远匹配不到),且 int32 本可 4 字节却占了 8 字节。
48
+ if (Number.isInteger(v)) {
49
+ if (v >= -2147483648 && v <= 2147483647) {
50
+ const b = Buffer.alloc(4);
51
+ b.writeInt32LE(v, 0);
52
+ body = Buffer.concat([body, Buffer.from([0x10]), name, Buffer.from([0]), b]);
53
+ } else if (Number.isSafeInteger(v)) {
54
+ const b = Buffer.alloc(8);
55
+ b.writeBigInt64LE(BigInt(v), 0);
56
+ body = Buffer.concat([body, Buffer.from([0x12]), name, Buffer.from([0]), b]);
57
+ } else {
58
+ // 超出安全整数范围:double 已是唯一无损的表示
59
+ const b = Buffer.alloc(8);
60
+ b.writeDoubleLE(v, 0);
61
+ body = Buffer.concat([body, Buffer.from([0x01]), name, Buffer.from([0]), b]);
62
+ }
63
+ continue;
64
+ }
45
65
  const b = Buffer.alloc(8);
46
66
  b.writeDoubleLE(v, 0);
47
67
  body = Buffer.concat([body, Buffer.from([0x01]), name, Buffer.from([0]), b]);
@@ -65,9 +85,16 @@ function bsonDocument(obj) {
65
85
  continue;
66
86
  }
67
87
  if (Buffer.isBuffer(v)) {
88
+ // #285:BSON Binary 布局 = type 0x05 + 字段名 + int32 长度 +
89
+ // **1 字节 subtype** + length 字节数据。
90
+ // 此前写成 Buffer.from([0, 0])(两个字节),比规范多 1 字节 ——
91
+ // 解码端按规范只跳 1 个 subtype 字节,于是冗余 0x00 被当成数据首字节,
92
+ // 整个字节流错位([1,2,3,4] 读回成 [0,0,1,2]),且后续字段解析失步。
68
93
  const lenBuf = Buffer.alloc(4);
69
94
  lenBuf.writeInt32LE(v.length, 0);
70
- body = Buffer.concat([body, Buffer.from([0x05]), name, Buffer.from([0]), lenBuf, Buffer.from([0, v.buffer ? 0 : 0]), v]);
95
+ const subtype = (v.subtype !== undefined && v.subtype !== null) ? (v.subtype & 0xff) : 0;
96
+ body = Buffer.concat([body, Buffer.from([0x05]), name, Buffer.from([0]), lenBuf,
97
+ Buffer.from([subtype]), v]);
71
98
  continue;
72
99
  }
73
100
  if (v instanceof Date) {
package/lib/sql.js CHANGED
@@ -3365,6 +3365,59 @@ const OPERATORS = {
3365
3365
  };
3366
3366
 
3367
3367
  /** CAST(expr AS type) 的类型转换 */
3368
+ const SIGNED_MAX = 9223372036854775807n;
3369
+ const SIGNED_MIN = -9223372036854775808n;
3370
+ const UNSIGNED_MAX = 18446744073709551615n;
3371
+ // 提前声明:const 有 TDZ,下面 applyCast 里要用到
3372
+ const MAX_SAFE_BIGINT = BigInt(Number.MAX_SAFE_INTEGER);
3373
+
3374
+ /**
3375
+ * 解析字符串的数字前缀,返回精确的整数(BigInt,必要时钳制到 64 位边界)。
3376
+ *
3377
+ * #243:CAST(... AS SIGNED/UNSIGNED) 此前用 Number() 解析,2^53 以上的整数
3378
+ * 会被浮点舍入掉低位('9223372036854775808' → 9223372036854776000)。
3379
+ * 现在改用 BigInt 精确构造,并支持科学计数法('1e3' → 1000)。
3380
+ *
3381
+ * 语义对齐 MySQL:
3382
+ * · 取数字前缀('12abc' → 12)
3383
+ * · 无数字前缀 → 0('abc' → 0)
3384
+ * · 小数四舍五入(半远离零)
3385
+ * · 溢出钳制到 64 位边界
3386
+ */
3387
+ function parseSqlNumericPrefix(raw) {
3388
+ const s = String(raw).trim();
3389
+ // 数字前缀:可带符号、小数、指数
3390
+ const m = s.match(/^([+-]?)(\d*)(?:\.(\d*))?(?:[eE]([+-]?\d+))?/);
3391
+ if (!m) return 0;
3392
+ const intPart = m[2] || '';
3393
+ const fracPart = m[3] || '';
3394
+ const expPart = m[4] !== undefined ? parseInt(m[4], 10) : 0;
3395
+ // 整段必须至少含一个数字,否则视为无法解析
3396
+ if (intPart === '' && fracPart === '') return 0;
3397
+
3398
+ const neg = m[1] === '-';
3399
+ // 把「整数部分 + 小数部分」拼成一个十进制数字串,用 BigInt 精确处理
3400
+ const digits = (intPart || '0') + fracPart;
3401
+ // 小数点后有 fracPart.length 位,指数再移动 expPart 位
3402
+ const scale = expPart - fracPart.length;
3403
+ let mag;
3404
+ if (scale >= 0) {
3405
+ // 纯整数(含 1e3 / 1.5e3 这类)
3406
+ mag = BigInt(digits) * (10n ** BigInt(scale));
3407
+ } else {
3408
+ // 有小数:先按 10^(-scale) 放大,再四舍五入(半远离零)
3409
+ const factor = 10n ** BigInt(-scale);
3410
+ const q = BigInt(digits) / factor;
3411
+ const r = BigInt(digits) % factor;
3412
+ // 2*r >= factor 表示「恰好一半或更多」→ 进位
3413
+ mag = (r * 2n >= factor) ? q + 1n : q;
3414
+ }
3415
+ if (neg) mag = -mag;
3416
+ // 不在此处钳制:UNSIGNED 的上界是 2^64-1,比 SIGNED 上界更大,
3417
+ // 钳制交给调用方按目标类型决定。
3418
+ return mag;
3419
+ }
3420
+
3368
3421
  function applyCast(value, dataType) {
3369
3422
  const t = String(dataType || '').toUpperCase().replace(/\(.*\)$/, '').trim();
3370
3423
  if (value === null || value === undefined) return null;
@@ -3382,12 +3435,34 @@ function applyCast(value, dataType) {
3382
3435
  if (typeof value === 'boolean') n = value ? 1 : 0;
3383
3436
  else if (typeof value === 'number') n = Number.isFinite(value) ? roundHalfAway(value) : 0;
3384
3437
  else {
3385
- const m = String(value).trim().match(/^[+-]?\d+(\.\d+)?/);
3386
- n = m ? roundHalfAway(Number(m[0])) : 0;
3438
+ // #243:改用 BigInt 精确解析。
3439
+ // 旧实现用 Number(m[0]) —— 2^53 以上的整数会被浮点舍入成
3440
+ // 9223372036854776000 这种值,低位全丢;正则也不接受科学计数法,
3441
+ // CAST('1e3' AS SIGNED) 只解析出 '1'。
3442
+ // 现在:
3443
+ // · 用正则整体取出数字前缀(含指数形式);
3444
+ // · 整数部分用 BigInt 精确构造(小数按四舍五入半远离零处理);
3445
+ // · 溢出按 64 位边界钳制(SIGNED → [-2^63, 2^63-1],
3446
+ // UNSIGNED → [0, 2^64-1]),与 MySQL 一致。
3447
+ const parsed = parseSqlNumericPrefix(value);
3448
+ n = parsed === null ? 0 : parsed;
3449
+ }
3450
+ // 超过安全整数范围时用 BigInt 保留精确值(结果序列化时 finalizeBigInts 会转字符串)
3451
+ if (typeof n === 'bigint') {
3452
+ if (t === 'UNSIGNED') {
3453
+ if (n < 0n) return BigInt.asUintN(64, n);
3454
+ if (n > UNSIGNED_MAX) return UNSIGNED_MAX;
3455
+ } else {
3456
+ if (n > SIGNED_MAX) return SIGNED_MAX;
3457
+ if (n < SIGNED_MIN) return SIGNED_MIN;
3458
+ }
3459
+ // 安全整数范围内保持 number 类型(与修复前的行为一致,
3460
+ // 否则 CAST('12abc' AS INT) 会从 12 变成字符串 "12")。
3461
+ if (n <= MAX_SAFE_BIGINT && n >= -MAX_SAFE_BIGINT) return Number(n);
3462
+ return n;
3387
3463
  }
3388
3464
  // CAST(... AS UNSIGNED) 是 BIGINT UNSIGNED:负数按 2^64 回绕,
3389
3465
  // 而不是原样保留负号。CAST(-5 AS UNSIGNED) 应为 18446744073709551611。
3390
- // 超过 2^53 的值用 BigInt 保留精确值(结果序列化时 finalizeBigInts 会转字符串)。
3391
3466
  if (t === 'UNSIGNED' && n < 0) {
3392
3467
  return BigInt.asUintN(64, BigInt(n));
3393
3468
  }
@@ -3586,7 +3661,6 @@ function valueKey(v) {
3586
3661
  // 边界与 MySQL 一致:移位量 < 0 或 >= 64 → 0;64 位溢出按无符号回绕。
3587
3662
  // ---------------------------------------------------------------------------
3588
3663
  const U64_MASK = (1n << 64n) - 1n;
3589
- const MAX_SAFE_BIGINT = BigInt(Number.MAX_SAFE_INTEGER);
3590
3664
 
3591
3665
  /** MySQL 整数转换:小数四舍五入(远离零),负数按补码转到 64 位无符号 */
3592
3666
  function toUint64(v) {
@@ -3713,20 +3787,84 @@ function bigintExactArith(l, r, op) {
3713
3787
  * 恒小,于是 ORDER BY col DESC 时 NULL 跑到最前,与普通 SELECT 的 ORDER BY
3714
3788
  * 不一致;抽成一个函数后两条排序路径不会再各写一套。
3715
3789
  */
3790
+ /**
3791
+ * SQL 比较用的类型归一(Issue #291 / #292)。
3792
+ *
3793
+ * MySQL 8.0(11.2 Type Conversion in Expression Evaluation):
3794
+ * "If one operand is a number and the other is a string, the string is
3795
+ * converted to a number."
3796
+ *
3797
+ * 因此混合类型比较时,若一侧是数值、另一侧是可解析为有限数值的字符串,
3798
+ * 应按数值比较,而不是退化成字典序。
3799
+ *
3800
+ * 返回归一后的值;两侧无法按数值统一时返回 undefined(调用方回退原逻辑)。
3801
+ */
3802
+ function sqlNumericCoerce(v) {
3803
+ if (typeof v === 'number') return Number.isFinite(v) ? v : undefined;
3804
+ if (typeof v === 'bigint') return undefined; // BigInt 与 number 混用另有口径
3805
+ if (typeof v === 'boolean') return v ? 1 : 0;
3806
+ if (typeof v === 'string') {
3807
+ const t = v.trim();
3808
+ if (t === '') return undefined;
3809
+ // 必须整串都是数字(可含小数/指数),否则 'abc' 不能当 0
3810
+ if (!/^[+-]?(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d+)?$/.test(t)) return undefined;
3811
+ const n = Number(t);
3812
+ return Number.isFinite(n) ? n : undefined;
3813
+ }
3814
+ return undefined;
3815
+ }
3816
+
3817
+ /**
3818
+ * 分组键 / 窗口分区键的归一化(Issue #291)。
3819
+ *
3820
+ * 分组按 SQL 比较规则分组:数字 1 与字符串 '1' 是同一个键值,必须落在
3821
+ * 同一组。此前直接对原始 JS 值做 JSON.stringify,两个键文本不同 →
3822
+ * 被拆成两个伪组,COUNT(*) 偏小、SUM/AVG 被割裂。
3823
+ *
3824
+ * 归一规则:
3825
+ * · 字符串能解析为有限数值 → 折叠为数值表示(与数字同键)
3826
+ * · 布尔 → 0/1
3827
+ * · 其余原样
3828
+ */
3829
+ function sqlGroupKeyNormalize(v) {
3830
+ if (v === null || v === undefined) return v;
3831
+ if (typeof v === 'boolean') return v ? 1 : 0;
3832
+ if (typeof v === 'string') {
3833
+ const n = sqlNumericCoerce(v);
3834
+ if (n !== undefined) return n;
3835
+ return v;
3836
+ }
3837
+ return v;
3838
+ }
3839
+
3716
3840
  function compareSqlValues(av, bv, dir) {
3717
- const desc = dir === 'desc';
3718
- if (av === bv) return 0;
3719
- const aNull = av === null || av === undefined;
3720
- const bNull = bv === null || bv === undefined;
3721
- if (aNull || bNull) {
3722
- if (aNull && bNull) return 0;
3723
- const r = aNull ? -1 : 1;
3841
+ const desc = dir === 'desc';
3842
+ if (av === bv) return 0;
3843
+ const aNull = av === null || av === undefined;
3844
+ const bNull = bv === null || bv === undefined;
3845
+ if (aNull || bNull) {
3846
+ if (aNull && bNull) return 0;
3847
+ const r = aNull ? -1 : 1;
3848
+ return desc ? -r : r;
3849
+ }
3850
+ let r;
3851
+ if (typeof av === 'number' && typeof bv === 'number') {
3852
+ r = av - bv;
3853
+ } else {
3854
+ // #292:混合 number/string 时先按 SQL 规则归一为数值比较。
3855
+ // 此前只要一侧是字符串就退化成字典序,于是 '10' 与 2 的排序反了
3856
+ // (实际输出 1, 10, 2;MySQL 是 1, 2, 10)。
3857
+ const na = sqlNumericCoerce(av);
3858
+ const nb = sqlNumericCoerce(bv);
3859
+ if (na !== undefined && nb !== undefined
3860
+ && (typeof av !== 'string' || typeof bv !== 'string' || na !== nb)) {
3861
+ // 两侧都是字符串且归一后相等(如 '1' 与 '1.0')→ 视为相等
3862
+ r = na === nb ? 0 : (na < nb ? -1 : 1);
3863
+ } else {
3864
+ r = String(av) < String(bv) ? -1 : String(av) > String(bv) ? 1 : 0;
3865
+ }
3866
+ }
3724
3867
  return desc ? -r : r;
3725
- }
3726
- const r = typeof av === 'number' && typeof bv === 'number'
3727
- ? av - bv
3728
- : (String(av) < String(bv) ? -1 : String(av) > String(bv) ? 1 : 0);
3729
- return desc ? -r : r;
3730
3868
  }
3731
3869
 
3732
3870
  function resolveOperand(operand, row, ctx) {
@@ -3845,18 +3983,26 @@ function resolveOperand(operand, row, ctx) {
3845
3983
  // MySQL 整数除法 DIV(结果向零取整)
3846
3984
  case 'DIV': return mysqlNum(r) === 0 ? null : Math.trunc(mysqlNum(l) / mysqlNum(r));
3847
3985
  // 位运算:先按整数归一,与 MySQL 的整数位运算语义一致
3848
- case '&': return (mysqlNum(l) | 0) & (mysqlNum(r) | 0);
3849
- case '|': return (mysqlNum(l) | 0) | (mysqlNum(r) | 0);
3850
- case '^': return (mysqlNum(l) | 0) ^ (mysqlNum(r) | 0);
3851
- // P1-22: JavaScript 位运算只使用 32 位整数,移位量对 32 取模
3852
- // 1 << 32 = 1 << 0 = 1,但 SQL 中 1 << 32 = 4294967296
3986
+ // #290:位运算按 64 位无符号整数语义(与 MySQL 和 doc/sql-reference.md 一致)。
3987
+ // 旧的 `| 0` 路径把操作数截成 32 位有符号整数,高位全丢,
3988
+ // 且与已经改成 64 位的 ~ / << / >> 口径不一致(如 5 & ~1 会算错)。
3989
+ case '&': return fromUint64(toUint64(l) & toUint64(r));
3990
+ case '|': return fromUint64(toUint64(l) | toUint64(r));
3991
+ case '^': return fromUint64(toUint64(l) ^ toUint64(r));
3853
3992
  // Issue #109:移位量截断为整数并用 BigInt 精确计算(见 sqlBitShift)
3854
3993
  case '<<': case '>>': return sqlBitShift(l, r, operand.op);
3855
3994
  }
3856
3995
  return null;
3857
3996
  }
3858
3997
  case 'bitnot':
3859
- return ~(mysqlNum(resolveOperand(operand.expr, row, ctx)) | 0);
3998
+ // #290:位非按 64 位无符号整数语义计算。
3999
+ // 旧实现 `~(x | 0)` 先截成 32 位有符号整数,JS 的 ~ 也是 32 位有符号,
4000
+ // 于是 ~0 = -1、~5 = -6,高 32 位全丢。MySQL 的位运算结果是
4001
+ // unsigned 64-bit integer:~0 = 18446744073709551615。
4002
+ // 复用 #109 建立的 sqlBitShift 同款路径(toUint64 / fromUint64)。
4003
+ // 注意 BigInt 的 ~ 是**有符号**取反,必须再用 asUintN(64) 回绕,
4004
+ // 否则 ~0n = -1n 会被 fromUint64 原样输出成 -1。
4005
+ return fromUint64(BigInt.asUintN(64, ~toUint64(resolveOperand(operand.expr, row, ctx))));
3860
4006
  case 'negate': {
3861
4007
  const v = resolveOperand(operand.operand, row, ctx);
3862
4008
  if (v === null || v === undefined) return null;
@@ -3888,9 +4034,12 @@ function resolveOperand(operand, row, ctx) {
3888
4034
  case '/': { const rn = mysqlNum(r); return rn === 0 ? null : mysqlNum(l) / rn; }
3889
4035
  case '%': { const rn = mysqlNum(r); return rn === 0 ? null : mysqlNum(l) % rn; }
3890
4036
  case 'DIV': return mysqlNum(r) === 0 ? null : Math.trunc(mysqlNum(l) / mysqlNum(r));
3891
- case '&': return (mysqlNum(l) | 0) & (mysqlNum(r) | 0);
3892
- case '|': return (mysqlNum(l) | 0) | (mysqlNum(r) | 0);
3893
- case '^': return (mysqlNum(l) | 0) ^ (mysqlNum(r) | 0);
4037
+ // #290:位运算按 64 位无符号整数语义(与 MySQL 和 doc/sql-reference.md 一致)。
4038
+ // 旧的 `| 0` 路径把操作数截成 32 位有符号整数,高位全丢,
4039
+ // 且与已经改成 64 位的 ~ / << / >> 口径不一致(如 5 & ~1 会算错)。
4040
+ case '&': return fromUint64(toUint64(l) & toUint64(r));
4041
+ case '|': return fromUint64(toUint64(l) | toUint64(r));
4042
+ case '^': return fromUint64(toUint64(l) ^ toUint64(r));
3894
4043
  // Issue #109:移位量截断 + BigInt 精确计算
3895
4044
  case '<<': case '>>': return sqlBitShift(l, r, operand.op);
3896
4045
  default: return null;
@@ -4839,9 +4988,14 @@ function applyScalarFunction(fnNode, row, ctx) {
4839
4988
  case 'INSERT': {
4840
4989
  const s = args[0], pos = args[1], len = args[2], ins = args[3];
4841
4990
  if (s == null || pos == null || len == null || ins == null) return null;
4842
- const str = String(s), p = Math.trunc(Number(pos)), l = Math.trunc(Number(len));
4843
- if (p < 1 || p > str.length + 1 || l < 0) return str;
4844
- return str.slice(0, p - 1) + String(ins) + str.slice(p - 1 + l);
4991
+ // #289:按 code point 切分。MySQL 的 INSERT() 是 multibyte safe 的,
4992
+ // 此前用 str.length / str.slice 按 UTF-16 code unit 切,
4993
+ // emoji(占两个 code unit)会被劈成孤立代理项。
4994
+ const cps = Array.from(String(s));
4995
+ const p = Math.trunc(Number(pos)), l = Math.trunc(Number(len));
4996
+ // MySQL:pos 不在字符串长度范围内时返回原串(含 pos = 0)。
4997
+ if (p < 1 || p > cps.length + 1 || l < 0) return String(s);
4998
+ return cps.slice(0, p - 1).join('') + String(ins) + cps.slice(p - 1 + l).join('');
4845
4999
  }
4846
5000
  case 'STRCMP': {
4847
5001
  if (args[0] == null || args[1] == null) return null;
@@ -5064,6 +5218,11 @@ function applyScalarFunction(fnNode, row, ctx) {
5064
5218
  // MySQL 语义:1-based;负数从末尾倒数;0 视为 1(MySQL 返回空串)
5065
5219
  if (start === 0) return '';
5066
5220
  if (start < 0) start = len + start + 1;
5221
+ // #288:负偏移调整后若仍落在字符串起始之前,结果应为空串。
5222
+ // 此前没有钳制 start,把负下标交给 Array.prototype.slice ——
5223
+ // JS 的 slice 对负下标按「从末尾倒数」解释,于是 SUBSTRING('abc',-10)
5224
+ // 返回整串 'abc'、SUBSTRING('abcdef',-10) 返回尾部 'cdef'。
5225
+ if (!Number.isFinite(start) || start < 1) return '';
5067
5226
  if (args[2] !== undefined) {
5068
5227
  const n = Number(args[2]);
5069
5228
  if (n < 0) return '';
@@ -6195,9 +6354,10 @@ function evaluateExpr(expr, row, ctx) {
6195
6354
  case '/': { const rn = mysqlNum(r); return rn === 0 ? null : mysqlNum(l) / rn; }
6196
6355
  case '%': { const rn = mysqlNum(r); return rn === 0 ? null : mysqlNum(l) % rn; }
6197
6356
  case 'DIV': return mysqlNum(r) === 0 ? null : Math.trunc(mysqlNum(l) / mysqlNum(r));
6198
- case '&': return (mysqlNum(l) | 0) & (mysqlNum(r) | 0);
6199
- case '|': return (mysqlNum(l) | 0) | (mysqlNum(r) | 0);
6200
- case '^': return (mysqlNum(l) | 0) ^ (mysqlNum(r) | 0);
6357
+ // #290:位运算按 64 位无符号整数语义(与 MySQL 和 doc/sql-reference.md 一致)
6358
+ case '&': return fromUint64(toUint64(l) & toUint64(r));
6359
+ case '|': return fromUint64(toUint64(l) | toUint64(r));
6360
+ case '^': return fromUint64(toUint64(l) ^ toUint64(r));
6201
6361
  // Issue #109:移位量截断 + BigInt 精确计算
6202
6362
  case '<<': case '>>': return sqlBitShift(l, r, expr.op);
6203
6363
  default: return null;
@@ -8975,7 +9135,7 @@ class SQLExecutor {
8975
9135
  const buckets = new Map();
8976
9136
  rows.forEach((r, idx) => {
8977
9137
  const key = partBy.length
8978
- ? partBy.map(p => JSON.stringify(resolveOperand(p, r, this.ctx))).join('')
9138
+ ? partBy.map(p => JSON.stringify(sqlGroupKeyNormalize(resolveOperand(p, r, this.ctx)))).join('')
8979
9139
  : '';
8980
9140
  if (!buckets.has(key)) buckets.set(key, []);
8981
9141
  buckets.get(key).push(idx);
@@ -9527,21 +9687,28 @@ class SQLExecutor {
9527
9687
  // 表达式分组(#51):直接对原始行求值表达式
9528
9688
  if (g && typeof g === 'object') {
9529
9689
  const v = resolveOperand(g, row, this.ctx);
9530
- return typeof v === 'bigint' ? v.toString() + 'n' : v;
9690
+ // #291:分组键按 SQL 比较规则归一 —— 数字 1 与字符串 '1'
9691
+ // 是同一个键值,必须落在同一组。
9692
+ const nv = sqlGroupKeyNormalize(v);
9693
+ return typeof nv === 'bigint' ? nv.toString() + 'n' : nv;
9531
9694
  }
9532
9695
  const key = String(g).toLowerCase();
9533
9696
  if (aliases[key]) {
9534
9697
  // 优先用行中已有的 alias 值(投影后才有),没有则尝试从原始列取值
9535
- if (row[key] !== undefined) return row[key];
9698
+ if (row[key] !== undefined) return sqlGroupKeyNormalize(row[key]);
9536
9699
  // alias → 原始列名 的映射(如 b → a),从原始行取该列的值
9537
- if (aliasToCol[key]) return resolveOperand({ type: 'column', name: aliasToCol[key] }, row, this.ctx);
9700
+ if (aliasToCol[key]) {
9701
+ return sqlGroupKeyNormalize(resolveOperand({ type: 'column', name: aliasToCol[key] }, row, this.ctx));
9702
+ }
9538
9703
  if (aliasExpr[key]) {
9539
9704
  const v = resolveOperand(aliasExpr[key], row, this.ctx);
9540
- return typeof v === 'bigint' ? v.toString() + 'n' : v;
9705
+ const nv = sqlGroupKeyNormalize(v);
9706
+ return typeof nv === 'bigint' ? nv.toString() + 'n' : nv;
9541
9707
  }
9542
9708
  return row[key]; // row[key] 为 undefined,但保持一致
9543
9709
  }
9544
- return resolveOperand({ type: 'column', name: g }, row, this.ctx);
9710
+ // #291:列分组的键同样归一
9711
+ return sqlGroupKeyNormalize(resolveOperand({ type: 'column', name: g }, row, this.ctx));
9545
9712
  }));
9546
9713
  if (!groups.has(key)) groups.set(key, []);
9547
9714
  groups.get(key).push(row);
package/lib/table.js CHANGED
@@ -27,6 +27,32 @@ const { ObjectId, valuesEqual, arrayIncludesValue, orAnyElement, anyElementRange
27
27
  const NOW_DEFAULT_RE = /^(?:CURRENT_TIMESTAMP|NOW|LOCALTIMESTAMP|LOCALTIME)\s*(?:\(\s*\d*\s*\))?$/i;
28
28
  const FUNC_CALL_DEFAULT_RE = /^[A-Za-z_$][\w$]*\s*\([\s\S]*\)$/;
29
29
 
30
+ /**
31
+ * 唯一键的「归一化比较键」(Issue #245)。
32
+ *
33
+ * 背景:等值比较走大小写折叠(lib/sql.js 的 ciEq,默认 utf8mb4_general_ci
34
+ * 大小写不敏感),而 UNIQUE 校验走原始值的严格相等 —— 两套口径从未统一。
35
+ * 结果是 `e VARCHAR(10) UNIQUE` 上 'a' 与 'A' 能共存,而 `WHERE e='a'`
36
+ * 又能同时命中两行,唯一约束形同虚设。
37
+ *
38
+ * MySQL 的 UNIQUE 索引按列的排序规则比较,utf8mb4_general_ci 下
39
+ * 'a' 与 'A' 是同一个键值,第二条 INSERT 必须报 1062。
40
+ *
41
+ * 规则:
42
+ * · 字符串 → 折叠大小写(toLowerCase),与 ciEq 一致;
43
+ * · BINARY / VARBINARY / BLOB 类型列 → 保持原样(字节敏感);
44
+ * · 其它值(数字、布尔、BigInt、null)→ 原样。
45
+ */
46
+ function uniqueCompareKey(value, def) {
47
+ if (typeof value !== 'string') return value;
48
+ const t = String((def && typeof def === 'object' ? def.type : def) || '').toLowerCase();
49
+ if (t === 'binary' || t === 'varbinary' || t === 'blob' || t === 'longblob'
50
+ || t === 'mediumblob' || t === 'tinyblob') {
51
+ return value; // 二进制列按字节比较,区分大小写
52
+ }
53
+ return value.toLowerCase();
54
+ }
55
+
30
56
  function resolveDefaultValue(dv, fieldName) {
31
57
  if (typeof dv === 'function') return dv();
32
58
  if (typeof dv !== 'string') return dv;
@@ -312,6 +338,9 @@ class Table {
312
338
  this._cachedDateFields = Object.keys(this._dateFields);
313
339
  this._cachedUniqueFields = this._cachedSchemaFields.filter(f => schema[f].unique);
314
340
  this._cachedRequiredFields = this._cachedSchemaFields.filter(f => schema[f].required);
341
+ // #245:需要按「折叠大小写后的键」做唯一性判定的列
342
+ this._ciUniqueFields = this._cachedUniqueFields.slice();
343
+ this._ciUnique = {}; // field -> Map(foldedKey -> count)
315
344
  this._autoCreateBTrees();
316
345
  }
317
346
 
@@ -556,7 +585,11 @@ class Table {
556
585
  for (const field of this._cachedUniqueFields) {
557
586
  uniqueTracker[field] = new Set();
558
587
  for (const row of this._rows) {
559
- if (row[field] !== undefined && row[field] !== null) uniqueTracker[field].add(row[field]);
588
+ // #245:与 _validateConstraints 同一口径 —— 用折叠键,
589
+ // 否则 'a' 与 'A' 在批量插入路径上仍能共存。
590
+ if (row[field] !== undefined && row[field] !== null) {
591
+ uniqueTracker[field].add(uniqueCompareKey(row[field], this._schema[field]));
592
+ }
560
593
  }
561
594
  }
562
595
  const compositeUniqueSets = this._compositeUniqueSets();
@@ -604,8 +637,10 @@ class Table {
604
637
  if ((def.primaryKey || def.primary === true) && !def.autoIncrement
605
638
  && data[field] === null) throw createError('ER_BAD_NULL_ERROR', field);
606
639
  if (def.unique && data[field] !== undefined && data[field] !== null) {
607
- if (uniqueTracker[field].has(data[field])) throw createError('ER_DUP_ENTRY', String(data[field]), field);
608
- uniqueTracker[field].add(data[field]);
640
+ // #245:折叠键,与 _validateConstraints 保持同一口径
641
+ const ukey = uniqueCompareKey(data[field], def);
642
+ if (uniqueTracker[field].has(ukey)) throw createError('ER_DUP_ENTRY', String(data[field]), field);
643
+ uniqueTracker[field].add(ukey);
609
644
  }
610
645
  if (def.length && typeof data[field] === 'string' && data[field].length > def.length) throw createError('ER_DATA_TOO_LONG', field);
611
646
  if (def.type === 'integer' || def.type === 'int' || def.type === 'bigint' || def.type === 'number') {
@@ -633,10 +668,11 @@ class Table {
633
668
  for (const fk of foreignKeys) {
634
669
  if (data[fk.field] !== undefined && data[fk.field] !== null) {
635
670
  const refTable = this._resolveTable(fk.table);
636
- if (refTable) {
637
- const exists = refTable.findOne({ [fk.refField]: data[fk.field] });
638
- if (!exists) throw createError('ER_NO_REFERENCED_ROW');
639
- }
671
+ // #246:解析不到父表时必须报错,不能静默跳过 ——
672
+ // 静默跳过等于「当作没有外键」,坏引用会被写进表。
673
+ if (!refTable) throw createError('ER_NO_REFERENCED_ROW');
674
+ const exists = refTable.findOne({ [fk.refField]: data[fk.field] });
675
+ if (!exists) throw createError('ER_NO_REFERENCED_ROW');
640
676
  }
641
677
  }
642
678
  if (autoIncField && data[autoIncField] === undefined) {
@@ -1249,10 +1285,11 @@ class Table {
1249
1285
  if (opts && opts.unique) {
1250
1286
  const key = columns.join('\u001f');
1251
1287
  // #207:在已有重复键的数据上建唯一索引必须失败,不能静默建成
1288
+ // #245:重复判定用折叠键,与写入路径同一口径
1252
1289
  const seen = new Set();
1253
1290
  for (const row of this._rows) {
1254
1291
  if (columns.some(c => row[c] === undefined || row[c] === null)) continue;
1255
- const k = columns.map(c => String(row[c])).join('\u001f');
1292
+ const k = columns.map(c => String(uniqueCompareKey(row[c], this._schema[c]))).join('\u001f');
1256
1293
  if (seen.has(k)) throw createError('ER_DUP_ENTRY', k, columns.join(','));
1257
1294
  seen.add(k);
1258
1295
  }
@@ -1288,7 +1325,8 @@ class Table {
1288
1325
  const u = uniques[j];
1289
1326
  if (u.columns.length < 2) continue;
1290
1327
  if (u.columns.some(c => data[c] === undefined || data[c] === null)) continue;
1291
- const k = u.columns.map(c => String(data[c])).join('\u001f');
1328
+ // #245:复合键同样按折叠口径比较(各列用自己的列定义决定是否折叠)
1329
+ const k = u.columns.map(c => String(uniqueCompareKey(data[c], this._schema[c]))).join('\u001f');
1292
1330
  if (existingSets) {
1293
1331
  if (existingSets[j].has(k)) throw createError('ER_DUP_ENTRY', k, u.columns.join(','));
1294
1332
  existingSets[j].add(k);
@@ -1297,7 +1335,8 @@ class Table {
1297
1335
  if (i === excludeIndex) continue;
1298
1336
  const row = this._rows[i];
1299
1337
  if (u.columns.some(c => row[c] === undefined || row[c] === null)) continue;
1300
- if (u.columns.map(c => String(row[c])).join('\u001f') === k) {
1338
+ const rk = u.columns.map(c => String(uniqueCompareKey(row[c], this._schema[c]))).join('\u001f');
1339
+ if (rk === k) {
1301
1340
  throw createError('ER_DUP_ENTRY', k, u.columns.join(','));
1302
1341
  }
1303
1342
  }
@@ -1310,7 +1349,8 @@ class Table {
1310
1349
  const set = new Set();
1311
1350
  for (const row of this._rows) {
1312
1351
  if (u.columns.some(c => row[c] === undefined || row[c] === null)) continue;
1313
- set.add(u.columns.map(c => String(row[c])).join('\u001f'));
1352
+ // #245:折叠键,与写入路径一致
1353
+ set.add(u.columns.map(c => String(uniqueCompareKey(row[c], this._schema[c]))).join('\u001f'));
1314
1354
  }
1315
1355
  return set;
1316
1356
  });
@@ -1925,15 +1965,27 @@ class Table {
1925
1965
  // PRIMARY KEY 唯一性(复合主键交给 _checkCompositeUnique 按元组判定)
1926
1966
  if ((def.primaryKey || def.primary === true) && !(this._primaryKeys && this._primaryKeys.length > 1)
1927
1967
  && data[field] !== undefined && data[field] !== null) {
1968
+ // #245:主键同样按折叠口径判定(MySQL 主键按列排序规则比较)
1969
+ const key = uniqueCompareKey(data[field], def);
1928
1970
  let dup = false;
1929
1971
  if (uniqueTracker && uniqueTracker[field]) {
1930
- dup = uniqueTracker[field].has(data[field]);
1931
- } else if (this._pkIndex) {
1972
+ dup = uniqueTracker[field].has(key);
1973
+ } else if (key === data[field] && this._pkIndex) {
1932
1974
  const idx = this._pkIndex.get(data[field]);
1933
1975
  dup = idx !== undefined && idx !== null && idx !== excludeIndex;
1934
- } else {
1976
+ } else if (key === data[field]) {
1935
1977
  const idx = this._rows.findIndex(r => r[field] === data[field]);
1936
1978
  dup = idx !== -1 && idx !== excludeIndex;
1979
+ } else {
1980
+ // 折叠后与原值不同 → B-Tree / _pkIndex(存原值)查不到,按列扫描
1981
+ for (let i = 0; i < this._rows.length; i++) {
1982
+ if (i === excludeIndex) continue;
1983
+ const row = this._rows[i];
1984
+ if (!row) continue;
1985
+ const rv = row[field];
1986
+ if (rv === undefined || rv === null) continue;
1987
+ if (uniqueCompareKey(rv, def) === key) { dup = true; break; }
1988
+ }
1937
1989
  }
1938
1990
  if (dup) {
1939
1991
  throw createError('ER_DUP_ENTRY', String(data[field]), field);
@@ -1942,16 +1994,37 @@ class Table {
1942
1994
 
1943
1995
  // UNIQUE(B-Tree 优化 O(log n))—— NULL 不参与唯一性
1944
1996
  if (def.unique && data[field] !== undefined && data[field] !== null) {
1997
+ // #245:唯一性判定必须与等值比较同一口径。
1998
+ // 等值比较走大小写折叠(ciEq / utf8mb4_general_ci),
1999
+ // 而这里此前用原始值的严格相等 —— 于是 'a' 与 'A' 能共存,
2000
+ // 而 `WHERE e='a'` 又同时命中两行,唯一约束形同虚设。
2001
+ // 现在统一用折叠键比较:MySQL 的 UNIQUE 索引按列排序规则比较,
2002
+ // utf8mb4_general_ci 下 'a' 与 'A' 是同一个键值。
2003
+ const key = uniqueCompareKey(data[field], def);
1945
2004
  if (uniqueTracker && uniqueTracker[field]) {
1946
- if (uniqueTracker[field].has(data[field])) {
2005
+ if (uniqueTracker[field].has(key)) {
1947
2006
  throw createError('ER_DUP_ENTRY', String(data[field]), field);
1948
2007
  }
1949
- uniqueTracker[field].add(data[field]);
2008
+ uniqueTracker[field].add(key);
1950
2009
  } else if (this._btrees[field]) {
1951
- const found = this._btrees[field].search(data[field]);
1952
- if (found.length > 0) {
1953
- for (const idx of found) {
1954
- if (idx !== excludeIndex && this._rows[idx] && this._rows[idx][field] === data[field]) {
2010
+ // B-Tree 存的是原始值,用折叠键查不到 —— 退回按列扫描。
2011
+ // 只有 UNIQUE + 字符串列才会走到这里(数值列的折叠键 == 原值,
2012
+ // 仍走 B-Tree 快路径)。
2013
+ if (key === data[field]) {
2014
+ const found = this._btrees[field].search(data[field]);
2015
+ if (found.length > 0) {
2016
+ for (const idx of found) {
2017
+ if (idx !== excludeIndex && this._rows[idx] && this._rows[idx][field] === data[field]) {
2018
+ throw createError('ER_DUP_ENTRY', String(data[field]), field);
2019
+ }
2020
+ }
2021
+ }
2022
+ } else {
2023
+ for (let i = 0; i < this._rows.length; i++) {
2024
+ if (i === excludeIndex) continue;
2025
+ const row = this._rows[i];
2026
+ if (row && row[field] !== undefined && row[field] !== null
2027
+ && uniqueCompareKey(row[field], def) === key) {
1955
2028
  throw createError('ER_DUP_ENTRY', String(data[field]), field);
1956
2029
  }
1957
2030
  }
@@ -1959,7 +2032,11 @@ class Table {
1959
2032
  } else {
1960
2033
  for (let i = 0; i < this._rows.length; i++) {
1961
2034
  if (i === excludeIndex) continue;
1962
- if (this._rows[i][field] === data[field]) {
2035
+ const row = this._rows[i];
2036
+ if (!row) continue;
2037
+ const rv = row[field];
2038
+ if (rv === undefined || rv === null) continue;
2039
+ if (uniqueCompareKey(rv, def) === key) {
1963
2040
  throw createError('ER_DUP_ENTRY', String(data[field]), field);
1964
2041
  }
1965
2042
  }
@@ -1991,16 +2068,43 @@ class Table {
1991
2068
  if (!opts.skipForeignKeys) this._validateForeignKeys(data);
1992
2069
  }
1993
2070
 
2071
+ /**
2072
+ * 查找与给定唯一键冲突的行(排除 excludeRow 自身)。
2073
+ *
2074
+ * #245:唯一性判定与等值比较必须同一口径 —— 默认 utf8mb4_general_ci
2075
+ * 大小写不敏感,所以 'a' 与 'A' 是同一个唯一键。Database.updateById
2076
+ * 此前用严格 === 判定,与 WHERE 的折叠比较互相拆台。
2077
+ *
2078
+ * @param {string} field 唯一列名
2079
+ * @param {*} value 新值
2080
+ * @param {object} [excludeRow] 排除的行(更新自身时跳过)
2081
+ * @returns {object|null} 冲突行,无冲突返回 null
2082
+ */
2083
+ _uniqueConflictRow(field, value, excludeRow) {
2084
+ if (value === undefined || value === null) return null;
2085
+ const def = this._schema ? this._schema[field] : null;
2086
+ const key = uniqueCompareKey(value, def);
2087
+ for (let i = 0; i < this._rows.length; i++) {
2088
+ const row = this._rows[i];
2089
+ if (!row || row === excludeRow) continue;
2090
+ const rv = row[field];
2091
+ if (rv === undefined || rv === null) continue;
2092
+ if (uniqueCompareKey(rv, def) === key) return row;
2093
+ }
2094
+ return null;
2095
+ }
2096
+
1994
2097
  /** 仅校验外键引用是否存在(供插入/更新路径复用) */
1995
2098
  _validateForeignKeys(data) {
1996
2099
  for (const fk of this._foreignKeys) {
1997
2100
  if (data[fk.field] !== undefined && data[fk.field] !== null) {
1998
2101
  const refTable = this._resolveTable(fk.table);
1999
- if (refTable) {
2000
- const exists = refTable.findOne({ [fk.refField]: data[fk.field] });
2001
- if (!exists) {
2002
- throw createError('ER_NO_REFERENCED_ROW');
2003
- }
2102
+ // #246:父表解析不到时必须报错 —— 静默跳过等于「当作没有外键」,
2103
+ // 坏引用会被写进表且删除父行时不再级联。
2104
+ if (!refTable) throw createError('ER_NO_REFERENCED_ROW');
2105
+ const exists = refTable.findOne({ [fk.refField]: data[fk.field] });
2106
+ if (!exists) {
2107
+ throw createError('ER_NO_REFERENCED_ROW');
2004
2108
  }
2005
2109
  }
2006
2110
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "jsql-neo",
3
- "version": "6.8.10",
3
+ "version": "6.8.12",
4
4
  "description": "JSQL-NEO — Rust-powered embedded database with WASM, REST API, B-Tree indexes, WAL, crash recovery",
5
5
  "main": "index.js",
6
6
  "types": "index.d.ts",
@@ -52,12 +52,12 @@
52
52
  "build:native": "node scripts/build-native.js",
53
53
  "check:release": "node scripts/check-release-metadata.js",
54
54
  "release:prep": "node scripts/release.js",
55
- "test": "npm run check:release && node test/smoke.js && node test/result-raw.test.js && node test/native-install.test.js && node test/native-cli.test.js && node test/finalize-bigint.test.js && node test/native.test.js && node test/json-functions.test.js && node test/sql-parser.test.js && node test/readme-audit.test.js && node test/query-opt.test.js && node test/wal-recovery.test.js && node test/mysql-compat-hijack.test.js && node test/dml-constraints.test.js && node test/star-nag.test.js && node test/plugin-xql.test.js && node test/bug-regression-2.test.js && node test/issue-34-35-36.test.js && node test/issue-g4.test.js && node test/issue-38.test.js && node test/issue-39.test.js && node test/issue-40.test.js && node test/issue-44.test.js && node test/issue-45.test.js && node test/issue-46.test.js && node test/issue-47.test.js && node test/issue-48.test.js && node test/issue-50.test.js && node test/issue-51.test.js && node test/issue-52.test.js && node test/issue-53.test.js && node test/issue-54.test.js && node test/issue-55.test.js && node test/issue-56.test.js && node test/issue-57.test.js && node test/issue-58.test.js && node test/issue-59.test.js && node test/issue-60.test.js && node test/issue-63-68.test.js && node test/network-policy.test.js && node test/issue-69-70.test.js && node test/issue-71-72.test.js && node test/issue-73-76.test.js && node test/issue-77-84.test.js && node test/issue-86-99.test.js && node test/issue-101-103.test.js && node test/issue-105.test.js && node test/issue-118-136.test.js && node test/issue-127.test.js && node test/issue-138-156.test.js && node test/issue-157-161.test.js && node test/issue-162-179.test.js && node test/issue-181-186.test.js && node test/issue-187.test.js && node test/issue-188-237.test.js && node test/issue-238-241.test.js && node test/bigint-math.test.js && node test/release-metadata.test.js && node test/date-conversions.test.js && node test/mysql-utility-functions.test.js && node test/limit-pushdown.test.js && node test/columnar.test.js && node test/columnar-vector.test.js && node test/cast-rounding.test.js && node test/convert-subquery.test.js && node test/mongo-persistence.test.js && node test/mongo-objectid.test.js && node test/mongo-arrays.test.js && node test/issue-117.test.js && node test/issue-314-321.test.js && node test/issue-312-320.test.js",
55
+ "test": "npm run check:release && node test/smoke.js && node test/result-raw.test.js && node test/native-install.test.js && node test/native-cli.test.js && node test/finalize-bigint.test.js && node test/native.test.js && node test/json-functions.test.js && node test/sql-parser.test.js && node test/readme-audit.test.js && node test/query-opt.test.js && node test/wal-recovery.test.js && node test/mysql-compat-hijack.test.js && node test/dml-constraints.test.js && node test/star-nag.test.js && node test/plugin-xql.test.js && node test/bug-regression-2.test.js && node test/issue-34-35-36.test.js && node test/issue-g4.test.js && node test/issue-38.test.js && node test/issue-39.test.js && node test/issue-40.test.js && node test/issue-44.test.js && node test/issue-45.test.js && node test/issue-46.test.js && node test/issue-47.test.js && node test/issue-48.test.js && node test/issue-50.test.js && node test/issue-51.test.js && node test/issue-52.test.js && node test/issue-53.test.js && node test/issue-54.test.js && node test/issue-55.test.js && node test/issue-56.test.js && node test/issue-57.test.js && node test/issue-58.test.js && node test/issue-59.test.js && node test/issue-60.test.js && node test/issue-63-68.test.js && node test/network-policy.test.js && node test/issue-69-70.test.js && node test/issue-71-72.test.js && node test/issue-73-76.test.js && node test/issue-77-84.test.js && node test/issue-86-99.test.js && node test/issue-101-103.test.js && node test/issue-105.test.js && node test/issue-118-136.test.js && node test/issue-127.test.js && node test/issue-138-156.test.js && node test/issue-157-161.test.js && node test/issue-162-179.test.js && node test/issue-181-186.test.js && node test/issue-187.test.js && node test/issue-188-237.test.js && node test/issue-238-241.test.js && node test/bigint-math.test.js && node test/release-metadata.test.js && node test/date-conversions.test.js && node test/mysql-utility-functions.test.js && node test/limit-pushdown.test.js && node test/columnar.test.js && node test/columnar-vector.test.js && node test/cast-rounding.test.js && node test/convert-subquery.test.js && node test/mongo-persistence.test.js && node test/mongo-objectid.test.js && node test/mongo-arrays.test.js && node test/issue-117.test.js && node test/issue-314-321.test.js && node test/issue-312-320.test.js && node test/issue-243-289.test.js && node test/issue-284-292.test.js",
56
56
  "test:parser": "node test/sql-parser.test.js",
57
57
  "test:btree": "node test/btree.test.js",
58
58
  "test:native": "node test/native.test.js",
59
59
  "test:regress": "node test/regress-5.1.0.js",
60
- "test:all": "npm run check:release && node test/smoke.js && node test/result-raw.test.js && node test/native-install.test.js && node test/native-cli.test.js && node test/finalize-bigint.test.js && node test/sql-parser.test.js && node test/readme-audit.test.js && node test/native.test.js && node test/native-multi-instance.test.js && node test/wal-recovery.test.js && node test/mysql-compat-hijack.test.js && node test/wasm.test.js && node test/coverage.js && node test/regress-5.1.0.js && node test/join.test.js && node test/btree.test.js && node test/dml-constraints.test.js && node test/savepoint.test.js && node test/alter-table.test.js && node test/null-semantics.test.js && node test/identifier-keywords.test.js && node test/issue-34-35-36.test.js && node test/sql-semantics.test.js && node test/extra-coverage.test.js && node test/filter-compile.test.js && node test/recursive-cte.test.js && node test/index-ddl.test.js && node test/mongo-group.test.js && node test/multiprotocol.test.js && node test/issue-g4.test.js && node test/issue-38.test.js && node test/issue-39.test.js && node test/issue-40.test.js && node test/issue-44.test.js && node test/issue-45.test.js && node test/issue-46.test.js && node test/issue-47.test.js && node test/issue-48.test.js && node test/issue-50.test.js && node test/issue-51.test.js && node test/issue-52.test.js && node test/issue-53.test.js && node test/issue-54.test.js && node test/issue-55.test.js && node test/issue-56.test.js && node test/issue-57.test.js && node test/issue-58.test.js && node test/issue-59.test.js && node test/issue-60.test.js && node test/issue-63-68.test.js && node test/network-policy.test.js && node test/issue-69-70.test.js && node test/issue-71-72.test.js && node test/issue-77-84.test.js && node test/issue-86-99.test.js && node test/issue-101-103.test.js && node test/issue-105.test.js && node test/issue-118-136.test.js && node test/issue-127.test.js && node test/issue-138-156.test.js && node test/issue-157-161.test.js && node test/issue-162-179.test.js && node test/issue-181-186.test.js && node test/issue-187.test.js && node test/issue-188-237.test.js && node test/issue-238-241.test.js && node test/bigint-math.test.js && node test/release-metadata.test.js && node test/date-conversions.test.js && node test/mysql-utility-functions.test.js && node test/limit-pushdown.test.js && node test/columnar.test.js && node test/columnar-vector.test.js && node test/cast-rounding.test.js && node test/convert-subquery.test.js && node test/mongo-persistence.test.js && node test/mongo-objectid.test.js && node test/mongo-arrays.test.js && node test/issue-117.test.js && node test/issue-314-321.test.js && node test/issue-312-320.test.js",
60
+ "test:all": "npm run check:release && node test/smoke.js && node test/result-raw.test.js && node test/native-install.test.js && node test/native-cli.test.js && node test/finalize-bigint.test.js && node test/sql-parser.test.js && node test/readme-audit.test.js && node test/native.test.js && node test/native-multi-instance.test.js && node test/wal-recovery.test.js && node test/mysql-compat-hijack.test.js && node test/wasm.test.js && node test/coverage.js && node test/regress-5.1.0.js && node test/join.test.js && node test/btree.test.js && node test/dml-constraints.test.js && node test/savepoint.test.js && node test/alter-table.test.js && node test/null-semantics.test.js && node test/identifier-keywords.test.js && node test/issue-34-35-36.test.js && node test/sql-semantics.test.js && node test/extra-coverage.test.js && node test/filter-compile.test.js && node test/recursive-cte.test.js && node test/index-ddl.test.js && node test/mongo-group.test.js && node test/multiprotocol.test.js && node test/issue-g4.test.js && node test/issue-38.test.js && node test/issue-39.test.js && node test/issue-40.test.js && node test/issue-44.test.js && node test/issue-45.test.js && node test/issue-46.test.js && node test/issue-47.test.js && node test/issue-48.test.js && node test/issue-50.test.js && node test/issue-51.test.js && node test/issue-52.test.js && node test/issue-53.test.js && node test/issue-54.test.js && node test/issue-55.test.js && node test/issue-56.test.js && node test/issue-57.test.js && node test/issue-58.test.js && node test/issue-59.test.js && node test/issue-60.test.js && node test/issue-63-68.test.js && node test/network-policy.test.js && node test/issue-69-70.test.js && node test/issue-71-72.test.js && node test/issue-77-84.test.js && node test/issue-86-99.test.js && node test/issue-101-103.test.js && node test/issue-105.test.js && node test/issue-118-136.test.js && node test/issue-127.test.js && node test/issue-138-156.test.js && node test/issue-157-161.test.js && node test/issue-162-179.test.js && node test/issue-181-186.test.js && node test/issue-187.test.js && node test/issue-188-237.test.js && node test/issue-238-241.test.js && node test/bigint-math.test.js && node test/release-metadata.test.js && node test/date-conversions.test.js && node test/mysql-utility-functions.test.js && node test/limit-pushdown.test.js && node test/columnar.test.js && node test/columnar-vector.test.js && node test/cast-rounding.test.js && node test/convert-subquery.test.js && node test/mongo-persistence.test.js && node test/mongo-objectid.test.js && node test/mongo-arrays.test.js && node test/issue-117.test.js && node test/issue-314-321.test.js && node test/issue-312-320.test.js && node test/issue-243-289.test.js && node test/issue-284-292.test.js",
61
61
  "test:coverage": "c8 --all --include='lib/**' --exclude='lib/web_ui.js' --reporter=text --reporter=lcov node test/coverage.js",
62
62
  "test:orms": "node examples/orms/run-all.js",
63
63
  "test:dml": "node test/dml-constraints.test.js",
@@ -0,0 +1,164 @@
1
+ /* ---- 回归:#243 / #245 / #246 / #288 / #289 ---- */
2
+ /*
3
+ * #243 CAST(... AS SIGNED/UNSIGNED) 丢失 >2^53 的精度,且不识别科学计数法。
4
+ * #245 UNIQUE 索引按字节区分大小写,而等值比较不区分 —— 'a' 与 'A' 能共存。
5
+ * #246 父表 RENAME 后,子表外键校验与 ON DELETE CASCADE 全部静默失效。
6
+ * #288 SUBSTRING(str, 负偏移越界) 无长度参数时返回整串/尾部片段,应为空串。
7
+ * #289 INSERT(str,pos,len,newstr) 按 UTF-16 code unit 切分,emoji 被劈开。
8
+ */
9
+ const path = require('path');
10
+ const ROOT = path.join(__dirname, '..');
11
+ const { Database, executeSQL } = require(path.join(ROOT, 'index.js'));
12
+
13
+ let pass = 0, fail = 0;
14
+ function ok(name, cond, got) {
15
+ if (cond) { pass++; console.log('[OK] ' + name); }
16
+ else { fail++; console.log('[FAIL] ' + name + ' -> ' + JSON.stringify(got)); }
17
+ }
18
+
19
+ (async () => {
20
+ const db = new Database(':memory:', { autoSave: false });
21
+ const q = async (sql) => (await executeSQL(db, sql, { safety: false })).rows;
22
+ const one = async (sql) => (await q(sql))[0][0];
23
+
24
+ // ================= #243 CAST 精度 =================
25
+ ok("CAST('9223372036854775808' AS SIGNED) 钳到 BIGINT 上界",
26
+ String(await one("SELECT CAST('9223372036854775808' AS SIGNED)")) === '9223372036854775807', null);
27
+ ok("CAST('18446744073709551615' AS UNSIGNED) 精确",
28
+ String(await one("SELECT CAST('18446744073709551615' AS UNSIGNED)")) === '18446744073709551615', null);
29
+ ok("CAST('999999999999999999999999' AS SIGNED) 钳到上界",
30
+ String(await one("SELECT CAST('999999999999999999999999' AS SIGNED)")) === '9223372036854775807', null);
31
+ ok("CAST('1e3' AS SIGNED) = 1000(识别科学计数法)",
32
+ await one("SELECT CAST('1e3' AS SIGNED)") === 1000, null);
33
+ ok("CAST('1.5e2' AS SIGNED) = 150",
34
+ await one("SELECT CAST('1.5e2' AS SIGNED)") === 150, null);
35
+ ok("CAST('12abc' AS SIGNED) = 12(取数字前缀)",
36
+ await one("SELECT CAST('12abc' AS SIGNED)") === 12, null);
37
+ ok("CAST('abc' AS SIGNED) = 0",
38
+ await one("SELECT CAST('abc' AS SIGNED)") === 0, null);
39
+ ok("CAST('1.5' AS SIGNED) = 2(四舍五入半远离零)",
40
+ await one("SELECT CAST('1.5' AS SIGNED)") === 2, null);
41
+ ok("CAST('-1.5' AS SIGNED) = -2",
42
+ await one("SELECT CAST('-1.5' AS SIGNED)") === -2, null);
43
+ ok("CAST(-5 AS UNSIGNED) 按 2^64 回绕",
44
+ String(await one("SELECT CAST(-5 AS UNSIGNED)")) === '18446744073709551611', null);
45
+ ok("CAST('3.9' AS INT) = 4(类型仍是 number)",
46
+ await one("SELECT CAST('3.9' AS INT)") === 4, null);
47
+ ok("CAST(NULL AS SIGNED) = NULL",
48
+ await one("SELECT CAST(NULL AS SIGNED)") === null, null);
49
+
50
+ // ================= #245 UNIQUE 大小写口径 =================
51
+ await q('CREATE TABLE u (id INT PRIMARY KEY, e VARCHAR(10) UNIQUE)');
52
+ await q("INSERT INTO u VALUES (1,'a')");
53
+ ok("WHERE e='A' 命中小写行(等值比较不区分大小写)",
54
+ JSON.stringify(await q("SELECT id,e FROM u WHERE e='A'")) === '[[1,"a"]]', null);
55
+ let dupErr = null;
56
+ try { await q("INSERT INTO u VALUES (2,'A')"); } catch (e) { dupErr = e; }
57
+ ok("INSERT 'A' 在已有 'a' 时报 1062(唯一约束同口径)", !!dupErr, dupErr && dupErr.message);
58
+ ok("报错是 Duplicate entry",
59
+ dupErr && /Duplicate entry/i.test(dupErr.message), dupErr && dupErr.message);
60
+ ok("WHERE e='a' 只命中 1 行(约束与查询不再互相拆台)",
61
+ JSON.stringify(await q("SELECT id,e FROM u WHERE e='a'")) === '[[1,"a"]]', null);
62
+
63
+ // UPDATE 成大小写变体:MySQL 语义 —— 唯一索引里折叠后是同一个键,
64
+ // 但冲突方就是本行自身,所以允许(唯一约束不与自己冲突)。
65
+ let updErr = null;
66
+ try { await q("UPDATE u SET e='A' WHERE id=1"); } catch (e) { updErr = e; }
67
+ ok("UPDATE 成自身的大小写变体不报冲突(MySQL 语义)", !updErr, updErr && updErr.message);
68
+ ok("UPDATE 后值变成 'A'",
69
+ JSON.stringify(await q('SELECT id,e FROM u')) === '[[1,"A"]]', null);
70
+
71
+ // 但 UPDATE 成别的行已占用的键必须报错
72
+ await q('CREATE TABLE u5 (id INT PRIMARY KEY, e VARCHAR(10) UNIQUE)');
73
+ await q("INSERT INTO u5 VALUES (1,'a')");
74
+ await q("INSERT INTO u5 VALUES (2,'b')");
75
+ let updErr2 = null;
76
+ try { await q("UPDATE u5 SET e='A' WHERE id=2"); } catch (e) { updErr2 = e; }
77
+ ok("UPDATE 成其它行已占用的键报 1062", !!updErr2, updErr2 && updErr2.message);
78
+
79
+ // 批量插入路径同样按折叠口径
80
+ await q('CREATE TABLE u2 (id INT PRIMARY KEY, e VARCHAR(10) UNIQUE)');
81
+ let bulkErr = null;
82
+ try { await db._tables.u2.insertMany([{ id: 1, e: 'x' }, { id: 2, e: 'X' }]); }
83
+ catch (e) { bulkErr = e; }
84
+ ok("insertMany 里 'x' / 'X' 被判为重复", !!bulkErr, bulkErr && bulkErr.message);
85
+
86
+ // 复合 UNIQUE 也按折叠口径
87
+ await q('CREATE TABLE u3 (id INT PRIMARY KEY, a VARCHAR(10), b VARCHAR(10), UNIQUE(a,b))');
88
+ await q("INSERT INTO u3 VALUES (1,'ab','c')");
89
+ let compErr = null;
90
+ try { await q("INSERT INTO u3 VALUES (2,'AB','c')"); } catch (e) { compErr = e; }
91
+ ok("复合 UNIQUE 里 'ab'/'AB' 判为重复", !!compErr, compErr && compErr.message);
92
+
93
+ // 数值列的唯一约束不受影响(折叠键 == 原值)
94
+ await q('CREATE TABLE u4 (id INT PRIMARY KEY, n INT UNIQUE)');
95
+ await q('INSERT INTO u4 VALUES (1, 10)');
96
+ let numErr = null;
97
+ try { await q('INSERT INTO u4 VALUES (2, 10)'); } catch (e) { numErr = e; }
98
+ ok("数值列 UNIQUE 仍报 1062", !!numErr, numErr && numErr.message);
99
+ let numOk = null;
100
+ try { await q('INSERT INTO u4 VALUES (2, 11)'); numOk = true; } catch (e) { numOk = false; }
101
+ ok("数值列 UNIQUE 不冲突值可插入', ", numOk === true, numOk);
102
+
103
+ // ================= #246 RENAME 后外键 =================
104
+ await q('CREATE TABLE p (id INT PRIMARY KEY)');
105
+ await q('CREATE TABLE c (id INT PRIMARY KEY, pid INT REFERENCES p(id) ON DELETE CASCADE)');
106
+ await q('INSERT INTO p VALUES (1)');
107
+ await q('INSERT INTO c VALUES (10,1)');
108
+ await q('ALTER TABLE p RENAME TO p2');
109
+ ok("改名后子表外键引用指向新表名",
110
+ db._tables.c._foreignKeys[0].table === 'p2', db._tables.c._foreignKeys);
111
+ let fkErr = null;
112
+ try { await q('INSERT INTO c VALUES (11, 999)'); } catch (e) { fkErr = e; }
113
+ ok("改名后写坏引用被拒绝(外键校验未失效)", !!fkErr, fkErr && fkErr.message);
114
+ ok("报错是 foreign key constraint fails",
115
+ fkErr && /foreign key/i.test(fkErr.message), fkErr && fkErr.message);
116
+ await db.delete('p2', { id: 1 });
117
+ ok("改名后删除父行仍级联删子行",
118
+ JSON.stringify(await q('SELECT * FROM c')) === '[]', null);
119
+
120
+ // ================= #288 SUBSTRING 负偏移越界 =================
121
+ ok("SUBSTRING('abc', -10) = ''(越界负偏移)",
122
+ await one("SELECT SUBSTRING('abc', -10)") === '', null);
123
+ ok("SUBSTRING('abcdef', -10) = ''",
124
+ await one("SELECT SUBSTRING('abcdef', -10)") === '', null);
125
+ ok("SUBSTRING('abcdef', -2) = 'ef'(合法负偏移不回归)",
126
+ await one("SELECT SUBSTRING('abcdef', -2)") === 'ef', null);
127
+ ok("SUBSTRING('Sakila', -3) = 'ila'",
128
+ await one("SELECT SUBSTRING('Sakila', -3)") === 'ila', null);
129
+ ok("SUBSTRING('abc', 2) = 'bc'(正常不回归)",
130
+ await one("SELECT SUBSTRING('abc', 2)") === 'bc', null);
131
+ ok("SUBSTRING('abc', 1, 2) = 'ab'",
132
+ await one("SELECT SUBSTRING('abc', 1, 2)") === 'ab', null);
133
+ ok("SUBSTR 同样钳制",
134
+ await one("SELECT SUBSTR('abc', -10)") === '', null);
135
+ ok("MID 同样钳制",
136
+ await one("SELECT MID('abc', -10)") === '', null);
137
+
138
+ // ================= #289 INSERT emoji =================
139
+ const ins = await one("SELECT INSERT('ab🚀cd', 3, 1, 'X')");
140
+ ok("INSERT('ab🚀cd',3,1,'X') = 'abXcd'(不劈开 emoji)",
141
+ ins === 'abXcd', ins);
142
+ ok("结果无孤立代理项", !/[\uD800-\uDFFF]/.test(String(ins).replace(/[\uD800-\uDBFF][\uDC00-\uDFFF]/g, '')), ins);
143
+ ok("INSERT('Quadratic',3,4,'What') = 'QuWhattic'(ASCII 不回归)",
144
+ await one("SELECT INSERT('Quadratic', 3, 4, 'What')") === 'QuWhattic', null);
145
+ ok("INSERT('abcdef',2,3,'XY') = 'aXYef'",
146
+ await one("SELECT INSERT('abcdef', 2, 3, 'XY')") === 'aXYef', null);
147
+ // pos=0 / 越界:MySQL 返回原串
148
+ ok("INSERT('abc',0,2,'X') = 'abc'(MySQL:pos 不在范围内返回原串)",
149
+ await one("SELECT INSERT('abc', 0, 2, 'X')") === 'abc', null);
150
+ ok("INSERT('abc',-1,2,'X') = 'abc'",
151
+ await one("SELECT INSERT('abc', -1, 2, 'X')") === 'abc', null);
152
+ ok("INSERT('abc',9,2,'X') = 'abc'(越界返回原串)",
153
+ await one("SELECT INSERT('abc', 9, 2, 'X')") === 'abc', null);
154
+ ok("INSERT('abc',1,0,'X') = 'Xabc'(len=0 纯插入)",
155
+ await one("SELECT INSERT('abc', 1, 0, 'X')") === 'Xabc', null);
156
+ ok("INSERT(NULL,...) = NULL",
157
+ await one("SELECT INSERT(NULL, 1, 1, 'X')") === null, null);
158
+
159
+ console.log(`\n${pass} passed, ${fail} failed`);
160
+ process.exit(fail === 0 ? 0 : 1);
161
+ })().catch(e => {
162
+ console.log('[FAIL] unexpected exception: ' + (e.stack || e).split('\n').slice(0, 4).join('\n'));
163
+ process.exit(1);
164
+ });
@@ -0,0 +1,154 @@
1
+ /* ---- 回归:#284 / #285 / #291 / #292 (+ #290 位运算) ---- */
2
+ /*
3
+ * #284 Mongo BSON 编码把所有整数都写成 Double(0x01),从不写 Int32(0x10)。
4
+ * #285 Mongo BSON Binary(0x05) 编码多写一个 subtype 字节,往返损坏错位。
5
+ * #291 GROUP BY 键未做 SQL 类型归一:数字 1 与字符串 '1' 被拆成两个组。
6
+ * #292 ORDER BY 混合 number/string 时退化为字典序,数值顺序排错。
7
+ * #290 位非 `~` 按 32 位有符号整数取反,与 MySQL 的 64 位无符号语义不符。
8
+ */
9
+ const path = require('path');
10
+ const net = require('net');
11
+ const ROOT = path.join(__dirname, '..');
12
+ const { Database, executeSQL } = require(path.join(ROOT, 'index.js'));
13
+ const { createMongoServer, bsonDocument, bsonReadDocument } = require(path.join(ROOT, 'lib/mongo_server.js'));
14
+
15
+ let pass = 0, fail = 0;
16
+ function ok(name, cond, got) {
17
+ if (cond) { pass++; console.log('[OK] ' + name); }
18
+ else { fail++; console.log('[FAIL] ' + name + ' -> ' + JSON.stringify(got)); }
19
+ }
20
+
21
+ function mongoOpMsg(doc) {
22
+ const p = bsonDocument(doc);
23
+ const h = Buffer.alloc(16);
24
+ h.writeInt32LE(16 + 4 + 1 + p.length, 0);
25
+ h.writeInt32LE(1, 4); h.writeInt32LE(0, 8); h.writeInt32LE(2013, 12);
26
+ return Buffer.concat([h, Buffer.alloc(4), Buffer.from([0]), p]);
27
+ }
28
+ function mongoCall(srv, doc) {
29
+ return new Promise((resolve, reject) => {
30
+ const sock = net.connect(srv._server.address().port, '127.0.0.1', () => sock.write(mongoOpMsg(doc)));
31
+ const chunks = [];
32
+ sock.on('error', reject);
33
+ sock.on('data', (c) => {
34
+ chunks.push(c);
35
+ const buf = Buffer.concat(chunks);
36
+ if (buf.length >= 16 && buf.length >= buf.readInt32LE(0)) {
37
+ try { resolve({ raw: buf, doc: bsonReadDocument(buf.slice(21), 0).value }); }
38
+ catch (e) { reject(e); }
39
+ sock.end();
40
+ }
41
+ });
42
+ });
43
+ }
44
+
45
+ (async () => {
46
+ // ================= #284 BSON 整数类型 =================
47
+ const enc = bsonDocument({ n: 30 });
48
+ const hex = enc.toString('hex');
49
+ // size(4) + type(1) + 'n'(2) + int32(4)
50
+ ok("编码 {n:30} 用 Int32(type byte 0x10)", hex.includes('106e00'), hex);
51
+ ok("Int32 只占 4 字节(文档总长 12)", enc.readInt32LE(0) === 12, enc.readInt32LE(0));
52
+
53
+ const encF = bsonDocument({ n: 2.5 });
54
+ ok("浮点仍用 Double(type byte 0x01)", encF.toString('hex').includes('016e00'), encF.toString('hex'));
55
+
56
+ const encBig = bsonDocument({ n: 3000000000 });
57
+ ok("超 int32 范围用 Int64(type byte 0x12)", encBig.toString('hex').includes('126e00'), encBig.toString('hex'));
58
+
59
+ // 端到端:线上回包的 type byte
60
+ const msrv = createMongoServer({ dataDir: ':memory:' });
61
+ await new Promise((r) => msrv.listen(r));
62
+ await mongoCall(msrv, { insert: 'it', documents: [{ n: 30 }], $db: 'test' });
63
+ const r1 = await mongoCall(msrv, { find: 'it', filter: {}, $db: 'test' });
64
+ const i1 = r1.raw.indexOf(Buffer.from('n\0'));
65
+ const typeByte = r1.raw.slice(i1 - 1, i1).toString('hex');
66
+ ok('线上回包 n 的 type byte = 10(int32)', typeByte === '10', typeByte);
67
+ ok('回读值仍是 30', r1.doc.cursor.firstBatch[0].n === 30, r1.doc.cursor.firstBatch[0].n);
68
+
69
+ // ================= #285 BSON Binary 往返 =================
70
+ const orig = Buffer.from([1, 2, 3, 4]);
71
+ const bEnc = bsonDocument({ data: orig });
72
+ const bHex = bEnc.toString('hex');
73
+ // size(4) + type(1) + 'data\0'(5) + len(4) + subtype(1) + data(4) + 结束符(1) = 20
74
+ ok('Binary 编码长度正确(20 字节)', bEnc.readInt32LE(0) === 20, bEnc.readInt32LE(0));
75
+ ok('Binary 只写 1 个 subtype 字节', /05646174610004000000 00 01020304/.test(bHex.replace(/ /g, ''))
76
+ || bHex.includes('056461746100040000000001020304'), bHex);
77
+ const bDec = bsonReadDocument(bEnc, 0).value;
78
+ ok('Binary 往返逐字节相等', Buffer.from(bDec.data).equals(orig), Buffer.from(bDec.data));
79
+
80
+ // 多字段文档:Binary 之后的字段不能解析失步
81
+ const multi = bsonDocument({ data: orig, tail: 7 });
82
+ const mDec = bsonReadDocument(multi, 0).value;
83
+ ok('Binary 之后的字段仍能正确解析', mDec.tail === 7, mDec);
84
+ ok('多字段文档里 Binary 数据完好', Buffer.from(mDec.data).equals(orig), Buffer.from(mDec.data));
85
+
86
+ // 端到端往返
87
+ await mongoCall(msrv, { insert: 'bin', documents: [{ _id: 'b', data: orig }], $db: 'test' });
88
+ const r2 = await mongoCall(msrv, { find: 'bin', filter: {}, $db: 'test' });
89
+ const got = Buffer.from(r2.doc.cursor.firstBatch[0].data);
90
+ ok('服务端往返二进制数据完好', got.equals(orig), got);
91
+
92
+ msrv.close();
93
+
94
+ // ================= #291 GROUP BY 键归一 =================
95
+ const db = new Database(':memory:', { autoSave: false });
96
+ const q = async (sql) => (await executeSQL(db, sql, { safety: false })).rows;
97
+
98
+ await q('CREATE TABLE m (k TEXT, v INT)');
99
+ await q("INSERT INTO m VALUES ('1',10),(1,20),('2',30),(2,40)");
100
+ const grouped = await q('SELECT k, COUNT(*), SUM(v) FROM m GROUP BY k ORDER BY k');
101
+ ok("GROUP BY 把 '1' 与 1 合并成 1 组", grouped.length === 2, grouped);
102
+ ok("GROUP BY '1' 组 COUNT=2, SUM=30",
103
+ JSON.stringify(grouped[0]) === JSON.stringify(['1', 2, 30]), grouped);
104
+ ok("GROUP BY '2' 组 COUNT=2, SUM=70",
105
+ JSON.stringify(grouped[1]) === JSON.stringify(['2', 2, 70]), grouped);
106
+
107
+ // 纯数值分组不回归
108
+ await q('CREATE TABLE m2 (k INT, v INT)');
109
+ await q('INSERT INTO m2 VALUES (1,10),(1,20),(2,30)');
110
+ const g2 = await q('SELECT k, COUNT(*), SUM(v) FROM m2 GROUP BY k ORDER BY k');
111
+ ok('纯数值 GROUP BY 不回归',
112
+ JSON.stringify(g2) === JSON.stringify([[1, 2, 30], [2, 1, 30]]), g2);
113
+
114
+ // ================= #292 ORDER BY 混合类型 =================
115
+ await q('CREATE TABLE s (k TEXT)');
116
+ await q("INSERT INTO s VALUES ('10'),(2),('1')");
117
+ const ordered = await q('SELECT k FROM s ORDER BY k');
118
+ const keys = ordered.map(r => r[0]);
119
+ ok("ORDER BY 混合类型按数值排序:1, 2, 10",
120
+ keys.length === 3 && Number(keys[0]) === 1 && Number(keys[1]) === 2 && Number(keys[2]) === 10, keys);
121
+
122
+ // 纯字符串排序仍按字典序
123
+ await q('CREATE TABLE s2 (k TEXT)');
124
+ await q("INSERT INTO s2 VALUES ('b'),('a'),('c')");
125
+ const o2 = await q('SELECT k FROM s2 ORDER BY k');
126
+ ok('纯字符串 ORDER BY 仍按字典序',
127
+ JSON.stringify(o2.map(r => r[0])) === JSON.stringify(['a', 'b', 'c']), o2);
128
+
129
+ // 非数字字符串仍按字典序(不能被误当数值)
130
+ await q('CREATE TABLE s3 (k TEXT)');
131
+ await q("INSERT INTO s3 VALUES ('b'),('10'),('a')");
132
+ const o3 = await q('SELECT k FROM s3 ORDER BY k');
133
+ ok("非数字字符串仍按字典序('10' < 'a' < 'b')",
134
+ JSON.stringify(o3.map(r => r[0])) === JSON.stringify(['10', 'a', 'b']), o3);
135
+
136
+ // ================= #290 位运算 64 位无符号 =================
137
+ const one = async (sql) => (await q(sql))[0][0];
138
+ ok("~0 = 18446744073709551615(MySQL 64 位无符号)",
139
+ String(await one('SELECT ~0')) === '18446744073709551615', null);
140
+ ok("~5 = 18446744073709551610",
141
+ String(await one('SELECT ~5')) === '18446744073709551610', null);
142
+ ok('5 & ~1 = 4', await one('SELECT 5 & ~1') === 4, null);
143
+ ok('12 & 10 = 8', await one('SELECT 12 & 10') === 8, null);
144
+ ok('12 | 10 = 14', await one('SELECT 12 | 10') === 14, null);
145
+ ok('12 ^ 10 = 6', await one('SELECT 12 ^ 10') === 6, null);
146
+ ok('1 << 63 仍是精确 BigInt',
147
+ String(await one('SELECT 1 << 63')) === '9223372036854775808', null);
148
+
149
+ console.log(`\n${pass} passed, ${fail} failed`);
150
+ process.exit(fail === 0 ? 0 : 1);
151
+ })().catch(e => {
152
+ console.log('[FAIL] unexpected exception: ' + (e.stack || e).split('\n').slice(0, 4).join('\n'));
153
+ process.exit(1);
154
+ });
@@ -88,7 +88,10 @@ async function main() {
88
88
  ok('取模 %', JSON.stringify(await rowsOf('SELECT 10 % 3 AS r')) === '[[1]]');
89
89
  ok('左移 <<', JSON.stringify(await rowsOf('SELECT 1 << 8 AS r')) === '[[256]]');
90
90
  ok('按位与 &', JSON.stringify(await rowsOf('SELECT 255 & 15 AS r')) === '[[15]]');
91
- ok('按位取反 ~', JSON.stringify(await rowsOf('SELECT ~0 AS r')) === '[[-1]]');
91
+ // #290:位运算结果按 64 位无符号整数语义(MySQL)。
92
+ // 旧实现 `~(x | 0)` 把值截成 32 位有符号整数,~0 得到 -1 —— 那是错的,
93
+ // MySQL 的 SELECT ~0 返回 18446744073709551615。
94
+ ok('按位取反 ~', JSON.stringify(await rowsOf('SELECT ~0 AS r')) === '[["18446744073709551615"]]');
92
95
  ok('WHERE 中位运算过滤',
93
96
  JSON.stringify(await rowsOf('SELECT name FROM emp WHERE flag & 1 = 1')) === '[["a"],["c"],["d"]]');
94
97