jsql-neo 6.5.32 → 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' },
@@ -959,9 +961,20 @@ class Parser {
959
961
  const fnTok = this.next();
960
962
  let name = String(fnTok.value);
961
963
  if (this.peek().type === 'op' && this.peek().value === '(') {
964
+ // 函数默认值可能带参数(NOW(6)、CURRENT_TIMESTAMP(3)):
965
+ // 原样保留括号内文本,交给 Table 侧按表达式求值/报错。
962
966
  this.next();
963
- this.expect('op', ')');
964
- 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 + ')';
965
978
  }
966
979
  def.default = name;
967
980
  def.defaultExpr = true;
@@ -1580,7 +1593,7 @@ class Parser {
1580
1593
  from = this.parseFrom();
1581
1594
  }
1582
1595
  let where = null;
1583
- if (this.isKeyword('WHERE')) { this.next(); where = this.parseBooleanExpr(); }
1596
+ if (this.isKeyword('WHERE')) { this.next(); where = this.parseBooleanExpr(); this._assertNoAggregateInWhere(where); }
1584
1597
  let groupBy = null;
1585
1598
  let rollup = false;
1586
1599
  if (this.isKeyword('GROUP')) {
@@ -1630,6 +1643,40 @@ class Parser {
1630
1643
  return node;
1631
1644
  }
1632
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
+
1633
1680
  /** ORDER BY 子句(可选)。返回 null 或 [{column, dir}]。 */
1634
1681
  parseOrderByClause() {
1635
1682
  if (!this.isKeyword('ORDER')) return null;
@@ -3444,14 +3491,14 @@ function resolveOperand(operand, row, ctx) {
3444
3491
  const d = new Date(base.getTime());
3445
3492
  const n = sign * Number(ivNode.value || 0);
3446
3493
  switch (String(ivNode.unit || '').toUpperCase()) {
3447
- case 'DAY': case 'DAYS': d.setDate(d.getDate() + n); break;
3448
- 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;
3449
3496
  case 'MONTH': case 'MONTHS': addMonthsClamped(d, n); break;
3450
3497
  case 'QUARTER': addMonthsClamped(d, n * 3); break;
3451
3498
  case 'YEAR': case 'YEARS': addMonthsClamped(d, n * 12); break;
3452
- case 'HOUR': case 'HOURS': d.setHours(d.getHours() + n); break;
3453
- case 'MINUTE': case 'MINUTES': d.setMinutes(d.getMinutes() + n); break;
3454
- 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;
3455
3502
  default: return null;
3456
3503
  }
3457
3504
  return fmtSqlDate(isDateOnly, d);
@@ -3667,27 +3714,64 @@ function resolveOperand(operand, row, ctx) {
3667
3714
  }
3668
3715
  }
3669
3716
 
3670
- /** 解析 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 标记的先换算成绝对时刻。 */
3671
3720
  function parseSqlDate(v) {
3672
3721
  if (v === null || v === undefined) return null;
3673
3722
  if (v instanceof Date) return Number.isNaN(v.getTime()) ? null : v;
3674
- const s = String(v).trim().replace(' ', 'T');
3675
- const d = new Date(s.length <= 10 ? s + 'T00:00:00' : s);
3676
- 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;
3677
3761
  }
3678
3762
 
3679
3763
  function pad2(n) { return String(n).padStart(2, '0'); }
3680
3764
 
3681
- /** 本地时区的 'YYYY-MM-DD HH:mm:ss'(MySQL 的 NOW() 语义;区别于 UTC_TIMESTAMP) */
3765
+ /** UTC 墙上时间的 'YYYY-MM-DD HH:mm:ss'(引擎统一基准;会话时区固定为 UTC) */
3682
3766
  function sqlLocalDateTime(d = new Date()) {
3683
- return d.getFullYear() + '-' + pad2(d.getMonth() + 1) + '-' + pad2(d.getDate()) + ' ' +
3684
- 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());
3685
3769
  }
3686
3770
 
3687
- /** 按输入形态回写日期:纯日期返回 YYYY-MM-DD,带时间返回 YYYY-MM-DD HH:MM:SS */
3771
+ /** 按输入形态回写日期(UTC):纯日期返回 YYYY-MM-DD,带时间返回 YYYY-MM-DD HH:MM:SS */
3688
3772
  function fmtSqlDate(dateOnly, d) {
3689
- const ymd = d.getFullYear() + '-' + pad2(d.getMonth() + 1) + '-' + pad2(d.getDate());
3690
- 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());
3691
3775
  }
3692
3776
 
3693
3777
  const DAY_NAMES = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
@@ -3700,21 +3784,21 @@ const TIME_UNITS = new Set([
3700
3784
  'SECONDS', 'MINUTES', 'HOURS', 'DAYS', 'WEEKS', 'MONTHS', 'YEARS',
3701
3785
  ]);
3702
3786
 
3703
- /** MySQL DATE_FORMAT 的 % 说明符 */
3787
+ /** MySQL DATE_FORMAT 的 % 说明符(全部取 UTC 部件,与落库值一致) */
3704
3788
  function strftime(d, fmt) {
3705
- const h12 = ((d.getHours() % 12) || 12);
3789
+ const h12 = ((d.getUTCHours() % 12) || 12);
3706
3790
  const map = {
3707
- '%Y': String(d.getFullYear()), '%y': pad2(d.getFullYear() % 100),
3708
- '%m': pad2(d.getMonth() + 1), '%c': String(d.getMonth() + 1),
3709
- '%d': pad2(d.getDate()), '%e': String(d.getDate()),
3710
- '%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()),
3711
3795
  '%h': pad2(h12), '%I': pad2(h12), '%l': String(h12),
3712
- '%i': pad2(d.getMinutes()), '%S': pad2(d.getSeconds()), '%s': pad2(d.getSeconds()),
3713
- '%p': d.getHours() < 12 ? 'AM' : 'PM',
3714
- '%M': MONTH_NAMES[d.getMonth()], '%b': MONTH_NAMES[d.getMonth()].slice(0, 3),
3715
- '%W': DAY_NAMES[d.getDay()], '%a': DAY_NAMES[d.getDay()].slice(0, 3),
3716
- '%w': String(d.getDay()),
3717
- '%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)),
3718
3802
  '%%': '%',
3719
3803
  };
3720
3804
  return String(fmt).replace(/%[A-Za-z%]/g, (m) => (m in map ? map[m] : m));
@@ -3789,31 +3873,32 @@ function strToDate(s, fmt) {
3789
3873
  default: break;
3790
3874
  }
3791
3875
  });
3792
- 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));
3793
3878
  return Number.isNaN(d.getTime()) ? null : d;
3794
3879
  }
3795
3880
 
3796
- /** PG DATE_PART / EXTRACT 的部件取值 */
3881
+ /** PG DATE_PART / EXTRACT 的部件取值(UTC 部件) */
3797
3882
  function pgDatePart(part, d) {
3798
3883
  switch (String(part).toLowerCase()) {
3799
- case 'year': case 'y': return d.getFullYear();
3800
- case 'month': case 'mon': case 'mm': return d.getMonth() + 1;
3801
- case 'day': case 'dd': case 'd': return d.getDate();
3802
- case 'hour': case 'hh': return d.getHours();
3803
- case 'minute': case 'mi': return d.getMinutes();
3804
- case 'second': case 'ss': return d.getSeconds();
3805
- case 'dow': return d.getDay();
3806
- case 'doy': return Math.round((d - new Date(d.getFullYear(), 0, 0)) / 86400000);
3807
- 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;
3808
3893
  case 'epoch': return Math.floor(d.getTime() / 1000);
3809
3894
  case 'week': {
3810
3895
  // ISO 8601 周序号
3811
- const t = new Date(d.getFullYear(), d.getMonth(), d.getDate());
3812
- const dayNr = (t.getDay() + 6) % 7;
3813
- t.setDate(t.getDate() - dayNr + 3);
3814
- const firstThursday = new Date(t.getFullYear(), 0, 4);
3815
- const fdayNr = (firstThursday.getDay() + 6) % 7;
3816
- 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);
3817
3902
  return 1 + Math.round((t - firstThursday) / (7 * 86400000));
3818
3903
  }
3819
3904
  default: return null;
@@ -3827,24 +3912,24 @@ function pgDatePart(part, d) {
3827
3912
  * 先 setDate(1) 再切月,避免切换过程中先溢出再被钳制。
3828
3913
  */
3829
3914
  function addMonthsClamped(d, n) {
3830
- const day = d.getDate();
3915
+ const day = d.getUTCDate();
3831
3916
  const t = new Date(d.getTime());
3832
- t.setDate(1);
3833
- t.setMonth(t.getMonth() + n);
3834
- const lastDay = new Date(t.getFullYear(), t.getMonth() + 1, 0).getDate();
3835
- 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));
3836
3921
  d.setTime(t.getTime());
3837
3922
  return d;
3838
3923
  }
3839
3924
 
3840
3925
  /** PG AGE(from, to) 的间隔文本:'6 years 7 mons 11 days' */
3841
3926
  function pgAge(from, to) {
3842
- let years = to.getFullYear() - from.getFullYear();
3843
- let months = to.getMonth() - from.getMonth();
3844
- 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();
3845
3930
  if (days < 0) {
3846
3931
  months -= 1;
3847
- days += new Date(to.getFullYear(), to.getMonth(), 0).getDate();
3932
+ days += new Date(Date.UTC(to.getUTCFullYear(), to.getUTCMonth(), 0)).getUTCDate();
3848
3933
  }
3849
3934
  if (months < 0) { years -= 1; months += 12; }
3850
3935
  return `${years} years ${months} mons ${days} days`;
@@ -3884,8 +3969,9 @@ function applyScalarFunction(fnNode, row, ctx) {
3884
3969
  case 'FOUND_ROWS': return session && session.foundRows !== undefined ? session.foundRows : 0;
3885
3970
  case 'CONNECTION_ID': return session && session.connectionId !== undefined ? session.connectionId : 0;
3886
3971
  case 'DATABASE': case 'SCHEMA': return session && session.currentDb ? session.currentDb : 'default';
3887
- // NOW() / CURDATE() / CURTIME() 返回会话时区(本地)时间,不能用 toISOString()(UTC)——
3888
- // 否则东八区凌晨会整整差一天(2024-02-29 被存成 2024-02-28)。
3972
+ // NOW() / CURDATE() / CURTIME() 返回 **UTC 墙上时间**(引擎会话时区固定为 UTC)。
3973
+ // 落库的日期字面量也按 UTC 基准,两者必须同一口径,否则 NOW() 写入值与
3974
+ // 字面量比较会错开整个主机时区偏移。
3889
3975
  case 'NOW': case 'CURRENT_TIMESTAMP': return sqlLocalDateTime();
3890
3976
  case 'CURDATE': case 'CURRENT_DATE': return sqlLocalDateTime().slice(0, 10);
3891
3977
  case 'CURTIME': return sqlLocalDateTime().slice(11, 19);
@@ -3936,16 +4022,16 @@ function applyScalarFunction(fnNode, row, ctx) {
3936
4022
  const d = parseSqlDate(args[1]);
3937
4023
  if (!d) return null;
3938
4024
  switch (unit) {
3939
- case 'YEAR': return d.getFullYear();
3940
- case 'MONTH': return d.getMonth() + 1;
3941
- case 'DAY': return d.getDate();
3942
- case 'HOUR': return d.getHours();
3943
- case 'MINUTE': return d.getMinutes();
3944
- case 'SECOND': return d.getSeconds();
3945
- case 'DOW': return d.getDay(); // 0 = 周日
3946
- 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 语义)
3947
4033
  case 'WEEK': {
3948
- const start = new Date(d.getFullYear(), 0, 1);
4034
+ const start = Date.UTC(d.getUTCFullYear(), 0, 1);
3949
4035
  return Math.floor((d - start) / 604800000) + 1;
3950
4036
  }
3951
4037
  default: return null;
@@ -3962,14 +4048,14 @@ function applyScalarFunction(fnNode, row, ctx) {
3962
4048
  const d = new Date(base.getTime());
3963
4049
  const n = sign * Number(iv.value || 0);
3964
4050
  switch (String(iv.unit || '').toUpperCase()) {
3965
- case 'DAY': case 'DAYS': d.setDate(d.getDate() + n); break;
3966
- 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;
3967
4053
  case 'MONTH': case 'MONTHS': addMonthsClamped(d, n); break;
3968
4054
  case 'QUARTER': addMonthsClamped(d, n * 3); break;
3969
4055
  case 'YEAR': case 'YEARS': addMonthsClamped(d, n * 12); break;
3970
- case 'HOUR': case 'HOURS': d.setHours(d.getHours() + n); break;
3971
- case 'MINUTE': case 'MINUTES': d.setMinutes(d.getMinutes() + n); break;
3972
- 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;
3973
4059
  default: return null;
3974
4060
  }
3975
4061
  return fmtSqlDate(isDateOnly, d);
@@ -3977,31 +4063,31 @@ function applyScalarFunction(fnNode, row, ctx) {
3977
4063
  // ===== 日期/时间(补齐 README 契约:此前这些全部缺失,静默返回 null)=====
3978
4064
  case 'YEAR': {
3979
4065
  const d = parseSqlDate(args[0]);
3980
- return d ? d.getFullYear() : null;
4066
+ return d ? d.getUTCFullYear() : null;
3981
4067
  }
3982
4068
  case 'MONTH': {
3983
4069
  const d = parseSqlDate(args[0]);
3984
- return d ? d.getMonth() + 1 : null;
4070
+ return d ? d.getUTCMonth() + 1 : null;
3985
4071
  }
3986
4072
  case 'DAY': case 'DAYOFMONTH': {
3987
4073
  const d = parseSqlDate(args[0]);
3988
- return d ? d.getDate() : null;
4074
+ return d ? d.getUTCDate() : null;
3989
4075
  }
3990
4076
  case 'HOUR': {
3991
4077
  const d = parseSqlDate(args[0]);
3992
- return d ? d.getHours() : null;
4078
+ return d ? d.getUTCHours() : null;
3993
4079
  }
3994
4080
  case 'MINUTE': {
3995
4081
  const d = parseSqlDate(args[0]);
3996
- return d ? d.getMinutes() : null;
4082
+ return d ? d.getUTCMinutes() : null;
3997
4083
  }
3998
4084
  case 'SECOND': {
3999
4085
  const d = parseSqlDate(args[0]);
4000
- return d ? d.getSeconds() : null;
4086
+ return d ? d.getUTCSeconds() : null;
4001
4087
  }
4002
4088
  case 'QUARTER': {
4003
4089
  const d = parseSqlDate(args[0]);
4004
- return d ? Math.floor(d.getMonth() / 3) + 1 : null;
4090
+ return d ? Math.floor(d.getUTCMonth() / 3) + 1 : null;
4005
4091
  }
4006
4092
  case 'WEEK': {
4007
4093
  const d = parseSqlDate(args[0]);
@@ -4010,15 +4096,15 @@ function applyScalarFunction(fnNode, row, ctx) {
4010
4096
  // mode 1/3(周一为一周之始且首周需 ≥4 天)走 ISO 周序;其余按 MySQL 默认 mode 0
4011
4097
  if (mode === 1 || mode === 3) return pgDatePart('week', d);
4012
4098
  // mode 0:周日为一周之始,第 1 周是本年第一个含周日的周(之前为第 0 周)
4013
- const jan1Dow = new Date(d.getFullYear(), 0, 1).getDay(); // 0=周日
4099
+ const jan1Dow = new Date(Date.UTC(d.getUTCFullYear(), 0, 1)).getUTCDay(); // 0=周日
4014
4100
  const firstSunday = jan1Dow === 0 ? 1 : 8 - jan1Dow;
4015
- 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);
4016
4102
  if (doy < firstSunday) return 0;
4017
4103
  return Math.floor((doy - firstSunday) / 7) + 1;
4018
4104
  }
4019
4105
  case 'DAYOFWEEK': { // MySQL:1=周日 … 7=周六
4020
4106
  const d = parseSqlDate(args[0]);
4021
- return d ? d.getDay() + 1 : null;
4107
+ return d ? d.getUTCDay() + 1 : null;
4022
4108
  }
4023
4109
  case 'DATE': {
4024
4110
  const d = parseSqlDate(args[0]);
@@ -4026,15 +4112,15 @@ function applyScalarFunction(fnNode, row, ctx) {
4026
4112
  }
4027
4113
  case 'TIME': {
4028
4114
  const d = parseSqlDate(args[0]);
4029
- 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;
4030
4116
  }
4031
4117
  case 'DATEDIFF': {
4032
4118
  const a = parseSqlDate(args[0]);
4033
4119
  const b = parseSqlDate(args[1]);
4034
4120
  if (!a || !b) return null;
4035
4121
  // MySQL 语义:按日期相减(忽略时间部分)
4036
- const ua = Date.UTC(a.getFullYear(), a.getMonth(), a.getDate());
4037
- 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());
4038
4124
  return Math.round((ua - ub) / 86400000);
4039
4125
  }
4040
4126
  case 'TIMESTAMPDIFF': {
@@ -4052,8 +4138,8 @@ function applyScalarFunction(fnNode, row, ctx) {
4052
4138
  // 只算日历月差会高估:
4053
4139
  // TIMESTAMPDIFF(MONTH,'2026-01-15','2026-03-14') = 1(差 1 个月零 29 天,不足 2 个月)
4054
4140
  // TIMESTAMPDIFF(MONTH,'2026-01-31','2026-03-01') = 1(1/31+1月=2/28,2/28+1月=3/28,够不到 3/1)
4055
- let months = (a.getFullYear() - b.getFullYear()) * 12 + (a.getMonth() - b.getMonth());
4056
- 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--;
4057
4143
  switch (unit) {
4058
4144
  case 'MICROSECOND': return Math.floor(ms * 1000);
4059
4145
  case 'SECOND': return Math.floor(ms / 1000);
@@ -4100,30 +4186,30 @@ function applyScalarFunction(fnNode, row, ctx) {
4100
4186
  }
4101
4187
  case 'LAST_DAY': {
4102
4188
  const d = parseSqlDate(args[0]);
4103
- 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;
4104
4190
  }
4105
4191
  case 'WEEKDAY': { // MySQL:0=周一 … 6=周日
4106
4192
  const d = parseSqlDate(args[0]);
4107
- return d ? (d.getDay() + 6) % 7 : null;
4193
+ return d ? (d.getUTCDay() + 6) % 7 : null;
4108
4194
  }
4109
4195
  case 'DAYOFYEAR': {
4110
4196
  const d = parseSqlDate(args[0]);
4111
- 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;
4112
4198
  }
4113
4199
  case 'DAYNAME': {
4114
4200
  const d = parseSqlDate(args[0]);
4115
- return d ? DAY_NAMES[d.getDay()] : null;
4201
+ return d ? DAY_NAMES[d.getUTCDay()] : null;
4116
4202
  }
4117
4203
  case 'MONTHNAME': {
4118
4204
  const d = parseSqlDate(args[0]);
4119
- return d ? MONTH_NAMES[d.getMonth()] : null;
4205
+ return d ? MONTH_NAMES[d.getUTCMonth()] : null;
4120
4206
  }
4121
4207
  case 'MAKEDATE': {
4122
4208
  const y = Number(args[0]);
4123
4209
  const doy = Number(args[1]);
4124
4210
  if (!Number.isFinite(y) || !Number.isFinite(doy)) return null;
4125
- const d = new Date(y, 0, 1);
4126
- d.setDate(doy);
4211
+ const d = new Date(Date.UTC(y, 0, 1));
4212
+ d.setUTCDate(doy);
4127
4213
  return fmtSqlDate(true, d);
4128
4214
  }
4129
4215
  case 'PERIOD_DIFF': {
@@ -4139,14 +4225,14 @@ function applyScalarFunction(fnNode, row, ctx) {
4139
4225
  if (!d) return null;
4140
4226
  let nd;
4141
4227
  switch (part) {
4142
- case 'year': nd = new Date(d.getFullYear(), 0, 1); break;
4143
- case 'quarter': nd = new Date(d.getFullYear(), Math.floor(d.getMonth() / 3) * 3, 1); break;
4144
- case 'month': nd = new Date(d.getFullYear(), d.getMonth(), 1); break;
4145
- case 'week': { const wd = (d.getDay() + 6) % 7; nd = new Date(d.getFullYear(), d.getMonth(), d.getDate() - wd); break; }
4146
- case 'day': nd = new Date(d.getFullYear(), d.getMonth(), d.getDate()); break;
4147
- case 'hour': nd = new Date(d.getFullYear(), d.getMonth(), d.getDate(), d.getHours()); break;
4148
- case 'minute': nd = new Date(d.getFullYear(), d.getMonth(), d.getDate(), d.getHours(), d.getMinutes()); break;
4149
- 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;
4150
4236
  default: return null;
4151
4237
  }
4152
4238
  return fmtSqlDate(false, nd);
@@ -4343,8 +4429,13 @@ function applyScalarFunction(fnNode, row, ctx) {
4343
4429
  case 'RAND': return args.length > 0 && args[0] != null ? seedRand(Number(args[0]))() : Math.random();
4344
4430
  case 'UNIX_TIMESTAMP': {
4345
4431
  if (args.length > 0 && args[0] != null) {
4346
- const d = new Date(String(args[0]).replace(' ', 'T'));
4347
- 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);
4348
4439
  }
4349
4440
  return Math.floor(Date.now() / 1000);
4350
4441
  }
@@ -6977,6 +7068,257 @@ class SQLExecutor {
6977
7068
  return out;
6978
7069
  }
6979
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
+
6980
7322
  /**
6981
7323
  * 校验语句里引用的列是否真实存在。
6982
7324
  * 之前 `SELECT nosuchcol FROM t` 会静默返回 null 而不是报错 —— 调用方拿到的
@@ -6986,7 +7328,11 @@ class SQLExecutor {
6986
7328
  * 不深入子查询节点:它们有自己的 FROM,列属于另一个作用域。
6987
7329
  */
6988
7330
  _validateColumnRefs(statement, rows) {
6989
- 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;
6990
7336
  const sample = rows[0];
6991
7337
  if (!sample || typeof sample !== 'object') return;
6992
7338
  const known = new Set();
@@ -7684,6 +8030,10 @@ class SQLExecutor {
7684
8030
  async executeSelect(statement) {
7685
8031
  // 视图:FROM 里的视图名展开成子查询
7686
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);
7687
8037
 
7688
8038
  // 集合运算:左分支不应用尾部 ORDER BY/LIMIT/OFFSET(它们属于整个组合结果)
7689
8039
  const setOpBase = { orderBy: null, limit: null, offset: 0, fetch: undefined };
@@ -7917,6 +8267,16 @@ class SQLExecutor {
7917
8267
 
7918
8268
  // 分组聚合
7919
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
+ });
7920
8280
  // MySQL 支持 GROUP BY alias,而 alias 指向 SELECT 列表的输出列名。
7921
8281
  // 解析时 groupBy[] 存的是原始字符串(如 "b"),必须先在 SELECT 别名里查找:
7922
8282
  // - 找到 → 取输出行里的 alias 值(因为 alias 已求出值了)
@@ -8497,7 +8857,7 @@ function escapeValue(value) {
8497
8857
  if (typeof value === 'boolean') return value ? 'true' : 'false';
8498
8858
  if (value instanceof Date) {
8499
8859
  const p = n => String(n).padStart(2, '0');
8500
- 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())}'`;
8501
8861
  }
8502
8862
  if (Buffer.isBuffer(value)) return "X'" + value.toString('hex') + "'";
8503
8863
  if (Array.isArray(value)) {