jsql-neo 6.8.27 → 6.10.2

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.
Files changed (139) hide show
  1. package/README.md +9 -4
  2. package/bin/jsql-server-control.js +58 -14
  3. package/index.d.ts +3 -0
  4. package/index.js +1 -1
  5. package/lib/bigint_json.js +13 -1
  6. package/lib/btree.js +12 -3
  7. package/lib/cache.js +12 -1
  8. package/lib/database.js +272 -36
  9. package/lib/jsql_format.js +22 -9
  10. package/lib/migrate.js +184 -98
  11. package/lib/mod.js +48 -13
  12. package/lib/mongo_server.js +652 -246
  13. package/lib/mysql_compat.js +54 -11
  14. package/lib/mysql_server.js +248 -65
  15. package/lib/nedb_compat.js +7 -1
  16. package/lib/objectid.js +14 -6
  17. package/lib/pg_server.js +385 -9
  18. package/lib/plugin.js +34 -3
  19. package/lib/query.js +12 -6
  20. package/lib/redis_server.js +102 -42
  21. package/lib/sql.js +446 -48
  22. package/lib/table.js +111 -41
  23. package/lib/tui.js +28 -9
  24. package/lib/web_ui.js +33 -2
  25. package/package.json +4 -4
  26. package/test/alter-table.test.js +11 -5
  27. package/test/compat-v1.test.js +1 -1
  28. package/test/extra-coverage.test.js +6 -7
  29. package/test/issue-258-300.test.js +6 -0
  30. package/test/issue-312-320.test.js +11 -4
  31. package/test/issue-326.test.js +42 -0
  32. package/test/issue-327-418.test.js +1 -1
  33. package/test/issue-336.test.js +56 -0
  34. package/test/issue-353.test.js +34 -0
  35. package/test/issue-356.test.js +27 -0
  36. package/test/issue-357-365.test.js +1 -1
  37. package/test/issue-361.test.js +55 -0
  38. package/test/issue-370.test.js +43 -0
  39. package/test/issue-373.test.js +40 -0
  40. package/test/issue-374.test.js +62 -0
  41. package/test/issue-378.test.js +39 -0
  42. package/test/issue-379.test.js +39 -0
  43. package/test/issue-38.test.js +2 -2
  44. package/test/issue-380.test.js +27 -0
  45. package/test/issue-383-402.test.js +4 -3
  46. package/test/issue-384.test.js +41 -0
  47. package/test/issue-392.test.js +25 -0
  48. package/test/issue-397.test.js +44 -0
  49. package/test/issue-403.test.js +47 -0
  50. package/test/issue-404.test.js +58 -0
  51. package/test/issue-407.test.js +40 -0
  52. package/test/issue-408.test.js +92 -0
  53. package/test/issue-409.test.js +32 -0
  54. package/test/issue-410.test.js +36 -0
  55. package/test/issue-411.test.js +38 -0
  56. package/test/issue-412.test.js +50 -0
  57. package/test/issue-414.test.js +46 -0
  58. package/test/issue-417.test.js +56 -0
  59. package/test/issue-420.test.js +87 -0
  60. package/test/issue-421.test.js +30 -0
  61. package/test/issue-422.test.js +33 -0
  62. package/test/issue-424.test.js +44 -0
  63. package/test/issue-425.test.js +22 -0
  64. package/test/issue-426.test.js +22 -0
  65. package/test/issue-427.test.js +36 -0
  66. package/test/issue-429.test.js +38 -0
  67. package/test/issue-431.test.js +41 -0
  68. package/test/issue-432.test.js +37 -0
  69. package/test/issue-436.test.js +47 -0
  70. package/test/issue-445-449.test.js +14 -7
  71. package/test/issue-455-459.test.js +6 -3
  72. package/test/issue-474.test.js +59 -0
  73. package/test/issue-475.test.js +38 -0
  74. package/test/issue-476.test.js +50 -0
  75. package/test/issue-477.test.js +54 -0
  76. package/test/issue-478.test.js +52 -0
  77. package/test/issue-479.test.js +44 -0
  78. package/test/issue-480.test.js +42 -0
  79. package/test/issue-481.test.js +51 -0
  80. package/test/issue-482.test.js +36 -0
  81. package/test/issue-483.test.js +57 -0
  82. package/test/issue-485.test.js +47 -0
  83. package/test/issue-486.test.js +69 -0
  84. package/test/issue-487.test.js +54 -0
  85. package/test/issue-488.test.js +69 -0
  86. package/test/issue-490.test.js +20 -0
  87. package/test/issue-491.test.js +21 -0
  88. package/test/issue-492.test.js +19 -0
  89. package/test/issue-493.test.js +30 -0
  90. package/test/issue-494.test.js +82 -0
  91. package/test/issue-495.test.js +86 -0
  92. package/test/issue-496.test.js +98 -0
  93. package/test/issue-497.test.js +29 -0
  94. package/test/issue-498.test.js +32 -0
  95. package/test/issue-499.test.js +41 -0
  96. package/test/issue-500.test.js +39 -0
  97. package/test/issue-501-506.test.js +29 -0
  98. package/test/issue-502.test.js +18 -0
  99. package/test/issue-503.test.js +43 -0
  100. package/test/issue-504.test.js +83 -0
  101. package/test/issue-505.test.js +29 -0
  102. package/test/issue-529.test.js +39 -0
  103. package/test/issue-530.test.js +69 -0
  104. package/test/issue-536.test.js +46 -0
  105. package/test/issue-537.test.js +52 -0
  106. package/test/issue-539.test.js +65 -0
  107. package/test/issue-540.test.js +31 -0
  108. package/test/issue-545.test.js +38 -0
  109. package/test/issue-546.test.js +68 -0
  110. package/test/issue-547.test.js +27 -0
  111. package/test/issue-548.test.js +68 -0
  112. package/test/issue-549.test.js +26 -0
  113. package/test/issue-550.test.js +52 -0
  114. package/test/issue-551.test.js +34 -0
  115. package/test/issue-552.test.js +30 -0
  116. package/test/issue-553.test.js +29 -0
  117. package/test/issue-554.test.js +29 -0
  118. package/test/issue-555.test.js +22 -0
  119. package/test/issue-556.test.js +25 -0
  120. package/test/issue-565.test.js +32 -0
  121. package/test/issue-566.test.js +30 -0
  122. package/test/issue-567.test.js +56 -0
  123. package/test/issue-568.test.js +46 -0
  124. package/test/issue-569.test.js +25 -0
  125. package/test/issue-570.test.js +30 -0
  126. package/test/issue-571.test.js +32 -0
  127. package/test/issue-572.test.js +64 -0
  128. package/test/issue-573.test.js +71 -0
  129. package/test/issue-574.test.js +63 -0
  130. package/test/issue-581.test.js +46 -0
  131. package/test/issue-59.test.js +17 -4
  132. package/test/issue-69-70.test.js +1 -1
  133. package/test/issue-mysql-harness.js +260 -0
  134. package/test/issue-pg5-helper.js +135 -0
  135. package/test/mongo-arrays.test.js +63 -0
  136. package/test/mongo-objectid.test.js +2 -2
  137. package/test/mongo-persistence.test.js +3 -3
  138. package/test/mongo-update-dates.test.js +128 -0
  139. package/test/wal-recovery.test.js +17 -9
package/lib/sql.js CHANGED
@@ -5,6 +5,13 @@ const { validateDateType } = require('./date-types');
5
5
  // #78:UNION/INTERSECT/EXCEPT 去重键对 BigInt 安全(JSON.stringify 遇到 BigInt 抛错)
6
6
  const bigintJson = require('./bigint_json');
7
7
 
8
+ // #577/#578:CTE / 视图的列名清单数量必须和 SELECT 列数一致(MySQL ER_VIEW_WRONG_LIST 1353)
9
+ function wrongColumnListError() {
10
+ const e = new Error('SELECT list and column names list have different column counts');
11
+ e.code = 1353;
12
+ return e;
13
+ }
14
+
8
15
  const DANGEROUS_SQL = [
9
16
  { re: /^INTO$/, next: /^(OUTFILE|DUMPFILE)$/, name: 'INTO OUTFILE/DUMPFILE' },
10
17
  { re: /^LOAD$/, next: /^(FILE|DATA)$/, name: 'LOAD_FILE/LOAD DATA' },
@@ -1822,10 +1829,16 @@ class Parser {
1822
1829
  return ORDER_END.some(w => this.isWord(w));
1823
1830
  };
1824
1831
  try {
1825
- col = this.parseColumnRef();
1826
- if (!endsClause(this.peek())) {
1827
- this.pos = save;
1832
+ // #473:CASE 是关键字,parseColumnRef/catch 里的裸关键字回退会把它
1833
+ // 当成列名吃掉,留下 WHEN 触发 "Unexpected token"。直接走标量表达式解析。
1834
+ if (this.isWord('CASE')) {
1828
1835
  col = this.parseScalar();
1836
+ } else {
1837
+ col = this.parseColumnRef();
1838
+ if (!endsClause(this.peek())) {
1839
+ this.pos = save;
1840
+ col = this.parseScalar();
1841
+ }
1829
1842
  }
1830
1843
  } catch (e) {
1831
1844
  this.pos = save;
@@ -1929,6 +1942,34 @@ class Parser {
1929
1942
  statement.union = union;
1930
1943
  statement.intersect = intersect;
1931
1944
  statement.except = except;
1945
+ // #544:混合运算符链(A UNION B EXCEPT C)在右操作数自己的 parseSelect 里
1946
+ // 被吃成 A UNION (B EXCEPT C)。旋转成左结合的运算链,按声明顺序逐个求值。
1947
+ const first = union || intersect || except;
1948
+ if (first) {
1949
+ // #544:先探测链上的运算符种类。只有出现不同运算符(如 UNION … EXCEPT …)
1950
+ // 才旋转成左结合链;纯 UNION 链必须保留嵌套 union 结构——递归 CTE 的
1951
+ // _evalRecursiveCte 依赖 sel.union 链拆分锚点/递归分支。
1952
+ const ops = new Set();
1953
+ ops.add(union ? 'UNION' : intersect ? 'INTERSECT' : 'EXCEPT');
1954
+ for (let p = first.select; p && (p.union || p.intersect || p.except);) {
1955
+ ops.add(p.union ? 'UNION' : p.intersect ? 'INTERSECT' : 'EXCEPT');
1956
+ p = (p.union || p.intersect || p.except).select;
1957
+ }
1958
+ if (ops.size > 1) {
1959
+ const chain = [{ op: union ? 'UNION' : intersect ? 'INTERSECT' : 'EXCEPT', all: first.all, select: first.select }];
1960
+ let rhs = first.select;
1961
+ while (rhs && (rhs.union || rhs.intersect || rhs.except)) {
1962
+ const op = rhs.union ? 'UNION' : rhs.intersect ? 'INTERSECT' : 'EXCEPT';
1963
+ const next = rhs.union || rhs.intersect || rhs.except;
1964
+ chain.push({ op, all: next.all, select: next.select });
1965
+ if (rhs.orderBy) { statement.orderBy = rhs.orderBy; rhs.orderBy = null; }
1966
+ if (rhs.limit !== null && rhs.limit !== undefined) { statement.limit = rhs.limit; rhs.limit = null; }
1967
+ rhs.union = rhs.intersect = rhs.except = null;
1968
+ rhs = next.select;
1969
+ }
1970
+ if (chain.length > 1) statement.setChain = chain;
1971
+ }
1972
+ }
1932
1973
  // 括号化操作数(#60)内部的 ORDER BY/LIMIT/OFFSET 属于它自己,不能提升;
1933
1974
  // 普通无括号的最右侧 SELECT 上挂的尾部子句才属于整个组合查询(#57)。
1934
1975
  if (!rhsParenthesized) {
@@ -2776,6 +2817,21 @@ class Parser {
2776
2817
  return { type: 'binary', operand };
2777
2818
  }
2778
2819
  }
2820
+ // #435:INTERVAL(N,N1,N2,...) 是比较函数;只有 INTERVAL n UNIT 才是区间字面量。
2821
+ // 紧跟 '(' 时按普通函数解析,避免把 N 当区间值、把 N1 当时间单位。
2822
+ if (this.isWord('INTERVAL') && this.peek(1).type === 'op' && this.peek(1).value === '(') {
2823
+ this.next(); this.next();
2824
+ const args = [];
2825
+ if (!(this.peek().type === 'op' && this.peek().value === ')')) {
2826
+ for (;;) {
2827
+ args.push(this.parseArgExpr());
2828
+ if (this.peek().type === 'op' && this.peek().value === ',') { this.next(); continue; }
2829
+ break;
2830
+ }
2831
+ }
2832
+ this.expect('op', ')');
2833
+ return { type: 'func', name: 'INTERVAL', args };
2834
+ }
2779
2835
  // MySQL 区间字面量:INTERVAL n UNIT(date + INTERVAL 3 DAY / date - INTERVAL 1 MONTH)
2780
2836
  if (this.isWord('INTERVAL')) {
2781
2837
  this.next();
@@ -3523,6 +3579,7 @@ function applyCast(value, dataType) {
3523
3579
  // · 整数部分用 BigInt 精确构造(小数按四舍五入半远离零处理);
3524
3580
  // · 溢出按 64 位边界钳制(SIGNED → [-2^63, 2^63-1],
3525
3581
  // UNSIGNED → [0, 2^64-1]),与 MySQL 一致。
3582
+ // 字符串转整数走统一的前导数字解析(小数四舍五入半远离零,如 '3.9' → 4)
3526
3583
  const parsed = parseSqlNumericPrefix(value);
3527
3584
  n = parsed === null ? 0 : parsed;
3528
3585
  }
@@ -3556,7 +3613,17 @@ function applyCast(value, dataType) {
3556
3613
  // 此前 DECIMAL 被并入 FLOAT 分支,p/s 被剥掉后原值返回(123.456 → 123.456)。
3557
3614
  const m = String(dataType).match(/\((\d+)(?:,(\d+))?\)/i);
3558
3615
  const scale = m && m[2] !== undefined ? parseInt(m[2], 10) : 0;
3559
- let n = Number(value);
3616
+ // #433:字符串转 DECIMAL 走与 SIGNED 一致的前导数字解析('abc'→0,'12a'→12),
3617
+ // 不能因为 Number('12a') 是 NaN 就返回 NULL。
3618
+ let n;
3619
+ if (typeof value === 'string') {
3620
+ // 纯数字(含小数/科学计数法)直接用 Number,保留小数位供标度四舍五入;
3621
+ // 带非数字后缀('12abc')才走前导数字解析。
3622
+ const t = value.trim();
3623
+ n = /^[+-]?(?:\d+\.?\d*|\.\d+)(?:[eE][+-]?\d+)?$/.test(t)
3624
+ ? Number(t)
3625
+ : Number(parseSqlNumericPrefix(value) ?? 0);
3626
+ } else n = Number(value);
3560
3627
  if (!Number.isFinite(n)) return null;
3561
3628
  // #325:MySQL 的 DECIMAL 舍入是「半远离零」,Math.round 对负半值朝 +∞
3562
3629
  const roundHalfAway = (x) => (x < 0 ? -Math.round(-x) : Math.round(x));
@@ -3574,6 +3641,22 @@ function applyCast(value, dataType) {
3574
3641
  const s = String(value).toLowerCase();
3575
3642
  return s === 'true' || s === '1' || s === 't' || s === 'yes';
3576
3643
  }
3644
+ if (t === 'DATE' || t === 'DATETIME' || t === 'TIMESTAMP') {
3645
+ // #517:CAST/CONVERT 到日期类型必须做严格日历校验,非法日期返回 NULL,
3646
+ // 不能像 DATE() 那样让 JS Date 把 2 月 30 日悄悄规整到 3 月 1 日。
3647
+ const d = parseSqlDate(value);
3648
+ if (!d) return null;
3649
+ if (typeof value === 'string') {
3650
+ const m = String(value).trim().match(/^(\d{4})-(\d{1,2})-(\d{1,2})(?:[T ]\d{1,2}:\d{2}(?::\d{2})?)?/);
3651
+ if (!m) return null;
3652
+ if (d.getUTCFullYear() !== +m[1] || d.getUTCMonth() + 1 !== +m[2] || d.getUTCDate() !== +m[3]) return null;
3653
+ }
3654
+ return fmtSqlDate(t === 'DATE', d);
3655
+ }
3656
+ if (t === 'TIME') {
3657
+ const d = parseSqlTimeOnly(value);
3658
+ return d ? pad2(d.getUTCHours()) + ':' + pad2(d.getUTCMinutes()) + ':' + pad2(d.getUTCSeconds()) : null;
3659
+ }
3577
3660
  if (t === 'TEXT' || t === 'VARCHAR' || t === 'CHAR' || t === 'STRING') return String(value);
3578
3661
  return value;
3579
3662
  }
@@ -3934,7 +4017,8 @@ function sqlGroupKeyNormalize(v) {
3934
4017
  if (typeof v === 'string') {
3935
4018
  const n = sqlNumericCoerce(v);
3936
4019
  if (n !== undefined) return n;
3937
- return v;
4020
+ // #532:默认排序规则大小写不敏感,分组键与 WHERE 等值口径保持一致
4021
+ return v.toLowerCase();
3938
4022
  }
3939
4023
  return v;
3940
4024
  }
@@ -4293,6 +4377,18 @@ function parseSqlDate(v) {
4293
4377
  return ms === null ? null : new Date(ms);
4294
4378
  }
4295
4379
 
4380
+ /** #562:解析纯 TIME 串 'HH:MM[:SS][.frac]';按 1970-01-01 的 UTC 时间承载,
4381
+ * 仅供 HOUR/MINUTE/SECOND/TIME_TO_SEC 等时间部件函数使用,不参与日期解析。 */
4382
+ function parseSqlTimeOnly(v) {
4383
+ if (v === null || v === undefined || v instanceof Date) return null;
4384
+ const m = String(v).trim().match(/^(\d{1,2}):(\d{2})(?::(\d{2}))?(?:\.(\d+))?$/);
4385
+ if (!m) return null;
4386
+ const h = +m[1], mi = +m[2], sec = m[3] === undefined ? 0 : +m[3];
4387
+ if (h > 23 || mi > 59 || sec > 59) return null;
4388
+ const ms = m[4] === undefined ? 0 : Math.floor(+('0.' + m[4]) * 1000);
4389
+ return new Date(Date.UTC(1970, 0, 1, h, mi, sec, ms));
4390
+ }
4391
+
4296
4392
  /** 'YYYY-MM-DD[ HH:MM[:SS]]' 无时区 → UTC 墙上时间的毫秒;带时区标记则按标记换算。
4297
4393
  * 非法返回 null。与 date-types 的解析保持一致,避免两套口径。 */
4298
4394
  /** 'Z' / '±HH:MM' / '±HHMM' → 相对 UTC 的分钟偏移;无标记或非法返回 null */
@@ -4354,12 +4450,28 @@ const TIME_UNITS = new Set([
4354
4450
  ]);
4355
4451
 
4356
4452
  /** MySQL DATE_FORMAT 的 % 说明符(全部取 UTC 部件,与落库值一致) */
4357
- function strftime(d, fmt) {
4453
+ function strftime(d, fmt, source) {
4358
4454
  const h12 = ((d.getUTCHours() % 12) || 12);
4455
+ const day = d.getUTCDate();
4456
+ // #564:补齐 MySQL DATE_FORMAT 标准说明符;未知说明符不再原样残留。
4457
+ const ordinal = (day % 100 >= 11 && day % 100 <= 13) ? 'th'
4458
+ : ({ 1: 'st', 2: 'nd', 3: 'rd' })[day % 10] || 'th';
4459
+ // Date 只有毫秒精度;原始字符串带更多分数位时从字符串取足 6 位微秒。
4460
+ let micros = String(d.getUTCMilliseconds()).padStart(3, '0') + '000';
4461
+ if (typeof source === 'string') {
4462
+ const fm = source.match(/\.(\d+)/);
4463
+ if (fm) micros = (fm[1] + '000000').slice(0, 6);
4464
+ }
4465
+ const isoWeek = pgDatePart('week', d);
4466
+ const sundayYear = new Date(d.getTime());
4467
+ sundayYear.setUTCDate(sundayYear.getUTCDate() - mysqlWeekMode0(d));
4468
+ const thu = new Date(Date.UTC(d.getUTCFullYear(), d.getUTCMonth(), day));
4469
+ thu.setUTCDate(thu.getUTCDate() - ((thu.getUTCDay() + 6) % 7) + 3);
4470
+ const hms = pad2(d.getUTCHours()) + ':' + pad2(d.getUTCMinutes()) + ':' + pad2(d.getUTCSeconds());
4359
4471
  const map = {
4360
4472
  '%Y': String(d.getUTCFullYear()), '%y': pad2(d.getUTCFullYear() % 100),
4361
4473
  '%m': pad2(d.getUTCMonth() + 1), '%c': String(d.getUTCMonth() + 1),
4362
- '%d': pad2(d.getUTCDate()), '%e': String(d.getUTCDate()),
4474
+ '%d': pad2(day), '%e': String(day),
4363
4475
  '%H': pad2(d.getUTCHours()), '%k': String(d.getUTCHours()),
4364
4476
  '%h': pad2(h12), '%I': pad2(h12), '%l': String(h12),
4365
4477
  '%i': pad2(d.getUTCMinutes()), '%S': pad2(d.getUTCSeconds()), '%s': pad2(d.getUTCSeconds()),
@@ -4368,6 +4480,12 @@ function strftime(d, fmt) {
4368
4480
  '%W': DAY_NAMES[d.getUTCDay()], '%a': DAY_NAMES[d.getUTCDay()].slice(0, 3),
4369
4481
  '%w': String(d.getUTCDay()),
4370
4482
  '%j': String(Math.round((d - Date.UTC(d.getUTCFullYear(), 0, 0)) / 86400000)).padStart(3, '0'),
4483
+ '%f': micros, '%T': hms,
4484
+ '%r': pad2(h12) + ':' + pad2(d.getUTCMinutes()) + ':' + pad2(d.getUTCSeconds()) + ' ' + (d.getUTCHours() < 12 ? 'AM' : 'PM'),
4485
+ '%D': String(day) + ordinal,
4486
+ '%U': String(mysqlWeekMode0(d)), '%u': String(isoWeek),
4487
+ '%V': String(isoWeek), '%v': String(isoWeek),
4488
+ '%X': String(sundayYear.getUTCFullYear()), '%x': String(thu.getUTCFullYear()),
4371
4489
  '%%': '%',
4372
4490
  };
4373
4491
  return String(fmt).replace(/%[A-Za-z%]/g, (m) => (m in map ? map[m] : m));
@@ -4430,7 +4548,9 @@ function strToDate(s, fmt) {
4430
4548
  case 'm': case 'c': month = num - 1; if (!inRange(num, 1, 12)) invalid = true; break;
4431
4549
  case 'M': case 'b': {
4432
4550
  const mi = MONTH_NAMES.findIndex((x) => x.toLowerCase().startsWith(String(v).toLowerCase().slice(0, 3)));
4433
- if (mi >= 0) month = mi;
4551
+ // #559:未知月份名必须判非法,不能静默落到默认的 1 月
4552
+ if (mi < 0) invalid = true;
4553
+ else month = mi;
4434
4554
  break;
4435
4555
  }
4436
4556
  case 'd': case 'e': day = num; if (!inRange(num, 1, 31)) invalid = true; break;
@@ -4756,7 +4876,10 @@ function applyScalarFunction(fnNode, row, ctx) {
4756
4876
  case 'SECOND': case 'SECONDS': d.setUTCSeconds(d.getUTCSeconds() + n); break;
4757
4877
  default: return null;
4758
4878
  }
4759
- return fmtSqlDate(isDateOnly, d);
4879
+ // #558:日期-only 输入加 HOUR/MINUTE/SECOND 后结果应是 DATETIME,
4880
+ // 不能再按输入长度的格式剥掉新增的时间部分。
4881
+ const timeUnit = /^(HOURS?|MINUTES?|SECONDS?|MICROSECONDS?)$/.test(String(iv.unit || '').toUpperCase());
4882
+ return fmtSqlDate(isDateOnly && !timeUnit, d);
4760
4883
  }
4761
4884
  // ===== 日期/时间(补齐 README 契约:此前这些全部缺失,静默返回 null)=====
4762
4885
  case 'YEAR': {
@@ -4772,15 +4895,16 @@ function applyScalarFunction(fnNode, row, ctx) {
4772
4895
  return d ? d.getUTCDate() : null;
4773
4896
  }
4774
4897
  case 'HOUR': {
4775
- const d = parseSqlDate(args[0]);
4898
+ // #562:参数也可以是 TIME('10:20:30'),不能只走日期解析
4899
+ const d = parseSqlDate(args[0]) || parseSqlTimeOnly(args[0]);
4776
4900
  return d ? d.getUTCHours() : null;
4777
4901
  }
4778
4902
  case 'MINUTE': {
4779
- const d = parseSqlDate(args[0]);
4903
+ const d = parseSqlDate(args[0]) || parseSqlTimeOnly(args[0]);
4780
4904
  return d ? d.getUTCMinutes() : null;
4781
4905
  }
4782
4906
  case 'SECOND': {
4783
- const d = parseSqlDate(args[0]);
4907
+ const d = parseSqlDate(args[0]) || parseSqlTimeOnly(args[0]);
4784
4908
  return d ? d.getUTCSeconds() : null;
4785
4909
  }
4786
4910
  case 'QUARTER': {
@@ -4850,7 +4974,14 @@ function applyScalarFunction(fnNode, row, ctx) {
4850
4974
  // TIMESTAMPDIFF(MONTH,'2026-01-15','2026-03-14') = 1(差 1 个月零 29 天,不足 2 个月)
4851
4975
  // TIMESTAMPDIFF(MONTH,'2026-01-31','2026-03-01') = 1(1/31+1月=2/28,2/28+1月=3/28,够不到 3/1)
4852
4976
  let months = (a.getUTCFullYear() - b.getUTCFullYear()) * 12 + (a.getUTCMonth() - b.getUTCMonth());
4853
- if (a.getUTCDate() < b.getUTCDate()) months--;
4977
+ // #557:借位要按时间先后做,保证差值为负时也只退一档(反对称)。
4978
+ // 先以较早者为起点算出正向整月数,再按 a<b 补上符号。
4979
+ const negative = months < 0 || (months === 0 && (a.getTime() < b.getTime()));
4980
+ const early = negative ? a : b;
4981
+ const late = negative ? b : a;
4982
+ let mag = (late.getUTCFullYear() - early.getUTCFullYear()) * 12 + (late.getUTCMonth() - early.getUTCMonth());
4983
+ if (late.getUTCDate() < early.getUTCDate()) mag--;
4984
+ months = negative ? -mag : mag;
4854
4985
  // MySQL 对负差值按「向零截断」取整;Math.floor 会向 -∞ 多减 1。
4855
4986
  switch (unit) {
4856
4987
  case 'MICROSECOND': return Math.trunc(ms * 1000);
@@ -4860,14 +4991,17 @@ function applyScalarFunction(fnNode, row, ctx) {
4860
4991
  case 'DAY': return Math.trunc(ms / 86400000);
4861
4992
  case 'WEEK': return Math.trunc(ms / (86400000 * 7));
4862
4993
  case 'MONTH': return months;
4863
- case 'QUARTER': return Math.trunc(months / 3);
4994
+ // #557:QUARTER 按日历季度序号差(年差 + 季度差)计,保证反向恰好多退一档被修正
4995
+ case 'QUARTER': return (a.getUTCFullYear() - b.getUTCFullYear()) +
4996
+ (Math.floor(a.getUTCMonth() / 3) - Math.floor(b.getUTCMonth() / 3));
4864
4997
  case 'YEAR': return Math.trunc(months / 12);
4865
4998
  default: return null;
4866
4999
  }
4867
5000
  }
4868
5001
  case 'DATE_FORMAT': {
4869
5002
  const d = parseSqlDate(args[0]);
4870
- return d ? strftime(d, String(args[1] || '%Y-%m-%d')) : null;
5003
+ // #564:把原始日期串传给 strftime,%f 才能取到 6 位微秒
5004
+ return d ? strftime(d, String(args[1] || '%Y-%m-%d'), args[0]) : null;
4871
5005
  }
4872
5006
  case 'STR_TO_DATE': {
4873
5007
  const d = strToDate(String(args[0] == null ? '' : args[0]), String(args[1] || ''));
@@ -5260,7 +5394,15 @@ function applyScalarFunction(fnNode, row, ctx) {
5260
5394
  }
5261
5395
  case 'FLOOR': return args[0] == null ? null : Math.floor(args[0]);
5262
5396
  case 'CEIL': case 'CEILING': return args[0] == null ? null : Math.ceil(args[0]);
5263
- case 'MOD': return (args[0] == null || args[1] === 0) ? null : args[0] % args[1];
5397
+ case 'MOD': {
5398
+ // #514:除数以字符串给出时先按数值上下文转换;'0'/'abc'→0 除零返回 NULL,
5399
+ // 且结果必须有限,不能把 JS NaN 泄漏进 SUM / 比较运算。
5400
+ if (args[0] == null || args[1] == null) return null;
5401
+ const d = Number(args[1]);
5402
+ if (!Number.isFinite(d) || d === 0) return null;
5403
+ const r = Number(args[0]) % d;
5404
+ return Number.isFinite(r) ? r : null;
5405
+ }
5264
5406
  case 'POWER': case 'POW': return (args[0] == null || args[1] == null) ? null : finiteOrNull(Math.pow(args[0], args[1]));
5265
5407
  case 'SQRT': return args[0] == null ? null : finiteOrNull(Math.sqrt(args[0]));
5266
5408
  // #117:这些函数在 MATH_SCALAR_FNS 里声明了,却没有 case 分支,落到
@@ -5476,7 +5618,8 @@ function applyScalarFunction(fnNode, row, ctx) {
5476
5618
  if (args[0] instanceof Date) ms = args[0].getTime();
5477
5619
  else if (typeof args[0] === 'number') ms = args[0] * 1000;
5478
5620
  else ms = parseUtcWallClock(String(args[0]));
5479
- if (ms === null || !Number.isFinite(ms)) return 0;
5621
+ // #561:非法/越界日期按 MySQL 返回 NULL,不能伪装成 1970-01-01 的时间戳 0
5622
+ if (ms === null || !Number.isFinite(ms)) return null;
5480
5623
  return Math.floor(ms / 1000);
5481
5624
  }
5482
5625
  return Math.floor(Date.now() / 1000);
@@ -5493,6 +5636,14 @@ function applyScalarFunction(fnNode, row, ctx) {
5493
5636
  if (!args.length || args.some(a => a == null)) return null;
5494
5637
  return args.reduce((m, a) => (a < m ? a : m));
5495
5638
  }
5639
+ case 'INTERVAL': {
5640
+ // #435:INTERVAL(N,N1,N2,...) 返回第一个 > N 的参数下标(N 小于全部时 0)
5641
+ if (!args.length || args.some(a => a == null)) return null;
5642
+ const n = Number(args[0]);
5643
+ let i = 1;
5644
+ while (i < args.length && n >= Number(args[i])) i++;
5645
+ return i - 1;
5646
+ }
5496
5647
  case 'UUID': return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, c => {
5497
5648
  const r = Math.random() * 16 | 0; const v = c === 'x' ? r : (r & 0x3 | 0x8);
5498
5649
  return v.toString(16);
@@ -5522,8 +5673,9 @@ function applyScalarFunction(fnNode, row, ctx) {
5522
5673
  return obj;
5523
5674
  }
5524
5675
  case 'JSON_ARRAY': {
5525
- // JSON_ARRAY(v1, v2, ...) → [v1, v2]
5526
- return args.map(v => v === undefined ? null : v);
5676
+ // #438:MySQL 返回 JSON 文本(文本协议下是字符串),不能泄漏 JS 数组对象
5677
+ const values = args.map(v => v === undefined ? null : v);
5678
+ return JSON.stringify(values);
5527
5679
  }
5528
5680
  case 'JSON_EXTRACT': {
5529
5681
  // JSON_EXTRACT(json, '$.key' or '$.a.b') → 值
@@ -5864,7 +6016,8 @@ function applyScalarFunction(fnNode, row, ctx) {
5864
6016
  case 'JSON_VALID': {
5865
6017
  // JSON_VALID(json) → 1 if valid JSON, 0 otherwise
5866
6018
  const val = args[0];
5867
- if (val == null) return 0;
6019
+ // #563:MySQL 的 JSON_VALID(NULL) 返回 NULL(未知值),不是 0(非法 JSON)
6020
+ if (val == null) return null;
5868
6021
  if (typeof val !== 'string') return 1; // 非字符串视为有效
5869
6022
  try { JSON.parse(val); return 1; } catch (e) { return 0; }
5870
6023
  }
@@ -5971,7 +6124,9 @@ function likeMatch(value, pattern, ci = true, escape = '\\') {
5971
6124
  else if (ch === '_') out += '.';
5972
6125
  else out += reEsc(ch);
5973
6126
  }
5974
- return new RegExp('^' + out + '$', ci ? 'i' : '').test(sv);
6127
+ // #560:u 标志让 `_` 编译出的 `.` 匹配一个 Unicode 字符(code point),
6128
+ // 而不是一个 UTF-16 code unit;否则 emoji 等代理对占两个单元会漏匹配。
6129
+ return new RegExp('^' + out + '$', (ci ? 'i' : '') + 'u').test(sv);
5975
6130
  }
5976
6131
 
5977
6132
  /** 解析 PG 的路径字面量:'{a,b}' 或数组 → ['a','b'] */
@@ -6186,7 +6341,13 @@ function sqlTruthy(v) {
6186
6341
  if (typeof v === 'number') return v !== 0;
6187
6342
  // Issue #108:二进制值按文本判定真值
6188
6343
  if (isBinaryValue(v)) return sqlTruthy(v.toString());
6189
- if (typeof v === 'string') return v !== '' && !(Number(v) === 0 && String(v).trim() !== '');
6344
+ if (typeof v === 'string') {
6345
+ // #516:MySQL 的逻辑运算先数值化操作数,非数字开头的字符串数值为 0(假)。
6346
+ // 沿用引擎的数值前缀解析:'5abc'→5 真,'abc'→0 假。
6347
+ const parsed = parseSqlNumericPrefix(v);
6348
+ const n = typeof parsed === 'bigint' ? Number(parsed) : parsed;
6349
+ return Number.isFinite(n) ? n !== 0 : false;
6350
+ }
6190
6351
  return Boolean(v);
6191
6352
  }
6192
6353
  // 三值真值表,入参已归一化为 true / false / null,返回 1 / 0 / null
@@ -6994,6 +7155,9 @@ class SQLExecutor {
6994
7155
  let toInsert = dataRows;
6995
7156
  let updated = 0;
6996
7157
  let skipped = 0;
7158
+ // #579/#580:按 MySQL affectedRows 口径分别累计「更新 2 / 替换删除 1」
7159
+ let updatedAffected = 0;
7160
+ let replaced = 0;
6997
7161
  // 非主键 UNIQUE 约束:默认动作(无 ON CONFLICT / IGNORE / REPLACE)下违反即 ER_DUP_ENTRY。
6998
7162
  // 主键冲突由下面的冲突逻辑处理;这里补唯一列(含批内重复)。
6999
7163
  if (uniqueCols.length > 0 && this._conflictAction(statement) === 'throw') {
@@ -7093,6 +7257,8 @@ class SQLExecutor {
7093
7257
  if (this.engine.removeByIds) await this.engine.removeByIds(statement.name, oldIds);
7094
7258
  else for (const id of oldIds) await this.engine.removeById(statement.name, id);
7095
7259
  }
7260
+ // #580:REPLACE 是「先删后插」,每个被删的旧行也要计入 affectedRows
7261
+ replaced = oldIds.length;
7096
7262
  toInsert = dataRows;
7097
7263
  await this.engine.flush();
7098
7264
  } else if (conflicts.length > 0 && conflictAction === 'update') {
@@ -7141,6 +7307,12 @@ class SQLExecutor {
7141
7307
  } else {
7142
7308
  for (const k of Object.keys(d)) if (!pkCols.includes(k)) data[k] = d[k];
7143
7309
  }
7310
+ // #579:写回当前值(未实际改动)按 MySQL 计 0;真正更新计 2
7311
+ const changed = !existingRow || Object.keys(data).some(k => {
7312
+ const a = existingRow[k], b = data[k];
7313
+ return (a == null) !== (b == null) || (a != null && b != null && a !== b);
7314
+ });
7315
+ if (changed) updatedAffected += 2;
7144
7316
  if (this.engine.updateById && existingId.length === 1) {
7145
7317
  await this.engine.updateById(statement.name, existingId[0], data);
7146
7318
  } else if (this.engine.update) {
@@ -7209,7 +7381,7 @@ class SQLExecutor {
7209
7381
  }
7210
7382
  const out = {
7211
7383
  ok: true, type: 'insert', table: statement.name,
7212
- affectedRows: toInsert.length + updated,
7384
+ affectedRows: toInsert.length + updatedAffected + replaced,
7213
7385
  insertId: Array.isArray(ids) && ids.length > 0 ? ids[0] : null,
7214
7386
  ids,
7215
7387
  duplicateUpdated: updated,
@@ -7247,9 +7419,9 @@ class SQLExecutor {
7247
7419
  const sel = JSON.parse(JSON.stringify(cte.select));
7248
7420
  // CTE 显式列名清单 `name (a, b) AS (...)`:按顺序重命名输出列
7249
7421
  if (cte.columns && cte.columns.length) {
7250
- sel.columns.forEach((c, i) => {
7251
- if (cte.columns[i] && !c.alias) c.alias = cte.columns[i];
7252
- });
7422
+ // #577:清单长度不等必须报错;#576:清单名无条件覆盖内层 SELECT 别名
7423
+ if (cte.columns.length !== sel.columns.length) throw wrongColumnListError();
7424
+ sel.columns.forEach((c, i) => { c.alias = cte.columns[i]; });
7253
7425
  }
7254
7426
  this._inlineCteRefs(sel, map);
7255
7427
  map.set(key, sel);
@@ -7293,6 +7465,11 @@ class SQLExecutor {
7293
7465
  };
7294
7466
  }
7295
7467
  case 'createView': {
7468
+ // #578:视图列名清单数量必须与 SELECT 列数一致
7469
+ if (statement.columns && statement.columns.length &&
7470
+ statement.select.columns && statement.columns.length !== statement.select.columns.length) {
7471
+ throw wrongColumnListError();
7472
+ }
7296
7473
  if (!this.engine._views) this.engine._views = Object.create(null);
7297
7474
  const key = String(statement.name).toLowerCase();
7298
7475
  if (this.engine._views[key] && !statement.orReplace) {
@@ -8334,6 +8511,8 @@ class SQLExecutor {
8334
8511
  */
8335
8512
  async _filterMutationRows(statement, rows) {
8336
8513
  if (!statement.where) return rows;
8514
+ // #582:UPDATE/DELETE 的 WHERE 也要做列存在性校验,不能把未知列当 undefined 静默按 FALSE 过滤
8515
+ this._validateColumnRefs({ where: statement.where }, rows);
8337
8516
  await this._materialize(statement.where);
8338
8517
  const aliases = new Set([String(statement.table || '').toLowerCase()]);
8339
8518
  const subs = this._collectSubqueries(statement.where).filter(n => this._isCorrelated(n, aliases));
@@ -8412,6 +8591,37 @@ class SQLExecutor {
8412
8591
  * 构造 WITH ROLLUP 的汇总行:把各组的原始行合并成一个"超级组",
8413
8592
  * 分组列不设值(投影时会取 null),聚合列则覆盖全部行。
8414
8593
  */
8594
+ /**
8595
+ * #522:多列 ROLLUP 要按 GROUP BY 列从右向左逐级回退生成小计行,
8596
+ * 最后才是全表总计。每个小计行的 _group 包含该层级覆盖的全部原始行。
8597
+ */
8598
+ _rollupRows(groupReps, groupBy) {
8599
+ if (!Array.isArray(groupBy) || groupBy.length < 2) return [this._rollupRow(groupReps)];
8600
+ const out = [];
8601
+ const valueOf = (r, g) => resolveOperand(typeof g === 'string' ? { type: 'column', name: g } : g, r, this.ctx);
8602
+ for (let keep = groupBy.length - 1; keep >= 1; keep--) {
8603
+ const levels = new Map();
8604
+ for (const r of groupReps) {
8605
+ const vals = groupBy.slice(0, keep).map(g => valueOf(r, g));
8606
+ const k = JSON.stringify(vals.map(sqlGroupKeyNormalize));
8607
+ if (!levels.has(k)) levels.set(k, { vals, members: [] });
8608
+ levels.get(k).members.push(...(r._group || [r]));
8609
+ }
8610
+ for (const { vals, members } of levels.values()) {
8611
+ const rep = {};
8612
+ groupBy.forEach((g, i) => {
8613
+ if (typeof g !== 'string') return;
8614
+ rep[g] = i < keep ? vals[i] : null;
8615
+ });
8616
+ rep._group = members;
8617
+ rep._rollup = true;
8618
+ out.push(rep);
8619
+ }
8620
+ }
8621
+ out.push(this._rollupRow(groupReps));
8622
+ return out;
8623
+ }
8624
+
8415
8625
  _rollupRow(groupReps) {
8416
8626
  const all = [];
8417
8627
  for (const rep of groupReps) {
@@ -8437,7 +8647,8 @@ class SQLExecutor {
8437
8647
  const noColumn = !op || op.type === 'star';
8438
8648
  // #293:JSON 聚合按整组求值,不能退化成每组取代表行
8439
8649
  if (fn === 'JSON_ARRAYAGG') {
8440
- const out = rows.map(r => resolveOperand(op, r, this.ctx));
8650
+ // #523:聚合返回路径要和普通投影一样把布尔归一为 1/0
8651
+ const out = rows.map(r => projectScalar(resolveOperand(op, r, this.ctx)));
8441
8652
  return out;
8442
8653
  }
8443
8654
  if (fn === 'JSON_OBJECTAGG') {
@@ -8448,7 +8659,7 @@ class SQLExecutor {
8448
8659
  const k = resolveOperand(items[0], r, this.ctx);
8449
8660
  const v = resolveOperand(items[1], r, this.ctx);
8450
8661
  if (k === null || k === undefined) continue;
8451
- obj[String(k)] = v === undefined ? null : v;
8662
+ obj[String(k)] = v === undefined ? null : projectScalar(v);
8452
8663
  }
8453
8664
  }
8454
8665
  return obj;
@@ -8461,8 +8672,11 @@ class SQLExecutor {
8461
8672
  .filter(v => v !== null && v !== undefined)
8462
8673
  // COUNT(DISTINCT a, b):先把多列拼成元组再聚合
8463
8674
  : op && op.type === 'tuple'
8464
- ? rows.map(r => JSON.stringify(op.items.map(it => resolveOperand(it, r, this.ctx))))
8465
- .filter(v => v !== null && v !== undefined)
8675
+ // #521:COUNT(DISTINCT a,b) 只要任一分量是 NULL 就整行排除,
8676
+ // 不能把 ["null","z"] 这样的字符串照常计入去重集合。
8677
+ ? rows.map(r => op.items.map(it => resolveOperand(it, r, this.ctx)))
8678
+ .filter(vals => vals.every(v => v !== null && v !== undefined))
8679
+ .map(vals => JSON.stringify(vals))
8466
8680
  : rows.map(r => resolveOperand(op, r, this.ctx)).filter(v => v !== null && v !== undefined);
8467
8681
  // COUNT(DISTINCT x) / SUM(DISTINCT x):先按值去重再聚合
8468
8682
  if (distinct) {
@@ -8536,7 +8750,7 @@ class SQLExecutor {
8536
8750
  const n = Number(vs[i]);
8537
8751
  if (fn === 'MIN' ? n < best : n > best) best = n;
8538
8752
  }
8539
- return best;
8753
+ return projectScalar(best);
8540
8754
  }
8541
8755
  let best = vs[0];
8542
8756
  for (const v of vs.slice(1)) {
@@ -8544,7 +8758,7 @@ class SQLExecutor {
8544
8758
  const b = String(best);
8545
8759
  if (fn === 'MIN' ? a < b : a > b) best = v;
8546
8760
  }
8547
- return best;
8761
+ return projectScalar(best);
8548
8762
  }
8549
8763
  if (fn === 'BIT_AND' || fn === 'BIT_OR' || fn === 'BIT_XOR') {
8550
8764
  // MySQL:64 位无符号按位聚合;空集 BIT_AND 为全 1,BIT_OR/BIT_XOR 为 0
@@ -8595,7 +8809,7 @@ class SQLExecutor {
8595
8809
  }
8596
8810
  if (joined.length === 0) return null;
8597
8811
  const sep = (separator !== undefined && separator !== null) ? String(separator) : ',';
8598
- return joined.map(v => (v === null || v === undefined ? '' : String(v))).join(sep);
8812
+ return joined.map(v => (v === null || v === undefined ? '' : String(projectScalar(v)))).join(sep);
8599
8813
  }
8600
8814
  // 标准差 / 方差族:_POP 与无后缀 VARIANCE/STDDEV/STD 为总体,仅 _SAMP 为样本
8601
8815
  if (VARIANCE_FUNCS.has(fn)) {
@@ -8993,7 +9207,11 @@ class SQLExecutor {
8993
9207
  const base = dot >= 0 ? n.slice(dot + 1) : n;
8994
9208
  // 限定列引用了本层 FROM 之外的表/别名 → 属于外层作用域(相关子查询),放行。
8995
9209
  // 否则 `WHERE EXISTS (SELECT 1 FROM b WHERE b.av = a.v)` 里的 a.v 会被误杀。
8996
- if (dot >= 0 && !localAliases.has(n.slice(0, dot))) return;
9210
+ if (dot >= 0 && !localAliases.has(n.slice(0, dot))) {
9211
+ // 限定列引用了本层 FROM 之外的表/别名 → 属于外层作用域(相关子查询),放行。
9212
+ // #543 严格校验会误伤校验时 __outer 尚未挂上的合法相关子查询,故维持放行。
9213
+ return;
9214
+ }
8997
9215
  if (!known.has(n) && !known.has(base)) {
8998
9216
  throw new Error(`no such column: ${node.name}`);
8999
9217
  }
@@ -9007,6 +9225,10 @@ class SQLExecutor {
9007
9225
  walk(statement.columns);
9008
9226
  walk(statement.where);
9009
9227
  walk(statement.having);
9228
+ // #543:JOIN ON 也必须校验列引用,未知列不能按 NULL 静默空连接
9229
+ if (statement.from && Array.isArray(statement.from.joins)) {
9230
+ for (const j of statement.from.joins) if (j) walk(j.on);
9231
+ }
9010
9232
  walk(statement.orderBy);
9011
9233
  // ORDER BY 的列在解析器里是裸字符串(非 {type:'column'} 对象),walk 检不到。
9012
9234
  // 字符串可能是输出别名/位置序号(已在 known 里豁免),也可能是真实列;
@@ -9393,6 +9615,10 @@ class SQLExecutor {
9393
9615
  const sc = c.scalar;
9394
9616
  const over = (sc && sc.over) || c.over;
9395
9617
  if (!over) continue;
9618
+ // #528:未定义的命名窗口不能静默回退成 OVER (),MySQL 报未知窗口
9619
+ if (over.windowName && !(statement.window && statement.window[over.windowName])) {
9620
+ throw createError('ER_PARSE_ERROR', `Unknown window '${over.windowName}'`);
9621
+ }
9396
9622
  const fn = sc && sc.type === 'aggregate' ? String(sc.fn)
9397
9623
  : (sc && sc.type === 'func' ? String(sc.name).toUpperCase()
9398
9624
  : String(c.aggregate || '').toUpperCase());
@@ -9454,6 +9680,27 @@ class SQLExecutor {
9454
9680
  return { start: 0, end };
9455
9681
  }
9456
9682
  let start = 0, end = ordered.length - 1;
9683
+ // #399:RANGE 帧按排序键的数值区间取 peer,ROWS 才按行号偏移
9684
+ if (String(f.unit || '').toUpperCase() === 'RANGE' && orderBy.length) {
9685
+ const ov = orderBy[0];
9686
+ const cur = resolveOperand(ov.column, rows[ordered[i]], this.ctx);
9687
+ const base = cur == null ? 0 : Number(cur);
9688
+ const bound = (b, isStart) => {
9689
+ if (!b) return isStart ? -Infinity : Infinity;
9690
+ if (b.type === 'unbounded') return b.direction === 'preceding' ? -Infinity : Infinity;
9691
+ if (b.type === 'currentRow') return base;
9692
+ return base + (b.direction === 'preceding' ? -1 : 1) * Number(b.value);
9693
+ };
9694
+ const lo = bound(f.start, true), hi = bound(f.end, false);
9695
+ const inRange = (r) => {
9696
+ const v = resolveOperand(ov.column, r, this.ctx);
9697
+ const n = v == null ? 0 : Number(v);
9698
+ return n >= lo && n <= hi;
9699
+ };
9700
+ while (start < ordered.length && !inRange(rows[ordered[start]])) start++;
9701
+ while (end >= 0 && !inRange(rows[ordered[end]])) end--;
9702
+ return { start, end };
9703
+ }
9457
9704
  const apply = (b, isStart) => {
9458
9705
  if (!b) return isStart ? 0 : ordered.length - 1;
9459
9706
  if (b.type === 'unbounded') return b.direction === 'preceding' ? 0 : ordered.length - 1;
@@ -9466,7 +9713,19 @@ class SQLExecutor {
9466
9713
  };
9467
9714
 
9468
9715
  const argNode = toNode((w.spec && (w.spec.column || (w.spec.args && w.spec.args[0]))) || w.col.column || w.col.expr);
9469
- const valAt = (rowIdx, node) => resolveOperand(node || { type: 'value', value: 1 }, rows[rowIdx], this.ctx);
9716
+ const valAt = (rowIdx, node) => {
9717
+ const r = rows[rowIdx];
9718
+ // #525:窗口参数里嵌套的聚合(SUM(MAX(x)) OVER ())应先按当前分组求值
9719
+ if (node && node.type === 'aggregate') {
9720
+ return this._aggValue(r._group || [r], node.fn, node.column, node.distinct, node.separator, node.orderBy);
9721
+ }
9722
+ if (node && containsAggregateNode(node)) {
9723
+ const nested = JSON.parse(JSON.stringify(node));
9724
+ this._replaceAggregates(nested, r._group || [r]);
9725
+ return projectScalar(resolveOperand(nested, r, this.ctx));
9726
+ }
9727
+ return resolveOperand(node || { type: 'value', value: 1 }, r, this.ctx);
9728
+ };
9470
9729
 
9471
9730
  // #102:RANK 值按需计算,PERCENT_RANK / CUME_DIST 复用
9472
9731
  const rankAt = (pos) => {
@@ -9527,6 +9786,10 @@ class SQLExecutor {
9527
9786
  case 'LAG':
9528
9787
  case 'LEAD': {
9529
9788
  const off = w.spec && w.spec.args && w.spec.args[1] ? Number(resolveOperand(w.spec.args[1], rows[rowIdx], this.ctx)) : 1;
9789
+ // #526:SQL 标准禁止负偏移,不能默默交换 LAG/LEAD 方向
9790
+ if (!Number.isFinite(off) || off < 0) {
9791
+ throw createError('ER_PARSE_ERROR', `${w.fn} offset must be a non-negative integer`);
9792
+ }
9530
9793
  const target = w.fn === 'LAG' ? pos - off : pos + off;
9531
9794
  if (target < 0 || target >= ordered.length) {
9532
9795
  v = w.spec && w.spec.args && w.spec.args[2] ? resolveOperand(w.spec.args[2], rows[rowIdx], this.ctx) : null;
@@ -9548,9 +9811,32 @@ class SQLExecutor {
9548
9811
  case 'MIN':
9549
9812
  case 'MAX':
9550
9813
  case 'GROUP_CONCAT': {
9814
+ const f = frameIdx(pos);
9815
+ const idxSlice = ordered.slice(f.start, f.end + 1);
9816
+ let slice = idxSlice.map(i => rows[i]);
9817
+ let aggColumn = argNode;
9818
+ // #525:SUM(MAX(x)) OVER () 这类嵌套聚合要先按分组算出内层值,
9819
+ // 再在窗口帧上对外层聚合,不能直接把聚合节点当操作数解析。
9820
+ if (argNode && (argNode.type === 'aggregate' || containsAggregateNode(argNode))) {
9821
+ slice = idxSlice.map(i => ({ __aggv: valAt(i, argNode) }));
9822
+ aggColumn = { type: 'column', name: '__aggv' };
9823
+ }
9824
+ v = this._aggValue(slice, w.fn, aggColumn,
9825
+ !!(w.distinct || (w.spec && w.spec.distinct)),
9826
+ w.spec && w.spec.separator, w.spec && w.spec.orderBy);
9827
+ break;
9828
+ }
9829
+ // #524:通用聚合族(STDDEV/VAR/BIT/JSON 聚合)也要走窗口帧,
9830
+ // 不能因为没有专用分支就塌缩成整表聚合或返回 NULL。
9831
+ case 'STDDEV': case 'STD': case 'STDDEV_POP': case 'STDDEV_SAMP':
9832
+ case 'VARIANCE': case 'VAR_POP': case 'VAR_SAMP':
9833
+ case 'BIT_AND': case 'BIT_OR': case 'BIT_XOR':
9834
+ case 'JSON_ARRAYAGG': case 'JSON_OBJECTAGG': {
9551
9835
  const f = frameIdx(pos);
9552
9836
  const slice = ordered.slice(f.start, f.end + 1).map(i => rows[i]);
9553
- v = this._aggValue(slice, w.fn, argNode,
9837
+ const multi = w.spec && w.spec.args && w.spec.args.length > 1
9838
+ ? { type: 'arglist', items: w.spec.args } : argNode;
9839
+ v = this._aggValue(slice, w.fn, multi,
9554
9840
  !!(w.distinct || (w.spec && w.spec.distinct)),
9555
9841
  w.spec && w.spec.separator, w.spec && w.spec.orderBy);
9556
9842
  break;
@@ -9607,7 +9893,8 @@ class SQLExecutor {
9607
9893
  if (!v) return;
9608
9894
  const sub = JSON.parse(JSON.stringify(v.select));
9609
9895
  if (v.columns && v.columns.length) {
9610
- sub.columns.forEach((c, i) => { if (v.columns[i] && !c.alias) c.alias = v.columns[i]; });
9896
+ // #575:视图列名清单是输出列名,无条件覆盖内层 SELECT 别名
9897
+ sub.columns.forEach((c, i) => { if (v.columns[i]) c.alias = v.columns[i]; });
9611
9898
  }
9612
9899
  this._expandViews(sub, depth + 1); // 视图里再引用视图
9613
9900
  item.subquery = sub;
@@ -9686,6 +9973,51 @@ class SQLExecutor {
9686
9973
  // 集合运算:左分支不应用尾部 ORDER BY/LIMIT/OFFSET(它们属于整个组合结果)
9687
9974
  const setOpBase = { orderBy: null, limit: null, offset: 0, fetch: undefined };
9688
9975
 
9976
+ // #544:混合集合运算链按左结合顺序求值:(A UNION B) EXCEPT C
9977
+ if (Array.isArray(statement.setChain) && statement.setChain.length > 1) {
9978
+ const leftStatement = { ...statement, ...setOpBase, setChain: null, union: null, intersect: null, except: null };
9979
+ const left = await this.executeSelect(leftStatement);
9980
+ let rows = left.rows;
9981
+ for (const step of statement.setChain) {
9982
+ const right = await this.executeSelect(step.select);
9983
+ assertSetOpColumnCount(left, right);
9984
+ if (step.op === 'UNION') {
9985
+ rows = rows.concat(right.rows);
9986
+ if (!step.all) rows = dedupeRows(rows);
9987
+ } else if (step.op === 'INTERSECT') {
9988
+ if (step.all) {
9989
+ const cnt = new Map();
9990
+ for (const r of right.rows) { const k = bigintJson.stringify(r); cnt.set(k, (cnt.get(k) || 0) + 1); }
9991
+ const used = new Map();
9992
+ rows = rows.filter(r => {
9993
+ const k = bigintJson.stringify(r), n = used.get(k) || 0;
9994
+ if (n >= (cnt.get(k) || 0)) return false;
9995
+ used.set(k, n + 1); return true;
9996
+ });
9997
+ } else {
9998
+ const seen = new Set(right.rows.map(r => bigintJson.stringify(r)));
9999
+ rows = dedupeRows(rows.filter(r => seen.has(bigintJson.stringify(r))));
10000
+ }
10001
+ } else {
10002
+ if (step.all) {
10003
+ const cnt = new Map();
10004
+ for (const r of right.rows) { const k = bigintJson.stringify(r); cnt.set(k, (cnt.get(k) || 0) + 1); }
10005
+ const used = new Map();
10006
+ rows = rows.filter(r => {
10007
+ const k = bigintJson.stringify(r), n = used.get(k) || 0;
10008
+ if (n < (cnt.get(k) || 0)) { used.set(k, n + 1); return false; }
10009
+ return true;
10010
+ });
10011
+ } else {
10012
+ const seen = new Set(right.rows.map(r => bigintJson.stringify(r)));
10013
+ rows = dedupeRows(rows.filter(r => !seen.has(bigintJson.stringify(r))));
10014
+ }
10015
+ }
10016
+ }
10017
+ rows = this._finalizeSetOp(rows, left.columns, statement);
10018
+ return { ok: true, type: 'select', columns: left.columns, rows, raw: rows };
10019
+ }
10020
+
9689
10021
  // UNION 处理
9690
10022
  if (statement.union) {
9691
10023
  const leftStatement = { ...statement, ...setOpBase, union: null };
@@ -10005,8 +10337,8 @@ class SQLExecutor {
10005
10337
  for (const c of statement.columns) {
10006
10338
  if (c.alias) {
10007
10339
  aliases[c.alias.toLowerCase()] = true;
10008
- // 别名指向的表达式:尝试从 expr/scalar 里提取列名
10009
- const src = c.expr || c.scalar;
10340
+ // 别名指向的表达式:#518 补上 caseExpr(CASE 列不在 expr/scalar 里)
10341
+ const src = c.expr || c.scalar || c.caseExpr;
10010
10342
  // expr 可能是字符串 'a'(列名)或对象 {type:'column', name:'a'}
10011
10343
  if (typeof src === 'string') aliasToCol[c.alias.toLowerCase()] = src;
10012
10344
  else if (src && src.type === 'column') aliasToCol[c.alias.toLowerCase()] = src.name;
@@ -10059,9 +10391,12 @@ class SQLExecutor {
10059
10391
  // 于是 HAVING COUNT(*) > 2 会把所有行滤掉、最终输出 0 而不是真实计数。
10060
10392
  if (statement.having && !statement.groupBy) {
10061
10393
  const wholeTable = rows.slice();
10062
- rows = rows.map((r) => ({ ...r, _group: wholeTable }));
10394
+ // #533:空源也要物化一个隐式聚合行,否则 HAVING 作用在空集上把唯一结果滤掉
10395
+ rows = rows.length ? rows.map((r) => ({ ...r, _group: wholeTable })) : [{ _group: wholeTable }];
10063
10396
  }
10064
10397
 
10398
+ // #535:HAVING 会过滤 groups,ROLLUP 总计必须基于过滤前的全部分组
10399
+ const rowsBeforeHaving = statement.having ? rows.slice() : null;
10065
10400
  if (statement.having) {
10066
10401
  const havingAst = JSON.parse(JSON.stringify(statement.having));
10067
10402
  rows = rows.filter(r => {
@@ -10077,6 +10412,33 @@ class SQLExecutor {
10077
10412
  if (c.alias) ctx[c.alias] = v;
10078
10413
  }
10079
10414
  }
10415
+ // #434:ONLY_FULL_GROUP_BY —— HAVING 中残留的裸列必须在 GROUP BY 或聚合别名里
10416
+ if (statement.groupBy) {
10417
+ const allowed = new Set();
10418
+ for (const g of statement.groupBy) {
10419
+ if (typeof g === 'string') allowed.add(g.toLowerCase().split('.').pop());
10420
+ }
10421
+ for (const c of statement.columns) {
10422
+ if (c.alias) allowed.add(String(c.alias).toLowerCase());
10423
+ if (typeof c.expr === 'string') allowed.add(c.expr.toLowerCase().split('.').pop());
10424
+ }
10425
+ const check = (n) => {
10426
+ if (!n || typeof n !== 'object') return;
10427
+ if (Array.isArray(n)) { for (const x of n) check(x); return; }
10428
+ // 子查询有自己的 FROM 作用域,其中的列引用不受本层 ONLY_FULL_GROUP_BY 约束
10429
+ if (n.type === 'select' || n.type === 'subquery' || n.type === 'exists') return;
10430
+ if (n.type === 'column' && typeof n.name === 'string') {
10431
+ const base = n.name.toLowerCase().split('.').pop();
10432
+ if (!allowed.has(base) && !base.startsWith('__agg_')) {
10433
+ const e = new Error(`Expression #1 of HAVING clause contains column '${n.name}' which is not in GROUP BY clause`);
10434
+ e.code = 1055;
10435
+ throw e;
10436
+ }
10437
+ }
10438
+ for (const k of Object.keys(n)) check(n[k]);
10439
+ };
10440
+ check(h);
10441
+ }
10080
10442
  return evaluateExpr(h, ctx);
10081
10443
  });
10082
10444
  }
@@ -10144,7 +10506,9 @@ class SQLExecutor {
10144
10506
  return { ok: true, type: 'select', table: tableName2, columns: cols, rows: [], aggregate: statement.aggregate };
10145
10507
  }
10146
10508
  const valueOf = (c) => {
10147
- if (c.aggregate) return this._aggValue(rows, c.aggregate || 'COUNT', c.column, c.distinct, c.separator, c.orderBy);
10509
+ // #533:HAVING 阶段挂了 _group 的隐式聚合行不能当作真实源行参与计数
10510
+ const aggSource = rows.length === 1 && rows[0]._group ? rows[0]._group : rows;
10511
+ if (c.aggregate) return this._aggValue(aggSource, c.aggregate || 'COUNT', c.column, c.distinct, c.separator, c.orderBy);
10148
10512
  if (c.scalar && c.scalar.type === 'func' && hasCustomAgg) {
10149
10513
  const fn = String(c.scalar.name).toUpperCase();
10150
10514
  if (Object.prototype.hasOwnProperty.call(this.ctx.aggregates, fn)) {
@@ -10155,7 +10519,7 @@ class SQLExecutor {
10155
10519
  // 先把参数里的聚合按整表求值替换掉,否则 ROUND(AVG(x),1) 会得到 null
10156
10520
  if (containsAggregateNode(c.scalar)) {
10157
10521
  const nested = JSON.parse(JSON.stringify(c.scalar));
10158
- this._replaceAggregates(nested, rows);
10522
+ this._replaceAggregates(nested, aggSource);
10159
10523
  return projectScalar(resolveOperand(nested, rows[0] || {}, this.ctx));
10160
10524
  }
10161
10525
  return projectScalar(resolveOperand(c.scalar, rows[0] || {}, this.ctx));
@@ -10164,7 +10528,7 @@ class SQLExecutor {
10164
10528
  // CASE 内嵌聚合按整表求值替换(#52)
10165
10529
  if (containsAggregateNode(c.caseExpr)) {
10166
10530
  const nestedCase = JSON.parse(JSON.stringify(c.caseExpr));
10167
- this._replaceAggregates(nestedCase, rows);
10531
+ this._replaceAggregates(nestedCase, aggSource);
10168
10532
  return projectScalar(evaluateCaseVal(nestedCase, rows[0] || {}, this.ctx));
10169
10533
  }
10170
10534
  return projectScalar(evaluateCaseVal(c.caseExpr, rows[0] || {}, this.ctx));
@@ -10172,15 +10536,22 @@ class SQLExecutor {
10172
10536
  if (c.expr !== null && c.expr !== '*') return rows[0] ? projectScalar(resolveOperand({ type: 'column', name: c.expr }, rows[0])) : null;
10173
10537
  return null;
10174
10538
  };
10175
- return { ok: true, type: 'select', table: tableName2, columns: cols, rows: [[...statement.columns.map(valueOf)]], aggregate: statement.aggregate };
10539
+ // #534:整表聚合也必须走 LIMIT 切片;LIMIT 0 应返回空集
10540
+ let aggRows = [[...statement.columns.map(valueOf)]];
10541
+ if (statement.limit !== null) {
10542
+ const start = statement.offset || 0;
10543
+ aggRows = (statement.limit <= 0 || start >= aggRows.length) ? [] : aggRows.slice(start, start + statement.limit);
10544
+ }
10545
+ return { ok: true, type: 'select', table: tableName2, columns: cols, rows: aggRows, aggregate: statement.aggregate };
10176
10546
  }
10177
10547
 
10178
10548
  // GROUP BY 输出:每组的列(含聚合列)
10179
10549
  if (statement.groupBy) {
10180
10550
  const cols = statement.columns.map(c => scalarColumnName(c));
10181
- const rowsForGroups = (statement.rollup && rows.length > 0)
10182
- // WITH ROLLUP:追加一个"全表汇总"分组(分组列取 NULL,聚合列覆盖全部行)
10183
- ? rows.concat([this._rollupRow(rows)])
10551
+ const rollupSource = rowsBeforeHaving || rows;
10552
+ const rowsForGroups = (statement.rollup && rollupSource.length > 0)
10553
+ // WITH ROLLUP:追加一个"全表汇总"分组(基于 HAVING 之前的全量行)
10554
+ ? rows.concat(this._rollupRows(rollupSource, statement.groupBy))
10184
10555
  : rows;
10185
10556
  const mapped = await this._projectRows(statement, rowsForGroups, (r) => {
10186
10557
  const group = r._group || [r];
@@ -10243,6 +10614,25 @@ class SQLExecutor {
10243
10614
  }
10244
10615
 
10245
10616
  if (statement.orderBy) {
10617
+ // #470:DISTINCT 查询的 ORDER BY 只能引用投影列,否则 MySQL 报 3065
10618
+ if (statement.distinct) {
10619
+ for (const o of statement.orderBy) {
10620
+ const c = o && o.column;
10621
+ if (c && typeof c === 'object') continue; // 位置序号 / 表达式
10622
+ if (typeof c === 'number') continue;
10623
+ const name = String(c).toLowerCase();
10624
+ const base = name.includes('.') ? name.slice(name.lastIndexOf('.') + 1) : name;
10625
+ const projected = statement.columns.some(col =>
10626
+ scalarColumnName(col).toLowerCase() === name ||
10627
+ scalarColumnName(col).toLowerCase() === base ||
10628
+ (col.alias && String(col.alias).toLowerCase() === name));
10629
+ if (!projected) {
10630
+ const e = new Error(`Expression #1 of ORDER BY clause is not in SELECT list, references column '${c}' which is not in SELECT list; this is incompatible with DISTINCT`);
10631
+ e.code = 3065;
10632
+ throw e;
10633
+ }
10634
+ }
10635
+ }
10246
10636
  // ORDER BY 项可能是列名字符串、表达式节点,或列的位置序号(ORDER BY 1,1-based)
10247
10637
  const ordNames = statement.columns.map(c => scalarColumnName(c));
10248
10638
  /*
@@ -10269,6 +10659,13 @@ class SQLExecutor {
10269
10659
  return v !== undefined ? v : resolveOperand(node, r, this.ctx);
10270
10660
  };
10271
10661
  }
10662
+ // #398:窗口列的值已在窗口阶段写回行上,不能把带 over 的标量节点
10663
+ // 再当普通函数重算(会触发 1305 FUNCTION ROW_NUMBER does not exist)。
10664
+ if (c._windowKey || c.over || (c.scalar && c.scalar.over)) {
10665
+ return (r) => windowColumnValue(c, r);
10666
+ }
10667
+ // #473/#527:投影列可能是 CASE 表达式,排序列取不到该表达式的值
10668
+ if (c.caseExpr) return (r) => evaluateCaseVal(c.caseExpr, r, this.ctx);
10272
10669
  if (c.scalar) return (r) => resolveOperand(c.scalar, r, this.ctx);
10273
10670
  if (c.aggregate) return (r) => this._aggValue([r], c.aggregate, c.column, c.distinct, c.separator, c.orderBy);
10274
10671
  const nm = c.alias;
@@ -10336,7 +10733,8 @@ class SQLExecutor {
10336
10733
  if (schema && !hasJoins) {
10337
10734
  // P1-17: SELECT * 按列声明顺序输出,不得把主键强制排到首位(MySQL 语义)
10338
10735
  cols = schemaKeys.filter(k => k !== '_softDelete');
10339
- } else if (rowsAll && rowsAll.columns) {
10736
+ } else if (rowsAll && rowsAll.columns && !hasJoins) {
10737
+ // #541:派生表作 JOIN 左表时不能只取左派生列清单,否则右表整列丢失
10340
10738
  cols = rowsAll.columns;
10341
10739
  } else {
10342
10740
  // JOIN 时:只使用带前缀的键,避免同一列重复。