jsql-neo 6.5.31 → 6.6.0

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/lib/sql.js CHANGED
@@ -1,5 +1,7 @@
1
1
  // N1-fix: createError 此前未导入,UPDATE 无主键表时抛 ReferenceError(而非预期的 SQL 错误)
2
2
  const { createError } = require('./errors');
3
+ // #75:WHERE 里 DATETIME 字面量要与 INSERT 走同一套规范化规则
4
+ const { validateDateType } = require('./date-types');
3
5
 
4
6
  const DANGEROUS_SQL = [
5
7
  { re: /^INTO$/, next: /^(OUTFILE|DUMPFILE)$/, name: 'INTO OUTFILE/DUMPFILE' },
@@ -466,7 +468,7 @@ function tokenize(sql) {
466
468
  // 注意:% & | ^ ~ 这些运算符必须在词法层产出 token。
467
469
  // 之前 parseTerm() 里写了 '%' 分支但字符集里没有 '%',
468
470
  // 导致 SELECT 10 % 3 直接报 "Unexpected character '%'",那段是死代码。
469
- if ('=<>+-*/(),.;%&|^~'.includes(c)) {
471
+ if ('=<>+-*/(),.;%&|^~!'.includes(c)) {
470
472
  tokens.push(new SQLToken('op', c, i));
471
473
  i++;
472
474
  continue;
@@ -751,6 +753,8 @@ class Parser {
751
753
  const schema = {};
752
754
  // 表级 FOREIGN KEY 可能写在列定义之前,先收集、待所有列解析完再绑定
753
755
  const pendingFKs = [];
756
+ // 表级 CHECK 条件(Issue #70):先收集 AST,等所有列解析完再挂到引用列上
757
+ const pendingChecks = [];
754
758
  let hasPk = false;
755
759
  while (true) {
756
760
  const t = this.peek();
@@ -787,14 +791,14 @@ class Parser {
787
791
  } else if (t.type === 'keyword' && t.value === 'CONSTRAINT') {
788
792
  this.expectKeyword('CONSTRAINT');
789
793
  if (this.peek().type === 'ident') this.next(); // 约束名
790
- this._parseTableConstraint(schema, pendingFKs);
794
+ this._parseTableConstraint(schema, pendingFKs, pendingChecks);
791
795
  } else if (this.isWord('FOREIGN') || this.isWord('CHECK') ||
792
796
  t.type === 'keyword' && (t.value === 'KEY' || t.value === 'INDEX')) {
793
797
  // 表级约束:FOREIGN KEY ... REFERENCES ... / CHECK (...) / KEY name (cols)
794
798
  // KEY/INDEX 是保留字:裸写作列名(如 CREATE TABLE t (key TEXT))必须报错,
795
799
  // 由 _parseTableConstraint 消费 KEY 后遇到类型 token 触发
796
800
  // "Expected ',' or ')'",见 identifier-keywords 测试。
797
- this._parseTableConstraint(schema, pendingFKs);
801
+ this._parseTableConstraint(schema, pendingFKs, pendingChecks);
798
802
  } else if (t.type === 'eof' || (t.type === 'op' && t.value === ')')) {
799
803
  break;
800
804
  } else {
@@ -832,6 +836,18 @@ class Parser {
832
836
  }
833
837
  schema[column].foreignKey = fk;
834
838
  }
839
+ // 表级 CHECK(Issue #70):挂到条件引用的第一个列上(找不到就用第一列)。
840
+ // 判定函数拿到的是整行数据,因此与挂在哪个列无关;放在 def.checks 数组里
841
+ // 是为了不与列自身的 CHECK 互相覆盖,同时供 lib/table.js 全局校验。
842
+ for (const cond of pendingChecks) {
843
+ const refs = collectCheckColumns(cond.ast);
844
+ let target = refs.find(c => schema[c] !== undefined);
845
+ if (!target) target = Object.keys(schema).find(k => k !== '_softDelete');
846
+ if (!target) continue;
847
+ const d = schema[target];
848
+ if (!Array.isArray(d.checks)) d.checks = [];
849
+ d.checks.push({ sql: cond.sql, fn: makeCheckFn(cond.ast) });
850
+ }
835
851
  return { type: 'createTable', name, schema, ifNotExists };
836
852
  }
837
853
 
@@ -885,13 +901,13 @@ class Parser {
885
901
  const t = this.peek();
886
902
  // 列级 CHECK (age INT CHECK(age >= 0))。
887
903
  // CHECK 刻意不在 KEYWORDS 里(避免影响同名标识符),所以用 isWord 匹配,
888
- // 放在 keyword switch 之外。表级 CHECK 已能被解析(同样只是跳过),
889
- // 列级此前会直接 return def,把 CHECK 留在流里 →
890
- // "Expected ',' or ')' in CREATE TABLE, got 'CHECK'"。
891
- // 与表级保持一致:解析并跳过,条件文本存到 def.check 供后续实现。
904
+ // 放在 keyword switch 之外。条件解析成 AST 并编译成判定函数(Issue #70):
905
+ // def.check 供 lib/table.js 直接调用,def.checkSql 用于持久化后重编译。
892
906
  if (this.isWord('CHECK')) {
893
907
  this.next();
894
- if (this.peek().type === 'op' && this.peek().value === '(') this._skipParens();
908
+ const cond = this._parseCheckCondition();
909
+ def.check = makeCheckFn(cond.ast);
910
+ def.checkSql = cond.sql;
895
911
  continue;
896
912
  }
897
913
  // 列级外键: pid INTEGER REFERENCES p(id) [ON DELETE ...] [ON UPDATE ...]
@@ -945,9 +961,20 @@ class Parser {
945
961
  const fnTok = this.next();
946
962
  let name = String(fnTok.value);
947
963
  if (this.peek().type === 'op' && this.peek().value === '(') {
964
+ // 函数默认值可能带参数(NOW(6)、CURRENT_TIMESTAMP(3)):
965
+ // 原样保留括号内文本,交给 Table 侧按表达式求值/报错。
948
966
  this.next();
949
- this.expect('op', ')');
950
- name += '()';
967
+ const start = this.pos;
968
+ let depth = 1;
969
+ while (this.peek().type !== 'eof' && depth > 0) {
970
+ const tk = this.next();
971
+ if (tk.type === 'op' && tk.value === '(') depth++;
972
+ else if (tk.type === 'op' && tk.value === ')') depth--;
973
+ }
974
+ if (depth > 0) throw createError('ER_PARSE_ERROR', "unclosed '(' in DEFAULT expression");
975
+ const argSrc = this.tokens.slice(start, this.pos - 1)
976
+ .map(tk => String(tk.value)).join('');
977
+ name += '(' + argSrc + ')';
951
978
  }
952
979
  def.default = name;
953
980
  def.defaultExpr = true;
@@ -995,6 +1022,25 @@ class Parser {
995
1022
  return stmt;
996
1023
  }
997
1024
 
1025
+ /**
1026
+ * 解析 CHECK 后的括号条件:CHECK (expr)。
1027
+ * 返回 { ast, sql }:AST 用于编译判定函数,sql 文本用于持久化。
1028
+ */
1029
+ _parseCheckCondition() {
1030
+ this.expect('op', '(');
1031
+ const start = this.pos;
1032
+ this.barePredicateDepth = (this.barePredicateDepth || 0) + 1;
1033
+ let ast;
1034
+ try {
1035
+ ast = this.parseExpr();
1036
+ } finally {
1037
+ this.barePredicateDepth--;
1038
+ }
1039
+ const sql = tokensToSql(this.tokens.slice(start, this.pos));
1040
+ this.expect('op', ')');
1041
+ return { ast, sql };
1042
+ }
1043
+
998
1044
  /** 跳过一对括号(含嵌套),用于表级约束里的列清单 */
999
1045
  _skipParens() {
1000
1046
  this.expect('op', '(');
@@ -1042,7 +1088,7 @@ class Parser {
1042
1088
  * FOREIGN KEY 会真正解析出 field/refTable/refField/onDelete/onUpdate 并登记,
1043
1089
  * 与列级 REFERENCES 行为一致(校验在 lib/table.js)。
1044
1090
  */
1045
- _parseTableConstraint(schema, pendingFKs) {
1091
+ _parseTableConstraint(schema, pendingFKs, pendingChecks) {
1046
1092
  if (this.isWord('FOREIGN')) {
1047
1093
  this.next();
1048
1094
  if (!this.isKeyword('KEY')) throw new Error(`Expected KEY after FOREIGN, got '${this.peek().value}'`);
@@ -1080,7 +1126,10 @@ class Parser {
1080
1126
  }
1081
1127
  if (this.isWord('CHECK')) {
1082
1128
  this.next();
1083
- if (this.peek().type === 'op' && this.peek().value === '(') this._skipParens();
1129
+ // 表级 CHECK 的条件在列清单解析完之前可能引用尚未定义的列,
1130
+ // 与 FOREIGN KEY 一样先收集,等 parseCreateTable 末尾再绑定。
1131
+ if (pendingChecks) pendingChecks.push(this._parseCheckCondition());
1132
+ else this._skipParens();
1084
1133
  return;
1085
1134
  }
1086
1135
  if (this.isKeyword('PRIMARY')) {
@@ -1544,7 +1593,7 @@ class Parser {
1544
1593
  from = this.parseFrom();
1545
1594
  }
1546
1595
  let where = null;
1547
- if (this.isKeyword('WHERE')) { this.next(); where = this.parseBooleanExpr(); }
1596
+ if (this.isKeyword('WHERE')) { this.next(); where = this.parseBooleanExpr(); this._assertNoAggregateInWhere(where); }
1548
1597
  let groupBy = null;
1549
1598
  let rollup = false;
1550
1599
  if (this.isKeyword('GROUP')) {
@@ -1594,6 +1643,40 @@ class Parser {
1594
1643
  return node;
1595
1644
  }
1596
1645
 
1646
+ /**
1647
+ * WHERE 中不允许聚合函数(Issue #71)。
1648
+ *
1649
+ * 此前 `SELECT id FROM a WHERE COUNT(*) > 0` 会被执行器静默求值成
1650
+ * NULL(聚合在逐行上下文中没有分组值),WHERE 过滤掉所有行、返回空集,
1651
+ * 调用方完全看不出语句是非法的。MySQL 在这里直接报错
1652
+ * (ER_INVALID_GROUP_FUNC_USE / 1111:Invalid use of group function)。
1653
+ *
1654
+ * 只检查当前 SELECT 的 WHERE,且不进入子查询 —— 子查询里自己的 WHERE
1655
+ * 由子查询解析时单独检查;`WHERE id IN (SELECT MAX(id) FROM t)` 合法。
1656
+ * HAVING 不在检查范围内(聚合本来就可以用)。
1657
+ */
1658
+ _assertNoAggregateInWhere(where) {
1659
+ if (!where || typeof where !== 'object') return;
1660
+ const fail = (fnName) => {
1661
+ throw createError('ER_INVALID_GROUP_FUNC_USE', String(fnName || '').toUpperCase());
1662
+ };
1663
+ const visit = (node) => {
1664
+ if (!node || typeof node !== 'object') return;
1665
+ if (Array.isArray(node)) { for (const it of node) visit(it); return; }
1666
+ // 子查询/EXISTS:结构内的聚合属于内层查询
1667
+ if (node.type === 'subquery' || node.type === 'exists') return;
1668
+ if (node.type === 'aggregate') fail(node.fn);
1669
+ if (node.type === 'func' && typeof node.name === 'string' && AGG_FUNCS.has(node.name.toUpperCase())) fail(node.name);
1670
+ // 投影分支构造的聚合节点:{ type: 'SUM', column, ... }
1671
+ if (typeof node.type === 'string' && AGG_FUNCS.has(node.type) && (node.column !== undefined || node.over === undefined)) fail(node.type);
1672
+ for (const [k, v] of Object.entries(node)) {
1673
+ if (k === 'type' || k === 'select' || k === 'subquery') continue;
1674
+ visit(v);
1675
+ }
1676
+ };
1677
+ visit(where);
1678
+ }
1679
+
1597
1680
  /** ORDER BY 子句(可选)。返回 null 或 [{column, dir}]。 */
1598
1681
  parseOrderByClause() {
1599
1682
  if (!this.isKeyword('ORDER')) return null;
@@ -2344,6 +2427,14 @@ class Parser {
2344
2427
  }
2345
2428
 
2346
2429
  parseNot() {
2430
+ // '!' 逻辑非(MySQL 语义):'!' 与 NOT 等价,而 '!=' / '!~' / '!~*' 已在
2431
+ // tokenize 的多字符分支处理,走到这里的裸 '!' 一定是逻辑非。
2432
+ if (this.peek().type === 'op' && this.peek().value === '!') {
2433
+ this.next();
2434
+ const inner = this.parseNot();
2435
+ if (inner && inner.type === 'exists') { inner.not = !inner.not; return inner; }
2436
+ return { type: 'not', expr: inner };
2437
+ }
2347
2438
  if (this.isKeyword('NOT')) {
2348
2439
  this.next();
2349
2440
  const inner = this.parseNot();
@@ -3253,6 +3344,72 @@ function mysqlNum(v) {
3253
3344
  return 0;
3254
3345
  }
3255
3346
 
3347
+ // ---------------------------------------------------------------------------
3348
+ // CHECK 约束(Issue #70)
3349
+ //
3350
+ // CREATE TABLE 里的 CHECK 条件此前被 _skipParens() 整段跳过:语法能过,
3351
+ // 但约束完全不生效(列级/表级都一样),非法数据静默入库。
3352
+ // 这里把条件解析成 AST,编译成 (val, row) => boolean 的判定函数:
3353
+ // • 求值走 evaluateExpr,与 WHERE 条件同一套语义(三值逻辑、类型强转一致);
3354
+ // • MySQL 规则:条件为 TRUE 或 UNKNOWN(NULL) 视为通过,只有 FALSE 才违反;
3355
+ // • JSON 持久化会丢函数,所以同时保存 checkSql,重载时由
3356
+ // compileCheckExpr() 重新编译(lib/table.js 惰性调用)。
3357
+ // ---------------------------------------------------------------------------
3358
+
3359
+ /** 把 token 还原成可再次解析的 SQL 文本(仅用于持久化 CHECK 条件)。 */
3360
+ function tokensToSql(tokens) {
3361
+ return tokens.map(t => {
3362
+ if (t.type === 'string') return "'" + String(t.value).replace(/\\/g, '\\\\').replace(/'/g, "''") + "'";
3363
+ if (t.type === 'number') return String(t.value);
3364
+ if (t.type === 'sysvar') return '@' + t.value;
3365
+ if (t.type === 'param') return '?';
3366
+ return t.text !== undefined ? t.text : String(t.value);
3367
+ }).join(' ');
3368
+ }
3369
+
3370
+ /** 编译 CHECK 条件 AST 为判定函数。 */
3371
+ function makeCheckFn(ast) {
3372
+ return function checkFn(val, row) {
3373
+ let res;
3374
+ try {
3375
+ res = evaluateExpr(ast, row || {}, {});
3376
+ } catch (_) {
3377
+ // 求值异常不能当成"约束通过",否则又是一次静默放行
3378
+ return false;
3379
+ }
3380
+ return res === null || res === undefined ? true : Boolean(res);
3381
+ };
3382
+ }
3383
+
3384
+ /** 从 CHECK 表达式里收集引用到的列名(按出现顺序去重)。 */
3385
+ function collectCheckColumns(node, out = []) {
3386
+ if (node === null || node === undefined) return out;
3387
+ if (Array.isArray(node)) {
3388
+ for (const item of node) collectCheckColumns(item, out);
3389
+ return out;
3390
+ }
3391
+ if (typeof node !== 'object') return out;
3392
+ if (node.type === 'column' && node.name) {
3393
+ const name = String(node.name);
3394
+ const bare = name.indexOf('.') === -1 ? name : name.slice(name.lastIndexOf('.') + 1);
3395
+ if (!out.includes(bare)) out.push(bare);
3396
+ }
3397
+ for (const key of Object.keys(node)) {
3398
+ if (key === 'type') continue;
3399
+ const v = node[key];
3400
+ if (v && typeof v === 'object') collectCheckColumns(v, out);
3401
+ }
3402
+ return out;
3403
+ }
3404
+
3405
+ /** 由 SQL 文本重新编译 CHECK 条件(持久化重载路径)。 */
3406
+ function compileCheckExpr(sqlText) {
3407
+ const p = new Parser(tokenize(String(sqlText)));
3408
+ const ast = p.parseBooleanExpr();
3409
+ if (p.peek().type !== 'eof') throw new Error(`Unexpected token '${p.peek().value}' after CHECK expression`);
3410
+ return makeCheckFn(ast);
3411
+ }
3412
+
3256
3413
  /**
3257
3414
  * BigInt 参与的整数算术(Issue #38)。
3258
3415
  *
@@ -3334,14 +3491,14 @@ function resolveOperand(operand, row, ctx) {
3334
3491
  const d = new Date(base.getTime());
3335
3492
  const n = sign * Number(ivNode.value || 0);
3336
3493
  switch (String(ivNode.unit || '').toUpperCase()) {
3337
- case 'DAY': case 'DAYS': d.setDate(d.getDate() + n); break;
3338
- case 'WEEK': case 'WEEKS': d.setDate(d.getDate() + n * 7); break;
3494
+ case 'DAY': case 'DAYS': d.setUTCDate(d.getUTCDate() + n); break;
3495
+ case 'WEEK': case 'WEEKS': d.setUTCDate(d.getUTCDate() + n * 7); break;
3339
3496
  case 'MONTH': case 'MONTHS': addMonthsClamped(d, n); break;
3340
3497
  case 'QUARTER': addMonthsClamped(d, n * 3); break;
3341
3498
  case 'YEAR': case 'YEARS': addMonthsClamped(d, n * 12); break;
3342
- case 'HOUR': case 'HOURS': d.setHours(d.getHours() + n); break;
3343
- case 'MINUTE': case 'MINUTES': d.setMinutes(d.getMinutes() + n); break;
3344
- case 'SECOND': case 'SECONDS': d.setSeconds(d.getSeconds() + n); break;
3499
+ case 'HOUR': case 'HOURS': d.setUTCHours(d.getUTCHours() + n); break;
3500
+ case 'MINUTE': case 'MINUTES': d.setUTCMinutes(d.getUTCMinutes() + n); break;
3501
+ case 'SECOND': case 'SECONDS': d.setUTCSeconds(d.getUTCSeconds() + n); break;
3345
3502
  default: return null;
3346
3503
  }
3347
3504
  return fmtSqlDate(isDateOnly, d);
@@ -3361,60 +3518,50 @@ function resolveOperand(operand, row, ctx) {
3361
3518
  // '5' + 5 = 10 '5' + '5' = 10 'abc' + 1 = 1 'a' + 'b' = 0
3362
3519
  // 任一侧是「数值」时做算术加法,另一侧非数值按 0;
3363
3520
  // 两侧都不是数值才是 0(JS 的 l + r 会把 '5' + 5 拼成 '55')。
3364
- if (typeof l === 'number' || typeof r === 'number') {
3365
- const ln2 = numericIfNumeric(l), rn2 = numericIfNumeric(r);
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;
3521
+ const ln = mysqlNum(l), rn = mysqlNum(r);
3522
+ return ln + rn;
3372
3523
  }
3373
3524
  case '-': {
3374
3525
  const bx = bigintExactArith(l, r, '-');
3375
3526
  if (bx !== undefined) return bx;
3376
- // P1-21: 'abc'-1 → NaN,应返回 null
3377
- const ln = Number(l), rn = Number(r);
3378
- if (isNaN(ln) || isNaN(rn)) return null;
3527
+ const ln = mysqlNum(l), rn = mysqlNum(r);
3379
3528
  return ln - rn;
3380
3529
  }
3381
3530
  case '*': {
3382
3531
  const bx = bigintExactArith(l, r, '*');
3383
3532
  if (bx !== undefined) return bx;
3384
- const ln = Number(l), rn = Number(r);
3385
- if (isNaN(ln) || isNaN(rn)) return null;
3533
+ const ln = mysqlNum(l), rn = mysqlNum(r);
3386
3534
  return ln * rn;
3387
3535
  }
3388
3536
  case '/': {
3389
- const ln = Number(l), rn = Number(r);
3390
- if (isNaN(ln) || isNaN(rn) || rn === 0) return null;
3537
+ const ln = mysqlNum(l), rn = mysqlNum(r);
3538
+ if (rn === 0) return null;
3391
3539
  return ln / rn;
3392
3540
  }
3393
3541
  case '%': {
3394
- const ln = Number(l), rn = Number(r);
3395
- if (isNaN(ln) || isNaN(rn) || rn === 0) return null;
3542
+ const ln = mysqlNum(l), rn = mysqlNum(r);
3543
+ if (rn === 0) return null;
3396
3544
  return ln % rn;
3397
3545
  }
3398
3546
  // MySQL 整数除法 DIV(结果向零取整)
3399
- case 'DIV': return r === 0 ? null : Math.trunc(Number(l) / Number(r));
3547
+ case 'DIV': return mysqlNum(r) === 0 ? null : Math.trunc(mysqlNum(l) / mysqlNum(r));
3400
3548
  // 位运算:先按整数归一,与 MySQL 的整数位运算语义一致
3401
- case '&': return (Number(l) | 0) & (Number(r) | 0);
3402
- case '|': return (Number(l) | 0) | (Number(r) | 0);
3403
- case '^': return (Number(l) | 0) ^ (Number(r) | 0);
3549
+ case '&': return (mysqlNum(l) | 0) & (mysqlNum(r) | 0);
3550
+ case '|': return (mysqlNum(l) | 0) | (mysqlNum(r) | 0);
3551
+ case '^': return (mysqlNum(l) | 0) ^ (mysqlNum(r) | 0);
3404
3552
  // P1-22: JavaScript 位运算只使用 32 位整数,移位量对 32 取模
3405
3553
  // 1 << 32 = 1 << 0 = 1,但 SQL 中 1 << 32 = 4294967296
3406
- case '<<': return Number(l) * Math.pow(2, Number(r));
3407
- case '>>': return Math.floor(Number(l) / Math.pow(2, Number(r)));
3554
+ case '<<': return mysqlNum(l) * Math.pow(2, mysqlNum(r));
3555
+ case '>>': return Math.floor(mysqlNum(l) / Math.pow(2, mysqlNum(r)));
3408
3556
  }
3409
3557
  return null;
3410
3558
  }
3411
3559
  case 'bitnot':
3412
- return ~(Number(resolveOperand(operand.expr, row, ctx)) | 0);
3560
+ return ~(mysqlNum(resolveOperand(operand.expr, row, ctx)) | 0);
3413
3561
  case 'negate': {
3414
3562
  const v = resolveOperand(operand.operand, row, ctx);
3415
3563
  if (v === null || v === undefined) return null;
3416
- const n = Number(v);
3417
- if (isNaN(n)) return null;
3564
+ const n = mysqlNum(v);
3418
3565
  return operand.positive ? n : -n;
3419
3566
  }
3420
3567
  // P1-19: ON DUPLICATE KEY UPDATE 表达式赋值,如 count = count + 1
@@ -3430,25 +3577,19 @@ function resolveOperand(operand, row, ctx) {
3430
3577
  case '+': {
3431
3578
  const bx = bigintExactArith(l, r, '+');
3432
3579
  if (bx !== undefined) return bx;
3433
- if (typeof l === 'number' || typeof r === 'number') {
3434
- const ln = numericIfNumeric(l), rn = numericIfNumeric(r);
3435
- return (ln === null ? 0 : ln) + (rn === null ? 0 : rn);
3436
- }
3437
- const ln = numericIfNumeric(l), rn = numericIfNumeric(r);
3438
- if (ln !== null) return ln + (rn === null ? 0 : rn);
3439
- if (rn !== null) return rn;
3440
- return 0;
3441
- }
3442
- 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; }
3443
- 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; }
3444
- case '/': { const ln = Number(l), rn = Number(r); return isNaN(ln) || isNaN(rn) || rn === 0 ? null : ln / rn; }
3445
- case '%': { const ln = Number(l), rn = Number(r); return isNaN(ln) || isNaN(rn) || rn === 0 ? null : ln % rn; }
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)));
3580
+ const ln = mysqlNum(l), rn = mysqlNum(r);
3581
+ return ln + rn;
3582
+ }
3583
+ case '-': { const bx = bigintExactArith(l, r, '-'); if (bx !== undefined) return bx; return mysqlNum(l) - mysqlNum(r); }
3584
+ case '*': { const bx = bigintExactArith(l, r, '*'); if (bx !== undefined) return bx; return mysqlNum(l) * mysqlNum(r); }
3585
+ case '/': { const rn = mysqlNum(r); return rn === 0 ? null : mysqlNum(l) / rn; }
3586
+ case '%': { const rn = mysqlNum(r); return rn === 0 ? null : mysqlNum(l) % rn; }
3587
+ case 'DIV': return mysqlNum(r) === 0 ? null : Math.trunc(mysqlNum(l) / mysqlNum(r));
3588
+ case '&': return (mysqlNum(l) | 0) & (mysqlNum(r) | 0);
3589
+ case '|': return (mysqlNum(l) | 0) | (mysqlNum(r) | 0);
3590
+ case '^': return (mysqlNum(l) | 0) ^ (mysqlNum(r) | 0);
3591
+ case '<<': return mysqlNum(l) * Math.pow(2, mysqlNum(r));
3592
+ case '>>': return Math.floor(mysqlNum(l) / Math.pow(2, mysqlNum(r)));
3452
3593
  default: return null;
3453
3594
  }
3454
3595
  }
@@ -3573,27 +3714,64 @@ function resolveOperand(operand, row, ctx) {
3573
3714
  }
3574
3715
  }
3575
3716
 
3576
- /** 解析 SQL 里的日期文本('YYYY-MM-DD' / 'YYYY-MM-DD HH:MM:SS' / Date) */
3717
+ /** 解析 SQL 里的日期文本('YYYY-MM-DD' / 'YYYY-MM-DD HH:MM:SS' / Date)
3718
+ * 时区基准:无时区标记按 UTC 墙上时间(不再用 new Date(s) 的本地时区解析)。
3719
+ * 带 Z / ±HH:MM 标记的先换算成绝对时刻。 */
3577
3720
  function parseSqlDate(v) {
3578
3721
  if (v === null || v === undefined) return null;
3579
3722
  if (v instanceof Date) return Number.isNaN(v.getTime()) ? null : v;
3580
- const s = String(v).trim().replace(' ', 'T');
3581
- const d = new Date(s.length <= 10 ? s + 'T00:00:00' : s);
3582
- return Number.isNaN(d.getTime()) ? null : d;
3723
+ const ms = parseUtcWallClock(String(v));
3724
+ return ms === null ? null : new Date(ms);
3725
+ }
3726
+
3727
+ /** 'YYYY-MM-DD[ HH:MM[:SS]]' 无时区 → UTC 墙上时间的毫秒;带时区标记则按标记换算。
3728
+ * 非法返回 null。与 date-types 的解析保持一致,避免两套口径。 */
3729
+ /** 'Z' / '±HH:MM' / '±HHMM' → 相对 UTC 的分钟偏移;无标记或非法返回 null */
3730
+ function tzOffsetMinutes(rest) {
3731
+ let s = String(rest == null ? '' : rest).trim();
3732
+ if (s.startsWith('.')) s = s.replace(/^\.\d+/, '');
3733
+ if (s === 'Z' || s === 'z') return 0;
3734
+ const m = s.match(/^([+-])(\d{2}):?(\d{2})$/);
3735
+ if (!m) return null;
3736
+ const hh = parseInt(m[2], 10), mm = parseInt(m[3], 10);
3737
+ if (hh > 23 || mm > 59) return null;
3738
+ return (m[1] === '-' ? -1 : 1) * (hh * 60 + mm);
3739
+ }
3740
+
3741
+ function parseUtcWallClock(str) {
3742
+ const s = String(str == null ? '' : str).trim();
3743
+ const m = s.match(/^(\d{4})-(\d{2})-(\d{2})(?:[T ](\d{1,2}):(\d{2})(?::(\d{2}))?(?:\.(\d+))?)?(.*)$/);
3744
+ if (!m) return null;
3745
+ const y = +m[1], mo = +m[2], day = +m[3];
3746
+ const h = m[4] === undefined ? 0 : +m[4];
3747
+ const mi = m[5] === undefined ? 0 : +m[5];
3748
+ const sec = m[6] === undefined ? 0 : +m[6];
3749
+ const frac = m[7] === undefined ? 0 : Math.floor(+('0.' + m[7]) * 1000);
3750
+ // 月份/日号越界非法;日号溢出当月天数沿用 JS 归一行为(2026-02-29 → 2026-03-01)
3751
+ if (mo < 1 || mo > 12 || day < 1 || day > 31) return null;
3752
+ if (h > 23 || mi > 59 || sec > 59) return null;
3753
+ let ms = Date.UTC(y, mo - 1, day, h, mi, sec, frac);
3754
+ const rest = (m[8] || '').trim();
3755
+ if (rest !== '') {
3756
+ const tz = tzOffsetMinutes(rest);
3757
+ if (tz === null) return null;
3758
+ ms -= tz * 60000;
3759
+ }
3760
+ return ms;
3583
3761
  }
3584
3762
 
3585
3763
  function pad2(n) { return String(n).padStart(2, '0'); }
3586
3764
 
3587
- /** 本地时区的 'YYYY-MM-DD HH:mm:ss'(MySQL 的 NOW() 语义;区别于 UTC_TIMESTAMP) */
3765
+ /** UTC 墙上时间的 'YYYY-MM-DD HH:mm:ss'(引擎统一基准;会话时区固定为 UTC) */
3588
3766
  function sqlLocalDateTime(d = new Date()) {
3589
- return d.getFullYear() + '-' + pad2(d.getMonth() + 1) + '-' + pad2(d.getDate()) + ' ' +
3590
- pad2(d.getHours()) + ':' + pad2(d.getMinutes()) + ':' + pad2(d.getSeconds());
3767
+ return d.getUTCFullYear() + '-' + pad2(d.getUTCMonth() + 1) + '-' + pad2(d.getUTCDate()) + ' ' +
3768
+ pad2(d.getUTCHours()) + ':' + pad2(d.getUTCMinutes()) + ':' + pad2(d.getUTCSeconds());
3591
3769
  }
3592
3770
 
3593
- /** 按输入形态回写日期:纯日期返回 YYYY-MM-DD,带时间返回 YYYY-MM-DD HH:MM:SS */
3771
+ /** 按输入形态回写日期(UTC):纯日期返回 YYYY-MM-DD,带时间返回 YYYY-MM-DD HH:MM:SS */
3594
3772
  function fmtSqlDate(dateOnly, d) {
3595
- const ymd = d.getFullYear() + '-' + pad2(d.getMonth() + 1) + '-' + pad2(d.getDate());
3596
- return dateOnly ? ymd : ymd + ' ' + pad2(d.getHours()) + ':' + pad2(d.getMinutes()) + ':' + pad2(d.getSeconds());
3773
+ const ymd = d.getUTCFullYear() + '-' + pad2(d.getUTCMonth() + 1) + '-' + pad2(d.getUTCDate());
3774
+ return dateOnly ? ymd : ymd + ' ' + pad2(d.getUTCHours()) + ':' + pad2(d.getUTCMinutes()) + ':' + pad2(d.getUTCSeconds());
3597
3775
  }
3598
3776
 
3599
3777
  const DAY_NAMES = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
@@ -3606,21 +3784,21 @@ const TIME_UNITS = new Set([
3606
3784
  'SECONDS', 'MINUTES', 'HOURS', 'DAYS', 'WEEKS', 'MONTHS', 'YEARS',
3607
3785
  ]);
3608
3786
 
3609
- /** MySQL DATE_FORMAT 的 % 说明符 */
3787
+ /** MySQL DATE_FORMAT 的 % 说明符(全部取 UTC 部件,与落库值一致) */
3610
3788
  function strftime(d, fmt) {
3611
- const h12 = ((d.getHours() % 12) || 12);
3789
+ const h12 = ((d.getUTCHours() % 12) || 12);
3612
3790
  const map = {
3613
- '%Y': String(d.getFullYear()), '%y': pad2(d.getFullYear() % 100),
3614
- '%m': pad2(d.getMonth() + 1), '%c': String(d.getMonth() + 1),
3615
- '%d': pad2(d.getDate()), '%e': String(d.getDate()),
3616
- '%H': pad2(d.getHours()), '%k': String(d.getHours()),
3791
+ '%Y': String(d.getUTCFullYear()), '%y': pad2(d.getUTCFullYear() % 100),
3792
+ '%m': pad2(d.getUTCMonth() + 1), '%c': String(d.getUTCMonth() + 1),
3793
+ '%d': pad2(d.getUTCDate()), '%e': String(d.getUTCDate()),
3794
+ '%H': pad2(d.getUTCHours()), '%k': String(d.getUTCHours()),
3617
3795
  '%h': pad2(h12), '%I': pad2(h12), '%l': String(h12),
3618
- '%i': pad2(d.getMinutes()), '%S': pad2(d.getSeconds()), '%s': pad2(d.getSeconds()),
3619
- '%p': d.getHours() < 12 ? 'AM' : 'PM',
3620
- '%M': MONTH_NAMES[d.getMonth()], '%b': MONTH_NAMES[d.getMonth()].slice(0, 3),
3621
- '%W': DAY_NAMES[d.getDay()], '%a': DAY_NAMES[d.getDay()].slice(0, 3),
3622
- '%w': String(d.getDay()),
3623
- '%j': String(Math.round((d - new Date(d.getFullYear(), 0, 0)) / 86400000)),
3796
+ '%i': pad2(d.getUTCMinutes()), '%S': pad2(d.getUTCSeconds()), '%s': pad2(d.getUTCSeconds()),
3797
+ '%p': d.getUTCHours() < 12 ? 'AM' : 'PM',
3798
+ '%M': MONTH_NAMES[d.getUTCMonth()], '%b': MONTH_NAMES[d.getUTCMonth()].slice(0, 3),
3799
+ '%W': DAY_NAMES[d.getUTCDay()], '%a': DAY_NAMES[d.getUTCDay()].slice(0, 3),
3800
+ '%w': String(d.getUTCDay()),
3801
+ '%j': String(Math.round((d - Date.UTC(d.getUTCFullYear(), 0, 0)) / 86400000)),
3624
3802
  '%%': '%',
3625
3803
  };
3626
3804
  return String(fmt).replace(/%[A-Za-z%]/g, (m) => (m in map ? map[m] : m));
@@ -3695,31 +3873,32 @@ function strToDate(s, fmt) {
3695
3873
  default: break;
3696
3874
  }
3697
3875
  });
3698
- const d = new Date(year, month, day, hour, min, sec);
3876
+ // 无时区 → UTC 墙上时间(与 parseSqlDate 一致)
3877
+ const d = new Date(Date.UTC(year, month, day, hour, min, sec));
3699
3878
  return Number.isNaN(d.getTime()) ? null : d;
3700
3879
  }
3701
3880
 
3702
- /** PG DATE_PART / EXTRACT 的部件取值 */
3881
+ /** PG DATE_PART / EXTRACT 的部件取值(UTC 部件) */
3703
3882
  function pgDatePart(part, d) {
3704
3883
  switch (String(part).toLowerCase()) {
3705
- case 'year': case 'y': return d.getFullYear();
3706
- case 'month': case 'mon': case 'mm': return d.getMonth() + 1;
3707
- case 'day': case 'dd': case 'd': return d.getDate();
3708
- case 'hour': case 'hh': return d.getHours();
3709
- case 'minute': case 'mi': return d.getMinutes();
3710
- case 'second': case 'ss': return d.getSeconds();
3711
- case 'dow': return d.getDay();
3712
- case 'doy': return Math.round((d - new Date(d.getFullYear(), 0, 0)) / 86400000);
3713
- case 'quarter': return Math.floor(d.getMonth() / 3) + 1;
3884
+ case 'year': case 'y': return d.getUTCFullYear();
3885
+ case 'month': case 'mon': case 'mm': return d.getUTCMonth() + 1;
3886
+ case 'day': case 'dd': case 'd': return d.getUTCDate();
3887
+ case 'hour': case 'hh': return d.getUTCHours();
3888
+ case 'minute': case 'mi': return d.getUTCMinutes();
3889
+ case 'second': case 'ss': return d.getUTCSeconds();
3890
+ case 'dow': return d.getUTCDay();
3891
+ case 'doy': return Math.round((d - Date.UTC(d.getUTCFullYear(), 0, 0)) / 86400000);
3892
+ case 'quarter': return Math.floor(d.getUTCMonth() / 3) + 1;
3714
3893
  case 'epoch': return Math.floor(d.getTime() / 1000);
3715
3894
  case 'week': {
3716
3895
  // ISO 8601 周序号
3717
- const t = new Date(d.getFullYear(), d.getMonth(), d.getDate());
3718
- const dayNr = (t.getDay() + 6) % 7;
3719
- t.setDate(t.getDate() - dayNr + 3);
3720
- const firstThursday = new Date(t.getFullYear(), 0, 4);
3721
- const fdayNr = (firstThursday.getDay() + 6) % 7;
3722
- firstThursday.setDate(firstThursday.getDate() - fdayNr + 3);
3896
+ const t = new Date(Date.UTC(d.getUTCFullYear(), d.getUTCMonth(), d.getUTCDate()));
3897
+ const dayNr = (t.getUTCDay() + 6) % 7;
3898
+ t.setUTCDate(t.getUTCDate() - dayNr + 3);
3899
+ const firstThursday = new Date(Date.UTC(t.getUTCFullYear(), 0, 4));
3900
+ const fdayNr = (firstThursday.getUTCDay() + 6) % 7;
3901
+ firstThursday.setUTCDate(firstThursday.getUTCDate() - fdayNr + 3);
3723
3902
  return 1 + Math.round((t - firstThursday) / (7 * 86400000));
3724
3903
  }
3725
3904
  default: return null;
@@ -3733,24 +3912,24 @@ function pgDatePart(part, d) {
3733
3912
  * 先 setDate(1) 再切月,避免切换过程中先溢出再被钳制。
3734
3913
  */
3735
3914
  function addMonthsClamped(d, n) {
3736
- const day = d.getDate();
3915
+ const day = d.getUTCDate();
3737
3916
  const t = new Date(d.getTime());
3738
- t.setDate(1);
3739
- t.setMonth(t.getMonth() + n);
3740
- const lastDay = new Date(t.getFullYear(), t.getMonth() + 1, 0).getDate();
3741
- t.setDate(Math.min(day, lastDay));
3917
+ t.setUTCDate(1);
3918
+ t.setUTCMonth(t.getUTCMonth() + n);
3919
+ const lastDay = new Date(Date.UTC(t.getUTCFullYear(), t.getUTCMonth() + 1, 0)).getUTCDate();
3920
+ t.setUTCDate(Math.min(day, lastDay));
3742
3921
  d.setTime(t.getTime());
3743
3922
  return d;
3744
3923
  }
3745
3924
 
3746
3925
  /** PG AGE(from, to) 的间隔文本:'6 years 7 mons 11 days' */
3747
3926
  function pgAge(from, to) {
3748
- let years = to.getFullYear() - from.getFullYear();
3749
- let months = to.getMonth() - from.getMonth();
3750
- let days = to.getDate() - from.getDate();
3927
+ let years = to.getUTCFullYear() - from.getUTCFullYear();
3928
+ let months = to.getUTCMonth() - from.getUTCMonth();
3929
+ let days = to.getUTCDate() - from.getUTCDate();
3751
3930
  if (days < 0) {
3752
3931
  months -= 1;
3753
- days += new Date(to.getFullYear(), to.getMonth(), 0).getDate();
3932
+ days += new Date(Date.UTC(to.getUTCFullYear(), to.getUTCMonth(), 0)).getUTCDate();
3754
3933
  }
3755
3934
  if (months < 0) { years -= 1; months += 12; }
3756
3935
  return `${years} years ${months} mons ${days} days`;
@@ -3790,8 +3969,9 @@ function applyScalarFunction(fnNode, row, ctx) {
3790
3969
  case 'FOUND_ROWS': return session && session.foundRows !== undefined ? session.foundRows : 0;
3791
3970
  case 'CONNECTION_ID': return session && session.connectionId !== undefined ? session.connectionId : 0;
3792
3971
  case 'DATABASE': case 'SCHEMA': return session && session.currentDb ? session.currentDb : 'default';
3793
- // NOW() / CURDATE() / CURTIME() 返回会话时区(本地)时间,不能用 toISOString()(UTC)——
3794
- // 否则东八区凌晨会整整差一天(2024-02-29 被存成 2024-02-28)。
3972
+ // NOW() / CURDATE() / CURTIME() 返回 **UTC 墙上时间**(引擎会话时区固定为 UTC)。
3973
+ // 落库的日期字面量也按 UTC 基准,两者必须同一口径,否则 NOW() 写入值与
3974
+ // 字面量比较会错开整个主机时区偏移。
3795
3975
  case 'NOW': case 'CURRENT_TIMESTAMP': return sqlLocalDateTime();
3796
3976
  case 'CURDATE': case 'CURRENT_DATE': return sqlLocalDateTime().slice(0, 10);
3797
3977
  case 'CURTIME': return sqlLocalDateTime().slice(11, 19);
@@ -3842,16 +4022,16 @@ function applyScalarFunction(fnNode, row, ctx) {
3842
4022
  const d = parseSqlDate(args[1]);
3843
4023
  if (!d) return null;
3844
4024
  switch (unit) {
3845
- case 'YEAR': return d.getFullYear();
3846
- case 'MONTH': return d.getMonth() + 1;
3847
- case 'DAY': return d.getDate();
3848
- case 'HOUR': return d.getHours();
3849
- case 'MINUTE': return d.getMinutes();
3850
- case 'SECOND': return d.getSeconds();
3851
- case 'DOW': return d.getDay(); // 0 = 周日
3852
- case 'DAYOFWEEK': return d.getDay() + 1; // 1 = 周日(MySQL 语义)
4025
+ case 'YEAR': return d.getUTCFullYear();
4026
+ case 'MONTH': return d.getUTCMonth() + 1;
4027
+ case 'DAY': return d.getUTCDate();
4028
+ case 'HOUR': return d.getUTCHours();
4029
+ case 'MINUTE': return d.getUTCMinutes();
4030
+ case 'SECOND': return d.getUTCSeconds();
4031
+ case 'DOW': return d.getUTCDay(); // 0 = 周日
4032
+ case 'DAYOFWEEK': return d.getUTCDay() + 1; // 1 = 周日(MySQL 语义)
3853
4033
  case 'WEEK': {
3854
- const start = new Date(d.getFullYear(), 0, 1);
4034
+ const start = Date.UTC(d.getUTCFullYear(), 0, 1);
3855
4035
  return Math.floor((d - start) / 604800000) + 1;
3856
4036
  }
3857
4037
  default: return null;
@@ -3868,14 +4048,14 @@ function applyScalarFunction(fnNode, row, ctx) {
3868
4048
  const d = new Date(base.getTime());
3869
4049
  const n = sign * Number(iv.value || 0);
3870
4050
  switch (String(iv.unit || '').toUpperCase()) {
3871
- case 'DAY': case 'DAYS': d.setDate(d.getDate() + n); break;
3872
- case 'WEEK': case 'WEEKS': d.setDate(d.getDate() + n * 7); break;
4051
+ case 'DAY': case 'DAYS': d.setUTCDate(d.getUTCDate() + n); break;
4052
+ case 'WEEK': case 'WEEKS': d.setUTCDate(d.getUTCDate() + n * 7); break;
3873
4053
  case 'MONTH': case 'MONTHS': addMonthsClamped(d, n); break;
3874
4054
  case 'QUARTER': addMonthsClamped(d, n * 3); break;
3875
4055
  case 'YEAR': case 'YEARS': addMonthsClamped(d, n * 12); break;
3876
- case 'HOUR': case 'HOURS': d.setHours(d.getHours() + n); break;
3877
- case 'MINUTE': case 'MINUTES': d.setMinutes(d.getMinutes() + n); break;
3878
- case 'SECOND': case 'SECONDS': d.setSeconds(d.getSeconds() + n); break;
4056
+ case 'HOUR': case 'HOURS': d.setUTCHours(d.getUTCHours() + n); break;
4057
+ case 'MINUTE': case 'MINUTES': d.setUTCMinutes(d.getUTCMinutes() + n); break;
4058
+ case 'SECOND': case 'SECONDS': d.setUTCSeconds(d.getUTCSeconds() + n); break;
3879
4059
  default: return null;
3880
4060
  }
3881
4061
  return fmtSqlDate(isDateOnly, d);
@@ -3883,31 +4063,31 @@ function applyScalarFunction(fnNode, row, ctx) {
3883
4063
  // ===== 日期/时间(补齐 README 契约:此前这些全部缺失,静默返回 null)=====
3884
4064
  case 'YEAR': {
3885
4065
  const d = parseSqlDate(args[0]);
3886
- return d ? d.getFullYear() : null;
4066
+ return d ? d.getUTCFullYear() : null;
3887
4067
  }
3888
4068
  case 'MONTH': {
3889
4069
  const d = parseSqlDate(args[0]);
3890
- return d ? d.getMonth() + 1 : null;
4070
+ return d ? d.getUTCMonth() + 1 : null;
3891
4071
  }
3892
4072
  case 'DAY': case 'DAYOFMONTH': {
3893
4073
  const d = parseSqlDate(args[0]);
3894
- return d ? d.getDate() : null;
4074
+ return d ? d.getUTCDate() : null;
3895
4075
  }
3896
4076
  case 'HOUR': {
3897
4077
  const d = parseSqlDate(args[0]);
3898
- return d ? d.getHours() : null;
4078
+ return d ? d.getUTCHours() : null;
3899
4079
  }
3900
4080
  case 'MINUTE': {
3901
4081
  const d = parseSqlDate(args[0]);
3902
- return d ? d.getMinutes() : null;
4082
+ return d ? d.getUTCMinutes() : null;
3903
4083
  }
3904
4084
  case 'SECOND': {
3905
4085
  const d = parseSqlDate(args[0]);
3906
- return d ? d.getSeconds() : null;
4086
+ return d ? d.getUTCSeconds() : null;
3907
4087
  }
3908
4088
  case 'QUARTER': {
3909
4089
  const d = parseSqlDate(args[0]);
3910
- return d ? Math.floor(d.getMonth() / 3) + 1 : null;
4090
+ return d ? Math.floor(d.getUTCMonth() / 3) + 1 : null;
3911
4091
  }
3912
4092
  case 'WEEK': {
3913
4093
  const d = parseSqlDate(args[0]);
@@ -3916,15 +4096,15 @@ function applyScalarFunction(fnNode, row, ctx) {
3916
4096
  // mode 1/3(周一为一周之始且首周需 ≥4 天)走 ISO 周序;其余按 MySQL 默认 mode 0
3917
4097
  if (mode === 1 || mode === 3) return pgDatePart('week', d);
3918
4098
  // mode 0:周日为一周之始,第 1 周是本年第一个含周日的周(之前为第 0 周)
3919
- const jan1Dow = new Date(d.getFullYear(), 0, 1).getDay(); // 0=周日
4099
+ const jan1Dow = new Date(Date.UTC(d.getUTCFullYear(), 0, 1)).getUTCDay(); // 0=周日
3920
4100
  const firstSunday = jan1Dow === 0 ? 1 : 8 - jan1Dow;
3921
- const doy = Math.round((d - new Date(d.getFullYear(), 0, 0)) / 86400000);
4101
+ const doy = Math.round((d - Date.UTC(d.getUTCFullYear(), 0, 0)) / 86400000);
3922
4102
  if (doy < firstSunday) return 0;
3923
4103
  return Math.floor((doy - firstSunday) / 7) + 1;
3924
4104
  }
3925
4105
  case 'DAYOFWEEK': { // MySQL:1=周日 … 7=周六
3926
4106
  const d = parseSqlDate(args[0]);
3927
- return d ? d.getDay() + 1 : null;
4107
+ return d ? d.getUTCDay() + 1 : null;
3928
4108
  }
3929
4109
  case 'DATE': {
3930
4110
  const d = parseSqlDate(args[0]);
@@ -3932,15 +4112,15 @@ function applyScalarFunction(fnNode, row, ctx) {
3932
4112
  }
3933
4113
  case 'TIME': {
3934
4114
  const d = parseSqlDate(args[0]);
3935
- return d ? pad2(d.getHours()) + ':' + pad2(d.getMinutes()) + ':' + pad2(d.getSeconds()) : null;
4115
+ return d ? pad2(d.getUTCHours()) + ':' + pad2(d.getUTCMinutes()) + ':' + pad2(d.getUTCSeconds()) : null;
3936
4116
  }
3937
4117
  case 'DATEDIFF': {
3938
4118
  const a = parseSqlDate(args[0]);
3939
4119
  const b = parseSqlDate(args[1]);
3940
4120
  if (!a || !b) return null;
3941
4121
  // MySQL 语义:按日期相减(忽略时间部分)
3942
- const ua = Date.UTC(a.getFullYear(), a.getMonth(), a.getDate());
3943
- const ub = Date.UTC(b.getFullYear(), b.getMonth(), b.getDate());
4122
+ const ua = Date.UTC(a.getUTCFullYear(), a.getUTCMonth(), a.getUTCDate());
4123
+ const ub = Date.UTC(b.getUTCFullYear(), b.getUTCMonth(), b.getUTCDate());
3944
4124
  return Math.round((ua - ub) / 86400000);
3945
4125
  }
3946
4126
  case 'TIMESTAMPDIFF': {
@@ -3958,8 +4138,8 @@ function applyScalarFunction(fnNode, row, ctx) {
3958
4138
  // 只算日历月差会高估:
3959
4139
  // TIMESTAMPDIFF(MONTH,'2026-01-15','2026-03-14') = 1(差 1 个月零 29 天,不足 2 个月)
3960
4140
  // TIMESTAMPDIFF(MONTH,'2026-01-31','2026-03-01') = 1(1/31+1月=2/28,2/28+1月=3/28,够不到 3/1)
3961
- let months = (a.getFullYear() - b.getFullYear()) * 12 + (a.getMonth() - b.getMonth());
3962
- if (a.getDate() < b.getDate()) months--;
4141
+ let months = (a.getUTCFullYear() - b.getUTCFullYear()) * 12 + (a.getUTCMonth() - b.getUTCMonth());
4142
+ if (a.getUTCDate() < b.getUTCDate()) months--;
3963
4143
  switch (unit) {
3964
4144
  case 'MICROSECOND': return Math.floor(ms * 1000);
3965
4145
  case 'SECOND': return Math.floor(ms / 1000);
@@ -4006,30 +4186,30 @@ function applyScalarFunction(fnNode, row, ctx) {
4006
4186
  }
4007
4187
  case 'LAST_DAY': {
4008
4188
  const d = parseSqlDate(args[0]);
4009
- return d ? fmtSqlDate(true, new Date(d.getFullYear(), d.getMonth() + 1, 0)) : null;
4189
+ return d ? fmtSqlDate(true, new Date(Date.UTC(d.getUTCFullYear(), d.getUTCMonth() + 1, 0))) : null;
4010
4190
  }
4011
4191
  case 'WEEKDAY': { // MySQL:0=周一 … 6=周日
4012
4192
  const d = parseSqlDate(args[0]);
4013
- return d ? (d.getDay() + 6) % 7 : null;
4193
+ return d ? (d.getUTCDay() + 6) % 7 : null;
4014
4194
  }
4015
4195
  case 'DAYOFYEAR': {
4016
4196
  const d = parseSqlDate(args[0]);
4017
- return d ? Math.round((d - new Date(d.getFullYear(), 0, 0)) / 86400000) : null;
4197
+ return d ? Math.round((d - Date.UTC(d.getUTCFullYear(), 0, 0)) / 86400000) : null;
4018
4198
  }
4019
4199
  case 'DAYNAME': {
4020
4200
  const d = parseSqlDate(args[0]);
4021
- return d ? DAY_NAMES[d.getDay()] : null;
4201
+ return d ? DAY_NAMES[d.getUTCDay()] : null;
4022
4202
  }
4023
4203
  case 'MONTHNAME': {
4024
4204
  const d = parseSqlDate(args[0]);
4025
- return d ? MONTH_NAMES[d.getMonth()] : null;
4205
+ return d ? MONTH_NAMES[d.getUTCMonth()] : null;
4026
4206
  }
4027
4207
  case 'MAKEDATE': {
4028
4208
  const y = Number(args[0]);
4029
4209
  const doy = Number(args[1]);
4030
4210
  if (!Number.isFinite(y) || !Number.isFinite(doy)) return null;
4031
- const d = new Date(y, 0, 1);
4032
- d.setDate(doy);
4211
+ const d = new Date(Date.UTC(y, 0, 1));
4212
+ d.setUTCDate(doy);
4033
4213
  return fmtSqlDate(true, d);
4034
4214
  }
4035
4215
  case 'PERIOD_DIFF': {
@@ -4045,14 +4225,14 @@ function applyScalarFunction(fnNode, row, ctx) {
4045
4225
  if (!d) return null;
4046
4226
  let nd;
4047
4227
  switch (part) {
4048
- case 'year': nd = new Date(d.getFullYear(), 0, 1); break;
4049
- case 'quarter': nd = new Date(d.getFullYear(), Math.floor(d.getMonth() / 3) * 3, 1); break;
4050
- case 'month': nd = new Date(d.getFullYear(), d.getMonth(), 1); break;
4051
- case 'week': { const wd = (d.getDay() + 6) % 7; nd = new Date(d.getFullYear(), d.getMonth(), d.getDate() - wd); break; }
4052
- case 'day': nd = new Date(d.getFullYear(), d.getMonth(), d.getDate()); break;
4053
- case 'hour': nd = new Date(d.getFullYear(), d.getMonth(), d.getDate(), d.getHours()); break;
4054
- case 'minute': nd = new Date(d.getFullYear(), d.getMonth(), d.getDate(), d.getHours(), d.getMinutes()); break;
4055
- case 'second': nd = new Date(d.getFullYear(), d.getMonth(), d.getDate(), d.getHours(), d.getMinutes(), d.getSeconds()); break;
4228
+ case 'year': nd = new Date(Date.UTC(d.getUTCFullYear(), 0, 1)); break;
4229
+ case 'quarter': nd = new Date(Date.UTC(d.getUTCFullYear(), Math.floor(d.getUTCMonth() / 3) * 3, 1)); break;
4230
+ case 'month': nd = new Date(Date.UTC(d.getUTCFullYear(), d.getUTCMonth(), 1)); break;
4231
+ case 'week': { const wd = (d.getUTCDay() + 6) % 7; nd = new Date(Date.UTC(d.getUTCFullYear(), d.getUTCMonth(), d.getUTCDate() - wd)); break; }
4232
+ case 'day': nd = new Date(Date.UTC(d.getUTCFullYear(), d.getUTCMonth(), d.getUTCDate())); break;
4233
+ case 'hour': nd = new Date(Date.UTC(d.getUTCFullYear(), d.getUTCMonth(), d.getUTCDate(), d.getUTCHours())); break;
4234
+ case 'minute': nd = new Date(Date.UTC(d.getUTCFullYear(), d.getUTCMonth(), d.getUTCDate(), d.getUTCHours(), d.getUTCMinutes())); break;
4235
+ case 'second': nd = new Date(Date.UTC(d.getUTCFullYear(), d.getUTCMonth(), d.getUTCDate(), d.getUTCHours(), d.getUTCMinutes(), d.getUTCSeconds())); break;
4056
4236
  default: return null;
4057
4237
  }
4058
4238
  return fmtSqlDate(false, nd);
@@ -4249,8 +4429,13 @@ function applyScalarFunction(fnNode, row, ctx) {
4249
4429
  case 'RAND': return args.length > 0 && args[0] != null ? seedRand(Number(args[0]))() : Math.random();
4250
4430
  case 'UNIX_TIMESTAMP': {
4251
4431
  if (args.length > 0 && args[0] != null) {
4252
- const d = new Date(String(args[0]).replace(' ', 'T'));
4253
- return isNaN(d.getTime()) ? 0 : Math.floor(d.getTime() / 1000);
4432
+ // 字符串按 UTC 基准解释(与落库值同口径),Date / 数字走绝对时刻
4433
+ let ms = null;
4434
+ if (args[0] instanceof Date) ms = args[0].getTime();
4435
+ else if (typeof args[0] === 'number') ms = args[0] * 1000;
4436
+ else ms = parseUtcWallClock(String(args[0]));
4437
+ if (ms === null || !Number.isFinite(ms)) return 0;
4438
+ return Math.floor(ms / 1000);
4254
4439
  }
4255
4440
  return Math.floor(Date.now() / 1000);
4256
4441
  }
@@ -5067,25 +5252,19 @@ function evaluateExpr(expr, row, ctx) {
5067
5252
  case '+': {
5068
5253
  const bx = bigintExactArith(l, r, '+');
5069
5254
  if (bx !== undefined) return bx;
5070
- if (typeof l === 'number' || typeof r === 'number') {
5071
- const ln = numericIfNumeric(l), rn = numericIfNumeric(r);
5072
- return (ln === null ? 0 : ln) + (rn === null ? 0 : rn);
5073
- }
5074
- const ln = numericIfNumeric(l), rn = numericIfNumeric(r);
5075
- if (ln !== null) return ln + (rn === null ? 0 : rn);
5076
- if (rn !== null) return rn;
5077
- return 0;
5078
- }
5079
- 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; }
5080
- 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; }
5081
- case '/': { const ln = Number(l), rn = Number(r); return isNaN(ln) || isNaN(rn) || rn === 0 ? null : ln / rn; }
5082
- case '%': { const ln = Number(l), rn = Number(r); return isNaN(ln) || isNaN(rn) || rn === 0 ? null : ln % rn; }
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)));
5255
+ const ln = mysqlNum(l), rn = mysqlNum(r);
5256
+ return ln + rn;
5257
+ }
5258
+ case '-': { const bx = bigintExactArith(l, r, '-'); if (bx !== undefined) return bx; return mysqlNum(l) - mysqlNum(r); }
5259
+ case '*': { const bx = bigintExactArith(l, r, '*'); if (bx !== undefined) return bx; return mysqlNum(l) * mysqlNum(r); }
5260
+ case '/': { const rn = mysqlNum(r); return rn === 0 ? null : mysqlNum(l) / rn; }
5261
+ case '%': { const rn = mysqlNum(r); return rn === 0 ? null : mysqlNum(l) % rn; }
5262
+ case 'DIV': return mysqlNum(r) === 0 ? null : Math.trunc(mysqlNum(l) / mysqlNum(r));
5263
+ case '&': return (mysqlNum(l) | 0) & (mysqlNum(r) | 0);
5264
+ case '|': return (mysqlNum(l) | 0) | (mysqlNum(r) | 0);
5265
+ case '^': return (mysqlNum(l) | 0) ^ (mysqlNum(r) | 0);
5266
+ case '<<': return mysqlNum(l) * Math.pow(2, mysqlNum(r));
5267
+ case '>>': return Math.floor(mysqlNum(l) / Math.pow(2, mysqlNum(r)));
5089
5268
  default: return null;
5090
5269
  }
5091
5270
  }
@@ -6889,6 +7068,257 @@ class SQLExecutor {
6889
7068
  return out;
6890
7069
  }
6891
7070
 
7071
+ /**
7072
+ * 把 GROUP BY <位置序号> 解析成对应的 SELECT 输出表达式(#73)。
7073
+ *
7074
+ * SQLite / MySQL 都把 GROUP BY 列表里的裸整数当作 1-based 位置引用:
7075
+ * SELECT a, COUNT(*) FROM t GROUP BY 1 == GROUP BY a
7076
+ * 解析器会把数字变成 { type: 'value', value: 1 },而执行层此前把它当常量
7077
+ * 对每行求值,分组键恒为 1,所有行塌成一组。
7078
+ *
7079
+ * 位置超出输出列数时必须报错(MySQL: Unknown column '99' in 'group statement';
7080
+ * 这里给出更直白的 out of range 提示)。
7081
+ */
7082
+ _groupByPosition(statement, pos) {
7083
+ const cols = Array.isArray(statement.columns) ? statement.columns : [];
7084
+ if (!Number.isInteger(pos) || pos < 1 || pos > cols.length) {
7085
+ throw new Error(`GROUP BY column index ${pos} is out of range`);
7086
+ }
7087
+ const c = cols[pos - 1];
7088
+ if (!c) return { type: 'value', value: pos };
7089
+ // 位置指向聚合列:MySQL 报 "Can't group on 'COUNT(*)'",这里明确报错,
7090
+ // 不能退化成按别名取值(那样会静默塌成一组)。
7091
+ if (c.aggregate) {
7092
+ throw new Error(`GROUP BY column index ${pos} refers to an aggregate function`);
7093
+ }
7094
+ // 还原成投影表达式本身:裸列名保持字符串形态(下游别名/列名解析都认),
7095
+ // 表达式则直接复用其 AST。
7096
+ if (typeof c.expr === 'string' && c.expr !== '*') return c.expr;
7097
+ if (c.scalar) return c.scalar;
7098
+ if (c.caseExpr) return c.caseExpr;
7099
+ if (c.alias) return c.alias;
7100
+ return { type: 'value', value: pos };
7101
+ }
7102
+
7103
+ /**
7104
+ * ORDER BY <位置序号> 越界检查(#74)。
7105
+ *
7106
+ * 此前 `SELECT a FROM t ORDER BY 2` 会取到 statement.columns[1] === undefined,
7107
+ * 排序键恒为 null,静默返回插入序 —— 用户完全看不出语句是错的。
7108
+ * 合法位置序号的排序行为不受影响。
7109
+ */
7110
+ _assertOrderByPositions(statement) {
7111
+ if (!statement || !Array.isArray(statement.orderBy) || statement.orderBy.length === 0) return;
7112
+ const n = Array.isArray(statement.columns) ? statement.columns.length : 0;
7113
+ for (const o of statement.orderBy) {
7114
+ if (!o) continue;
7115
+ const c = o.column;
7116
+ const pos = (c && typeof c === 'object' && c.type === 'value' && typeof c.value === 'number')
7117
+ ? c.value
7118
+ : (typeof c === 'number' ? c : null);
7119
+ if (pos === null || pos === undefined) continue;
7120
+ if (!Number.isInteger(pos) || pos < 1 || pos > n) {
7121
+ throw new Error(`ORDER BY column index ${pos} is out of range`);
7122
+ }
7123
+ }
7124
+ }
7125
+
7126
+ /**
7127
+ * 收集 FROM 中各表/别名的日期列类型(#75)。
7128
+ * 返回 Map<小写列名(含 '表.列' 与裸列名), 'date'|'datetime'|null>;
7129
+ * 同名裸列类型冲突时置 null(不参与规范化,交给 #76 的歧义检查)。
7130
+ */
7131
+ _dateColumnTypes(statement) {
7132
+ const types = new Map();
7133
+ const add = (name, type) => {
7134
+ const n = String(name).toLowerCase();
7135
+ if (types.has(n) && types.get(n) !== type) { types.set(n, null); return; }
7136
+ types.set(n, type);
7137
+ };
7138
+ if (!statement || !statement.from || !this.engine
7139
+ || typeof this.engine.getTableSchema !== 'function') return types;
7140
+ const items = (statement.from.tables || []).concat((statement.from.joins || []).map(j => j.item));
7141
+ for (const it of items) {
7142
+ if (!it || !it.table) continue;
7143
+ let schema = null;
7144
+ try { schema = this.engine.getTableSchema(it.table); } catch (_) { continue; }
7145
+ if (!schema || typeof schema.then === 'function') continue;
7146
+ const prefixes = [String(it.table).toLowerCase()];
7147
+ if (it.alias) prefixes.push(String(it.alias).toLowerCase());
7148
+ for (const [col, def] of Object.entries(schema)) {
7149
+ const t = (def && typeof def === 'object' && def.type) ? String(def.type).toLowerCase() : '';
7150
+ if (t !== 'datetime' && t !== 'date') continue;
7151
+ for (const p of prefixes) add(p + '.' + col, t);
7152
+ add(col, t);
7153
+ }
7154
+ }
7155
+ return types;
7156
+ }
7157
+
7158
+ /**
7159
+ * WHERE 里 DATETIME / DATE 字面量规范化(#75)。
7160
+ *
7161
+ * INSERT 路径用 validateDateTime 把 '2024-01-15T10:30:00Z' 时区换算成
7162
+ * 本地 '2024-01-15 18:30:00' 落库,而 WHERE 比较路径此前直接拿原字符串
7163
+ * 跟落库值比,同一字面量永远匹配不上(返回 0 行)。
7164
+ *
7165
+ * 这里只处理「与日期类型列比较、且带 T 分隔符的字符串字面量」,
7166
+ * 'YYYY-MM-DD HH:MM:SS' 已是落库格式、纯字符串列比较均不受影响。
7167
+ * 改写落在 WHERE AST 上,相关子查询逐行重算时同样生效。
7168
+ */
7169
+ _normalizeDateLiterals(statement) {
7170
+ if (!statement || !statement.where) return;
7171
+ const types = this._dateColumnTypes(statement);
7172
+ if (!types.size) return;
7173
+ const typeOf = (node) => {
7174
+ if (!node || typeof node !== 'object' || node.type !== 'column' || typeof node.name !== 'string') return null;
7175
+ const n = node.name.toLowerCase();
7176
+ const t = types.has(n) ? types.get(n) : types.get(n.slice(n.lastIndexOf('.') + 1));
7177
+ return t || null;
7178
+ };
7179
+ const norm = (value, type) => {
7180
+ if (typeof value !== 'string') return value;
7181
+ const s = value.trim();
7182
+ // 仅 ISO-8601 的 T 分隔形式(含可选的 Z / ±HH:MM)需要换算
7183
+ if (!/^\d{4}-\d{2}-\d{2}T/.test(s)) return value;
7184
+ try {
7185
+ const v = validateDateType(s, type, '');
7186
+ return typeof v === 'string' ? v : value;
7187
+ } catch (_) {
7188
+ return value; // 非法字面量保持原样,让比较逻辑自己得出结果
7189
+ }
7190
+ };
7191
+ const isLit = (n) => n && typeof n === 'object' && (n.type === 'value' || n.type === 'literal');
7192
+ const fixLit = (litNode, type) => {
7193
+ if (!isLit(litNode) || typeof litNode.value !== 'string') return;
7194
+ litNode.value = norm(litNode.value, type);
7195
+ };
7196
+ const visit = (node) => {
7197
+ if (!node || typeof node !== 'object') return;
7198
+ if (Array.isArray(node)) { for (const n of node) visit(n); return; }
7199
+ // 子查询有自己的 FROM/作用域,交给它自己的 executeSelect 处理
7200
+ if (node.type === 'select' || node.type === 'subquery' || node.type === 'exists') return;
7201
+ if (node.type === 'compare') {
7202
+ const lt = typeOf(node.left);
7203
+ const rt = typeOf(node.right);
7204
+ if (lt) fixLit(node.right, lt);
7205
+ if (rt) fixLit(node.left, rt);
7206
+ } else if (node.type === 'between') {
7207
+ const t = typeOf(node.operand);
7208
+ if (t) { fixLit(node.low, t); fixLit(node.high, t); }
7209
+ } else if (node.type === 'in') {
7210
+ const t = typeOf(node.operand);
7211
+ if (t && Array.isArray(node.list)) {
7212
+ node.list = node.list.map((x) => {
7213
+ if (isLit(x)) return Object.assign({}, x, { value: norm(x.value, t) });
7214
+ if (typeof x === 'string') return norm(x, t);
7215
+ return x;
7216
+ });
7217
+ }
7218
+ }
7219
+ for (const k of Object.keys(node)) {
7220
+ if (k === 'type' || k === 'select' || k === 'subquery') continue;
7221
+ visit(node[k]);
7222
+ }
7223
+ };
7224
+ visit(statement.where);
7225
+ }
7226
+
7227
+ /**
7228
+ * 把 FROM 里每个可解析表/别名的列名归属收集起来(#76)。
7229
+ *
7230
+ * 两个来源,互斥使用,避免同一张表被算两次:
7231
+ * - 有样本行:用行里的 `表/别名.列` 前缀键(唯一能覆盖派生表、视图、
7232
+ * 自连接自动别名 t1/t2 的运行时来源);
7233
+ * - 无样本行(空表):回退到表 schema,用「表名#出现序号」区分自连接。
7234
+ *
7235
+ * 返回 Map<裸列名, Set(归属标识)>。
7236
+ */
7237
+ _columnOwners(statement, sample) {
7238
+ const owners = new Map();
7239
+ const add = (scope, col) => {
7240
+ const c = String(col).toLowerCase();
7241
+ if (!c || c.startsWith('_')) return; // _rid / _softDelete 等内部字段
7242
+ if (!owners.has(c)) owners.set(c, new Set());
7243
+ owners.get(c).add(scope);
7244
+ };
7245
+ if (!statement) return owners;
7246
+
7247
+ if (sample && typeof sample === 'object') {
7248
+ const scopes = new Set(this._outerAliases(statement));
7249
+ for (const k of Object.keys(sample)) {
7250
+ const dot = k.indexOf('.');
7251
+ if (dot <= 0) continue;
7252
+ const pre = k.slice(0, dot).toLowerCase();
7253
+ if (scopes.size > 0 && !scopes.has(pre) && !/^t\d+$/.test(pre)) continue;
7254
+ add(pre, k.slice(dot + 1));
7255
+ }
7256
+ return owners;
7257
+ }
7258
+
7259
+ if (!statement.from || !this.engine || typeof this.engine.getTableSchema !== 'function') return owners;
7260
+ const items = (statement.from.tables || []).concat((statement.from.joins || []).map(j => j.item));
7261
+ const seen = new Map();
7262
+ for (const it of items) {
7263
+ if (!it || !it.table) continue;
7264
+ let schema = null;
7265
+ try { schema = this.engine.getTableSchema(it.table); } catch (_) { continue; }
7266
+ if (!schema || typeof schema.then === 'function') continue;
7267
+ const base = String(it.alias || it.table).toLowerCase();
7268
+ const n = (seen.get(base) || 0) + 1;
7269
+ seen.set(base, n);
7270
+ const scope = base + '#' + n;
7271
+ for (const col of Object.keys(schema)) add(scope, col);
7272
+ }
7273
+ return owners;
7274
+ }
7275
+
7276
+ /**
7277
+ * JOIN 里同一个裸列名来自多张表时必须报歧义错误(#76)。
7278
+ *
7279
+ * 此前 `SELECT id FROM u JOIN o ON o.u_id = u.id` 静默返回 o.id
7280
+ * (拼接时右表的裸列键覆盖了左表),用户完全看不出列名是歧义的。
7281
+ * 已加表名前缀的引用(o.id / u.id)与单表查询不受影响。
7282
+ */
7283
+ _assertNoAmbiguousRefs(statement, sample) {
7284
+ if (!statement || !statement.from) return;
7285
+ const owners = this._columnOwners(statement, sample);
7286
+ if (owners.size === 0) return;
7287
+ let ambiguous = null;
7288
+ const check = (name) => {
7289
+ if (ambiguous) return;
7290
+ if (typeof name !== 'string') return;
7291
+ const n = name.toLowerCase();
7292
+ if (n.indexOf('.') >= 0) return; // 限定引用不可能歧义
7293
+ const set = owners.get(n);
7294
+ if (set && set.size > 1) ambiguous = name;
7295
+ };
7296
+ const walk = (node) => {
7297
+ if (ambiguous || !node || typeof node !== 'object') return;
7298
+ if (Array.isArray(node)) { for (const x of node) walk(x); return; }
7299
+ // 子查询/嵌套 SELECT 有自己的 FROM,交给它自己校验
7300
+ if (node.type === 'select' || node.type === 'subquery' || node.type === 'exists') return;
7301
+ if (node.type === 'column') check(node.name);
7302
+ if (node.type === 'aggregate' && typeof node.column === 'string') check(node.column);
7303
+ for (const k of Object.keys(node)) {
7304
+ if (k === 'type' || k === 'select' || k === 'subquery') continue;
7305
+ walk(node[k]);
7306
+ }
7307
+ };
7308
+ walk(statement.columns);
7309
+ walk(statement.where);
7310
+ walk(statement.having);
7311
+ walk(statement.orderBy);
7312
+ // ORDER BY / GROUP BY 的列在解析器里是裸字符串(非 {type:'column'}),walk 检不到
7313
+ for (const o of (Array.isArray(statement.orderBy) ? statement.orderBy : [])) {
7314
+ if (o && typeof o.column === 'string') check(o.column);
7315
+ }
7316
+ for (const g of (Array.isArray(statement.groupBy) ? statement.groupBy : [])) {
7317
+ if (typeof g === 'string') check(g);
7318
+ }
7319
+ if (ambiguous) throw new Error(`column reference '${ambiguous}' is ambiguous`);
7320
+ }
7321
+
6892
7322
  /**
6893
7323
  * 校验语句里引用的列是否真实存在。
6894
7324
  * 之前 `SELECT nosuchcol FROM t` 会静默返回 null 而不是报错 —— 调用方拿到的
@@ -6898,7 +7328,11 @@ class SQLExecutor {
6898
7328
  * 不深入子查询节点:它们有自己的 FROM,列属于另一个作用域。
6899
7329
  */
6900
7330
  _validateColumnRefs(statement, rows) {
6901
- if (!statement || !Array.isArray(rows) || rows.length === 0) return;
7331
+ if (!statement) return;
7332
+ // #76:歧义列名必须在任何过滤/空表的情况下都能报出来,
7333
+ // 所以放到「样本行是否存在」的早退之前。
7334
+ this._assertNoAmbiguousRefs(statement, Array.isArray(rows) && rows.length ? rows[0] : null);
7335
+ if (!Array.isArray(rows) || rows.length === 0) return;
6902
7336
  const sample = rows[0];
6903
7337
  if (!sample || typeof sample !== 'object') return;
6904
7338
  const known = new Set();
@@ -7596,6 +8030,10 @@ class SQLExecutor {
7596
8030
  async executeSelect(statement) {
7597
8031
  // 视图:FROM 里的视图名展开成子查询
7598
8032
  if (this.engine && this.engine._views) this._expandViews(statement);
8033
+ // #74:ORDER BY <位置序号> 越界必须报错(含 GROUP BY / 组合查询路径)
8034
+ this._assertOrderByPositions(statement);
8035
+ // #75:WHERE 里比较 DATETIME 列时,字面量按 INSERT 的规则规范化
8036
+ this._normalizeDateLiterals(statement);
7599
8037
 
7600
8038
  // 集合运算:左分支不应用尾部 ORDER BY/LIMIT/OFFSET(它们属于整个组合结果)
7601
8039
  const setOpBase = { orderBy: null, limit: null, offset: 0, fetch: undefined };
@@ -7829,6 +8267,16 @@ class SQLExecutor {
7829
8267
 
7830
8268
  // 分组聚合
7831
8269
  if (statement.groupBy) {
8270
+ // #73:GROUP BY <整数> 是 SELECT 列表的 1-based 位置引用(MySQL / SQLite 语义),
8271
+ // 此前数字被当成常量表达式对每一行求值,分组键恒为同一个值 → 全部行塌成一组。
8272
+ // 超出列表长度必须报错,不能静默当成常量。
8273
+ statement.groupBy = statement.groupBy.map((g) => {
8274
+ if (typeof g === 'number') return this._groupByPosition(statement, g);
8275
+ if (g && typeof g === 'object' && g.type === 'value' && typeof g.value === 'number') {
8276
+ return this._groupByPosition(statement, g.value);
8277
+ }
8278
+ return g;
8279
+ });
7832
8280
  // MySQL 支持 GROUP BY alias,而 alias 指向 SELECT 列表的输出列名。
7833
8281
  // 解析时 groupBy[] 存的是原始字符串(如 "b"),必须先在 SELECT 别名里查找:
7834
8282
  // - 找到 → 取输出行里的 alias 值(因为 alias 已求出值了)
@@ -8409,7 +8857,7 @@ function escapeValue(value) {
8409
8857
  if (typeof value === 'boolean') return value ? 'true' : 'false';
8410
8858
  if (value instanceof Date) {
8411
8859
  const p = n => String(n).padStart(2, '0');
8412
- return `'${value.getFullYear()}-${p(value.getMonth() + 1)}-${p(value.getDate())} ${p(value.getHours())}:${p(value.getMinutes())}:${p(value.getSeconds())}'`;
8860
+ return `'${value.getUTCFullYear()}-${p(value.getUTCMonth() + 1)}-${p(value.getUTCDate())} ${p(value.getUTCHours())}:${p(value.getUTCMinutes())}:${p(value.getUTCSeconds())}'`;
8413
8861
  }
8414
8862
  if (Buffer.isBuffer(value)) return "X'" + value.toString('hex') + "'";
8415
8863
  if (Array.isArray(value)) {
@@ -8803,6 +9251,7 @@ module.exports = {
8803
9251
  splitStatements, applyParams, escapeValue, escapeId,
8804
9252
  AST,
8805
9253
  walk: AST.walk,
9254
+ compileCheckExpr,
8806
9255
  transform: AST.transform,
8807
9256
  visit: AST.StatementVisitor
8808
9257
  };