jsql-neo 6.5.28 → 6.5.30

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
@@ -534,6 +534,24 @@ class Parser {
534
534
  parseStatement() {
535
535
  const t = this.peek();
536
536
  if (t.type === 'eof') return null;
537
+ // 括号化的查询表达式(#60):(SELECT ...) UNION (SELECT ...)。
538
+ // 解析完括号内的 SELECT 后,括号外仍可能有集合运算符/ORDER BY/LIMIT。
539
+ if (t.type === 'op' && t.value === '(' && this.isKeyword('SELECT', 1)) {
540
+ this.next();
541
+ const stmt = this.parseSelect();
542
+ this.expect('op', ')');
543
+ // 括号内 SELECT 自身的 ORDER BY/LIMIT/OFFSET 属于该操作数,
544
+ // 不能作为整个组合查询的尾部子句(否则会作用到 union 后的结果)。
545
+ if (this.isKeyword('UNION') || this.isKeyword('INTERSECT') || this.isKeyword('EXCEPT')) {
546
+ stmt._operandTail = { orderBy: stmt.orderBy, limit: stmt.limit, offset: stmt.offset };
547
+ stmt.orderBy = null;
548
+ stmt.limit = null;
549
+ stmt.offset = 0;
550
+ }
551
+ this.parseSetOps(stmt);
552
+ this.optionalTailSemicolon();
553
+ return stmt;
554
+ }
537
555
  if (t.type !== 'keyword') {
538
556
  // 少数语句起始词刻意不进关键字表(它们同时是常见标识符),按上下文识别
539
557
  const w = String(t.value).toUpperCase();
@@ -1533,7 +1551,25 @@ class Parser {
1533
1551
  this.expectKeyword('GROUP'); this.expectKeyword('BY');
1534
1552
  groupBy = [];
1535
1553
  while (true) {
1536
- groupBy.push(this.parseColumnRef());
1554
+ // 支持表达式分组:GROUP BY a%2、GROUP BY UPPER(name)(#51)。
1555
+ // 裸列名仍保留字符串形态,避免破坏既有别名解析与下游处理。
1556
+ let g;
1557
+ const save = this.pos;
1558
+ const GROUP_END = ['HAVING', 'ORDER', 'LIMIT', 'OFFSET', 'UNION', 'INTERSECT',
1559
+ 'EXCEPT', 'RETURNING', 'WITH'];
1560
+ const endsGroupItem = (tk) => {
1561
+ if (tk.type === 'eof') return true;
1562
+ if (tk.type === 'op' && (tk.value === ',' || tk.value === ';' || tk.value === ')')) return true;
1563
+ return GROUP_END.some(w => this.isWord(w));
1564
+ };
1565
+ try {
1566
+ g = this.parseColumnRef();
1567
+ if (!endsGroupItem(this.peek())) { this.pos = save; g = this.parseScalar(); }
1568
+ } catch (e) {
1569
+ this.pos = save;
1570
+ g = this.parseScalar();
1571
+ }
1572
+ groupBy.push(g);
1537
1573
  if (this.peek().type === 'op' && this.peek().value === ',') { this.next(); continue; }
1538
1574
  break;
1539
1575
  }
@@ -1546,53 +1582,70 @@ class Parser {
1546
1582
  }
1547
1583
  let having = null;
1548
1584
  if (this.isKeyword('HAVING')) { this.next(); having = this.parseBooleanExpr(); }
1549
- let orderBy = null;
1550
- if (this.isKeyword('ORDER')) {
1551
- this.expectKeyword('ORDER'); this.expectKeyword('BY');
1552
- orderBy = [];
1553
- while (true) {
1554
- // 支持表达式排序:ORDER BY a + b DESC、ORDER BY UPPER(name)
1555
- // 纯列名仍走 parseColumnRef,保持既有字符串形态不破坏下游
1556
- let col;
1557
- const save = this.pos;
1558
- // ORDER BY 项的合法结束符;不是这些就说明是表达式(如 a+b、UPPER(name))
1559
- const ORDER_END = ['ASC', 'DESC', 'LIMIT', 'OFFSET', 'FETCH', 'UNION', 'INTERSECT',
1560
- 'EXCEPT', 'RETURNING', 'FOR', 'WITH'];
1561
- const endsClause = (tk) => {
1562
- if (tk.type === 'eof') return true;
1563
- if (tk.type === 'op' && (tk.value === ',' || tk.value === ';' || tk.value === ')')) return true;
1564
- return ORDER_END.some(w => this.isWord(w));
1565
- };
1566
- try {
1567
- col = this.parseColumnRef();
1568
- if (!endsClause(this.peek())) {
1569
- this.pos = save;
1570
- col = this.parseScalar();
1571
- }
1572
- } catch (e) {
1585
+ const orderBy = this.parseOrderByClause();
1586
+ const lim = this.parseLimitOffset();
1587
+ const limit = lim.limit;
1588
+ const offset = lim.offset;
1589
+ const node = { type: 'select', columns, aggregate, distinct, from, where, groupBy, having, orderBy, limit, offset, union: null, intersect: null, except: null, rollup };
1590
+ this.parseSetOps(node);
1591
+ this.optionalTailSemicolon();
1592
+ this.depth--;
1593
+
1594
+ return node;
1595
+ }
1596
+
1597
+ /** ORDER BY 子句(可选)。返回 null 或 [{column, dir}]。 */
1598
+ parseOrderByClause() {
1599
+ if (!this.isKeyword('ORDER')) return null;
1600
+ this.expectKeyword('ORDER'); this.expectKeyword('BY');
1601
+ const orderBy = [];
1602
+ while (true) {
1603
+ // 支持表达式排序:ORDER BY a + b DESC、ORDER BY UPPER(name)
1604
+ // 纯列名仍走 parseColumnRef,保持既有字符串形态不破坏下游
1605
+ let col;
1606
+ const save = this.pos;
1607
+ // ORDER BY 项的合法结束符;不是这些就说明是表达式(如 a+b、UPPER(name))
1608
+ const ORDER_END = ['ASC', 'DESC', 'LIMIT', 'OFFSET', 'FETCH', 'UNION', 'INTERSECT',
1609
+ 'EXCEPT', 'RETURNING', 'FOR', 'WITH'];
1610
+ const endsClause = (tk) => {
1611
+ if (tk.type === 'eof') return true;
1612
+ if (tk.type === 'op' && (tk.value === ',' || tk.value === ';' || tk.value === ')')) return true;
1613
+ return ORDER_END.some(w => this.isWord(w));
1614
+ };
1615
+ try {
1616
+ col = this.parseColumnRef();
1617
+ if (!endsClause(this.peek())) {
1573
1618
  this.pos = save;
1574
- // ORDER BY 可以引用输出列别名,而别名可能与聚合函数同名:
1575
- // SELECT AVG(v) AS avg FROM t GROUP BY g ORDER BY avg DESC
1576
- // 这种 token 已被词法器标成 keyword(AVG/SUM/COUNT/MAX/MIN 都在关键字表里),
1577
- // parseColumnRef 只认 ident 会失败,parseScalar 又会把它当函数调用 → "got 'AVG'"。
1578
- // 此处把裸 keyword 当作列名,与 SQLite / MySQL 的行为一致。
1579
- const tk = this.peek();
1580
- if (tk.type === 'keyword' && !this.isWord('ASC') && !this.isWord('DESC')
1581
- && !ORDER_END.some(w => this.isWord(w))) {
1582
- this.next();
1583
- col = tk.value;
1584
- } else {
1585
- col = this.parseScalar();
1586
- }
1619
+ col = this.parseScalar();
1620
+ }
1621
+ } catch (e) {
1622
+ this.pos = save;
1623
+ // ORDER BY 可以引用输出列别名,而别名可能与聚合函数同名:
1624
+ // SELECT AVG(v) AS avg FROM t GROUP BY g ORDER BY avg DESC
1625
+ // 这种 token 已被词法器标成 keyword(AVG/SUM/COUNT/MAX/MIN 都在关键字表里),
1626
+ // parseColumnRef 只认 ident 会失败,parseScalar 又会把它当函数调用 → "got 'AVG'"。
1627
+ // 此处把裸 keyword 当作列名,与 SQLite / MySQL 的行为一致。
1628
+ const tk = this.peek();
1629
+ if (tk.type === 'keyword' && !this.isWord('ASC') && !this.isWord('DESC')
1630
+ && !ORDER_END.some(w => this.isWord(w))) {
1631
+ this.next();
1632
+ col = tk.value;
1633
+ } else {
1634
+ col = this.parseScalar();
1587
1635
  }
1588
- let dir = 'asc';
1589
- if (this.isKeyword('ASC')) { this.next(); }
1590
- else if (this.isKeyword('DESC')) { this.next(); dir = 'desc'; }
1591
- orderBy.push({ column: col, dir });
1592
- if (this.peek().type === 'op' && this.peek().value === ',') { this.next(); continue; }
1593
- break;
1594
1636
  }
1637
+ let dir = 'asc';
1638
+ if (this.isKeyword('ASC')) { this.next(); }
1639
+ else if (this.isKeyword('DESC')) { this.next(); dir = 'desc'; }
1640
+ orderBy.push({ column: col, dir });
1641
+ if (this.peek().type === 'op' && this.peek().value === ',') { this.next(); continue; }
1642
+ break;
1595
1643
  }
1644
+ return orderBy;
1645
+ }
1646
+
1647
+ /** LIMIT / OFFSET 子句(MySQL 语法,含 LIMIT a,b 与独立 OFFSET)。 */
1648
+ parseLimitOffset() {
1596
1649
  let limit = null, offset = 0;
1597
1650
  if (this.isKeyword('LIMIT')) {
1598
1651
  this.next();
@@ -1610,26 +1663,66 @@ class Parser {
1610
1663
  if (typeof offset === 'number' && offset < 0) throw new Error(`OFFSET must be a non-negative integer, got ${offset}`);
1611
1664
  limit = Number.MAX_SAFE_INTEGER;
1612
1665
  }
1613
- // 集合运算:UNION [ALL|DISTINCT] / INTERSECT [ALL|DISTINCT] / EXCEPT [ALL|DISTINCT]
1666
+ return { limit, offset };
1667
+ }
1668
+
1669
+ /**
1670
+ * 集合运算后缀(#60):UNION [ALL|DISTINCT] / INTERSECT / EXCEPT。
1671
+ * 右侧操作数允许括号化的 SELECT((SELECT ...))。
1672
+ * 标准 SQL 里组合查询尾部的 ORDER BY / LIMIT / OFFSET 作用于整个结果,
1673
+ * 语法上它们先被解析进最右侧 SELECT(#57),这里逐层提升到外层,
1674
+ * 否则执行层在 concat 后直接返回,尾部子句被静默丢弃。
1675
+ *
1676
+ * 单独成方法,供普通 SELECT 与括号化根节点 (SELECT ...) UNION ... 共用。
1677
+ */
1678
+ parseSetOps(statement) {
1614
1679
  let union = null, intersect = null, except = null;
1680
+ let rhsParenthesized = false;
1681
+ const rhsOperand = () => {
1682
+ const operand = this.parseSetOperand();
1683
+ rhsParenthesized = operand.parenthesized;
1684
+ return operand.select;
1685
+ };
1615
1686
  if (this.isKeyword('UNION')) {
1616
1687
  this.next();
1617
1688
  const all = this.isKeyword('ALL');
1618
1689
  if (all) this.next();
1619
1690
  else if (this.isKeyword('DISTINCT')) this.next();
1620
- union = { all, select: this.parseSelect() };
1691
+ union = { all, select: rhsOperand() };
1621
1692
  } else if (this.isKeyword('INTERSECT')) {
1622
1693
  this.next();
1623
1694
  const all = this.isKeyword('ALL');
1624
1695
  if (all) this.next();
1625
1696
  else if (this.isKeyword('DISTINCT')) this.next();
1626
- intersect = { all, select: this.parseSelect() };
1697
+ intersect = { all, select: rhsOperand() };
1627
1698
  } else if (this.isKeyword('EXCEPT')) {
1628
1699
  this.next();
1629
1700
  const all = this.isKeyword('ALL');
1630
1701
  if (all) this.next();
1631
1702
  else if (this.isKeyword('DISTINCT')) this.next();
1632
- except = { all, select: this.parseSelect() };
1703
+ except = { all, select: rhsOperand() };
1704
+ }
1705
+ statement.union = union;
1706
+ statement.intersect = intersect;
1707
+ statement.except = except;
1708
+ // 括号化操作数(#60)内部的 ORDER BY/LIMIT/OFFSET 属于它自己,不能提升;
1709
+ // 普通无括号的最右侧 SELECT 上挂的尾部子句才属于整个组合查询(#57)。
1710
+ if (!rhsParenthesized) {
1711
+ const rhsSel = (union || intersect || except || {}).select;
1712
+ if (rhsSel) {
1713
+ if (rhsSel.orderBy) { statement.orderBy = rhsSel.orderBy; rhsSel.orderBy = null; }
1714
+ if (rhsSel.limit !== null && rhsSel.limit !== undefined) { statement.limit = rhsSel.limit; rhsSel.limit = null; }
1715
+ if (rhsSel.offset) { statement.offset = rhsSel.offset; rhsSel.offset = 0; }
1716
+ }
1717
+ }
1718
+ // 括号化操作数会把尾部 ORDER BY/LIMIT/OFFSET 留在括号外(#60):
1719
+ // 此时它们属于整个组合查询,在此直接解析。普通路径下这些子句已被
1720
+ // 最右侧 SELECT 消费并提升,不会重复解析。
1721
+ if (this.isKeyword('ORDER')) statement.orderBy = this.parseOrderByClause();
1722
+ if (this.isKeyword('LIMIT') || this.isKeyword('OFFSET')) {
1723
+ const tail = this.parseLimitOffset();
1724
+ statement.limit = tail.limit;
1725
+ statement.offset = tail.offset;
1633
1726
  }
1634
1727
  // FETCH FIRST n ROWS ONLY(SQL 标准的 LIMIT 写法)
1635
1728
  if (this.isWord('FETCH')) {
@@ -1640,14 +1733,26 @@ class Parser {
1640
1733
  let n = nTok.type === 'number' ? nTok.value : Number(nTok.value);
1641
1734
  if (typeof n === 'bigint') n = Number(n <= BigInt(Number.MAX_SAFE_INTEGER) ? n : BigInt(Number.MAX_SAFE_INTEGER));
1642
1735
  if (!Number.isFinite(n)) throw new Error(`Expected row count after FETCH FIRST, got '${nTok.value}'`);
1643
- limit = n;
1736
+ statement.limit = n;
1644
1737
  if (this.isWord('ROW') || this.isWord('ROWS')) this.next();
1645
1738
  if (this.isWord('ONLY')) this.next();
1646
1739
  }
1647
- this.optionalTailSemicolon();
1648
- this.depth--;
1740
+ return statement;
1741
+ }
1649
1742
 
1650
- return { type: 'select', columns, aggregate, distinct, from, where, groupBy, having, orderBy, limit, offset, union, intersect, except, rollup };
1743
+ /** 集合运算的操作数:普通 SELECT,或括号化的 SELECT(#60)。 */
1744
+ parseSetOperand() {
1745
+ if (this.peek().type === 'op' && this.peek().value === '(' && this.isKeyword('SELECT', 1)) {
1746
+ this.next();
1747
+ const inner = this.parseSelect();
1748
+ this.expect('op', ')');
1749
+ // A UNION (B) UNION C —— 括号后若仍有集合运算符,继续挂到该操作数上。
1750
+ if (this.isKeyword('UNION') || this.isKeyword('INTERSECT') || this.isKeyword('EXCEPT')) {
1751
+ this.parseSetOps(inner);
1752
+ }
1753
+ return { select: inner, parenthesized: true };
1754
+ }
1755
+ return { select: this.parseSelect(), parenthesized: false };
1651
1756
  }
1652
1757
 
1653
1758
  parseFrom() {
@@ -4673,6 +4778,22 @@ function dedupeRows(rows) {
4673
4778
  });
4674
4779
  }
4675
4780
 
4781
+ /**
4782
+ * 集合运算两侧列数必须一致(#60)。
4783
+ * MySQL/PostgreSQL 遇到列数不同的组合查询会直接报错;此前 jsql-neo 静默按左分支
4784
+ * 截断,第二个 SELECT 多出的列被丢弃 → 静默数据丢失。
4785
+ */
4786
+ function assertSetOpColumnCount(left, right) {
4787
+ const lc = (left && left.columns ? left.columns.length : 0);
4788
+ const rc = (right && right.columns ? right.columns.length : 0);
4789
+ if (lc !== rc) {
4790
+ const err = new Error('The used SELECT statements have a different number of columns');
4791
+ err.code = 'ER_WRONG_NUMBER_OF_COLUMNS_IN_SELECT';
4792
+ err.errno = 1222;
4793
+ throw err;
4794
+ }
4795
+ }
4796
+
4676
4797
  // 比较前把布尔归一化为 1/0,但只在“另一侧是数值/布尔”时做,
4677
4798
  // 避免把 true 与字符串 'true' 的比较悄悄改成 1 与 'true' 的比较。
4678
4799
  function normalizeCmpValue(a, other) {
@@ -4964,6 +5085,24 @@ function evaluateCaseVal(caseExpr, row, ctx) {
4964
5085
  return caseExpr.elseVal ? resolveOperand(caseExpr.elseVal, row, ctx) : null;
4965
5086
  }
4966
5087
 
5088
+ /**
5089
+ * 聚合参数的可读列名(#54):c.column 通常是 AST 节点({type:'column',name:'b'}),
5090
+ * 直接字符串拼理会得到 "SUM([object Object])"。
5091
+ */
5092
+ function columnLabel(col) {
5093
+ if (col === undefined || col === null) return '*';
5094
+ if (typeof col === 'string') return col;
5095
+ if (typeof col === 'number' || typeof col === 'bigint') return String(col);
5096
+ if (typeof col === 'object') {
5097
+ if (col.type === 'column' && col.name !== undefined) return String(col.name);
5098
+ if (col.type === 'star' || col.type === '*') return '*';
5099
+ if (col.type === 'value' || col.type === 'literal') return String(col.value);
5100
+ if (col.type === 'tuple' && Array.isArray(col.items)) return col.items.map(columnLabel).join(', ');
5101
+ try { return scalarName(col); } catch (e) { return 'expr'; }
5102
+ }
5103
+ return String(col);
5104
+ }
5105
+
4967
5106
  function scalarName(node) {
4968
5107
  if (!node) return 'expr';
4969
5108
  switch (node.type) {
@@ -4976,7 +5115,7 @@ function scalarName(node) {
4976
5115
  case 'literal': return String(node.value);
4977
5116
  case 'arith': return scalarName(node.left) + ' ' + node.op + ' ' + scalarName(node.right);
4978
5117
  case 'case': return 'CASE';
4979
- case 'aggregate': return node.fn + '(' + (node.column || '*') + ')';
5118
+ case 'aggregate': return node.fn + '(' + columnLabel(node.column) + ')';
4980
5119
  default: return 'expr';
4981
5120
  }
4982
5121
  }
@@ -4989,7 +5128,7 @@ function scalarColumnName(c) {
4989
5128
  }
4990
5129
  if (c.alias) return c.alias;
4991
5130
  if (c.scalar) return scalarName(c.scalar);
4992
- if (c.aggregate) return c.alias || (c.aggregate === 'COUNT' ? 'COUNT(*)' : c.aggregate + '(' + c.column + ')');
5131
+ if (c.aggregate) return c.alias || c.aggregate + '(' + columnLabel(c.column) + ')';
4993
5132
  if (c.literal !== undefined) return String(c.literal);
4994
5133
  if (c.caseExpr) return 'CASE';
4995
5134
  if (c.expr === '*') return '*';
@@ -5050,7 +5189,16 @@ function scalarColumnValue(c, r, ctx) {
5050
5189
  }
5051
5190
 
5052
5191
  if (c.literal !== undefined) return c.literal;
5053
- if (c.caseExpr) return projectScalar(evaluateCaseVal(c.caseExpr, r, ctx));
5192
+ if (c.caseExpr) {
5193
+ // CASE WHEN 内嵌聚合(#52):先把聚合按当前分组替换成字面值,
5194
+ // 否则 resolveOperand 不认识 aggregate 节点,条件恒为假 → 恒走 ELSE。
5195
+ if (ctx && ctx._replaceAggregates && containsAggregateNode(c.caseExpr)) {
5196
+ const copy = JSON.parse(JSON.stringify(c.caseExpr));
5197
+ ctx._replaceAggregates(copy, ctx.group || [r]);
5198
+ return projectScalar(evaluateCaseVal(copy, r, ctx));
5199
+ }
5200
+ return projectScalar(evaluateCaseVal(c.caseExpr, r, ctx));
5201
+ }
5054
5202
  if (c.expr === '*') return r[Object.keys(r).find(k => !k.startsWith('_'))];
5055
5203
  return projectScalar(resolveOperand({ type: 'column', name: c.expr }, r, ctx));
5056
5204
  }
@@ -6524,13 +6672,42 @@ class SQLExecutor {
6524
6672
  return typeof agg.result === 'function' ? agg.result(state) : state;
6525
6673
  }
6526
6674
  }
6675
+ // 整数精确累加(#56):SUM/AVG 若全为整数,用 BigInt 累加,
6676
+ // 避免 >2^53 时 Number 浮点加法把 9007199254740993 + 9007199254740992
6677
+ // 舍入成 18014398509481984。结果在安全范围内仍返回 number。
6678
+ const exactIntSum = () => {
6679
+ let total = 0n;
6680
+ for (const v of values) {
6681
+ if (typeof v === 'bigint') { total += v; continue; }
6682
+ if (typeof v === 'number' && Number.isInteger(v)) { total += BigInt(v); continue; }
6683
+ if (typeof v === 'string' && /^[-+]?\d+$/.test(v.trim())) {
6684
+ try { total += BigInt(v.trim()); continue; } catch (e) { return undefined; }
6685
+ }
6686
+ return undefined;
6687
+ }
6688
+ return total;
6689
+ };
6690
+ const SAFE_MAX = BigInt(Number.MAX_SAFE_INTEGER);
6691
+ const SAFE_MIN = BigInt(Number.MIN_SAFE_INTEGER);
6527
6692
  if (fn === 'SUM') {
6528
6693
  // MySQL 语义:空集(或无任何非 NULL 值)的 SUM 为 NULL,而非 0。
6529
6694
  // AVG/MIN/MAX 已按此处理,此前只有 SUM 漏了。
6530
6695
  if (!values.length) return null;
6696
+ const exact = exactIntSum();
6697
+ if (exact !== undefined) {
6698
+ return (exact >= SAFE_MIN && exact <= SAFE_MAX) ? Number(exact) : exact;
6699
+ }
6531
6700
  return values.reduce((s, v) => s + (typeof v === 'number' ? v : Number(v) || 0), 0);
6532
6701
  }
6533
- if (fn === 'AVG') return values.length ? values.reduce((s, v) => s + (typeof v === 'number' ? v : Number(v) || 0), 0) / values.length : null;
6702
+ if (fn === 'AVG') {
6703
+ if (!values.length) return null;
6704
+ const exact = exactIntSum();
6705
+ if (exact !== undefined) {
6706
+ // 先精确求和,再除以行数;Number(total) 只在最后一步转换
6707
+ return Number(exact) / values.length;
6708
+ }
6709
+ return values.reduce((s, v) => s + (typeof v === 'number' ? v : Number(v) || 0), 0) / values.length;
6710
+ }
6534
6711
  if (fn === 'MIN' || fn === 'MAX') {
6535
6712
  const vs = values.filter(v => v !== null && v !== undefined);
6536
6713
  if (!vs.length) return null;
@@ -7327,36 +7504,117 @@ class SQLExecutor {
7327
7504
  return statement;
7328
7505
  }
7329
7506
 
7507
+ /**
7508
+ * 组合查询(UNION/INTERSECT/EXCEPT)尾部的 ORDER BY / LIMIT / OFFSET(#57)。
7509
+ * 此时 rows 已是投影后的数组,排序键按左分支列名或 1-based 列序号解析。
7510
+ */
7511
+ _finalizeSetOp(rows, columns, statement) {
7512
+ let out = rows;
7513
+ const orderBy = statement.orderBy;
7514
+ if (Array.isArray(orderBy) && orderBy.length) {
7515
+ const idxOf = (name) => {
7516
+ const n = String(name).toLowerCase();
7517
+ for (let i = 0; i < columns.length; i++) {
7518
+ if (String(columns[i]).toLowerCase() === n) return i;
7519
+ }
7520
+ return -1;
7521
+ };
7522
+ const objOf = (r) => {
7523
+ if (r && !Array.isArray(r) && typeof r === 'object') return r;
7524
+ const o = {};
7525
+ for (let i = 0; i < columns.length; i++) o[columns[i]] = r ? r[i] : undefined;
7526
+ return o;
7527
+ };
7528
+ const keyed = out.map((r, i) => ({ r, i, o: objOf(r) }));
7529
+ const keyOf = (entry, o) => {
7530
+ const c = o.column;
7531
+ if (typeof c === 'number') {
7532
+ if (c >= 1 && c <= columns.length) return entry.r[c - 1];
7533
+ throw new Error(`ORDER BY position ${c} is out of range`);
7534
+ }
7535
+ if (typeof c === 'string' || (c && (c.type === 'column' || (c.type === 'value' && typeof c.value === 'number')))) {
7536
+ if (c && c.type === 'value') {
7537
+ const n = Number(c.value);
7538
+ if (n >= 1 && n <= columns.length) return entry.r[n - 1];
7539
+ throw new Error(`ORDER BY position ${n} is out of range`);
7540
+ }
7541
+ const name = typeof c === 'string' ? c : c.name;
7542
+ const idx = idxOf(name);
7543
+ if (idx === -1) throw new Error(`no such column: ${name}`);
7544
+ return entry.r[idx];
7545
+ }
7546
+ // 表达式排序:按列名构造对象后求值
7547
+ return resolveOperand(c, entry.o, this.ctx);
7548
+ };
7549
+ keyed.sort((a, b) => {
7550
+ for (const o of orderBy) {
7551
+ const av = keyOf(a, o);
7552
+ const bv = keyOf(b, o);
7553
+ if (av === bv) continue;
7554
+ const aNull = av === null || av === undefined;
7555
+ const bNull = bv === null || bv === undefined;
7556
+ if (aNull || bNull) {
7557
+ const r = aNull && bNull ? 0 : (aNull ? -1 : 1);
7558
+ return o.dir === 'desc' ? -r : r;
7559
+ }
7560
+ const d = typeof av === 'number' && typeof bv === 'number'
7561
+ ? av - bv : String(av).localeCompare(String(bv));
7562
+ if (d !== 0) return o.dir === 'desc' ? -d : d;
7563
+ }
7564
+ return a.i - b.i;
7565
+ });
7566
+ out = keyed.map(x => x.r);
7567
+ }
7568
+ if (statement.offset) out = out.slice(statement.offset);
7569
+ if (statement.limit !== null && statement.limit !== undefined) out = out.slice(0, statement.limit);
7570
+ return out;
7571
+ }
7572
+
7330
7573
  async executeSelect(statement) {
7331
7574
  // 视图:FROM 里的视图名展开成子查询
7332
7575
  if (this.engine && this.engine._views) this._expandViews(statement);
7333
7576
 
7577
+ // 集合运算:左分支不应用尾部 ORDER BY/LIMIT/OFFSET(它们属于整个组合结果)
7578
+ const setOpBase = { orderBy: null, limit: null, offset: 0, fetch: undefined };
7579
+
7334
7580
  // UNION 处理
7335
7581
  if (statement.union) {
7336
- const left = await this.executeSelect({ ...statement, union: null });
7582
+ const leftStatement = { ...statement, ...setOpBase, union: null };
7583
+ if (statement._operandTail) Object.assign(leftStatement, statement._operandTail);
7584
+ const left = await this.executeSelect(leftStatement);
7337
7585
  const right = await this.executeSelect(statement.union.select);
7586
+ assertSetOpColumnCount(left, right);
7338
7587
  let rows = left.rows.concat(right.rows);
7339
7588
  if (!statement.union.all) rows = dedupeRows(rows);
7589
+ rows = this._finalizeSetOp(rows, left.columns, statement);
7340
7590
  return { ok: true, type: 'select', columns: left.columns, rows, raw: rows };
7341
7591
  }
7342
7592
 
7343
7593
  // INTERSECT:保留同时出现在右侧结果中的行(默认 DISTINCT,与 UNION 的处理保持一致)
7344
7594
  if (statement.intersect) {
7345
- const left = await this.executeSelect({ ...statement, intersect: null, except: null });
7595
+ const leftStatement = { ...statement, ...setOpBase, intersect: null, except: null };
7596
+ if (statement._operandTail) Object.assign(leftStatement, statement._operandTail);
7597
+ const left = await this.executeSelect(leftStatement);
7346
7598
  const right = await this.executeSelect(statement.intersect.select);
7599
+ assertSetOpColumnCount(left, right);
7347
7600
  const seen = new Set(right.rows.map(r => JSON.stringify(r)));
7348
7601
  let out = left.rows.filter(r => seen.has(JSON.stringify(r)));
7349
7602
  if (!statement.intersect.all) out = dedupeRows(out);
7603
+ out = this._finalizeSetOp(out, left.columns, statement);
7350
7604
  return { ok: true, type: 'select', columns: left.columns, rows: out, raw: out };
7351
7605
  }
7352
7606
 
7353
7607
  // EXCEPT:去掉出现在右侧结果中的行(默认 DISTINCT)
7354
7608
  if (statement.except) {
7355
- const left = await this.executeSelect({ ...statement, intersect: null, except: null });
7609
+ const leftStatement = { ...statement, ...setOpBase, intersect: null, except: null };
7610
+ if (statement._operandTail) Object.assign(leftStatement, statement._operandTail);
7611
+ const left = await this.executeSelect(leftStatement);
7356
7612
  const right = await this.executeSelect(statement.except.select);
7613
+ assertSetOpColumnCount(left, right);
7357
7614
  const seen = new Set(right.rows.map(r => JSON.stringify(r)));
7358
7615
  let out = left.rows.filter(r => !seen.has(JSON.stringify(r)));
7359
7616
  if (!statement.except.all) out = dedupeRows(out);
7617
+ out = this._finalizeSetOp(out, left.columns, statement);
7360
7618
  return { ok: true, type: 'select', columns: left.columns, rows: out, raw: out };
7361
7619
  }
7362
7620
 
@@ -7555,7 +7813,8 @@ class SQLExecutor {
7555
7813
  // 此前全用 resolveOperand({type:'column', name:g}) 按列名取,导致 GROUP BY b
7556
7814
  // 取 row['b'],而原始行里没有 b 列(b 是别名),全返回 undefined 并成一组。
7557
7815
  const aliases = {}; // alias名字 → true(存在性检查用)
7558
- const aliasToCol = {}; // alias名字 → 对应的表达式(用于从原始行取值)
7816
+ const aliasToCol = {}; // alias名字 → 对应的列名(用于从原始行取值)
7817
+ const aliasExpr = {}; // alias名字 → 对应的表达式 AST(GROUP BY 表达式别名,#51)
7559
7818
  if (statement.columns) {
7560
7819
  for (const c of statement.columns) {
7561
7820
  if (c.alias) {
@@ -7565,18 +7824,28 @@ class SQLExecutor {
7565
7824
  // expr 可能是字符串 'a'(列名)或对象 {type:'column', name:'a'}
7566
7825
  if (typeof src === 'string') aliasToCol[c.alias.toLowerCase()] = src;
7567
7826
  else if (src && src.type === 'column') aliasToCol[c.alias.toLowerCase()] = src.name;
7827
+ else if (src && typeof src === 'object') aliasExpr[c.alias.toLowerCase()] = src;
7568
7828
  }
7569
7829
  }
7570
7830
  }
7571
7831
  const groups = new Map();
7572
7832
  for (const row of rows) {
7573
7833
  const key = JSON.stringify(statement.groupBy.map(g => {
7834
+ // 表达式分组(#51):直接对原始行求值表达式
7835
+ if (g && typeof g === 'object') {
7836
+ const v = resolveOperand(g, row, this.ctx);
7837
+ return typeof v === 'bigint' ? v.toString() + 'n' : v;
7838
+ }
7574
7839
  const key = String(g).toLowerCase();
7575
7840
  if (aliases[key]) {
7576
7841
  // 优先用行中已有的 alias 值(投影后才有),没有则尝试从原始列取值
7577
7842
  if (row[key] !== undefined) return row[key];
7578
7843
  // alias → 原始列名 的映射(如 b → a),从原始行取该列的值
7579
7844
  if (aliasToCol[key]) return resolveOperand({ type: 'column', name: aliasToCol[key] }, row, this.ctx);
7845
+ if (aliasExpr[key]) {
7846
+ const v = resolveOperand(aliasExpr[key], row, this.ctx);
7847
+ return typeof v === 'bigint' ? v.toString() + 'n' : v;
7848
+ }
7580
7849
  return row[key]; // row[key] 为 undefined,但保持一致
7581
7850
  }
7582
7851
  return resolveOperand({ type: 'column', name: g }, row, this.ctx);
@@ -7647,7 +7916,14 @@ class SQLExecutor {
7647
7916
  return allKeys.map(k => r[k]);
7648
7917
  }
7649
7918
  if (c.scalar) return resolveOperand(c.scalar, r, this.ctx);
7650
- if (c.caseExpr) return evaluateCaseVal(c.caseExpr, r);
7919
+ if (c.caseExpr) {
7920
+ if (containsAggregateNode(c.caseExpr)) {
7921
+ const cc = JSON.parse(JSON.stringify(c.caseExpr));
7922
+ this._replaceAggregates(cc, r._group || [r]);
7923
+ return evaluateCaseVal(cc, r, this.ctx);
7924
+ }
7925
+ return evaluateCaseVal(c.caseExpr, r, this.ctx);
7926
+ }
7651
7927
  if (c.aggregate) return this._aggValue(r._group || [r], c.aggregate || 'COUNT', c.column, c.distinct, c.separator, c.orderBy);
7652
7928
  return resolveOperand({ type: 'column', name: c.expr }, r, this.ctx);
7653
7929
  }));
@@ -7663,7 +7939,8 @@ class SQLExecutor {
7663
7939
  // 无 GROUP BY 的整表聚合:顶层是聚合(AVG(x))、自定义聚合(total(x)),
7664
7940
  // 以及嵌套聚合(ROUND(AVG(x),1) —— 聚合藏在 scalar 的参数里,顶层 c.aggregate 为空)
7665
7941
  const hasNestedAgg = !statement.groupBy &&
7666
- statement.columns.some(c => c.scalar && containsAggregateNode(c.scalar));
7942
+ statement.columns.some(c => (c.scalar && containsAggregateNode(c.scalar)) ||
7943
+ (c.caseExpr && containsAggregateNode(c.caseExpr)));
7667
7944
  if (!statement.groupBy && (statement.columns.some(c => c.aggregate && !c.window) || hasCustomAgg || hasNestedAgg)) {
7668
7945
  const cols = statement.columns.map(c => scalarColumnName(c));
7669
7946
  const tableName2 = statement.from ? (statement.from.tables[0].table || null) : null;
@@ -7688,7 +7965,15 @@ class SQLExecutor {
7688
7965
  }
7689
7966
  return projectScalar(resolveOperand(c.scalar, rows[0] || {}, this.ctx));
7690
7967
  }
7691
- if (c.caseExpr) return projectScalar(resolveOperand(c.caseExpr, rows[0] || {}, this.ctx));
7968
+ if (c.caseExpr) {
7969
+ // CASE 内嵌聚合按整表求值替换(#52)
7970
+ if (containsAggregateNode(c.caseExpr)) {
7971
+ const nestedCase = JSON.parse(JSON.stringify(c.caseExpr));
7972
+ this._replaceAggregates(nestedCase, rows);
7973
+ return projectScalar(evaluateCaseVal(nestedCase, rows[0] || {}, this.ctx));
7974
+ }
7975
+ return projectScalar(evaluateCaseVal(c.caseExpr, rows[0] || {}, this.ctx));
7976
+ }
7692
7977
  if (c.expr !== null && c.expr !== '*') return rows[0] ? projectScalar(resolveOperand({ type: 'column', name: c.expr }, rows[0])) : null;
7693
7978
  return null;
7694
7979
  };
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "jsql-neo",
3
- "version": "6.5.28",
4
- "description": "JSQL-NEO \u2014 Rust-powered embedded database with WASM, REST API, B-Tree indexes, WAL, crash recovery",
3
+ "version": "6.5.30",
4
+ "description": "JSQL-NEO — Rust-powered embedded database with WASM, REST API, B-Tree indexes, WAL, crash recovery",
5
5
  "main": "index.js",
6
6
  "types": "index.d.ts",
7
7
  "exports": {
@@ -50,12 +50,12 @@
50
50
  "scripts": {
51
51
  "postinstall": "node postinstall.js",
52
52
  "build:native": "node scripts/build-native.js",
53
- "test": "node test/smoke.js && node test/result-raw.test.js && node test/native-install.test.js && node test/native-cli.test.js && node test/finalize-bigint.test.js && node test/native.test.js && node test/json-functions.test.js && node test/sql-parser.test.js && node test/readme-audit.test.js && node test/query-opt.test.js && node test/wal-recovery.test.js && node test/mysql-compat-hijack.test.js && node test/dml-constraints.test.js && node test/star-nag.test.js && node test/plugin-xql.test.js && node test/bug-regression-2.test.js && node test/issue-34-35-36.test.js && node test/issue-g4.test.js && node test/issue-38.test.js && node test/issue-39.test.js && node test/issue-40.test.js && node test/issue-44.test.js && node test/issue-45.test.js && node test/issue-46.test.js && node test/issue-47.test.js && node test/issue-48.test.js",
53
+ "test": "node test/smoke.js && node test/result-raw.test.js && node test/native-install.test.js && node test/native-cli.test.js && node test/finalize-bigint.test.js && node test/native.test.js && node test/json-functions.test.js && node test/sql-parser.test.js && node test/readme-audit.test.js && node test/query-opt.test.js && node test/wal-recovery.test.js && node test/mysql-compat-hijack.test.js && node test/dml-constraints.test.js && node test/star-nag.test.js && node test/plugin-xql.test.js && node test/bug-regression-2.test.js && node test/issue-34-35-36.test.js && node test/issue-g4.test.js && node test/issue-38.test.js && node test/issue-39.test.js && node test/issue-40.test.js && node test/issue-44.test.js && node test/issue-45.test.js && node test/issue-46.test.js && node test/issue-47.test.js && node test/issue-48.test.js && node test/issue-50.test.js && node test/issue-51.test.js && node test/issue-52.test.js && node test/issue-53.test.js && node test/issue-54.test.js && node test/issue-55.test.js && node test/issue-56.test.js && node test/issue-57.test.js && node test/issue-58.test.js && node test/issue-59.test.js && node test/issue-60.test.js",
54
54
  "test:parser": "node test/sql-parser.test.js",
55
55
  "test:btree": "node test/btree.test.js",
56
56
  "test:native": "node test/native.test.js",
57
57
  "test:regress": "node test/regress-5.1.0.js",
58
- "test:all": "node test/smoke.js && node test/result-raw.test.js && node test/native-install.test.js && node test/native-cli.test.js && node test/finalize-bigint.test.js && node test/sql-parser.test.js && node test/readme-audit.test.js && node test/native.test.js && node test/native-multi-instance.test.js && node test/wal-recovery.test.js && node test/mysql-compat-hijack.test.js && node test/wasm.test.js && node test/coverage.js && node test/regress-5.1.0.js && node test/join.test.js && node test/btree.test.js && node test/dml-constraints.test.js && node test/savepoint.test.js && node test/alter-table.test.js && node test/null-semantics.test.js && node test/identifier-keywords.test.js && node test/issue-34-35-36.test.js && node test/sql-semantics.test.js && node test/extra-coverage.test.js && node test/filter-compile.test.js && node test/recursive-cte.test.js && node test/index-ddl.test.js && node test/mongo-group.test.js && node test/multiprotocol.test.js && node test/issue-g4.test.js && node test/issue-38.test.js && node test/issue-39.test.js && node test/issue-40.test.js && node test/issue-44.test.js && node test/issue-45.test.js && node test/issue-46.test.js && node test/issue-47.test.js && node test/issue-48.test.js",
58
+ "test:all": "node test/smoke.js && node test/result-raw.test.js && node test/native-install.test.js && node test/native-cli.test.js && node test/finalize-bigint.test.js && node test/sql-parser.test.js && node test/readme-audit.test.js && node test/native.test.js && node test/native-multi-instance.test.js && node test/wal-recovery.test.js && node test/mysql-compat-hijack.test.js && node test/wasm.test.js && node test/coverage.js && node test/regress-5.1.0.js && node test/join.test.js && node test/btree.test.js && node test/dml-constraints.test.js && node test/savepoint.test.js && node test/alter-table.test.js && node test/null-semantics.test.js && node test/identifier-keywords.test.js && node test/issue-34-35-36.test.js && node test/sql-semantics.test.js && node test/extra-coverage.test.js && node test/filter-compile.test.js && node test/recursive-cte.test.js && node test/index-ddl.test.js && node test/mongo-group.test.js && node test/multiprotocol.test.js && node test/issue-g4.test.js && node test/issue-38.test.js && node test/issue-39.test.js && node test/issue-40.test.js && node test/issue-44.test.js && node test/issue-45.test.js && node test/issue-46.test.js && node test/issue-47.test.js && node test/issue-48.test.js && node test/issue-50.test.js && node test/issue-51.test.js && node test/issue-52.test.js && node test/issue-53.test.js && node test/issue-54.test.js && node test/issue-55.test.js && node test/issue-56.test.js && node test/issue-57.test.js && node test/issue-58.test.js && node test/issue-59.test.js && node test/issue-60.test.js",
59
59
  "test:coverage": "c8 --all --include='lib/**' --exclude='lib/web_ui.js' --reporter=text --reporter=lcov node test/coverage.js",
60
60
  "test:orms": "node examples/orms/run-all.js",
61
61
  "test:dml": "node test/dml-constraints.test.js",
@@ -103,4 +103,4 @@
103
103
  "devDependencies": {
104
104
  "c8": "^10.1.2"
105
105
  }
106
- }
106
+ }