jsql-neo 6.6.3 → 6.6.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -3,7 +3,7 @@
3
3
  > **One engine to rule them all** — a Rust-powered embedded database that speaks your language:
4
4
  > MySQL, PostgreSQL, MongoDB, Redis, SQL, TypeScript, **and the browser**.
5
5
 
6
- > **v6.6.3** — stable release · [github.com/vexify-org/JSQL-neo](https://github.com/vexify-org/JSQL-neo) · [jsql.vexify.top](https://jsql.vexify.top)
6
+ > **v6.6.4** — stable release · [github.com/vexify-org/JSQL-neo](https://github.com/vexify-org/JSQL-neo) · [jsql.vexify.top](https://jsql.vexify.top)
7
7
 
8
8
  ![Engines](https://img.shields.io/badge/engines-Native%20%7C%20WASM%20%7C%20Pure%20JS-7ee787)
9
9
  ![MySQL](https://img.shields.io/badge/protocol-MySQL%20compatible-1f6feb)
package/index.js CHANGED
@@ -1,5 +1,5 @@
1
1
  /**
2
- * JSQL-NEO v6.6.3 — Rust-Powered Embedded Database (WASM + HTTP)
2
+ * JSQL-NEO v6.6.4 — Rust-Powered Embedded Database (WASM + HTTP)
3
3
  *
4
4
  * @example
5
5
  * const jsql = require('jsql-neo');
package/lib/sql.js CHANGED
@@ -3452,6 +3452,30 @@ function bigintExactArith(l, r, op) {
3452
3452
  }
3453
3453
  }
3454
3454
 
3455
+ /**
3456
+ * 统一的 SQL 标量排序比较器(普通 ORDER BY / 窗口函数 / 组合查询共用,#103)。
3457
+ *
3458
+ * NULL 排序策略:ASC 时 NULL 排在最前,DESC 时 NULL 排在最后
3459
+ * (MySQL / SQLite 的默认语义)。此前窗口函数的比较器把 NULL 硬编码成
3460
+ * 恒小,于是 ORDER BY col DESC 时 NULL 跑到最前,与普通 SELECT 的 ORDER BY
3461
+ * 不一致;抽成一个函数后两条排序路径不会再各写一套。
3462
+ */
3463
+ function compareSqlValues(av, bv, dir) {
3464
+ const desc = dir === 'desc';
3465
+ if (av === bv) return 0;
3466
+ const aNull = av === null || av === undefined;
3467
+ const bNull = bv === null || bv === undefined;
3468
+ if (aNull || bNull) {
3469
+ if (aNull && bNull) return 0;
3470
+ const r = aNull ? -1 : 1;
3471
+ return desc ? -r : r;
3472
+ }
3473
+ const r = typeof av === 'number' && typeof bv === 'number'
3474
+ ? av - bv
3475
+ : (String(av) < String(bv) ? -1 : String(av) > String(bv) ? 1 : 0);
3476
+ return desc ? -r : r;
3477
+ }
3478
+
3455
3479
  function resolveOperand(operand, row, ctx) {
3456
3480
  if (operand === null || operand === undefined) return null;
3457
3481
  if (typeof operand === 'string') return resolveOperand({ type: 'column', name: operand }, row, ctx);
@@ -7930,11 +7954,8 @@ class SQLExecutor {
7930
7954
  for (const o of orderBy) {
7931
7955
  const av = resolveOperand(o.column, ra, this.ctx);
7932
7956
  const bv = resolveOperand(o.column, rb, this.ctx);
7933
- if (av === bv) continue;
7934
- if (av === undefined || av === null) return -1;
7935
- if (bv === undefined || bv === null) return 1;
7936
- const d = typeof av === 'number' && typeof bv === 'number' ? av - bv : String(av).localeCompare(String(bv));
7937
- if (d !== 0) return o.dir === 'asc' ? d : -d;
7957
+ const d = compareSqlValues(av, bv, o.dir);
7958
+ if (d !== 0) return d;
7938
7959
  }
7939
7960
  return ia - ib;
7940
7961
  });
@@ -7977,16 +7998,35 @@ class SQLExecutor {
7977
7998
  const argNode = toNode((w.spec && (w.spec.column || (w.spec.args && w.spec.args[0]))) || w.col.column || w.col.expr);
7978
7999
  const valAt = (rowIdx, node) => resolveOperand(node || { type: 'value', value: 1 }, rows[rowIdx], this.ctx);
7979
8000
 
8001
+ // #102:RANK 值按需计算,PERCENT_RANK / CUME_DIST 复用
8002
+ const rankAt = (pos) => {
8003
+ let rank = 1;
8004
+ for (let k = 0; k < pos; k++) {
8005
+ if (this._windowPeerCmp(rows[ordered[k]], rows[ordered[pos]], orderBy, this.ctx) !== 0) rank++;
8006
+ }
8007
+ return rank;
8008
+ };
8009
+
7980
8010
  ordered.forEach((rowIdx, pos) => {
7981
8011
  let v = null;
7982
8012
  switch (w.fn) {
7983
8013
  case 'ROW_NUMBER': v = pos + 1; break;
7984
- case 'RANK': {
7985
- // RANK = 1 + 分区内排在本行之前、且不是同值(peer)的行数
7986
- v = 1;
7987
- for (let k = 0; k < pos; k++) {
7988
- if (this._windowPeerCmp(rows[ordered[k]], rows[rowIdx], orderBy, this.ctx) !== 0) v++;
7989
- }
8014
+ case 'RANK': v = rankAt(pos); break;
8015
+ case 'PERCENT_RANK': {
8016
+ // (rank - 1) / (total_rows - 1),单行 / 无 ORDER BY 分区返回 0
8017
+ const rank = rankAt(pos);
8018
+ const total = ordered.length;
8019
+ v = total > 1 ? (rank - 1) / (total - 1) : 0;
8020
+ break;
8021
+ }
8022
+ case 'CUME_DIST': {
8023
+ // 分区内 值 <= 当前行 的行数占比(所有 peer 同值)
8024
+ const total = ordered.length;
8025
+ const curKey = this._windowPeerKey(rows[rowIdx], orderBy, this.ctx);
8026
+ let end = pos;
8027
+ while (end + 1 < total &&
8028
+ this._windowPeerKey(rows[ordered[end + 1]], orderBy, this.ctx) === curKey) end++;
8029
+ v = total > 0 ? (end + 1) / total : null;
7990
8030
  break;
7991
8031
  }
7992
8032
  case 'DENSE_RANK': {
@@ -8045,7 +8085,9 @@ class SQLExecutor {
8045
8085
 
8046
8086
  _windowPeerKey(row, orderBy, ctx) {
8047
8087
  if (!orderBy.length) return '';
8048
- return orderBy.map(o => JSON.stringify(resolveOperand(o.column, row, ctx))).join('');
8088
+ // null 与 undefined 视为同一取值(都是 SQL NULL),否则二者会被当成不同 peer
8089
+ const norm = (v) => (v === null || v === undefined ? 'null' : JSON.stringify(v));
8090
+ return orderBy.map(o => norm(resolveOperand(o.column, row, ctx))).join('');
8049
8091
  }
8050
8092
 
8051
8093
  _windowPeerCmp(rowA, rowB, orderBy, ctx) {
@@ -8053,10 +8095,7 @@ class SQLExecutor {
8053
8095
  for (const o of orderBy) {
8054
8096
  const av = resolveOperand(o.column, rowA, ctx);
8055
8097
  const bv = resolveOperand(o.column, rowB, ctx);
8056
- if (av === bv) continue;
8057
- if (av === undefined || av === null) return -1;
8058
- if (bv === undefined || bv === null) return 1;
8059
- const d = typeof av === 'number' && typeof bv === 'number' ? av - bv : String(av).localeCompare(String(bv));
8098
+ const d = compareSqlValues(av, bv, o.dir);
8060
8099
  if (d !== 0) return d;
8061
8100
  }
8062
8101
  return 0;
@@ -8143,18 +8182,8 @@ class SQLExecutor {
8143
8182
  };
8144
8183
  keyed.sort((a, b) => {
8145
8184
  for (const o of orderBy) {
8146
- const av = keyOf(a, o);
8147
- const bv = keyOf(b, o);
8148
- if (av === bv) continue;
8149
- const aNull = av === null || av === undefined;
8150
- const bNull = bv === null || bv === undefined;
8151
- if (aNull || bNull) {
8152
- const r = aNull && bNull ? 0 : (aNull ? -1 : 1);
8153
- return o.dir === 'desc' ? -r : r;
8154
- }
8155
- const d = typeof av === 'number' && typeof bv === 'number'
8156
- ? av - bv : String(av).localeCompare(String(bv));
8157
- if (d !== 0) return o.dir === 'desc' ? -d : d;
8185
+ const d = compareSqlValues(keyOf(a, o), keyOf(b, o), o.dir);
8186
+ if (d !== 0) return d;
8158
8187
  }
8159
8188
  return a.i - b.i;
8160
8189
  });
@@ -8237,29 +8266,42 @@ class SQLExecutor {
8237
8266
  all = [{ _virtual: true }];
8238
8267
  } else {
8239
8268
  const items = statement.from.tables.concat(statement.from.joins.map(j => j.item));
8240
- // B5 修复:自连接(同表多次出现且无别名)时,用 t1/t2 等自动别名(MySQL 惯例),
8241
- // 而非直接用表名。不同表无别名时仍用表名,保持与 SQL 查询中的表名限定一致。
8242
- const tableCount = new Map();
8269
+ // #101:自连接(同一张表在 FROM 中出现多次)时,行前缀的分配规则:
8270
+ // - 显式别名优先;
8271
+ // - 无别名的实例默认仍用**表名**作为前缀,这样 SQL 里写的 `t.col` 才能解析到;
8272
+ // - 只有当这个名字已经被前面的实例占用时,才生成 t1/t2 这类自动别名,
8273
+ // 并且跳过所有已被显式别名占用的名字。
8274
+ // 此前对「同表出现多次」一律自动别名 t1/t2,导致查询里用原表名限定的
8275
+ // `t.id` 完全解析不到(行里只有 t1.id/t2.id),JOIN ON 恒假 → INNER 空、LEFT 全 NULL。
8276
+ const autoAliasMap = new Map();
8277
+ const usedPrefixes = new Set();
8278
+ // 先把显式别名登记为保留名,自动别名不能撞上
8279
+ const reservedPrefixes = new Set();
8243
8280
  for (const item of items) {
8244
- if (item.table) {
8245
- const c = (tableCount.get(item.table) || 0) + 1;
8246
- tableCount.set(item.table, c);
8247
- }
8281
+ if (!item) continue;
8282
+ if (item.alias) reservedPrefixes.add(String(item.alias).toLowerCase());
8283
+ else if (item.subquery && item.subquery.alias) reservedPrefixes.add(String(item.subquery.alias).toLowerCase());
8248
8284
  }
8249
- const autoAliasMap = new Map();
8250
8285
  let autoIdx = 0;
8286
+ const nextAutoAlias = () => {
8287
+ let name;
8288
+ do { autoIdx++; name = `t${autoIdx}`; }
8289
+ while (reservedPrefixes.has(name.toLowerCase()) || usedPrefixes.has(name.toLowerCase()));
8290
+ return name;
8291
+ };
8251
8292
  const prefix = item => {
8252
- if (item.alias) return item.alias;
8253
- if (item.subquery) return item.subquery.alias || item.alias;
8254
- // 无别名且同表出现多次时生成 t1, t2;否则用表名
8255
- if (item.table && (tableCount.get(item.table) || 0) > 1) {
8256
- if (!autoAliasMap.has(item)) {
8257
- autoIdx++;
8258
- autoAliasMap.set(item, `t${autoIdx}`);
8259
- }
8260
- return autoAliasMap.get(item);
8261
- }
8262
- return item.table;
8293
+ if (!item) return null;
8294
+ if (autoAliasMap.has(item)) return autoAliasMap.get(item);
8295
+ let p;
8296
+ if (item.alias) p = item.alias;
8297
+ else if (item.subquery) p = item.subquery.alias || item.alias || nextAutoAlias();
8298
+ else if (item.table) {
8299
+ p = item.table;
8300
+ if (usedPrefixes.has(String(p).toLowerCase())) p = nextAutoAlias();
8301
+ } else p = nextAutoAlias();
8302
+ usedPrefixes.add(String(p).toLowerCase());
8303
+ autoAliasMap.set(item, p);
8304
+ return p;
8263
8305
  };
8264
8306
 
8265
8307
  // 读第一表
@@ -8626,13 +8668,8 @@ class SQLExecutor {
8626
8668
  };
8627
8669
  const cmp = (a, b) => {
8628
8670
  for (const o of statement.orderBy) {
8629
- const av = ordVal(a.row, o);
8630
- const bv = ordVal(b.row, o);
8631
- if (av === bv || (av === undefined && bv === undefined)) continue;
8632
- if (av === undefined || av === null) return o.dir === 'asc' ? -1 : 1;
8633
- if (bv === undefined || bv === null) return o.dir === 'asc' ? 1 : -1;
8634
- const r = typeof av === 'number' && typeof bv === 'number' ? av - bv : String(av).localeCompare(String(bv));
8635
- if (r !== 0) return o.dir === 'asc' ? r : -r;
8671
+ const r = compareSqlValues(ordVal(a.row, o), ordVal(b.row, o), o.dir);
8672
+ if (r !== 0) return r;
8636
8673
  }
8637
8674
  return 0;
8638
8675
  };
@@ -8709,14 +8746,9 @@ class SQLExecutor {
8709
8746
  const cmp = (a, b) => {
8710
8747
  for (let i = 0; i < ordKeys.length; i++) {
8711
8748
  const k = ordKeys[i];
8712
- const av = k.at(a);
8713
- const bv = k.at(b);
8714
- if (av === bv || (av === undefined && bv === undefined)) continue;
8715
- if (av === undefined || av === null) return -1 * k.dir;
8716
- if (bv === undefined || bv === null) return 1 * k.dir;
8717
- // P2-1: localeCompare 对字符串排序受 locale 影响,应使用简单字符串比较
8718
- const r = typeof av === 'number' && typeof bv === 'number' ? av - bv : (String(av) < String(bv) ? -1 : String(av) > String(bv) ? 1 : 0);
8719
- if (r !== 0) return r * k.dir;
8749
+ // P2-1: 字符串排序不走 localeCompare(受 locale 影响),统一在 compareSqlValues 里处理
8750
+ const r = compareSqlValues(k.at(a), k.at(b), k.dir === 1 ? 'asc' : 'desc');
8751
+ if (r !== 0) return r;
8720
8752
  }
8721
8753
  return 0;
8722
8754
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "jsql-neo",
3
- "version": "6.6.3",
3
+ "version": "6.6.4",
4
4
  "description": "JSQL-NEO — Rust-powered embedded database with WASM, REST API, B-Tree indexes, WAL, crash recovery",
5
5
  "main": "index.js",
6
6
  "types": "index.d.ts",
@@ -50,12 +50,12 @@
50
50
  "scripts": {
51
51
  "postinstall": "node postinstall.js",
52
52
  "build:native": "node scripts/build-native.js",
53
- "test": "node test/smoke.js && node test/result-raw.test.js && node test/native-install.test.js && node test/native-cli.test.js && node test/finalize-bigint.test.js && node test/native.test.js && node test/json-functions.test.js && node test/sql-parser.test.js && node test/readme-audit.test.js && node test/query-opt.test.js && node test/wal-recovery.test.js && node test/mysql-compat-hijack.test.js && node test/dml-constraints.test.js && node test/star-nag.test.js && node test/plugin-xql.test.js && node test/bug-regression-2.test.js && node test/issue-34-35-36.test.js && node test/issue-g4.test.js && node test/issue-38.test.js && node test/issue-39.test.js && node test/issue-40.test.js && node test/issue-44.test.js && node test/issue-45.test.js && node test/issue-46.test.js && node test/issue-47.test.js && node test/issue-48.test.js && node test/issue-50.test.js && node test/issue-51.test.js && node test/issue-52.test.js && node test/issue-53.test.js && node test/issue-54.test.js && node test/issue-55.test.js && node test/issue-56.test.js && node test/issue-57.test.js && node test/issue-58.test.js && node test/issue-59.test.js && node test/issue-60.test.js && node test/issue-63-68.test.js && node test/network-policy.test.js && node test/issue-69-70.test.js && node test/issue-71-72.test.js && node test/issue-73-76.test.js && node test/issue-77-84.test.js && node test/issue-86-99.test.js",
53
+ "test": "node test/smoke.js && node test/result-raw.test.js && node test/native-install.test.js && node test/native-cli.test.js && node test/finalize-bigint.test.js && node test/native.test.js && node test/json-functions.test.js && node test/sql-parser.test.js && node test/readme-audit.test.js && node test/query-opt.test.js && node test/wal-recovery.test.js && node test/mysql-compat-hijack.test.js && node test/dml-constraints.test.js && node test/star-nag.test.js && node test/plugin-xql.test.js && node test/bug-regression-2.test.js && node test/issue-34-35-36.test.js && node test/issue-g4.test.js && node test/issue-38.test.js && node test/issue-39.test.js && node test/issue-40.test.js && node test/issue-44.test.js && node test/issue-45.test.js && node test/issue-46.test.js && node test/issue-47.test.js && node test/issue-48.test.js && node test/issue-50.test.js && node test/issue-51.test.js && node test/issue-52.test.js && node test/issue-53.test.js && node test/issue-54.test.js && node test/issue-55.test.js && node test/issue-56.test.js && node test/issue-57.test.js && node test/issue-58.test.js && node test/issue-59.test.js && node test/issue-60.test.js && node test/issue-63-68.test.js && node test/network-policy.test.js && node test/issue-69-70.test.js && node test/issue-71-72.test.js && node test/issue-73-76.test.js && node test/issue-77-84.test.js && node test/issue-86-99.test.js && node test/issue-101-103.test.js",
54
54
  "test:parser": "node test/sql-parser.test.js",
55
55
  "test:btree": "node test/btree.test.js",
56
56
  "test:native": "node test/native.test.js",
57
57
  "test:regress": "node test/regress-5.1.0.js",
58
- "test:all": "node test/smoke.js && node test/result-raw.test.js && node test/native-install.test.js && node test/native-cli.test.js && node test/finalize-bigint.test.js && node test/sql-parser.test.js && node test/readme-audit.test.js && node test/native.test.js && node test/native-multi-instance.test.js && node test/wal-recovery.test.js && node test/mysql-compat-hijack.test.js && node test/wasm.test.js && node test/coverage.js && node test/regress-5.1.0.js && node test/join.test.js && node test/btree.test.js && node test/dml-constraints.test.js && node test/savepoint.test.js && node test/alter-table.test.js && node test/null-semantics.test.js && node test/identifier-keywords.test.js && node test/issue-34-35-36.test.js && node test/sql-semantics.test.js && node test/extra-coverage.test.js && node test/filter-compile.test.js && node test/recursive-cte.test.js && node test/index-ddl.test.js && node test/mongo-group.test.js && node test/multiprotocol.test.js && node test/issue-g4.test.js && node test/issue-38.test.js && node test/issue-39.test.js && node test/issue-40.test.js && node test/issue-44.test.js && node test/issue-45.test.js && node test/issue-46.test.js && node test/issue-47.test.js && node test/issue-48.test.js && node test/issue-50.test.js && node test/issue-51.test.js && node test/issue-52.test.js && node test/issue-53.test.js && node test/issue-54.test.js && node test/issue-55.test.js && node test/issue-56.test.js && node test/issue-57.test.js && node test/issue-58.test.js && node test/issue-59.test.js && node test/issue-60.test.js && node test/issue-63-68.test.js && node test/network-policy.test.js && node test/issue-69-70.test.js && node test/issue-71-72.test.js && node test/issue-77-84.test.js && node test/issue-86-99.test.js",
58
+ "test:all": "node test/smoke.js && node test/result-raw.test.js && node test/native-install.test.js && node test/native-cli.test.js && node test/finalize-bigint.test.js && node test/sql-parser.test.js && node test/readme-audit.test.js && node test/native.test.js && node test/native-multi-instance.test.js && node test/wal-recovery.test.js && node test/mysql-compat-hijack.test.js && node test/wasm.test.js && node test/coverage.js && node test/regress-5.1.0.js && node test/join.test.js && node test/btree.test.js && node test/dml-constraints.test.js && node test/savepoint.test.js && node test/alter-table.test.js && node test/null-semantics.test.js && node test/identifier-keywords.test.js && node test/issue-34-35-36.test.js && node test/sql-semantics.test.js && node test/extra-coverage.test.js && node test/filter-compile.test.js && node test/recursive-cte.test.js && node test/index-ddl.test.js && node test/mongo-group.test.js && node test/multiprotocol.test.js && node test/issue-g4.test.js && node test/issue-38.test.js && node test/issue-39.test.js && node test/issue-40.test.js && node test/issue-44.test.js && node test/issue-45.test.js && node test/issue-46.test.js && node test/issue-47.test.js && node test/issue-48.test.js && node test/issue-50.test.js && node test/issue-51.test.js && node test/issue-52.test.js && node test/issue-53.test.js && node test/issue-54.test.js && node test/issue-55.test.js && node test/issue-56.test.js && node test/issue-57.test.js && node test/issue-58.test.js && node test/issue-59.test.js && node test/issue-60.test.js && node test/issue-63-68.test.js && node test/network-policy.test.js && node test/issue-69-70.test.js && node test/issue-71-72.test.js && node test/issue-77-84.test.js && node test/issue-86-99.test.js && node test/issue-101-103.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",
@@ -0,0 +1,204 @@
1
+ /*
2
+ * Regression tests for issues #101 / #102 / #103.
3
+ *
4
+ * node test/issue-101-103.test.js
5
+ *
6
+ * #101 自连接:左表未起别名、SQL 里用原表名(t.col)引用列
7
+ * → INNER JOIN 必须返回匹配行,LEFT JOIN 必须保留左表行
8
+ * #102 窗口函数 PERCENT_RANK() / CUME_DIST() 此前落到 default 分支恒返回 NULL
9
+ * #103 窗口函数 ORDER BY col DESC 的 NULL 排序必须与普通 ORDER BY 一致
10
+ */
11
+ const path = require('path');
12
+
13
+ const ROOT = path.join(__dirname, '..');
14
+ const Database = require(path.join(ROOT, 'lib/database'));
15
+ const { executeSQL } = require(path.join(ROOT, 'lib/sql'));
16
+
17
+ let passed = 0, failed = 0;
18
+ function ok(name, cond, extra) {
19
+ if (cond) { passed++; console.log('[OK]', name); }
20
+ else { failed++; console.log('[FAIL]', name, extra !== undefined ? '-> ' + JSON.stringify(extra) : ''); }
21
+ }
22
+ function eq(a, b) { return JSON.stringify(a) === JSON.stringify(b); }
23
+
24
+ function near(a, b) { return typeof a === 'number' && typeof b === 'number' && Math.abs(a - b) < 1e-9; }
25
+
26
+ (async () => {
27
+ /* ===================== #101 自连接 ===================== */
28
+ {
29
+ const db = new Database(':memory:', { autoSave: false });
30
+ await executeSQL(db, 'CREATE TABLE t (id INT, v INT)');
31
+ await executeSQL(db, 'INSERT INTO t VALUES (1,10),(2,20),(3,30)');
32
+ const q = sql => executeSQL(db, sql);
33
+
34
+ let r = await q('SELECT t.id, b.id AS bid FROM t JOIN t b ON t.id = b.id ORDER BY t.id');
35
+ ok('#101 INNER 自连接(左表用原表名限定)返回匹配行',
36
+ eq(r.rows, [[1, 1], [2, 2], [3, 3]]), r.rows);
37
+
38
+ r = await q('SELECT t.id, b.id AS bid FROM t LEFT JOIN t b ON t.id = b.id ORDER BY t.id');
39
+ ok('#101 LEFT 自连接(左表用原表名限定)左表行保留且不全是 NULL',
40
+ eq(r.rows, [[1, 1], [2, 2], [3, 3]]), r.rows);
41
+
42
+ r = await q('SELECT t.id, b.v AS bv FROM t JOIN t b ON t.id = b.id - 1 ORDER BY t.id');
43
+ ok('#101 自连接 ON 条件不对称(b.id = t.id + 1)',
44
+ eq(r.rows, [[1, 20], [2, 30]]), r.rows);
45
+
46
+ r = await q('SELECT t.id, b.id AS bid FROM t LEFT JOIN t b ON t.id = b.id - 1 ORDER BY t.id');
47
+ ok('#101 LEFT 自连接存在未匹配行时右侧补 NULL',
48
+ eq(r.rows, [[1, 2], [2, 3], [3, null]]), r.rows);
49
+
50
+ // 双侧显式别名仍然正常
51
+ r = await q('SELECT a.id, b.id AS bid FROM t a JOIN t b ON a.id = b.id ORDER BY a.id');
52
+ ok('#101 双侧都起别名不受影响', eq(r.rows, [[1, 1], [2, 2], [3, 3]]), r.rows);
53
+
54
+ // 左表别名 + 右表原表名
55
+ r = await q('SELECT a.id, t.id AS tid FROM t a JOIN t ON a.id = t.id ORDER BY a.id');
56
+ ok('#101 左表别名 + 右表用原表名', eq(r.rows, [[1, 1], [2, 2], [3, 3]]), r.rows);
57
+
58
+ // 同名表三实例:第一实例用表名,后面用自动别名
59
+ r = await q('SELECT t.id FROM t JOIN t b ON t.id = b.id JOIN t c ON t.id = c.id ORDER BY t.id');
60
+ ok('#101 三个自连接实例', eq(r.rows, [[1], [2], [3]]), r.rows);
61
+
62
+ // 非自连接的表名限定引用不该受影响
63
+ await executeSQL(db, 'CREATE TABLE u (id INT, t_id INT)');
64
+ await executeSQL(db, 'INSERT INTO u VALUES (7,2),(8,3)');
65
+ r = await q('SELECT t.id, u.id AS uid FROM t JOIN u ON u.t_id = t.id ORDER BY t.id');
66
+ ok('#101 普通 JOIN 不受影响', eq(r.rows, [[2, 7], [3, 8]]), r.rows);
67
+ }
68
+
69
+ /* ===================== #102 PERCENT_RANK / CUME_DIST ===================== */
70
+ {
71
+ const db = new Database(':memory:', { autoSave: false });
72
+ await executeSQL(db, 'CREATE TABLE w (id INT, g TEXT, v INT)');
73
+ await executeSQL(db, "INSERT INTO w VALUES (1,'a',10),(2,'a',20),(3,'a',20),(4,'a',30),(5,'b',5)");
74
+ const q = sql => executeSQL(db, sql);
75
+
76
+ let r = await q("SELECT id, PERCENT_RANK() OVER (PARTITION BY g ORDER BY v) AS pr FROM w WHERE g='a' ORDER BY id");
77
+ ok('#102 PERCENT_RANK 含并列值',
78
+ eq(r.rows, [[1, 0], [2, 1 / 3], [3, 1 / 3], [4, 1]]), r.rows);
79
+
80
+ r = await q("SELECT id, CUME_DIST() OVER (PARTITION BY g ORDER BY v) AS cd FROM w WHERE g='a' ORDER BY id");
81
+ ok('#102 CUME_DIST 含并列值',
82
+ eq(r.rows, [[1, 0.25], [2, 0.75], [3, 0.75], [4, 1]]), r.rows);
83
+
84
+ // 多分区
85
+ r = await q('SELECT id, PERCENT_RANK() OVER (PARTITION BY g ORDER BY v) AS pr FROM w ORDER BY g, id');
86
+ ok('#102 PERCENT_RANK 多分区(b 分区单行 → 0)',
87
+ eq(r.rows, [[1, 0], [2, 1 / 3], [3, 1 / 3], [4, 1], [5, 0]]), r.rows);
88
+
89
+ r = await q('SELECT id, CUME_DIST() OVER (PARTITION BY g ORDER BY v) AS cd FROM w ORDER BY g, id');
90
+ ok('#102 CUME_DIST 多分区(b 分区单行 → 1)',
91
+ eq(r.rows, [[1, 0.25], [2, 0.75], [3, 0.75], [4, 1], [5, 1]]), r.rows);
92
+
93
+ // 单行分区
94
+ await executeSQL(db, 'CREATE TABLE s1 (id INT, v INT)');
95
+ await executeSQL(db, 'INSERT INTO s1 VALUES (1, 42)');
96
+ r = await q('SELECT PERCENT_RANK() OVER (ORDER BY v) AS pr, CUME_DIST() OVER (ORDER BY v) AS cd FROM s1');
97
+ ok('#102 单行分区:PERCENT_RANK=0,CUME_DIST=1(无除零)',
98
+ eq(r.rows, [[0, 1]]), r.rows);
99
+
100
+ // 全同值
101
+ await executeSQL(db, 'CREATE TABLE same (id INT, v INT)');
102
+ await executeSQL(db, 'INSERT INTO same VALUES (1,5),(2,5),(3,5)');
103
+ r = await q('SELECT id, PERCENT_RANK() OVER (ORDER BY v) AS pr, CUME_DIST() OVER (ORDER BY v) AS cd FROM same ORDER BY id');
104
+ ok('#102 全同值:PERCENT_RANK 全 0,CUME_DIST 全 1',
105
+ eq(r.rows, [[1, 0, 1], [2, 0, 1], [3, 0, 1]]), r.rows);
106
+
107
+ // 乱序插入
108
+ await executeSQL(db, 'CREATE TABLE unsorted (id INT, v INT)');
109
+ await executeSQL(db, 'INSERT INTO unsorted VALUES (1,30),(2,10),(3,20),(4,40)');
110
+ r = await q('SELECT id, PERCENT_RANK() OVER (ORDER BY v) AS pr, CUME_DIST() OVER (ORDER BY v) AS cd FROM unsorted ORDER BY id');
111
+ ok('#102 乱序插入',
112
+ eq(r.rows, [[1, 2 / 3, 0.75], [2, 0, 0.25], [3, 1 / 3, 0.5], [4, 1, 1]]), r.rows);
113
+
114
+ // NULL 值(NULL 属于同一 peer 组;ASC 时 NULL 排最前)
115
+ await executeSQL(db, 'CREATE TABLE withnull (id INT, v INT)');
116
+ await executeSQL(db, 'INSERT INTO withnull VALUES (1,NULL),(2,10),(3,NULL),(4,20)');
117
+ r = await q('SELECT id, PERCENT_RANK() OVER (ORDER BY v) AS pr, CUME_DIST() OVER (ORDER BY v) AS cd FROM withnull ORDER BY id');
118
+ ok('#102 含 NULL:NULL 视为同一组,ASC 排最前',
119
+ eq(r.rows, [[1, 0, 0.5], [2, 2 / 3, 0.75], [3, 0, 0.5], [4, 1, 1]]), r.rows);
120
+
121
+ // 无 ORDER BY:全部互为 peer
122
+ r = await q('SELECT id, PERCENT_RANK() OVER () AS pr, CUME_DIST() OVER () AS cd FROM unsorted ORDER BY id');
123
+ ok('#102 无 ORDER BY:PERCENT_RANK=0 / CUME_DIST=1',
124
+ eq(r.rows, [[1, 0, 1], [2, 0, 1], [3, 0, 1], [4, 0, 1]]), r.rows);
125
+
126
+ // 与 RANK 的一致性:PR = (RANK-1)/(n-1)
127
+ r = await q('SELECT id, RANK() OVER (ORDER BY v) AS rk, PERCENT_RANK() OVER (ORDER BY v) AS pr FROM unsorted ORDER BY id');
128
+ ok('#102 PERCENT_RANK == (RANK-1)/(n-1)',
129
+ r.rows.every(([, rk, pr]) => near(pr, (rk - 1) / 3)), r.rows);
130
+ }
131
+
132
+ /* ===================== #103 窗口 ORDER BY DESC 的 NULL 排序 ===================== */
133
+ {
134
+ const db = new Database(':memory:', { autoSave: false });
135
+ await executeSQL(db, 'CREATE TABLE n (id INT, v INT)');
136
+ await executeSQL(db, 'INSERT INTO n VALUES (1,10),(2,NULL),(3,30),(4,NULL),(5,20)');
137
+ const q = sql => executeSQL(db, sql);
138
+
139
+ // 普通 ORDER BY 的基准行为:ASC → NULL 最前;DESC → NULL 最后
140
+ let r = await q('SELECT id, v FROM n ORDER BY v ASC, id');
141
+ ok('#103 基线:普通 ORDER BY ASC NULL 在前',
142
+ eq(r.rows, [[2, null], [4, null], [1, 10], [5, 20], [3, 30]]), r.rows);
143
+
144
+ r = await q('SELECT id, v FROM n ORDER BY v DESC, id');
145
+ ok('#103 基线:普通 ORDER BY DESC NULL 在后',
146
+ eq(r.rows, [[3, 30], [5, 20], [1, 10], [2, null], [4, null]]), r.rows);
147
+
148
+ // ROW_NUMBER:DESC 时 NULL 应拿最后的名次
149
+ r = await q('SELECT id, ROW_NUMBER() OVER (ORDER BY v DESC, id) AS rn FROM n ORDER BY id');
150
+ ok('#103 ROW_NUMBER OVER (ORDER BY v DESC) NULL 拿到最后名次',
151
+ eq(r.rows, [[1, 3], [2, 4], [3, 1], [4, 5], [5, 2]]), r.rows);
152
+
153
+ r = await q('SELECT id, ROW_NUMBER() OVER (ORDER BY v ASC, id) AS rn FROM n ORDER BY id');
154
+ ok('#103 ROW_NUMBER OVER (ORDER BY v ASC) NULL 拿到最前名次',
155
+ eq(r.rows, [[1, 3], [2, 1], [3, 5], [4, 2], [5, 4]]), r.rows);
156
+
157
+ // LAG / LEAD 跟随同一排序
158
+ r = await q('SELECT id, LAG(v) OVER (ORDER BY v DESC) AS lg FROM n ORDER BY id');
159
+ ok('#103 LAG OVER (ORDER BY v DESC) 与普通 DESC 顺序一致',
160
+ eq(r.rows, [[1, 20], [2, 10], [3, null], [4, null], [5, 30]]), r.rows);
161
+
162
+ r = await q('SELECT id, LEAD(v) OVER (ORDER BY v DESC) AS ld FROM n ORDER BY id');
163
+ ok('#103 LEAD OVER (ORDER BY v DESC) 与普通 DESC 顺序一致',
164
+ eq(r.rows, [[1, null], [2, null], [3, 20], [4, null], [5, 10]]), r.rows);
165
+
166
+ // RANK / DENSE_RANK:两个 NULL 并列,且排在最后
167
+ r = await q('SELECT id, RANK() OVER (ORDER BY v DESC) AS rk, DENSE_RANK() OVER (ORDER BY v DESC) AS dr FROM n ORDER BY id');
168
+ ok('#103 RANK/DENSE_RANK DESC:NULL 并列且排在最后',
169
+ eq(r.rows, [[1, 3, 3], [2, 4, 4], [3, 1, 1], [4, 4, 4], [5, 2, 2]]), r.rows);
170
+
171
+ r = await q('SELECT id, RANK() OVER (ORDER BY v ASC) AS rk, DENSE_RANK() OVER (ORDER BY v ASC) AS dr FROM n ORDER BY id');
172
+ ok('#103 RANK/DENSE_RANK ASC:NULL 并列且排在最前',
173
+ eq(r.rows, [[1, 3, 2], [2, 1, 1], [3, 5, 4], [4, 1, 1], [5, 4, 3]]), r.rows);
174
+
175
+ // 累计帧(SUM OVER ORDER BY DESC)也要走同一排序
176
+ r = await q('SELECT id, SUM(v) OVER (ORDER BY v DESC ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) AS s FROM n ORDER BY id');
177
+ ok('#103 SUM OVER (ORDER BY v DESC) 累计帧:NULL 在最后且被 SUM 忽略',
178
+ eq(r.rows, [[1, 60], [2, 60], [3, 30], [4, 60], [5, 50]]), r.rows);
179
+
180
+ // 多分区 + DESC + NULL
181
+ await executeSQL(db, 'CREATE TABLE p (id INT, g TEXT, v INT)');
182
+ await executeSQL(db, "INSERT INTO p VALUES (1,'a',10),(2,'a',NULL),(3,'b',20),(4,'b',NULL),(5,'b',30)");
183
+ r = await q('SELECT id, ROW_NUMBER() OVER (PARTITION BY g ORDER BY v DESC, id) AS rn FROM p ORDER BY id');
184
+ ok('#103 PARTITION BY + DESC:每个分区内 NULL 都排最后',
185
+ eq(r.rows, [[1, 1], [2, 2], [3, 2], [4, 3], [5, 1]]), r.rows);
186
+
187
+ // NULL 在首/中/尾三种位置都覆盖
188
+ await executeSQL(db, 'CREATE TABLE mix (id INT, v INT)');
189
+ await executeSQL(db, 'INSERT INTO mix VALUES (1,NULL),(2,5),(3,NULL),(4,10),(5,NULL)');
190
+ r = await q('SELECT id, ROW_NUMBER() OVER (ORDER BY v DESC, id) AS rn FROM mix ORDER BY id');
191
+ ok('#103 NULL 在首/中/尾:DESC 时全部聚在尾部',
192
+ eq(r.rows, [[1, 3], [2, 2], [3, 4], [4, 1], [5, 5]]), r.rows);
193
+
194
+ r = await q('SELECT id, ROW_NUMBER() OVER (ORDER BY v ASC, id) AS rn FROM mix ORDER BY id');
195
+ ok('#103 NULL 在首/中/尾:ASC 时全部聚在头部',
196
+ eq(r.rows, [[1, 1], [2, 4], [3, 2], [4, 5], [5, 3]]), r.rows);
197
+ }
198
+
199
+ console.log(`\n${passed} passed, ${failed} failed`);
200
+ process.exit(failed === 0 ? 0 : 1);
201
+ })().catch(e => {
202
+ console.error('[FATAL]', e && e.stack || e);
203
+ process.exit(1);
204
+ });