jsql-neo 6.5.31 → 6.5.32
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 +7 -0
- package/lib/sql.js +163 -74
- package/lib/table.js +58 -13
- package/package.json +3 -3
- package/test/issue-69-70.test.js +152 -0
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.5.
|
|
6
|
+
> **v6.5.32** — 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
|
@@ -1962,6 +1962,11 @@ class Database {
|
|
|
1962
1962
|
if (table._foreignKeys && table._foreignKeys.length) {
|
|
1963
1963
|
table._validateForeignKeys({ ...row, ...validated });
|
|
1964
1964
|
}
|
|
1965
|
+
// CHECK 约束(Issue #70):Database.updateById 直接 Object.assign 写行,
|
|
1966
|
+
// 绕过了 Table.updateById 的约束校验,导致 CHECK 在 UPDATE 上失效。
|
|
1967
|
+
if (typeof table._enforceChecks === 'function') {
|
|
1968
|
+
table._enforceChecks({ ...row, ...validated });
|
|
1969
|
+
}
|
|
1965
1970
|
// 改主键/唯一值时索引必须同步:否则 _pkIndex 还指向旧值,
|
|
1966
1971
|
// 后续 FK 校验 findOne({id:新值}) 查不到刚更新的父行。
|
|
1967
1972
|
{
|
|
@@ -1987,6 +1992,8 @@ class Database {
|
|
|
1987
1992
|
for (const [id, data] of pairs) {
|
|
1988
1993
|
const row = this._resolveId(table, id);
|
|
1989
1994
|
if (row) {
|
|
1995
|
+
// CHECK 约束(Issue #70):批量更新同样不能在无校验的情况下写行
|
|
1996
|
+
if (typeof table._enforceChecks === 'function') table._enforceChecks({ ...row, ...data });
|
|
1990
1997
|
Object.assign(row, data);
|
|
1991
1998
|
count++;
|
|
1992
1999
|
if (pk) this._walWrite({ op: 'update', table: tableName, pk, id, row: { ...data } });
|
package/lib/sql.js
CHANGED
|
@@ -466,7 +466,7 @@ function tokenize(sql) {
|
|
|
466
466
|
// 注意:% & | ^ ~ 这些运算符必须在词法层产出 token。
|
|
467
467
|
// 之前 parseTerm() 里写了 '%' 分支但字符集里没有 '%',
|
|
468
468
|
// 导致 SELECT 10 % 3 直接报 "Unexpected character '%'",那段是死代码。
|
|
469
|
-
if ('=<>+-*/()
|
|
469
|
+
if ('=<>+-*/(),.;%&|^~!'.includes(c)) {
|
|
470
470
|
tokens.push(new SQLToken('op', c, i));
|
|
471
471
|
i++;
|
|
472
472
|
continue;
|
|
@@ -751,6 +751,8 @@ class Parser {
|
|
|
751
751
|
const schema = {};
|
|
752
752
|
// 表级 FOREIGN KEY 可能写在列定义之前,先收集、待所有列解析完再绑定
|
|
753
753
|
const pendingFKs = [];
|
|
754
|
+
// 表级 CHECK 条件(Issue #70):先收集 AST,等所有列解析完再挂到引用列上
|
|
755
|
+
const pendingChecks = [];
|
|
754
756
|
let hasPk = false;
|
|
755
757
|
while (true) {
|
|
756
758
|
const t = this.peek();
|
|
@@ -787,14 +789,14 @@ class Parser {
|
|
|
787
789
|
} else if (t.type === 'keyword' && t.value === 'CONSTRAINT') {
|
|
788
790
|
this.expectKeyword('CONSTRAINT');
|
|
789
791
|
if (this.peek().type === 'ident') this.next(); // 约束名
|
|
790
|
-
this._parseTableConstraint(schema, pendingFKs);
|
|
792
|
+
this._parseTableConstraint(schema, pendingFKs, pendingChecks);
|
|
791
793
|
} else if (this.isWord('FOREIGN') || this.isWord('CHECK') ||
|
|
792
794
|
t.type === 'keyword' && (t.value === 'KEY' || t.value === 'INDEX')) {
|
|
793
795
|
// 表级约束:FOREIGN KEY ... REFERENCES ... / CHECK (...) / KEY name (cols)
|
|
794
796
|
// KEY/INDEX 是保留字:裸写作列名(如 CREATE TABLE t (key TEXT))必须报错,
|
|
795
797
|
// 由 _parseTableConstraint 消费 KEY 后遇到类型 token 触发
|
|
796
798
|
// "Expected ',' or ')'",见 identifier-keywords 测试。
|
|
797
|
-
this._parseTableConstraint(schema, pendingFKs);
|
|
799
|
+
this._parseTableConstraint(schema, pendingFKs, pendingChecks);
|
|
798
800
|
} else if (t.type === 'eof' || (t.type === 'op' && t.value === ')')) {
|
|
799
801
|
break;
|
|
800
802
|
} else {
|
|
@@ -832,6 +834,18 @@ class Parser {
|
|
|
832
834
|
}
|
|
833
835
|
schema[column].foreignKey = fk;
|
|
834
836
|
}
|
|
837
|
+
// 表级 CHECK(Issue #70):挂到条件引用的第一个列上(找不到就用第一列)。
|
|
838
|
+
// 判定函数拿到的是整行数据,因此与挂在哪个列无关;放在 def.checks 数组里
|
|
839
|
+
// 是为了不与列自身的 CHECK 互相覆盖,同时供 lib/table.js 全局校验。
|
|
840
|
+
for (const cond of pendingChecks) {
|
|
841
|
+
const refs = collectCheckColumns(cond.ast);
|
|
842
|
+
let target = refs.find(c => schema[c] !== undefined);
|
|
843
|
+
if (!target) target = Object.keys(schema).find(k => k !== '_softDelete');
|
|
844
|
+
if (!target) continue;
|
|
845
|
+
const d = schema[target];
|
|
846
|
+
if (!Array.isArray(d.checks)) d.checks = [];
|
|
847
|
+
d.checks.push({ sql: cond.sql, fn: makeCheckFn(cond.ast) });
|
|
848
|
+
}
|
|
835
849
|
return { type: 'createTable', name, schema, ifNotExists };
|
|
836
850
|
}
|
|
837
851
|
|
|
@@ -885,13 +899,13 @@ class Parser {
|
|
|
885
899
|
const t = this.peek();
|
|
886
900
|
// 列级 CHECK (age INT CHECK(age >= 0))。
|
|
887
901
|
// CHECK 刻意不在 KEYWORDS 里(避免影响同名标识符),所以用 isWord 匹配,
|
|
888
|
-
// 放在 keyword switch
|
|
889
|
-
//
|
|
890
|
-
// "Expected ',' or ')' in CREATE TABLE, got 'CHECK'"。
|
|
891
|
-
// 与表级保持一致:解析并跳过,条件文本存到 def.check 供后续实现。
|
|
902
|
+
// 放在 keyword switch 之外。条件解析成 AST 并编译成判定函数(Issue #70):
|
|
903
|
+
// def.check 供 lib/table.js 直接调用,def.checkSql 用于持久化后重编译。
|
|
892
904
|
if (this.isWord('CHECK')) {
|
|
893
905
|
this.next();
|
|
894
|
-
|
|
906
|
+
const cond = this._parseCheckCondition();
|
|
907
|
+
def.check = makeCheckFn(cond.ast);
|
|
908
|
+
def.checkSql = cond.sql;
|
|
895
909
|
continue;
|
|
896
910
|
}
|
|
897
911
|
// 列级外键: pid INTEGER REFERENCES p(id) [ON DELETE ...] [ON UPDATE ...]
|
|
@@ -995,6 +1009,25 @@ class Parser {
|
|
|
995
1009
|
return stmt;
|
|
996
1010
|
}
|
|
997
1011
|
|
|
1012
|
+
/**
|
|
1013
|
+
* 解析 CHECK 后的括号条件:CHECK (expr)。
|
|
1014
|
+
* 返回 { ast, sql }:AST 用于编译判定函数,sql 文本用于持久化。
|
|
1015
|
+
*/
|
|
1016
|
+
_parseCheckCondition() {
|
|
1017
|
+
this.expect('op', '(');
|
|
1018
|
+
const start = this.pos;
|
|
1019
|
+
this.barePredicateDepth = (this.barePredicateDepth || 0) + 1;
|
|
1020
|
+
let ast;
|
|
1021
|
+
try {
|
|
1022
|
+
ast = this.parseExpr();
|
|
1023
|
+
} finally {
|
|
1024
|
+
this.barePredicateDepth--;
|
|
1025
|
+
}
|
|
1026
|
+
const sql = tokensToSql(this.tokens.slice(start, this.pos));
|
|
1027
|
+
this.expect('op', ')');
|
|
1028
|
+
return { ast, sql };
|
|
1029
|
+
}
|
|
1030
|
+
|
|
998
1031
|
/** 跳过一对括号(含嵌套),用于表级约束里的列清单 */
|
|
999
1032
|
_skipParens() {
|
|
1000
1033
|
this.expect('op', '(');
|
|
@@ -1042,7 +1075,7 @@ class Parser {
|
|
|
1042
1075
|
* FOREIGN KEY 会真正解析出 field/refTable/refField/onDelete/onUpdate 并登记,
|
|
1043
1076
|
* 与列级 REFERENCES 行为一致(校验在 lib/table.js)。
|
|
1044
1077
|
*/
|
|
1045
|
-
_parseTableConstraint(schema, pendingFKs) {
|
|
1078
|
+
_parseTableConstraint(schema, pendingFKs, pendingChecks) {
|
|
1046
1079
|
if (this.isWord('FOREIGN')) {
|
|
1047
1080
|
this.next();
|
|
1048
1081
|
if (!this.isKeyword('KEY')) throw new Error(`Expected KEY after FOREIGN, got '${this.peek().value}'`);
|
|
@@ -1080,7 +1113,10 @@ class Parser {
|
|
|
1080
1113
|
}
|
|
1081
1114
|
if (this.isWord('CHECK')) {
|
|
1082
1115
|
this.next();
|
|
1083
|
-
|
|
1116
|
+
// 表级 CHECK 的条件在列清单解析完之前可能引用尚未定义的列,
|
|
1117
|
+
// 与 FOREIGN KEY 一样先收集,等 parseCreateTable 末尾再绑定。
|
|
1118
|
+
if (pendingChecks) pendingChecks.push(this._parseCheckCondition());
|
|
1119
|
+
else this._skipParens();
|
|
1084
1120
|
return;
|
|
1085
1121
|
}
|
|
1086
1122
|
if (this.isKeyword('PRIMARY')) {
|
|
@@ -2344,6 +2380,14 @@ class Parser {
|
|
|
2344
2380
|
}
|
|
2345
2381
|
|
|
2346
2382
|
parseNot() {
|
|
2383
|
+
// '!' 逻辑非(MySQL 语义):'!' 与 NOT 等价,而 '!=' / '!~' / '!~*' 已在
|
|
2384
|
+
// tokenize 的多字符分支处理,走到这里的裸 '!' 一定是逻辑非。
|
|
2385
|
+
if (this.peek().type === 'op' && this.peek().value === '!') {
|
|
2386
|
+
this.next();
|
|
2387
|
+
const inner = this.parseNot();
|
|
2388
|
+
if (inner && inner.type === 'exists') { inner.not = !inner.not; return inner; }
|
|
2389
|
+
return { type: 'not', expr: inner };
|
|
2390
|
+
}
|
|
2347
2391
|
if (this.isKeyword('NOT')) {
|
|
2348
2392
|
this.next();
|
|
2349
2393
|
const inner = this.parseNot();
|
|
@@ -3253,6 +3297,72 @@ function mysqlNum(v) {
|
|
|
3253
3297
|
return 0;
|
|
3254
3298
|
}
|
|
3255
3299
|
|
|
3300
|
+
// ---------------------------------------------------------------------------
|
|
3301
|
+
// CHECK 约束(Issue #70)
|
|
3302
|
+
//
|
|
3303
|
+
// CREATE TABLE 里的 CHECK 条件此前被 _skipParens() 整段跳过:语法能过,
|
|
3304
|
+
// 但约束完全不生效(列级/表级都一样),非法数据静默入库。
|
|
3305
|
+
// 这里把条件解析成 AST,编译成 (val, row) => boolean 的判定函数:
|
|
3306
|
+
// • 求值走 evaluateExpr,与 WHERE 条件同一套语义(三值逻辑、类型强转一致);
|
|
3307
|
+
// • MySQL 规则:条件为 TRUE 或 UNKNOWN(NULL) 视为通过,只有 FALSE 才违反;
|
|
3308
|
+
// • JSON 持久化会丢函数,所以同时保存 checkSql,重载时由
|
|
3309
|
+
// compileCheckExpr() 重新编译(lib/table.js 惰性调用)。
|
|
3310
|
+
// ---------------------------------------------------------------------------
|
|
3311
|
+
|
|
3312
|
+
/** 把 token 还原成可再次解析的 SQL 文本(仅用于持久化 CHECK 条件)。 */
|
|
3313
|
+
function tokensToSql(tokens) {
|
|
3314
|
+
return tokens.map(t => {
|
|
3315
|
+
if (t.type === 'string') return "'" + String(t.value).replace(/\\/g, '\\\\').replace(/'/g, "''") + "'";
|
|
3316
|
+
if (t.type === 'number') return String(t.value);
|
|
3317
|
+
if (t.type === 'sysvar') return '@' + t.value;
|
|
3318
|
+
if (t.type === 'param') return '?';
|
|
3319
|
+
return t.text !== undefined ? t.text : String(t.value);
|
|
3320
|
+
}).join(' ');
|
|
3321
|
+
}
|
|
3322
|
+
|
|
3323
|
+
/** 编译 CHECK 条件 AST 为判定函数。 */
|
|
3324
|
+
function makeCheckFn(ast) {
|
|
3325
|
+
return function checkFn(val, row) {
|
|
3326
|
+
let res;
|
|
3327
|
+
try {
|
|
3328
|
+
res = evaluateExpr(ast, row || {}, {});
|
|
3329
|
+
} catch (_) {
|
|
3330
|
+
// 求值异常不能当成"约束通过",否则又是一次静默放行
|
|
3331
|
+
return false;
|
|
3332
|
+
}
|
|
3333
|
+
return res === null || res === undefined ? true : Boolean(res);
|
|
3334
|
+
};
|
|
3335
|
+
}
|
|
3336
|
+
|
|
3337
|
+
/** 从 CHECK 表达式里收集引用到的列名(按出现顺序去重)。 */
|
|
3338
|
+
function collectCheckColumns(node, out = []) {
|
|
3339
|
+
if (node === null || node === undefined) return out;
|
|
3340
|
+
if (Array.isArray(node)) {
|
|
3341
|
+
for (const item of node) collectCheckColumns(item, out);
|
|
3342
|
+
return out;
|
|
3343
|
+
}
|
|
3344
|
+
if (typeof node !== 'object') return out;
|
|
3345
|
+
if (node.type === 'column' && node.name) {
|
|
3346
|
+
const name = String(node.name);
|
|
3347
|
+
const bare = name.indexOf('.') === -1 ? name : name.slice(name.lastIndexOf('.') + 1);
|
|
3348
|
+
if (!out.includes(bare)) out.push(bare);
|
|
3349
|
+
}
|
|
3350
|
+
for (const key of Object.keys(node)) {
|
|
3351
|
+
if (key === 'type') continue;
|
|
3352
|
+
const v = node[key];
|
|
3353
|
+
if (v && typeof v === 'object') collectCheckColumns(v, out);
|
|
3354
|
+
}
|
|
3355
|
+
return out;
|
|
3356
|
+
}
|
|
3357
|
+
|
|
3358
|
+
/** 由 SQL 文本重新编译 CHECK 条件(持久化重载路径)。 */
|
|
3359
|
+
function compileCheckExpr(sqlText) {
|
|
3360
|
+
const p = new Parser(tokenize(String(sqlText)));
|
|
3361
|
+
const ast = p.parseBooleanExpr();
|
|
3362
|
+
if (p.peek().type !== 'eof') throw new Error(`Unexpected token '${p.peek().value}' after CHECK expression`);
|
|
3363
|
+
return makeCheckFn(ast);
|
|
3364
|
+
}
|
|
3365
|
+
|
|
3256
3366
|
/**
|
|
3257
3367
|
* BigInt 参与的整数算术(Issue #38)。
|
|
3258
3368
|
*
|
|
@@ -3361,60 +3471,50 @@ function resolveOperand(operand, row, ctx) {
|
|
|
3361
3471
|
// '5' + 5 = 10 '5' + '5' = 10 'abc' + 1 = 1 'a' + 'b' = 0
|
|
3362
3472
|
// 任一侧是「数值」时做算术加法,另一侧非数值按 0;
|
|
3363
3473
|
// 两侧都不是数值才是 0(JS 的 l + r 会把 '5' + 5 拼成 '55')。
|
|
3364
|
-
|
|
3365
|
-
|
|
3366
|
-
return (ln2 === null ? 0 : ln2) + (rn2 === null ? 0 : rn2);
|
|
3367
|
-
}
|
|
3368
|
-
const ln = numericIfNumeric(l), rn = numericIfNumeric(r);
|
|
3369
|
-
if (ln !== null) return ln + (rn === null ? 0 : rn);
|
|
3370
|
-
if (rn !== null) return rn; // 左侧非数值按 0
|
|
3371
|
-
return 0;
|
|
3474
|
+
const ln = mysqlNum(l), rn = mysqlNum(r);
|
|
3475
|
+
return ln + rn;
|
|
3372
3476
|
}
|
|
3373
3477
|
case '-': {
|
|
3374
3478
|
const bx = bigintExactArith(l, r, '-');
|
|
3375
3479
|
if (bx !== undefined) return bx;
|
|
3376
|
-
|
|
3377
|
-
const ln = Number(l), rn = Number(r);
|
|
3378
|
-
if (isNaN(ln) || isNaN(rn)) return null;
|
|
3480
|
+
const ln = mysqlNum(l), rn = mysqlNum(r);
|
|
3379
3481
|
return ln - rn;
|
|
3380
3482
|
}
|
|
3381
3483
|
case '*': {
|
|
3382
3484
|
const bx = bigintExactArith(l, r, '*');
|
|
3383
3485
|
if (bx !== undefined) return bx;
|
|
3384
|
-
const ln =
|
|
3385
|
-
if (isNaN(ln) || isNaN(rn)) return null;
|
|
3486
|
+
const ln = mysqlNum(l), rn = mysqlNum(r);
|
|
3386
3487
|
return ln * rn;
|
|
3387
3488
|
}
|
|
3388
3489
|
case '/': {
|
|
3389
|
-
const ln =
|
|
3390
|
-
if (
|
|
3490
|
+
const ln = mysqlNum(l), rn = mysqlNum(r);
|
|
3491
|
+
if (rn === 0) return null;
|
|
3391
3492
|
return ln / rn;
|
|
3392
3493
|
}
|
|
3393
3494
|
case '%': {
|
|
3394
|
-
const ln =
|
|
3395
|
-
if (
|
|
3495
|
+
const ln = mysqlNum(l), rn = mysqlNum(r);
|
|
3496
|
+
if (rn === 0) return null;
|
|
3396
3497
|
return ln % rn;
|
|
3397
3498
|
}
|
|
3398
3499
|
// MySQL 整数除法 DIV(结果向零取整)
|
|
3399
|
-
case 'DIV': return r === 0 ? null : Math.trunc(
|
|
3500
|
+
case 'DIV': return mysqlNum(r) === 0 ? null : Math.trunc(mysqlNum(l) / mysqlNum(r));
|
|
3400
3501
|
// 位运算:先按整数归一,与 MySQL 的整数位运算语义一致
|
|
3401
|
-
case '&': return (
|
|
3402
|
-
case '|': return (
|
|
3403
|
-
case '^': return (
|
|
3502
|
+
case '&': return (mysqlNum(l) | 0) & (mysqlNum(r) | 0);
|
|
3503
|
+
case '|': return (mysqlNum(l) | 0) | (mysqlNum(r) | 0);
|
|
3504
|
+
case '^': return (mysqlNum(l) | 0) ^ (mysqlNum(r) | 0);
|
|
3404
3505
|
// P1-22: JavaScript 位运算只使用 32 位整数,移位量对 32 取模
|
|
3405
3506
|
// 1 << 32 = 1 << 0 = 1,但 SQL 中 1 << 32 = 4294967296
|
|
3406
|
-
case '<<': return
|
|
3407
|
-
case '>>': return Math.floor(
|
|
3507
|
+
case '<<': return mysqlNum(l) * Math.pow(2, mysqlNum(r));
|
|
3508
|
+
case '>>': return Math.floor(mysqlNum(l) / Math.pow(2, mysqlNum(r)));
|
|
3408
3509
|
}
|
|
3409
3510
|
return null;
|
|
3410
3511
|
}
|
|
3411
3512
|
case 'bitnot':
|
|
3412
|
-
return ~(
|
|
3513
|
+
return ~(mysqlNum(resolveOperand(operand.expr, row, ctx)) | 0);
|
|
3413
3514
|
case 'negate': {
|
|
3414
3515
|
const v = resolveOperand(operand.operand, row, ctx);
|
|
3415
3516
|
if (v === null || v === undefined) return null;
|
|
3416
|
-
const n =
|
|
3417
|
-
if (isNaN(n)) return null;
|
|
3517
|
+
const n = mysqlNum(v);
|
|
3418
3518
|
return operand.positive ? n : -n;
|
|
3419
3519
|
}
|
|
3420
3520
|
// P1-19: ON DUPLICATE KEY UPDATE 表达式赋值,如 count = count + 1
|
|
@@ -3430,25 +3530,19 @@ function resolveOperand(operand, row, ctx) {
|
|
|
3430
3530
|
case '+': {
|
|
3431
3531
|
const bx = bigintExactArith(l, r, '+');
|
|
3432
3532
|
if (bx !== undefined) return bx;
|
|
3433
|
-
|
|
3434
|
-
|
|
3435
|
-
|
|
3436
|
-
|
|
3437
|
-
|
|
3438
|
-
|
|
3439
|
-
|
|
3440
|
-
|
|
3441
|
-
|
|
3442
|
-
case '
|
|
3443
|
-
case '
|
|
3444
|
-
case '
|
|
3445
|
-
case '
|
|
3446
|
-
case 'DIV': return r === 0 ? null : Math.trunc(Number(l) / Number(r));
|
|
3447
|
-
case '&': return (Number(l) | 0) & (Number(r) | 0);
|
|
3448
|
-
case '|': return (Number(l) | 0) | (Number(r) | 0);
|
|
3449
|
-
case '^': return (Number(l) | 0) ^ (Number(r) | 0);
|
|
3450
|
-
case '<<': return Number(l) * Math.pow(2, Number(r));
|
|
3451
|
-
case '>>': return Math.floor(Number(l) / Math.pow(2, Number(r)));
|
|
3533
|
+
const ln = mysqlNum(l), rn = mysqlNum(r);
|
|
3534
|
+
return ln + rn;
|
|
3535
|
+
}
|
|
3536
|
+
case '-': { const bx = bigintExactArith(l, r, '-'); if (bx !== undefined) return bx; return mysqlNum(l) - mysqlNum(r); }
|
|
3537
|
+
case '*': { const bx = bigintExactArith(l, r, '*'); if (bx !== undefined) return bx; return mysqlNum(l) * mysqlNum(r); }
|
|
3538
|
+
case '/': { const rn = mysqlNum(r); return rn === 0 ? null : mysqlNum(l) / rn; }
|
|
3539
|
+
case '%': { const rn = mysqlNum(r); return rn === 0 ? null : mysqlNum(l) % rn; }
|
|
3540
|
+
case 'DIV': return mysqlNum(r) === 0 ? null : Math.trunc(mysqlNum(l) / mysqlNum(r));
|
|
3541
|
+
case '&': return (mysqlNum(l) | 0) & (mysqlNum(r) | 0);
|
|
3542
|
+
case '|': return (mysqlNum(l) | 0) | (mysqlNum(r) | 0);
|
|
3543
|
+
case '^': return (mysqlNum(l) | 0) ^ (mysqlNum(r) | 0);
|
|
3544
|
+
case '<<': return mysqlNum(l) * Math.pow(2, mysqlNum(r));
|
|
3545
|
+
case '>>': return Math.floor(mysqlNum(l) / Math.pow(2, mysqlNum(r)));
|
|
3452
3546
|
default: return null;
|
|
3453
3547
|
}
|
|
3454
3548
|
}
|
|
@@ -5067,25 +5161,19 @@ function evaluateExpr(expr, row, ctx) {
|
|
|
5067
5161
|
case '+': {
|
|
5068
5162
|
const bx = bigintExactArith(l, r, '+');
|
|
5069
5163
|
if (bx !== undefined) return bx;
|
|
5070
|
-
|
|
5071
|
-
|
|
5072
|
-
|
|
5073
|
-
|
|
5074
|
-
|
|
5075
|
-
|
|
5076
|
-
|
|
5077
|
-
|
|
5078
|
-
|
|
5079
|
-
case '
|
|
5080
|
-
case '
|
|
5081
|
-
case '
|
|
5082
|
-
case '
|
|
5083
|
-
case 'DIV': return r === 0 ? null : Math.trunc(Number(l) / Number(r));
|
|
5084
|
-
case '&': return (Number(l) | 0) & (Number(r) | 0);
|
|
5085
|
-
case '|': return (Number(l) | 0) | (Number(r) | 0);
|
|
5086
|
-
case '^': return (Number(l) | 0) ^ (Number(r) | 0);
|
|
5087
|
-
case '<<': return Number(l) * Math.pow(2, Number(r));
|
|
5088
|
-
case '>>': return Math.floor(Number(l) / Math.pow(2, Number(r)));
|
|
5164
|
+
const ln = mysqlNum(l), rn = mysqlNum(r);
|
|
5165
|
+
return ln + rn;
|
|
5166
|
+
}
|
|
5167
|
+
case '-': { const bx = bigintExactArith(l, r, '-'); if (bx !== undefined) return bx; return mysqlNum(l) - mysqlNum(r); }
|
|
5168
|
+
case '*': { const bx = bigintExactArith(l, r, '*'); if (bx !== undefined) return bx; return mysqlNum(l) * mysqlNum(r); }
|
|
5169
|
+
case '/': { const rn = mysqlNum(r); return rn === 0 ? null : mysqlNum(l) / rn; }
|
|
5170
|
+
case '%': { const rn = mysqlNum(r); return rn === 0 ? null : mysqlNum(l) % rn; }
|
|
5171
|
+
case 'DIV': return mysqlNum(r) === 0 ? null : Math.trunc(mysqlNum(l) / mysqlNum(r));
|
|
5172
|
+
case '&': return (mysqlNum(l) | 0) & (mysqlNum(r) | 0);
|
|
5173
|
+
case '|': return (mysqlNum(l) | 0) | (mysqlNum(r) | 0);
|
|
5174
|
+
case '^': return (mysqlNum(l) | 0) ^ (mysqlNum(r) | 0);
|
|
5175
|
+
case '<<': return mysqlNum(l) * Math.pow(2, mysqlNum(r));
|
|
5176
|
+
case '>>': return Math.floor(mysqlNum(l) / Math.pow(2, mysqlNum(r)));
|
|
5089
5177
|
default: return null;
|
|
5090
5178
|
}
|
|
5091
5179
|
}
|
|
@@ -8803,6 +8891,7 @@ module.exports = {
|
|
|
8803
8891
|
splitStatements, applyParams, escapeValue, escapeId,
|
|
8804
8892
|
AST,
|
|
8805
8893
|
walk: AST.walk,
|
|
8894
|
+
compileCheckExpr,
|
|
8806
8895
|
transform: AST.transform,
|
|
8807
8896
|
visit: AST.StatementVisitor
|
|
8808
8897
|
};
|
package/lib/table.js
CHANGED
|
@@ -28,6 +28,16 @@ const INT64_MAX = 9223372036854775807n;
|
|
|
28
28
|
const SAFE_INT_MIN = BigInt(Number.MIN_SAFE_INTEGER);
|
|
29
29
|
const SAFE_INT_MAX = BigInt(Number.MAX_SAFE_INTEGER);
|
|
30
30
|
const DECIMAL_INT_RE = /^[+-]?\d+$/;
|
|
31
|
+
/**
|
|
32
|
+
* 从持久化的 CHECK SQL 文本重新编译判定函数(Issue #70)。
|
|
33
|
+
* 惰性 require 避免 table.js ↔ sql.js 的加载顺序耦合。
|
|
34
|
+
* 编译失败直接抛错:约束无法重建时必须显式失败,不能静默丢弃。
|
|
35
|
+
*/
|
|
36
|
+
function compileCheckSql(sqlText) {
|
|
37
|
+
const { compileCheckExpr } = require('./sql');
|
|
38
|
+
return compileCheckExpr(sqlText);
|
|
39
|
+
}
|
|
40
|
+
|
|
31
41
|
|
|
32
42
|
function integerError(type, v) {
|
|
33
43
|
return createError('ER_TRUNCATED_WRONG_VALUE', type, v);
|
|
@@ -208,9 +218,7 @@ class Table {
|
|
|
208
218
|
if (def.default !== undefined) {
|
|
209
219
|
this._defaults[field] = def.default;
|
|
210
220
|
}
|
|
211
|
-
|
|
212
|
-
this._checkConstraints.push({ field, fn: def.check });
|
|
213
|
-
}
|
|
221
|
+
this._registerChecks(field, def);
|
|
214
222
|
if (def.foreignKey) {
|
|
215
223
|
this._foreignKeys.push({
|
|
216
224
|
field,
|
|
@@ -253,6 +261,46 @@ class Table {
|
|
|
253
261
|
this._cachedComputedFields = this._cachedSchemaFields.filter(f => this._computedFields[f]);
|
|
254
262
|
}
|
|
255
263
|
|
|
264
|
+
/**
|
|
265
|
+
* 注册一个列的 CHECK 约束(Issue #70)。
|
|
266
|
+
* 支持三种来源:
|
|
267
|
+
* • def.check —— 已编译的判定函数(CREATE TABLE 解析时生成)
|
|
268
|
+
* • def.checks[] —— 表级 CHECK,元素形如 { sql, fn }
|
|
269
|
+
* • def.checkSql —— JSON 持久化后只剩文本,惰性重新编译
|
|
270
|
+
* 判定函数统一签名为 (值, 整行) => boolean,跨列条件也能拿到整行。
|
|
271
|
+
*/
|
|
272
|
+
_registerChecks(field, def) {
|
|
273
|
+
if (!def) return;
|
|
274
|
+
if (typeof def.check === 'function') {
|
|
275
|
+
this._checkConstraints.push({ field, fn: def.check });
|
|
276
|
+
} else if (typeof def.checkSql === 'string' && def.checkSql) {
|
|
277
|
+
const fn = compileCheckSql(def.checkSql);
|
|
278
|
+
if (fn) this._checkConstraints.push({ field, fn });
|
|
279
|
+
}
|
|
280
|
+
if (Array.isArray(def.checks)) {
|
|
281
|
+
for (const entry of def.checks) {
|
|
282
|
+
if (!entry) continue;
|
|
283
|
+
let fn = typeof entry === 'function' ? entry : entry.fn;
|
|
284
|
+
if (typeof fn !== 'function' && entry.sql) fn = compileCheckSql(entry.sql);
|
|
285
|
+
if (fn) this._checkConstraints.push({ field, fn });
|
|
286
|
+
}
|
|
287
|
+
}
|
|
288
|
+
}
|
|
289
|
+
|
|
290
|
+
/** 校验全部 CHECK 约束(整行上下文,列级/表级统一走这里)。 */
|
|
291
|
+
_enforceChecks(data) {
|
|
292
|
+
for (const { field, fn } of this._checkConstraints) {
|
|
293
|
+
if (typeof fn !== 'function') continue;
|
|
294
|
+
let ok;
|
|
295
|
+
try {
|
|
296
|
+
ok = fn(data ? data[field] : undefined, data || {});
|
|
297
|
+
} catch (_) {
|
|
298
|
+
ok = false; // 求值失败视为违反,绝不静默放行
|
|
299
|
+
}
|
|
300
|
+
if (!ok) throw createError('ER_CHECK_CONSTRAINT', this._name + '.' + field);
|
|
301
|
+
}
|
|
302
|
+
}
|
|
303
|
+
|
|
256
304
|
_autoCreateBTrees() {
|
|
257
305
|
for (const [field, def] of Object.entries(this._schema)) {
|
|
258
306
|
if (field === '_softDelete') continue;
|
|
@@ -366,8 +414,9 @@ class Table {
|
|
|
366
414
|
if (raw !== undefined && raw !== null && def.min !== undefined && v < min) throw createError('ER_OUT_OF_RANGE', field);
|
|
367
415
|
if (raw !== undefined && raw !== null && def.max !== undefined && v > max) throw createError('ER_OUT_OF_RANGE', field);
|
|
368
416
|
}
|
|
369
|
-
if (def.check && data[field] !== undefined && !def.check(data[field], data)) throw createError('ER_CHECK_CONSTRAINT', this._name + '.' + field);
|
|
370
417
|
}
|
|
418
|
+
// CHECK 约束统一在列循环外整体校验(支持跨列/表级约束)
|
|
419
|
+
this._enforceChecks(data);
|
|
371
420
|
// 主键唯一性检查(主键可能不在 _cachedUniqueFields 中)
|
|
372
421
|
if (this._primaryKey && data[this._primaryKey] !== undefined && data[this._primaryKey] !== null) {
|
|
373
422
|
const pkVal = data[this._primaryKey];
|
|
@@ -774,7 +823,7 @@ class Table {
|
|
|
774
823
|
}
|
|
775
824
|
}
|
|
776
825
|
}
|
|
777
|
-
|
|
826
|
+
this._registerChecks(field, definition);
|
|
778
827
|
if (definition.foreignKey) {
|
|
779
828
|
this._foreignKeys.push({
|
|
780
829
|
field,
|
|
@@ -885,7 +934,7 @@ class Table {
|
|
|
885
934
|
this._schema[field] = { ...this._schema[field], ...definition };
|
|
886
935
|
if (definition.default !== undefined) this._defaults[field] = definition.default;
|
|
887
936
|
this._checkConstraints = this._checkConstraints.filter(c => c.field !== field);
|
|
888
|
-
|
|
937
|
+
this._registerChecks(field, definition);
|
|
889
938
|
if (definition.primaryKey !== undefined || definition.unique !== undefined) {
|
|
890
939
|
if (definition.primaryKey || definition.unique) {
|
|
891
940
|
if (!this._btrees[field]) this._btrees[field] = new BTree(64, true);
|
|
@@ -1499,6 +1548,9 @@ class Table {
|
|
|
1499
1548
|
// ============================================================
|
|
1500
1549
|
|
|
1501
1550
|
_validateConstraints(data, excludeIndex, uniqueTracker, opts = {}) {
|
|
1551
|
+
// CHECK 约束(含跨列/表级):整行校验一次,不能按"当前列"门控 ——
|
|
1552
|
+
// 否则 UPDATE 只改 y 时,挂在 x 上的 CHECK(x > y) 就漏检了。
|
|
1553
|
+
this._enforceChecks(data);
|
|
1502
1554
|
for (const [field, def] of Object.entries(this._schema)) {
|
|
1503
1555
|
if (field === '_softDelete') continue;
|
|
1504
1556
|
|
|
@@ -1561,13 +1613,6 @@ class Table {
|
|
|
1561
1613
|
}
|
|
1562
1614
|
}
|
|
1563
1615
|
|
|
1564
|
-
// CHECK
|
|
1565
|
-
for (const { field: cf, fn } of this._checkConstraints) {
|
|
1566
|
-
if (cf === field && data[field] !== undefined && !fn(data[field], data)) {
|
|
1567
|
-
throw createError('ER_CHECK_CONSTRAINT', this._name + '.' + field);
|
|
1568
|
-
}
|
|
1569
|
-
}
|
|
1570
|
-
|
|
1571
1616
|
// 长度限制
|
|
1572
1617
|
if (def.length && typeof data[field] === 'string' && data[field].length > def.length) {
|
|
1573
1618
|
throw createError('ER_DATA_TOO_LONG', field);
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "jsql-neo",
|
|
3
|
-
"version": "6.5.
|
|
3
|
+
"version": "6.5.32",
|
|
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",
|
|
@@ -50,12 +50,12 @@
|
|
|
50
50
|
"scripts": {
|
|
51
51
|
"postinstall": "node postinstall.js",
|
|
52
52
|
"build:native": "node scripts/build-native.js",
|
|
53
|
-
"test": "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",
|
|
53
|
+
"test": "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/issue-69-70.test.js",
|
|
54
54
|
"test:parser": "node test/sql-parser.test.js",
|
|
55
55
|
"test:btree": "node test/btree.test.js",
|
|
56
56
|
"test:native": "node test/native.test.js",
|
|
57
57
|
"test:regress": "node test/regress-5.1.0.js",
|
|
58
|
-
"test:all": "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",
|
|
58
|
+
"test:all": "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/issue-69-70.test.js",
|
|
59
59
|
"test:coverage": "c8 --all --include='lib/**' --exclude='lib/web_ui.js' --reporter=text --reporter=lcov node test/coverage.js",
|
|
60
60
|
"test:orms": "node examples/orms/run-all.js",
|
|
61
61
|
"test:dml": "node test/dml-constraints.test.js",
|
|
@@ -0,0 +1,152 @@
|
|
|
1
|
+
/* ---- issue #69 / #70 回归 ---- */
|
|
2
|
+
const path = require('path');
|
|
3
|
+
const fs = require('fs');
|
|
4
|
+
const os = require('os');
|
|
5
|
+
const ROOT = path.join(__dirname, '..');
|
|
6
|
+
const { Database, executeSQL } = require(path.join(ROOT, 'index.js'));
|
|
7
|
+
|
|
8
|
+
let pass = 0, fail = 0;
|
|
9
|
+
function ok(name, cond, got) {
|
|
10
|
+
if (cond) { pass++; console.log('[OK] ' + name); }
|
|
11
|
+
else { fail++; console.log('[FAIL] ' + name + ' -> ' + JSON.stringify(got)); }
|
|
12
|
+
}
|
|
13
|
+
async function run(db, sql) { return executeSQL(db, sql, { safety: false }); }
|
|
14
|
+
async function cell(db, sql) { return (await run(db, sql)).rows[0][0]; }
|
|
15
|
+
async function throwsCode(fn, code) {
|
|
16
|
+
try { await fn(); return false; }
|
|
17
|
+
catch (e) { return code ? (e.code === code || e.code === 3819) : true; }
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
(async () => {
|
|
21
|
+
// =========================================================
|
|
22
|
+
// #69 字符串算术:MySQL 宽松转换(数值前缀)
|
|
23
|
+
// =========================================================
|
|
24
|
+
{
|
|
25
|
+
const db = new Database(':memory:', { autoSave: false });
|
|
26
|
+
const cases = [
|
|
27
|
+
["SELECT '5a' + 1", 6],
|
|
28
|
+
["SELECT '5a' + 0", 5],
|
|
29
|
+
["SELECT '12abc' + 0", 12],
|
|
30
|
+
["SELECT '5a' + '3'", 8],
|
|
31
|
+
["SELECT '5a' - 1", 4],
|
|
32
|
+
["SELECT '5a' * 2", 10],
|
|
33
|
+
["SELECT '6a' / 2", 3],
|
|
34
|
+
["SELECT '5a' % 2", 1],
|
|
35
|
+
["SELECT '3.5x' + 1", 4.5],
|
|
36
|
+
["SELECT '-2x' + 1", -1],
|
|
37
|
+
["SELECT 'abc' + 1", 1],
|
|
38
|
+
["SELECT 'a' + 'b'", 0],
|
|
39
|
+
["SELECT '' + 5", 5],
|
|
40
|
+
];
|
|
41
|
+
for (const [sql, want] of cases) {
|
|
42
|
+
const got = await cell(db, sql);
|
|
43
|
+
ok('#69 ' + sql + ' = ' + want, got === want, got);
|
|
44
|
+
}
|
|
45
|
+
ok("#69 '5a' = 5 为真(数值比较)", (await cell(db, "SELECT '5a' = 5")) === 1, null);
|
|
46
|
+
ok("#69 '5a' > 4 为真", (await cell(db, "SELECT '5a' > 4")) === 1, null);
|
|
47
|
+
|
|
48
|
+
// 列数据:TEXT 列里的脏数字同样按数值前缀参与算术
|
|
49
|
+
await run(db, 'CREATE TABLE t69 (id INT PRIMARY KEY, v TEXT)');
|
|
50
|
+
await db.insert('t69', { id: 1, v: '5abc' });
|
|
51
|
+
await db.insert('t69', { id: 2, v: '12x' });
|
|
52
|
+
ok('#69 列值 v + 1', (await cell(db, 'SELECT v + 1 FROM t69 WHERE id = 1')) === 6, null);
|
|
53
|
+
ok('#69 WHERE v + 0 = 12 命中', (await cell(db, 'SELECT COUNT(*) FROM t69 WHERE v + 0 = 12')) === 1, null);
|
|
54
|
+
ok('#69 聚合 SUM(v + 0)', (await cell(db, 'SELECT SUM(v + 0) FROM t69')) === 17, null);
|
|
55
|
+
|
|
56
|
+
// 保持既有语义:NULL 参与运算仍是 NULL
|
|
57
|
+
ok('#69 NULL + 1 = NULL', (await cell(db, 'SELECT NULL + 1')) === null, null);
|
|
58
|
+
// 精确整数 / BigInt 路径不受影响
|
|
59
|
+
ok('#69 BigInt 加法仍精确', (await cell(db, 'SELECT 9007199254740993 + 1')) === 9007199254740994n ||
|
|
60
|
+
String(await cell(db, 'SELECT 9007199254740993 + 1')) === '9007199254740994', null);
|
|
61
|
+
// '!' 逻辑非(解析器此前会抛 Unexpected token '!')
|
|
62
|
+
ok('#69 !1 = 0', (await cell(db, 'SELECT !1')) === 0, null);
|
|
63
|
+
ok('#69 !0 = 1', (await cell(db, 'SELECT !0')) === 1, null);
|
|
64
|
+
ok('#69 != 未被破坏', (await cell(db, 'SELECT 1 != 2')) === 1, null);
|
|
65
|
+
await db.close?.();
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
// =========================================================
|
|
69
|
+
// #70 CHECK 约束:列级 / 表级 / 更新 / 批量 / 语法错误
|
|
70
|
+
// =========================================================
|
|
71
|
+
{
|
|
72
|
+
const db = new Database(':memory:', { autoSave: false });
|
|
73
|
+
|
|
74
|
+
// ---- 列级 ----
|
|
75
|
+
await run(db, 'CREATE TABLE ck (id INT PRIMARY KEY, age INT CHECK (age >= 0))');
|
|
76
|
+
ok('#70 列级 CHECK 合法插入', await throwsCode(async () => db.insert('ck', { id: 1, age: 10 }), null) === false, null);
|
|
77
|
+
ok('#70 列级 CHECK 拒绝负值', await throwsCode(() => db.insert('ck', { id: 2, age: -1 }), 'ER_CHECK_CONSTRAINT'), null);
|
|
78
|
+
ok('#70 列级 CHECK 拒绝 SQL 插入', await throwsCode(() => run(db, 'INSERT INTO ck (id, age) VALUES (3, -5)'), 'ER_CHECK_CONSTRAINT'), null);
|
|
79
|
+
ok('#70 列级 CHECK 允许 NULL', await throwsCode(async () => db.insert('ck', { id: 4, age: null }), null) === false, null);
|
|
80
|
+
|
|
81
|
+
// ---- UPDATE 两条路径都要校验 ----
|
|
82
|
+
ok('#70 SQL UPDATE 违反 CHECK 报错', await throwsCode(() => run(db, 'UPDATE ck SET age = -1 WHERE id = 1'), 'ER_CHECK_CONSTRAINT'), null);
|
|
83
|
+
ok('#70 updateById 违反 CHECK 报错', await throwsCode(() => db.updateById('ck', 1, { age: -1 }), 'ER_CHECK_CONSTRAINT'), null);
|
|
84
|
+
ok('#70 合法 UPDATE 生效', (await run(db, 'UPDATE ck SET age = 20 WHERE id = 1')).affectedRows === 1, null);
|
|
85
|
+
ok('#70 UPDATE 后值正确', (await cell(db, 'SELECT age FROM ck WHERE id = 1')) === 20, null);
|
|
86
|
+
|
|
87
|
+
// ---- 批量插入 ----
|
|
88
|
+
const many = await throwsCode(() => db.insert('ck', [{ id: 10, age: 1 }, { id: 11, age: -2 }]), 'ER_CHECK_CONSTRAINT');
|
|
89
|
+
ok('#70 insertMany 违反 CHECK 报错', many, null);
|
|
90
|
+
ok('#70 insertMany 失败行未写入', (await cell(db, 'SELECT COUNT(*) FROM ck WHERE id = 11')) === 0, null);
|
|
91
|
+
|
|
92
|
+
// ---- 表级(跨列) ----
|
|
93
|
+
await run(db, 'CREATE TABLE tk (x INT, y INT, CHECK (x > y))');
|
|
94
|
+
ok('#70 表级跨列满足', await throwsCode(async () => db.insert('tk', { x: 10, y: 1 }), null) === false, null);
|
|
95
|
+
ok('#70 表级跨列违反(插入)', await throwsCode(() => db.insert('tk', { x: 1, y: 10 }), 'ER_CHECK_CONSTRAINT'), null);
|
|
96
|
+
ok('#70 表级跨列违反(只更新一列)', await throwsCode(() => db.updateById('tk', 1, { y: 99 }), 'ER_CHECK_CONSTRAINT'), null);
|
|
97
|
+
ok('#70 表级跨列违反(SQL UPDATE)', await throwsCode(() => run(db, 'UPDATE tk SET y = 50 WHERE x = 10'), 'ER_CHECK_CONSTRAINT'), null);
|
|
98
|
+
|
|
99
|
+
// ---- 具名约束 / 多条约束 / 复杂条件 ----
|
|
100
|
+
await run(db, `CREATE TABLE ck2 (
|
|
101
|
+
id INT PRIMARY KEY,
|
|
102
|
+
a INT,
|
|
103
|
+
b INT,
|
|
104
|
+
CONSTRAINT ck_ab CHECK (a < b),
|
|
105
|
+
CHECK (b < 100),
|
|
106
|
+
CHECK (a >= 0 AND b >= 0)
|
|
107
|
+
)`);
|
|
108
|
+
ok('#70 多约束合法行', await throwsCode(async () => db.insert('ck2', { id: 1, a: 1, b: 2 }), null) === false, null);
|
|
109
|
+
ok('#70 多约束 ck_ab 违反', await throwsCode(() => db.insert('ck2', { id: 2, a: 3, b: 2 }), 'ER_CHECK_CONSTRAINT'), null);
|
|
110
|
+
ok('#70 多约束 b < 100 违反', await throwsCode(() => db.insert('ck2', { id: 3, a: 1, b: 200 }), 'ER_CHECK_CONSTRAINT'), null);
|
|
111
|
+
ok('#70 AND 条件违反', await throwsCode(() => db.insert('ck2', { id: 4, a: -1, b: 2 }), 'ER_CHECK_CONSTRAINT'), null);
|
|
112
|
+
ok('#70 任一列为 NULL 时条件为 UNKNOWN→通过', await throwsCode(async () => db.insert('ck2', { id: 5, a: null, b: 2 }), null) === false, null);
|
|
113
|
+
|
|
114
|
+
// ---- 函数 / IN 条件也能编译执行 ----
|
|
115
|
+
await run(db, "CREATE TABLE ck3 (id INT PRIMARY KEY, s TEXT CHECK (LENGTH(s) > 0 AND s NOT IN ('bad')))");
|
|
116
|
+
ok('#70 函数条件合法', await throwsCode(async () => db.insert('ck3', { id: 1, s: 'ok' }), null) === false, null);
|
|
117
|
+
ok('#70 函数条件违反(空串)', await throwsCode(() => db.insert('ck3', { id: 2, s: '' }), 'ER_CHECK_CONSTRAINT'), null);
|
|
118
|
+
ok('#70 IN 条件违反', await throwsCode(() => db.insert('ck3', { id: 3, s: 'bad' }), 'ER_CHECK_CONSTRAINT'), null);
|
|
119
|
+
|
|
120
|
+
// ---- 语法错误不能被静默吞掉 ----
|
|
121
|
+
ok('#70 CHECK 语法错误在 CREATE 时报错', await throwsCode(() => run(db, 'CREATE TABLE bad1 (a INT CHECK (a >=))')), null);
|
|
122
|
+
ok('#70 CHECK 缺少右括号报错', await throwsCode(() => run(db, 'CREATE TABLE bad2 (a INT CHECK (a > 0)')), null);
|
|
123
|
+
|
|
124
|
+
// ---- 程序化 createTable(JS API)不受影响 ----
|
|
125
|
+
await db.createTable('prog', { id: { type: 'integer', primaryKey: true }, n: { type: 'integer', check: (v) => v > 0 } });
|
|
126
|
+
ok('#70 JS API def.check 仍生效', await throwsCode(() => db.insert('prog', { id: 1, n: -1 }), 'ER_CHECK_CONSTRAINT'), null);
|
|
127
|
+
|
|
128
|
+
await db.close?.();
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
// =========================================================
|
|
132
|
+
// #70 持久化:磁盘目录模式重开后 CHECK 仍生效
|
|
133
|
+
// =========================================================
|
|
134
|
+
{
|
|
135
|
+
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'jsql-ck70-'));
|
|
136
|
+
let db = new Database(dir, { mode: 'disk' });
|
|
137
|
+
await run(db, 'CREATE TABLE p (id INT PRIMARY KEY, age INT CHECK (age >= 0), CHECK (age < 100))');
|
|
138
|
+
await db.insert('p', { id: 1, age: 5 });
|
|
139
|
+
await db.close();
|
|
140
|
+
|
|
141
|
+
db = new Database(dir, { mode: 'disk' });
|
|
142
|
+
ok('#70 重开后数据仍在', (await db.find('p', {}))[0].age === 5, null);
|
|
143
|
+
ok('#70 重开后列级 CHECK 生效', await throwsCode(() => db.insert('p', { id: 2, age: -1 }), 'ER_CHECK_CONSTRAINT'), null);
|
|
144
|
+
ok('#70 重开后表级 CHECK 生效', await throwsCode(() => db.insert('p', { id: 3, age: 200 }), 'ER_CHECK_CONSTRAINT'), null);
|
|
145
|
+
ok('#70 重开后合法数据可插入', await throwsCode(async () => db.insert('p', { id: 4, age: 8 }), null) === false, null);
|
|
146
|
+
await db.close();
|
|
147
|
+
fs.rmSync(dir, { recursive: true, force: true });
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
console.log(`\n${pass} passed, ${fail} failed`);
|
|
151
|
+
process.exit(fail > 0 ? 1 : 0);
|
|
152
|
+
})().catch((e) => { console.error('[FATAL]', e); process.exit(1); });
|