jsql-neo 6.8.10 → 6.8.11
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 +1 -1
- package/index.js +1 -1
- package/lib/database.js +29 -1
- package/lib/sql.js +115 -19
- package/lib/table.js +130 -26
- package/package.json +3 -3
- package/test/issue-243-289.test.js +164 -0
- package/test/readme-audit.test.js +4 -1
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.
|
|
6
|
+
> **v6.8.11** — 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
|

|
|
9
9
|

|
package/index.js
CHANGED
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
|
-
|
|
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 传播到引用它的子表;改自身外键列时校验引用存在。
|
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
|
-
|
|
3386
|
-
|
|
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) {
|
|
@@ -3845,18 +3919,26 @@ function resolveOperand(operand, row, ctx) {
|
|
|
3845
3919
|
// MySQL 整数除法 DIV(结果向零取整)
|
|
3846
3920
|
case 'DIV': return mysqlNum(r) === 0 ? null : Math.trunc(mysqlNum(l) / mysqlNum(r));
|
|
3847
3921
|
// 位运算:先按整数归一,与 MySQL 的整数位运算语义一致
|
|
3848
|
-
|
|
3849
|
-
|
|
3850
|
-
|
|
3851
|
-
|
|
3852
|
-
|
|
3922
|
+
// #290:位运算按 64 位无符号整数语义(与 MySQL 和 doc/sql-reference.md 一致)。
|
|
3923
|
+
// 旧的 `| 0` 路径把操作数截成 32 位有符号整数,高位全丢,
|
|
3924
|
+
// 且与已经改成 64 位的 ~ / << / >> 口径不一致(如 5 & ~1 会算错)。
|
|
3925
|
+
case '&': return fromUint64(toUint64(l) & toUint64(r));
|
|
3926
|
+
case '|': return fromUint64(toUint64(l) | toUint64(r));
|
|
3927
|
+
case '^': return fromUint64(toUint64(l) ^ toUint64(r));
|
|
3853
3928
|
// Issue #109:移位量截断为整数并用 BigInt 精确计算(见 sqlBitShift)
|
|
3854
3929
|
case '<<': case '>>': return sqlBitShift(l, r, operand.op);
|
|
3855
3930
|
}
|
|
3856
3931
|
return null;
|
|
3857
3932
|
}
|
|
3858
3933
|
case 'bitnot':
|
|
3859
|
-
|
|
3934
|
+
// #290:位非按 64 位无符号整数语义计算。
|
|
3935
|
+
// 旧实现 `~(x | 0)` 先截成 32 位有符号整数,JS 的 ~ 也是 32 位有符号,
|
|
3936
|
+
// 于是 ~0 = -1、~5 = -6,高 32 位全丢。MySQL 的位运算结果是
|
|
3937
|
+
// unsigned 64-bit integer:~0 = 18446744073709551615。
|
|
3938
|
+
// 复用 #109 建立的 sqlBitShift 同款路径(toUint64 / fromUint64)。
|
|
3939
|
+
// 注意 BigInt 的 ~ 是**有符号**取反,必须再用 asUintN(64) 回绕,
|
|
3940
|
+
// 否则 ~0n = -1n 会被 fromUint64 原样输出成 -1。
|
|
3941
|
+
return fromUint64(BigInt.asUintN(64, ~toUint64(resolveOperand(operand.expr, row, ctx))));
|
|
3860
3942
|
case 'negate': {
|
|
3861
3943
|
const v = resolveOperand(operand.operand, row, ctx);
|
|
3862
3944
|
if (v === null || v === undefined) return null;
|
|
@@ -3888,9 +3970,12 @@ function resolveOperand(operand, row, ctx) {
|
|
|
3888
3970
|
case '/': { const rn = mysqlNum(r); return rn === 0 ? null : mysqlNum(l) / rn; }
|
|
3889
3971
|
case '%': { const rn = mysqlNum(r); return rn === 0 ? null : mysqlNum(l) % rn; }
|
|
3890
3972
|
case 'DIV': return mysqlNum(r) === 0 ? null : Math.trunc(mysqlNum(l) / mysqlNum(r));
|
|
3891
|
-
|
|
3892
|
-
|
|
3893
|
-
|
|
3973
|
+
// #290:位运算按 64 位无符号整数语义(与 MySQL 和 doc/sql-reference.md 一致)。
|
|
3974
|
+
// 旧的 `| 0` 路径把操作数截成 32 位有符号整数,高位全丢,
|
|
3975
|
+
// 且与已经改成 64 位的 ~ / << / >> 口径不一致(如 5 & ~1 会算错)。
|
|
3976
|
+
case '&': return fromUint64(toUint64(l) & toUint64(r));
|
|
3977
|
+
case '|': return fromUint64(toUint64(l) | toUint64(r));
|
|
3978
|
+
case '^': return fromUint64(toUint64(l) ^ toUint64(r));
|
|
3894
3979
|
// Issue #109:移位量截断 + BigInt 精确计算
|
|
3895
3980
|
case '<<': case '>>': return sqlBitShift(l, r, operand.op);
|
|
3896
3981
|
default: return null;
|
|
@@ -4839,9 +4924,14 @@ function applyScalarFunction(fnNode, row, ctx) {
|
|
|
4839
4924
|
case 'INSERT': {
|
|
4840
4925
|
const s = args[0], pos = args[1], len = args[2], ins = args[3];
|
|
4841
4926
|
if (s == null || pos == null || len == null || ins == null) return null;
|
|
4842
|
-
|
|
4843
|
-
|
|
4844
|
-
|
|
4927
|
+
// #289:按 code point 切分。MySQL 的 INSERT() 是 multibyte safe 的,
|
|
4928
|
+
// 此前用 str.length / str.slice 按 UTF-16 code unit 切,
|
|
4929
|
+
// emoji(占两个 code unit)会被劈成孤立代理项。
|
|
4930
|
+
const cps = Array.from(String(s));
|
|
4931
|
+
const p = Math.trunc(Number(pos)), l = Math.trunc(Number(len));
|
|
4932
|
+
// MySQL:pos 不在字符串长度范围内时返回原串(含 pos = 0)。
|
|
4933
|
+
if (p < 1 || p > cps.length + 1 || l < 0) return String(s);
|
|
4934
|
+
return cps.slice(0, p - 1).join('') + String(ins) + cps.slice(p - 1 + l).join('');
|
|
4845
4935
|
}
|
|
4846
4936
|
case 'STRCMP': {
|
|
4847
4937
|
if (args[0] == null || args[1] == null) return null;
|
|
@@ -5064,6 +5154,11 @@ function applyScalarFunction(fnNode, row, ctx) {
|
|
|
5064
5154
|
// MySQL 语义:1-based;负数从末尾倒数;0 视为 1(MySQL 返回空串)
|
|
5065
5155
|
if (start === 0) return '';
|
|
5066
5156
|
if (start < 0) start = len + start + 1;
|
|
5157
|
+
// #288:负偏移调整后若仍落在字符串起始之前,结果应为空串。
|
|
5158
|
+
// 此前没有钳制 start,把负下标交给 Array.prototype.slice ——
|
|
5159
|
+
// JS 的 slice 对负下标按「从末尾倒数」解释,于是 SUBSTRING('abc',-10)
|
|
5160
|
+
// 返回整串 'abc'、SUBSTRING('abcdef',-10) 返回尾部 'cdef'。
|
|
5161
|
+
if (!Number.isFinite(start) || start < 1) return '';
|
|
5067
5162
|
if (args[2] !== undefined) {
|
|
5068
5163
|
const n = Number(args[2]);
|
|
5069
5164
|
if (n < 0) return '';
|
|
@@ -6195,9 +6290,10 @@ function evaluateExpr(expr, row, ctx) {
|
|
|
6195
6290
|
case '/': { const rn = mysqlNum(r); return rn === 0 ? null : mysqlNum(l) / rn; }
|
|
6196
6291
|
case '%': { const rn = mysqlNum(r); return rn === 0 ? null : mysqlNum(l) % rn; }
|
|
6197
6292
|
case 'DIV': return mysqlNum(r) === 0 ? null : Math.trunc(mysqlNum(l) / mysqlNum(r));
|
|
6198
|
-
|
|
6199
|
-
case '
|
|
6200
|
-
case '
|
|
6293
|
+
// #290:位运算按 64 位无符号整数语义(与 MySQL 和 doc/sql-reference.md 一致)
|
|
6294
|
+
case '&': return fromUint64(toUint64(l) & toUint64(r));
|
|
6295
|
+
case '|': return fromUint64(toUint64(l) | toUint64(r));
|
|
6296
|
+
case '^': return fromUint64(toUint64(l) ^ toUint64(r));
|
|
6201
6297
|
// Issue #109:移位量截断 + BigInt 精确计算
|
|
6202
6298
|
case '<<': case '>>': return sqlBitShift(l, r, expr.op);
|
|
6203
6299
|
default: return null;
|
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
|
-
|
|
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
|
-
|
|
608
|
-
|
|
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
|
-
|
|
637
|
-
|
|
638
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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(
|
|
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(
|
|
2005
|
+
if (uniqueTracker[field].has(key)) {
|
|
1947
2006
|
throw createError('ER_DUP_ENTRY', String(data[field]), field);
|
|
1948
2007
|
}
|
|
1949
|
-
uniqueTracker[field].add(
|
|
2008
|
+
uniqueTracker[field].add(key);
|
|
1950
2009
|
} else if (this._btrees[field]) {
|
|
1951
|
-
|
|
1952
|
-
|
|
1953
|
-
|
|
1954
|
-
|
|
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
|
-
|
|
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
|
-
|
|
2000
|
-
|
|
2001
|
-
|
|
2002
|
-
|
|
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.
|
|
3
|
+
"version": "6.8.11",
|
|
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",
|
|
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",
|
|
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
|
+
});
|
|
@@ -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
|
-
|
|
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
|
|