jsql-neo 6.5.30 → 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 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.30** — stable release · [github.com/vexify-org/JSQL-neo](https://github.com/vexify-org/JSQL-neo) · [jsql.vexify.top](https://jsql.vexify.top)
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
  ![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.5.30 — Rust-Powered Embedded Database (WASM + HTTP)
2
+ * JSQL-NEO v6.5.32 — Rust-Powered Embedded Database (WASM + HTTP)
3
3
  *
4
4
  * @example
5
5
  * const jsql = require('jsql-neo');
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/date-types.js CHANGED
@@ -74,8 +74,14 @@ function validateDate(value, fieldName) {
74
74
  return toLocalDateString(value);
75
75
  }
76
76
  if (typeof value === 'number') {
77
- // Unix timestamp → date
78
- return toLocalDateString(new Date(value * 1000));
77
+ // Unix timestamp → date。NaN / ±Infinity / 超出 Date 范围的数会生成
78
+ // Invalid Date,此前被格式化成字面量 "NaN-NaN-NaN" 静默落库(#64);
79
+ // 与字符串分支保持一致,直接判为非法日期值。
80
+ const d = new Date(value * 1000);
81
+ if (!Number.isFinite(value) || Number.isNaN(d.getTime())) {
82
+ throw createError('ER_INVALID_DATE', fieldName, String(value));
83
+ }
84
+ return toLocalDateString(d);
79
85
  }
80
86
  if (typeof value === 'string') {
81
87
  const s = value.trim();
@@ -131,7 +137,12 @@ function validateDateTime(value, fieldName) {
131
137
  return toLocalDateTimeString(value);
132
138
  }
133
139
  if (typeof value === 'number') {
134
- return toLocalDateTimeString(new Date(value * 1000));
140
+ // 同 validateDate:拒绝 NaN / Infinity / 越界时间戳(#64)
141
+ const d = new Date(value * 1000);
142
+ if (!Number.isFinite(value) || Number.isNaN(d.getTime())) {
143
+ throw createError('ER_INVALID_DATE', fieldName, String(value));
144
+ }
145
+ return toLocalDateTimeString(d);
135
146
  }
136
147
  if (typeof value === 'string') {
137
148
  // ISO format: 2024-01-15T10:30:00.000Z / +08:00(可能带时区标记)
@@ -504,7 +504,8 @@ class RedisServer {
504
504
  case 'ZSCORE': {
505
505
  const v = this._get(args[0]);
506
506
  if (!v || v.type !== 'zset' || !(args[1] in v.val)) return null;
507
- return v.val[args[1]];
507
+ // ZSCORE 的分数恒为 bulk string(含整数分数),不能落进 integer reply(#67)
508
+ return String(v.val[args[1]]);
508
509
  }
509
510
  case 'ZCARD': {
510
511
  const v = this._get(args[0]);
@@ -535,7 +536,8 @@ class RedisServer {
535
536
  const member = args[2];
536
537
  zset[member] = (zset[member] || 0) + inc;
537
538
  this._scheduleSnapshot();
538
- return zset[member];
539
+ // 同 ZSCORE:分数用 bulk string 回复(#67)
540
+ return String(zset[member]);
539
541
  }
540
542
  case 'MSET': {
541
543
  const rest = args;
@@ -741,10 +743,19 @@ class RedisServer {
741
743
  } else if (val === null) {
742
744
  out = '$-1\r\n';
743
745
  } else if (typeof val === 'number') {
744
- out = ':' + val + '\r\n';
746
+ // RESP integer reply 只能是十进制整数;小数必须走 bulk string(#67)。
747
+ // ZSCORE / ZINCRBY 的分数已在 handler 里转成字符串,这里是非整数数字的最后兜底。
748
+ out = Number.isInteger(val)
749
+ ? ':' + val + '\r\n'
750
+ : '$' + Buffer.byteLength(String(val), 'utf8') + '\r\n' + val + '\r\n';
745
751
  } else if (Array.isArray(val)) {
746
- // 长度用字节数,不能用 String.length —— 否则中文等多字节值会让客户端解帧错位
747
- out = '*' + val.length + '\r\n' + val.map(v => '$' + Buffer.byteLength(String(v), 'utf8') + '\r\n' + v + '\r\n').join('');
752
+ // 长度用字节数,不能用 String.length —— 否则中文等多字节值会让客户端解帧错位。
753
+ // 批量回复里缺失的键必须是 nil bulk ($-1),不能是 "null" 字符串(#66)。
754
+ out = '*' + val.length + '\r\n' + val.map(v =>
755
+ (v === null || v === undefined)
756
+ ? '$-1\r\n'
757
+ : '$' + Buffer.byteLength(String(v), 'utf8') + '\r\n' + v + '\r\n'
758
+ ).join('');
748
759
  } else if (typeof val === 'string') {
749
760
  if (val === 'OK' || val === 'PONG') {
750
761
  out = '+' + val + '\r\n';
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 ('=<>+-*/(),.;%&|^~'.includes(c)) {
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 之外。表级 CHECK 已能被解析(同样只是跳过),
889
- // 列级此前会直接 return def,把 CHECK 留在流里 →
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
- if (this.peek().type === 'op' && this.peek().value === '(') this._skipParens();
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
- if (this.peek().type === 'op' && this.peek().value === '(') this._skipParens();
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();
@@ -2609,6 +2653,20 @@ class Parser {
2609
2653
  if (this.peek().type === 'op' && this.peek().value === '(') { this.next(); this.expect('op', ')'); }
2610
2654
  return { type: 'func', name, args: [] };
2611
2655
  }
2656
+ // POSITION(substr IN str) —— 标准 SQL / MySQL 写法,等价于 LOCATE(substr, str)。
2657
+ // IN 是关键字,通用函数参数循环会把它当成 IN 表达式的一部分并报
2658
+ // "Expected ( but got 'abc'",所以在这里单独归一(#63)。
2659
+ if (String(t.value).toUpperCase() === 'POSITION' && this.peek().type === 'op' && this.peek().value === '(') {
2660
+ this.next();
2661
+ const substr = this.parseOperand();
2662
+ if (!(this.isWord('IN') || this.isKeyword('IN'))) {
2663
+ throw new Error(`Expected IN in POSITION, got '${this.peek().value}'`);
2664
+ }
2665
+ this.next();
2666
+ const str = this.parseOperand();
2667
+ this.expect('op', ')');
2668
+ return { type: 'func', name: 'LOCATE', args: [substr, str] };
2669
+ }
2612
2670
  // EXTRACT(YEAR FROM expr) —— 标准 SQL 的 FROM 形式
2613
2671
  if (String(t.value).toUpperCase() === 'EXTRACT' && this.peek().type === 'op' && this.peek().value === '(') {
2614
2672
  this.next();
@@ -3239,6 +3297,72 @@ function mysqlNum(v) {
3239
3297
  return 0;
3240
3298
  }
3241
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
+
3242
3366
  /**
3243
3367
  * BigInt 参与的整数算术(Issue #38)。
3244
3368
  *
@@ -3347,60 +3471,50 @@ function resolveOperand(operand, row, ctx) {
3347
3471
  // '5' + 5 = 10 '5' + '5' = 10 'abc' + 1 = 1 'a' + 'b' = 0
3348
3472
  // 任一侧是「数值」时做算术加法,另一侧非数值按 0;
3349
3473
  // 两侧都不是数值才是 0(JS 的 l + r 会把 '5' + 5 拼成 '55')。
3350
- if (typeof l === 'number' || typeof r === 'number') {
3351
- const ln2 = numericIfNumeric(l), rn2 = numericIfNumeric(r);
3352
- return (ln2 === null ? 0 : ln2) + (rn2 === null ? 0 : rn2);
3353
- }
3354
- const ln = numericIfNumeric(l), rn = numericIfNumeric(r);
3355
- if (ln !== null) return ln + (rn === null ? 0 : rn);
3356
- if (rn !== null) return rn; // 左侧非数值按 0
3357
- return 0;
3474
+ const ln = mysqlNum(l), rn = mysqlNum(r);
3475
+ return ln + rn;
3358
3476
  }
3359
3477
  case '-': {
3360
3478
  const bx = bigintExactArith(l, r, '-');
3361
3479
  if (bx !== undefined) return bx;
3362
- // P1-21: 'abc'-1 → NaN,应返回 null
3363
- const ln = Number(l), rn = Number(r);
3364
- if (isNaN(ln) || isNaN(rn)) return null;
3480
+ const ln = mysqlNum(l), rn = mysqlNum(r);
3365
3481
  return ln - rn;
3366
3482
  }
3367
3483
  case '*': {
3368
3484
  const bx = bigintExactArith(l, r, '*');
3369
3485
  if (bx !== undefined) return bx;
3370
- const ln = Number(l), rn = Number(r);
3371
- if (isNaN(ln) || isNaN(rn)) return null;
3486
+ const ln = mysqlNum(l), rn = mysqlNum(r);
3372
3487
  return ln * rn;
3373
3488
  }
3374
3489
  case '/': {
3375
- const ln = Number(l), rn = Number(r);
3376
- if (isNaN(ln) || isNaN(rn) || rn === 0) return null;
3490
+ const ln = mysqlNum(l), rn = mysqlNum(r);
3491
+ if (rn === 0) return null;
3377
3492
  return ln / rn;
3378
3493
  }
3379
3494
  case '%': {
3380
- const ln = Number(l), rn = Number(r);
3381
- if (isNaN(ln) || isNaN(rn) || rn === 0) return null;
3495
+ const ln = mysqlNum(l), rn = mysqlNum(r);
3496
+ if (rn === 0) return null;
3382
3497
  return ln % rn;
3383
3498
  }
3384
3499
  // MySQL 整数除法 DIV(结果向零取整)
3385
- case 'DIV': return r === 0 ? null : Math.trunc(Number(l) / Number(r));
3500
+ case 'DIV': return mysqlNum(r) === 0 ? null : Math.trunc(mysqlNum(l) / mysqlNum(r));
3386
3501
  // 位运算:先按整数归一,与 MySQL 的整数位运算语义一致
3387
- case '&': return (Number(l) | 0) & (Number(r) | 0);
3388
- case '|': return (Number(l) | 0) | (Number(r) | 0);
3389
- case '^': return (Number(l) | 0) ^ (Number(r) | 0);
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);
3390
3505
  // P1-22: JavaScript 位运算只使用 32 位整数,移位量对 32 取模
3391
3506
  // 1 << 32 = 1 << 0 = 1,但 SQL 中 1 << 32 = 4294967296
3392
- case '<<': return Number(l) * Math.pow(2, Number(r));
3393
- case '>>': return Math.floor(Number(l) / Math.pow(2, Number(r)));
3507
+ case '<<': return mysqlNum(l) * Math.pow(2, mysqlNum(r));
3508
+ case '>>': return Math.floor(mysqlNum(l) / Math.pow(2, mysqlNum(r)));
3394
3509
  }
3395
3510
  return null;
3396
3511
  }
3397
3512
  case 'bitnot':
3398
- return ~(Number(resolveOperand(operand.expr, row, ctx)) | 0);
3513
+ return ~(mysqlNum(resolveOperand(operand.expr, row, ctx)) | 0);
3399
3514
  case 'negate': {
3400
3515
  const v = resolveOperand(operand.operand, row, ctx);
3401
3516
  if (v === null || v === undefined) return null;
3402
- const n = Number(v);
3403
- if (isNaN(n)) return null;
3517
+ const n = mysqlNum(v);
3404
3518
  return operand.positive ? n : -n;
3405
3519
  }
3406
3520
  // P1-19: ON DUPLICATE KEY UPDATE 表达式赋值,如 count = count + 1
@@ -3416,25 +3530,19 @@ function resolveOperand(operand, row, ctx) {
3416
3530
  case '+': {
3417
3531
  const bx = bigintExactArith(l, r, '+');
3418
3532
  if (bx !== undefined) return bx;
3419
- if (typeof l === 'number' || typeof r === 'number') {
3420
- const ln = numericIfNumeric(l), rn = numericIfNumeric(r);
3421
- return (ln === null ? 0 : ln) + (rn === null ? 0 : rn);
3422
- }
3423
- const ln = numericIfNumeric(l), rn = numericIfNumeric(r);
3424
- if (ln !== null) return ln + (rn === null ? 0 : rn);
3425
- if (rn !== null) return rn;
3426
- return 0;
3427
- }
3428
- case '-': { const bx = bigintExactArith(l, r, '-'); if (bx !== undefined) return bx; const ln = Number(l), rn = Number(r); return isNaN(ln) || isNaN(rn) ? null : ln - rn; }
3429
- case '*': { const bx = bigintExactArith(l, r, '*'); if (bx !== undefined) return bx; const ln = Number(l), rn = Number(r); return isNaN(ln) || isNaN(rn) ? null : ln * rn; }
3430
- case '/': { const ln = Number(l), rn = Number(r); return isNaN(ln) || isNaN(rn) || rn === 0 ? null : ln / rn; }
3431
- case '%': { const ln = Number(l), rn = Number(r); return isNaN(ln) || isNaN(rn) || rn === 0 ? null : ln % rn; }
3432
- case 'DIV': return r === 0 ? null : Math.trunc(Number(l) / Number(r));
3433
- case '&': return (Number(l) | 0) & (Number(r) | 0);
3434
- case '|': return (Number(l) | 0) | (Number(r) | 0);
3435
- case '^': return (Number(l) | 0) ^ (Number(r) | 0);
3436
- case '<<': return Number(l) * Math.pow(2, Number(r));
3437
- 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)));
3438
3546
  default: return null;
3439
3547
  }
3440
3548
  }
@@ -3742,6 +3850,15 @@ function pgAge(from, to) {
3742
3850
  return `${years} years ${months} mons ${days} days`;
3743
3851
  }
3744
3852
 
3853
+ /**
3854
+ * 数学定义域外的输入(SQRT(-1) / POWER(-2,0.5) 等)在 JS 里会得到
3855
+ * NaN / Infinity。MySQL 语义应返回 NULL;NaN 还会通过后续算术与聚合
3856
+ * 继续传播,且 JSON.stringify(NaN) === 'null' 会在序列化时把问题藏起来。
3857
+ * 统一在这里拦掉(#65)。
3858
+ */
3859
+ function finiteOrNull(x) {
3860
+ return (typeof x === 'number' && !Number.isFinite(x)) ? null : x;
3861
+ }
3745
3862
  function applyScalarFunction(fnNode, row, ctx) {
3746
3863
  const name = (fnNode.name || '').toUpperCase();
3747
3864
  const rawArgs = fnNode.args || [];
@@ -4084,8 +4201,8 @@ function applyScalarFunction(fnNode, row, ctx) {
4084
4201
  case 'FLOOR': return args[0] == null ? null : Math.floor(args[0]);
4085
4202
  case 'CEIL': case 'CEILING': return args[0] == null ? null : Math.ceil(args[0]);
4086
4203
  case 'MOD': return (args[0] == null || args[1] === 0) ? null : args[0] % args[1];
4087
- case 'POWER': case 'POW': return (args[0] == null || args[1] == null) ? null : Math.pow(args[0], args[1]);
4088
- case 'SQRT': return args[0] == null ? null : Math.sqrt(args[0]);
4204
+ case 'POWER': case 'POW': return (args[0] == null || args[1] == null) ? null : finiteOrNull(Math.pow(args[0], args[1]));
4205
+ case 'SQRT': return args[0] == null ? null : finiteOrNull(Math.sqrt(args[0]));
4089
4206
  case 'IFNULL': case 'NVL': return args[0] != null ? args[0] : args[1];
4090
4207
  case 'COALESCE': {
4091
4208
  // 不能直接 return find(...):全都取不到值时 find 返回 undefined,
@@ -5044,25 +5161,19 @@ function evaluateExpr(expr, row, ctx) {
5044
5161
  case '+': {
5045
5162
  const bx = bigintExactArith(l, r, '+');
5046
5163
  if (bx !== undefined) return bx;
5047
- if (typeof l === 'number' || typeof r === 'number') {
5048
- const ln = numericIfNumeric(l), rn = numericIfNumeric(r);
5049
- return (ln === null ? 0 : ln) + (rn === null ? 0 : rn);
5050
- }
5051
- const ln = numericIfNumeric(l), rn = numericIfNumeric(r);
5052
- if (ln !== null) return ln + (rn === null ? 0 : rn);
5053
- if (rn !== null) return rn;
5054
- return 0;
5055
- }
5056
- case '-': { const bx = bigintExactArith(l, r, '-'); if (bx !== undefined) return bx; const ln = Number(l), rn = Number(r); return isNaN(ln) || isNaN(rn) ? null : ln - rn; }
5057
- case '*': { const bx = bigintExactArith(l, r, '*'); if (bx !== undefined) return bx; const ln = Number(l), rn = Number(r); return isNaN(ln) || isNaN(rn) ? null : ln * rn; }
5058
- case '/': { const ln = Number(l), rn = Number(r); return isNaN(ln) || isNaN(rn) || rn === 0 ? null : ln / rn; }
5059
- case '%': { const ln = Number(l), rn = Number(r); return isNaN(ln) || isNaN(rn) || rn === 0 ? null : ln % rn; }
5060
- case 'DIV': return r === 0 ? null : Math.trunc(Number(l) / Number(r));
5061
- case '&': return (Number(l) | 0) & (Number(r) | 0);
5062
- case '|': return (Number(l) | 0) | (Number(r) | 0);
5063
- case '^': return (Number(l) | 0) ^ (Number(r) | 0);
5064
- case '<<': return Number(l) * Math.pow(2, Number(r));
5065
- 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)));
5066
5177
  default: return null;
5067
5178
  }
5068
5179
  }
@@ -8780,6 +8891,7 @@ module.exports = {
8780
8891
  splitStatements, applyParams, escapeValue, escapeId,
8781
8892
  AST,
8782
8893
  walk: AST.walk,
8894
+ compileCheckExpr,
8783
8895
  transform: AST.transform,
8784
8896
  visit: AST.StatementVisitor
8785
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
- if (def.check) {
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
- if (definition.check) this._checkConstraints.push({ field, fn: definition.check });
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
- if (definition.check) this._checkConstraints.push({ field, fn: definition.check });
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);
@@ -492,6 +492,26 @@ function compileQuery(q, opts = {}) {
492
492
  B.push(' for (let _i = 0; _i < rows.length; _i++) _out.push(rows[_i]);');
493
493
  }
494
494
 
495
+ // 3) ORDER BY
496
+ if (orderBy) {
497
+ // 每个排序键一个块。注意不能用 continue —— 块级作用域里没有循环可继续,
498
+ // 改成 if 包裹。
499
+ //
500
+ // 字符串用 < / > 而不是 localeCompare:后者是 locale 感知的排序,
501
+ // 6.8 万行排序要调 ~110 万次,实测比朴素比较多一个量级
502
+ // (这一项就是从 2.93 倍降到持平的关键)。
503
+ const cmp = orderBy.map((o, i) => ` { const av = _ok${i}(a), bv = _ok${i}(b);
504
+ if (av !== bv) {
505
+ if (av === null || av === undefined) return -1 * ${o.dir};
506
+ if (bv === null || bv === undefined) return 1 * ${o.dir};
507
+ const d = (typeof av === 'number' && typeof bv === 'number') || (typeof av === 'boolean' && typeof bv === 'boolean')
508
+ ? (av < bv ? -1 : 1)
509
+ : (String(av) < String(bv) ? -1 : 1);
510
+ if (d !== 0) return d * ${o.dir};
511
+ } }`).join('\n');
512
+ B.push(' _out.sort((a, b) => {\n' + cmp + '\n return 0;\n });');
513
+ }
514
+
495
515
  // 2) SELECT —— 与 WHERE 同理,投影语句也内联进循环。
496
516
  // 每列调一次函数的话,6.8 万行 × 2 列就是 13.6 万次调用,
497
517
  // 实测占掉整个管道的大半时间(2.81 倍差距主要来自这里)。
@@ -542,26 +562,6 @@ function compileQuery(q, opts = {}) {
542
562
  const limit = q.limit;
543
563
  const offset = q.offset || 0;
544
564
 
545
- // 3) ORDER BY
546
- if (orderBy) {
547
- // 每个排序键一个块。注意不能用 continue —— 块级作用域里没有循环可继续,
548
- // 改成 if 包裹。
549
- //
550
- // 字符串用 < / > 而不是 localeCompare:后者是 locale 感知的排序,
551
- // 6.8 万行排序要调 ~110 万次,实测比朴素比较多一个量级
552
- // (这一项就是从 2.93 倍降到持平的关键)。
553
- const cmp = orderBy.map((o, i) => ` { const av = _ok${i}(a), bv = _ok${i}(b);
554
- if (av !== bv) {
555
- if (av === null || av === undefined) return -1 * ${o.dir};
556
- if (bv === null || bv === undefined) return 1 * ${o.dir};
557
- const d = (typeof av === 'number' && typeof bv === 'number') || (typeof av === 'boolean' && typeof bv === 'boolean')
558
- ? (av < bv ? -1 : 1)
559
- : (String(av) < String(bv) ? -1 : 1);
560
- if (d !== 0) return d * ${o.dir};
561
- } }`).join('\n');
562
- B.push(' _out.sort((a, b) => {\n' + cmp + '\n return 0;\n });');
563
- }
564
-
565
565
  // 4) OFFSET / LIMIT
566
566
  if (offset || (limit !== null && limit !== undefined)) {
567
567
  const end = (limit === null || limit === undefined) ? 'undefined' : String(offset + limit);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "jsql-neo",
3
- "version": "6.5.30",
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",
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",
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",
@@ -561,10 +561,13 @@ test('数学函数:ABS / CEIL / FLOOR / ROUND / POWER / SQRT', async () => {
561
561
  assert.strictEqual(await one(q, 'SELECT SQRT(16)'), 4);
562
562
  });
563
563
 
564
- test('SQRT 负数返回 NaN', async () => {
564
+ // #65:此前断言 SQRT(-1) 返回 NaN,等于把 bug 钉成了预期。
565
+ // MySQL 语义下数学定义域外的输入应返回 NULL;NaN 会污染后续算术/聚合,
566
+ // 且 JSON.stringify(NaN) === 'null' 会在序列化时把问题藏起来。
567
+ test('SQRT 负数返回 NULL', async () => {
565
568
  const { q } = makeDb();
566
569
  const v = await one(q, 'SELECT SQRT(-1)');
567
- assert.ok(Number.isNaN(v));
570
+ assert.strictEqual(v, null);
568
571
  });
569
572
 
570
573
  test('REPLACE 函数', async () => {
@@ -0,0 +1,91 @@
1
+ /* ---- issue #63~#68 回归 ---- */
2
+ const path = require('path');
3
+ const ROOT = path.join(__dirname, '..');
4
+ const { Database, executeSQL } = require(path.join(ROOT, 'index.js'));
5
+
6
+ let pass = 0, fail = 0;
7
+ function ok(name, cond, got) {
8
+ if (cond) { pass++; console.log('[OK] ' + name); }
9
+ else { fail++; console.log('[FAIL] ' + name + ' -> ' + JSON.stringify(got)); }
10
+ }
11
+ const isNull = (v) => v === null || v === undefined;
12
+
13
+ (async () => {
14
+ const db = new Database(':memory:', { autoSave: false });
15
+ const q = async (sql) => (await executeSQL(db, sql, { safety: false })).rows[0][0];
16
+
17
+ // ---------- #63 POSITION(substr IN str) ----------
18
+ ok('#63 POSITION 命中', await q("SELECT POSITION('b' IN 'abc')") === 2, await q("SELECT POSITION('b' IN 'abc')"));
19
+ ok('#63 POSITION 未命中返回 0', await q("SELECT POSITION('z' IN 'abc')") === 0, await q("SELECT POSITION('z' IN 'abc')"));
20
+ ok('#63 与 LOCATE 等价', await q("SELECT LOCATE('b','abc')") === await q("SELECT POSITION('b' IN 'abc')"), null);
21
+ ok('#63 支持列引用', await q("SELECT POSITION('b' IN CONCAT('a','bc'))") === 2, null);
22
+
23
+ // ---------- #64 日期类型拒绝非法数字 ----------
24
+ const dt = require(path.join(ROOT, 'lib', 'date-types.js'));
25
+ for (const v of [NaN, Infinity, -Infinity, 1e20]) {
26
+ let threw = false;
27
+ try { dt.validateDateType(v, 'date', 'd'); } catch (e) { threw = /Incorrect date value/.test(e.message); }
28
+ ok('#64 date 拒绝 ' + String(v), threw, null);
29
+ let threw2 = false;
30
+ try { dt.validateDateType(v, 'datetime', 'd'); } catch (e) { threw2 = /Incorrect date value/.test(e.message); }
31
+ ok('#64 datetime 拒绝 ' + String(v), threw2, null);
32
+ }
33
+ ok('#64 合法时间戳仍可用', dt.validateDateType(0, 'date', 'd') === '1970-01-01', dt.validateDateType(0, 'date', 'd'));
34
+
35
+ // ---------- #65 数值域错误返回 NULL ----------
36
+ for (const sql of ['SELECT SQRT(-1)', 'SELECT POWER(-2,0.5)', 'SELECT SQRT(-1) + 5', 'SELECT LOG(-5)', 'SELECT ACOS(2)']) {
37
+ const v = await q(sql);
38
+ ok('#65 ' + sql + ' → NULL', isNull(v), v);
39
+ }
40
+ ok('#65 SQRT(4) 仍为 2', await q('SELECT SQRT(4)') === 2, null);
41
+ ok('#65 POWER(2,3) 仍为 8', await q('SELECT POWER(2,3)') === 8, null);
42
+
43
+ // ---------- #66 / #67 Redis RESP 序列化 ----------
44
+ const { createRedisServer } = require(path.join(ROOT, 'lib', 'redis_server.js'));
45
+ const srv = createRedisServer({ port: 0 });
46
+ function send(cmd, args) {
47
+ const out = [];
48
+ srv._handle({ write: (s) => out.push(s) }, cmd, args);
49
+ return out.join('');
50
+ }
51
+ send('SET', ['a', '1']);
52
+ const mget = send('MGET', ['a', 'missing']);
53
+ ok('#66 MGET 缺失键为 nil bulk', mget.includes('$-1\r\n') && !mget.includes('$4\r\nnull'), mget);
54
+ ok('#66 MGET 存在的键仍正常', mget.includes('$1\r\n1\r\n'), mget);
55
+
56
+ send('ZADD', ['z', '10.5', 'm']);
57
+ const zscore = send('ZSCORE', ['z', 'm']);
58
+ ok('#67 ZSCORE 小数分数为 bulk string', zscore === '$4\r\n10.5\r\n', zscore);
59
+ const zincr = send('ZINCRBY', ['z', '0.5', 'm']);
60
+ // 10.5 + 0.5 = 11,"11" 是 2 字节,所以是 $2 而不是 $3
61
+ ok('#67 ZINCRBY 分数为 bulk string', /^\$2\r\n11\r\n$/.test(zincr) || /^\$\d+\r\n11\.0+\r\n$/.test(zincr), zincr);
62
+ send('ZADD', ['zi', '10', 'm']);
63
+ const zint = send('ZSCORE', ['zi', 'm']);
64
+ ok('#67 整数分数也是 bulk(不是 :10)', zint === '$2\r\n10\r\n', zint);
65
+ ok('#67 _send 非整数 number 不产出非法 integer reply',
66
+ (() => { const o = []; srv._send({ write: (s) => o.push(s) }, 10.5); return o[0] === '$4\r\n10.5\r\n'; })(), null);
67
+ ok('#67 _send 整数仍是 integer reply',
68
+ (() => { const o = []; srv._send({ write: (s) => o.push(s) }, 3); return o[0] === ':3\r\n'; })(), null);
69
+
70
+ // ---------- #68 XQL ORDER BY 非投影列 ----------
71
+ const { xql } = require(path.join(ROOT, 'lib', 'plugins'));
72
+ const db2 = new Database(':memory:', { autoSave: false });
73
+ await db2.createTable('users', {
74
+ id: { type: 'integer', primaryKey: true, autoIncrement: true },
75
+ name: { type: 'string' }, age: { type: 'integer' },
76
+ });
77
+ await db2.insert('users', [{ name: 'alice', age: 30 }, { name: 'bob', age: 25 }, { name: 'carol', age: 30 }]);
78
+ db2.use(xql());
79
+ const both = await db2.xql('FROM users |> ORDER BY age DESC |> SELECT name, age');
80
+ const nameOnly = await db2.xql('FROM users |> ORDER BY age DESC |> SELECT name');
81
+ ok('#68 投影含排序列时结果正确', both.map(r => r.name).join(',') === 'alice,carol,bob', both.map(r => r.name));
82
+ ok('#68 排序列不在投影里也生效', nameOnly.map(r => r.name).join(',') === 'alice,carol,bob', nameOnly.map(r => r.name));
83
+ const asc = await db2.xql('FROM users |> ORDER BY age ASC |> SELECT name');
84
+ ok('#68 升序同样生效', asc[0].name === 'bob', asc.map(r => r.name));
85
+
86
+ console.log(`\n${pass} passed, ${fail} failed`);
87
+ process.exit(fail === 0 ? 0 : 1);
88
+ })().catch(e => {
89
+ console.log('[FAIL] unexpected exception: ' + e.stack.split('\n').slice(0, 3).join('\n'));
90
+ process.exit(1);
91
+ });
@@ -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); });