jsql-neo 6.6.6 → 6.7.0-beta.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
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.6** — stable release · [github.com/vexify-org/JSQL-neo](https://github.com/vexify-org/JSQL-neo) · [jsql.vexify.top](https://jsql.vexify.top)
6
+ > **v6.7.0-beta.2** — beta 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)
@@ -210,6 +210,21 @@ Full reference: [doc/sql-reference.md](doc/sql-reference.md).
210
210
  `JSON_TYPE` / `JSON_DEPTH` follow **this project's** documented semantics
211
211
  (lowercase type names, flat object depth 1), not MySQL's. See the SQL reference.
212
212
 
213
+ ## Columnar storage (one-shot convert)
214
+
215
+ ```js
216
+ db.convertToColumnar('events'); // split each column into its own array
217
+ db.convertToRow('events'); // back to row storage
218
+ ```
219
+
220
+ A **derived in-memory view**, not an on-disk format: any write invalidates it
221
+ (reads fall back to row storage), so the two can never disagree. Aggregates and
222
+ single-column `GROUP BY` scan the column arrays directly (no row objects).
223
+
224
+ Point queries measure **2.7–6.5x faster than DuckDB**; aggregation is now
225
+ **2–8x slower** (it was 36–70x before the vectorized column path). Still behind —
226
+ not claimed otherwise. Honest numbers: [doc/columnar.md](doc/columnar.md).
227
+
213
228
  ## ✨ XQL 集成
214
229
 
215
230
  用 [XQL](https://github.com/vexify-org/XQL) 查询 JSQL 表:把 SQL 直接接到文档上,
package/index.js CHANGED
@@ -1,5 +1,5 @@
1
1
  /**
2
- * JSQL-NEO v6.6.6 — Rust-Powered Embedded Database (WASM + HTTP)
2
+ * JSQL-NEO v6.7.0-beta.2 — Rust-Powered Embedded Database (WASM + HTTP)
3
3
  *
4
4
  * @example
5
5
  * const jsql = require('jsql-neo');
@@ -0,0 +1,262 @@
1
+ 'use strict';
2
+ /**
3
+ * 列存的向量化快路径 —— 纯函数,不依赖 SQLExecutor,便于单测。
4
+ *
5
+ * 输入是 `Table._columnar`({ names, cols: Map<col, array[]>, rowCount }),
6
+ * 输出是 SELECT 结果骨架;返回 null 表示「这条查询不适用快路径」,
7
+ * 由调用方走通用行路径。
8
+ */
9
+
10
+ /** AST 节点 → 列名;非简单列引用返回 null。 */
11
+ function colNameOf(node) {
12
+ if (!node) return null;
13
+ if (typeof node === 'string') return node;
14
+ return node.type === 'column' ? node.name : null;
15
+ }
16
+
17
+ /**
18
+ * 把 WHERE 编译成「命中行下标数组」。
19
+ * 只支持 `列 OP 字面量` 以及它们的 AND 组合;其它(OR / LIKE / 函数 / 子查询 /
20
+ * 列与列比较)一律返回 null,交给通用路径 —— 宁可慢,不可错。
21
+ */
22
+ function whereIndices(statement, data) {
23
+ const w = statement.where;
24
+ if (!w) return null;
25
+ const build = (node) => {
26
+ if (!node) return null;
27
+ if (node.type === 'and') {
28
+ const l = build(node.left), r = build(node.right);
29
+ if (!l || !r) return null;
30
+ return { and: [l, r] };
31
+ }
32
+ if (node.type === 'or') {
33
+ const l = build(node.left), r = build(node.right);
34
+ if (!l || !r) return null;
35
+ return { or: [l, r] };
36
+ }
37
+ if (node.type === 'compare') {
38
+ const col = colNameOf(node.left);
39
+ if (!col || !node.right || node.right.type !== 'value') return null;
40
+ const arr = data.cols.get(col);
41
+ if (!arr) return null;
42
+ return { arr, op: node.op, val: node.right.value };
43
+ }
44
+ return null;
45
+ };
46
+ const root = build(w);
47
+ if (!root) return null;
48
+
49
+ const n = data.rowCount;
50
+ const idx = new Uint32Array(n);
51
+ let m = 0;
52
+ const test = (x, op, v) => {
53
+ switch (op) {
54
+ case '=': return x === v;
55
+ case '!=': case '<>': return x !== v;
56
+ case '>': return x > v;
57
+ case '>=': return x >= v;
58
+ case '<': return x < v;
59
+ case '<=': return x <= v;
60
+ default: return false;
61
+ }
62
+ };
63
+ const hit = (node, i) => {
64
+ if (node.and) return hit(node.and[0], i) && hit(node.and[1], i);
65
+ if (node.or) return hit(node.or[0], i) || hit(node.or[1], i);
66
+ return test(node.arr[i], node.op, node.val);
67
+ };
68
+ for (let i = 0; i < n; i++) if (hit(root, i)) idx[m++] = i;
69
+ return idx.subarray(0, m);
70
+ }
71
+
72
+ /**
73
+ * 纯聚合(无 GROUP BY / HAVING / DISTINCT / LIMIT)。
74
+ * 直接扫列数组,不构造任何行对象。
75
+ */
76
+ function aggregate(statement, data) {
77
+ const cols = statement.columns || [];
78
+ if (!cols.length) return null;
79
+ if (statement.groupBy || statement.having || statement.distinct) return null;
80
+ if (statement.limit != null && statement.limit !== Infinity) return null;
81
+
82
+ const indices = statement.where ? whereIndices(statement, data) : null;
83
+ if (statement.where && !indices) return null;
84
+ const scanLen = indices ? indices.length : data.rowCount;
85
+ const at = (k) => (indices ? indices[k] : k);
86
+
87
+ const outRow = [];
88
+ const outCols = [];
89
+ for (const c of cols) {
90
+ if (!c || !c.aggregate) return null;
91
+ // COUNT(DISTINCT x) / SUM(DISTINCT x) 需要去重,快路径不实现 → 退回通用路径。
92
+ // 漏这条会让 COUNT(DISTINCT age) 直接返回行数(静默错值)。
93
+ if (c.distinct) return null;
94
+ const fn = String(c.aggregate).toUpperCase();
95
+ const argNode = c.column;
96
+ const argName = colNameOf(argNode);
97
+ if (argNode != null && !argName) return null;
98
+ const values = argName ? data.cols.get(argName) : null;
99
+ if (argName && !values) return null;
100
+
101
+ let v;
102
+ switch (fn) {
103
+ case 'COUNT': {
104
+ if (!argName) { v = scanLen; break; }
105
+ let n = 0;
106
+ for (let k = 0; k < scanLen; k++) {
107
+ const x = values[at(k)];
108
+ if (x !== null && x !== undefined) n++;
109
+ }
110
+ v = n;
111
+ break;
112
+ }
113
+ case 'SUM': {
114
+ let s = 0, seen = false;
115
+ for (let k = 0; k < scanLen; k++) {
116
+ const x = values[at(k)];
117
+ if (x === null || x === undefined) continue;
118
+ if (typeof x !== 'number') return null; // BigInt 等 → 通用路径
119
+ s += x; seen = true;
120
+ }
121
+ v = seen ? s : null;
122
+ break;
123
+ }
124
+ case 'AVG': {
125
+ let s = 0, n = 0;
126
+ for (let k = 0; k < scanLen; k++) {
127
+ const x = values[at(k)];
128
+ if (x === null || x === undefined) continue;
129
+ if (typeof x !== 'number') return null;
130
+ s += x; n++;
131
+ }
132
+ v = n ? s / n : null;
133
+ break;
134
+ }
135
+ case 'MIN': case 'MAX': {
136
+ let best, seen = false;
137
+ for (let k = 0; k < scanLen; k++) {
138
+ const x = values[at(k)];
139
+ if (x === null || x === undefined) continue;
140
+ if (typeof x !== 'number' && typeof x !== 'string') return null;
141
+ if (!seen) { best = x; seen = true; }
142
+ else if (fn === 'MIN' ? x < best : x > best) best = x;
143
+ }
144
+ v = seen ? best : null;
145
+ break;
146
+ }
147
+ default: return null;
148
+ }
149
+ outRow.push(v);
150
+ outCols.push(c.alias || (fn + '()'));
151
+ }
152
+ return { type: 'select', columns: outCols, rows: [outRow] };
153
+ }
154
+
155
+ /**
156
+ * 单列 GROUP BY + 聚合。
157
+ *
158
+ * 条件:GROUP BY 恰好一列、投影 = 该分组列 + COUNT/SUM/AVG/MIN/MAX、
159
+ * 无 HAVING / DISTINCT / LIMIT。命中时扫一遍分组列建桶,再输出每组的聚合值,
160
+ * 全程不构造行对象。
161
+ *
162
+ * 注意输出顺序是「分组值首次出现的顺序」,不保证与通用路径一致 ——
163
+ * 需要确定性顺序请加 ORDER BY(那样会退回通用路径)。
164
+ */
165
+ function groupBy(statement, data) {
166
+ const g = statement.groupBy;
167
+ if (!Array.isArray(g) || !g.length) return null;
168
+ if (statement.having || statement.distinct) return null;
169
+ if (statement.limit != null) return null;
170
+ const gNames = g.map(colNameOf);
171
+ if (gNames.some(n => !n)) return null;
172
+ const keyArrs = gNames.map(n => data.cols.get(n));
173
+ if (keyArrs.some(a => !a)) return null;
174
+
175
+ const cols = statement.columns || [];
176
+ if (!cols.length) return null;
177
+ const aggs = [];
178
+ let sawGroupCol = false;
179
+ for (const c of cols) {
180
+ if (c && c.aggregate) {
181
+ // 同 aggregate:DISTINCT 聚合不适用快路径
182
+ if (c.distinct) return null;
183
+ const fn = String(c.aggregate).toUpperCase();
184
+ if (!['COUNT', 'SUM', 'AVG', 'MIN', 'MAX'].includes(fn)) return null;
185
+ const argName = colNameOf(c.column);
186
+ if (c.column != null && !argName) return null;
187
+ const arr = argName ? data.cols.get(argName) : null;
188
+ if (argName && !arr) return null;
189
+ aggs.push({ c, fn, argName, arr });
190
+ continue;
191
+ }
192
+ const n = colNameOf(c && (c.scalar || c.expr));
193
+ if (!gNames.includes(n)) return null;
194
+ sawGroupCol = true;
195
+ }
196
+ if (!sawGroupCol) return null;
197
+
198
+ const indices = statement.where ? whereIndices(statement, data) : null;
199
+ if (statement.where && !indices) return null;
200
+ const scanLen = indices ? indices.length : data.rowCount;
201
+ const at = (k) => (indices ? indices[k] : k);
202
+
203
+ // 分组的键多数是数字或短字符串,用 Map 即可;每组一个累加器数组。
204
+ const groups = new Map();
205
+ const nKeys = keyArrs.length;
206
+ for (let k = 0; k < scanLen; k++) {
207
+ const i = at(k);
208
+ // 多列分组键:用 \u0000 拼接(SQL 字符串列不会包含 NUL),Map 里只存这个串。
209
+ let ck = '';
210
+ for (let q = 0; q < nKeys; q++) ck += (q ? '\u0000' : '') + String(keyArrs[q][i]);
211
+ let entry = groups.get(ck);
212
+ if (!entry) {
213
+ entry = {
214
+ keyVals: keyArrs.map(a => a[i]),
215
+ acc: aggs.map(() => ({ n: 0, s: 0, best: undefined, seen: false })),
216
+ };
217
+ groups.set(ck, entry);
218
+ }
219
+ const acc = entry.acc;
220
+ for (let j = 0; j < aggs.length; j++) {
221
+ const a = aggs[j], st = acc[j];
222
+ if (a.fn === 'COUNT') {
223
+ if (!a.argName) { st.n++; continue; }
224
+ const x = a.arr[i];
225
+ if (x !== null && x !== undefined) st.n++;
226
+ continue;
227
+ }
228
+ const x = a.arr[i];
229
+ if (x === null || x === undefined) continue;
230
+ if (typeof x !== 'number') return null; // BigInt 等 → 通用路径
231
+ st.n++; st.s += x;
232
+ if (!st.seen) { st.best = x; st.seen = true; }
233
+ else if (a.fn === 'MIN' ? x < st.best : x > st.best) st.best = x;
234
+ }
235
+ }
236
+
237
+ const outRows = [];
238
+ for (const [, entry] of groups) {
239
+ const row = [];
240
+ for (const c of cols) {
241
+ if (c.aggregate) {
242
+ const j = aggs.findIndex(a => a.c === c);
243
+ const st = entry.acc[j];
244
+ const fn = String(c.aggregate).toUpperCase();
245
+ if (fn === 'COUNT') row.push(st.n);
246
+ else if (fn === 'SUM') row.push(st.seen ? st.s : null);
247
+ else if (fn === 'AVG') row.push(st.n ? st.s / st.n : null);
248
+ else row.push(st.seen ? st.best : null);
249
+ } else {
250
+ const n = colNameOf(c.scalar || c.expr);
251
+ row.push(entry.keyVals[gNames.indexOf(n)]);
252
+ }
253
+ }
254
+ outRows.push(row);
255
+ }
256
+ const outCols = cols.map(c => c.alias || (c.aggregate
257
+ ? String(c.aggregate).toUpperCase() + '()'
258
+ : colNameOf(c.scalar || c.expr)));
259
+ return { type: 'select', columns: outCols, rows: outRows };
260
+ }
261
+
262
+ module.exports = { colNameOf, whereIndices, aggregate, groupBy };
package/lib/database.js CHANGED
@@ -1869,6 +1869,27 @@ class Database {
1869
1869
  return rows;
1870
1870
  }
1871
1871
 
1872
+ /**
1873
+ * 一键把表转成列存(按字段拆成「每列一个数组」)。
1874
+ *
1875
+ * 适合「批量导入 → 转换 → 反复扫描/聚合」的读多写少场景。
1876
+ * `_rows` 始终是权威数据;列存是查询用的派生缓存,任何写入都会让它
1877
+ * 失效(下次读取自动回到行存路径),因此不会出现两份数据不一致。
1878
+ * 需要重新转换后可再次调用。
1879
+ */
1880
+ convertToColumnar(tableName) {
1881
+ const table = this._ensureTable(tableName);
1882
+ if (!table) throw createError('ER_NO_SUCH_TABLE', tableName);
1883
+ return table.toColumnar();
1884
+ }
1885
+
1886
+ /** 把表转回行存(丢弃列存缓存)。 */
1887
+ convertToRow(tableName) {
1888
+ const table = this._ensureTable(tableName);
1889
+ if (!table) throw createError('ER_NO_SUCH_TABLE', tableName);
1890
+ return table.toRow();
1891
+ }
1892
+
1872
1893
  exists(tableName, filter = {}) {
1873
1894
  const table = this._ensureTable(tableName);
1874
1895
  if (!table) throw createError('ER_NO_SUCH_TABLE', tableName);
package/lib/sql.js CHANGED
@@ -4741,13 +4741,15 @@ function applyScalarFunction(fnNode, row, ctx) {
4741
4741
  // ===== JSON 函数(B2 修复:此前未实现,静默返回 NULL)=====
4742
4742
  // 辅助函数:获取 JSON 值的类型
4743
4743
  function getJsonType(val) {
4744
- if (val === null) return 'null';
4745
- if (Array.isArray(val)) return 'array';
4746
- if (typeof val === 'object') return 'object';
4747
- if (typeof val === 'string') return 'string';
4748
- if (typeof val === 'number') return Number.isInteger(val) ? 'integer' : 'number';
4749
- if (typeof val === 'boolean') return 'boolean';
4750
- return 'unknown';
4744
+ // MySQL 8.0 的 JSON_TYPE 返回**大写**类型名,且数字区分 INTEGER / DOUBLE
4745
+ // (此前返回小写、数字统一 'number',与 MySQL 不一致)。
4746
+ if (val === null) return 'NULL';
4747
+ if (Array.isArray(val)) return 'ARRAY';
4748
+ if (typeof val === 'object') return 'OBJECT';
4749
+ if (typeof val === 'string') return 'STRING';
4750
+ if (typeof val === 'number') return Number.isInteger(val) ? 'INTEGER' : 'DOUBLE';
4751
+ if (typeof val === 'boolean') return 'BOOLEAN';
4752
+ return 'UNKNOWN';
4751
4753
  }
4752
4754
  case 'JSON_OBJECT': {
4753
4755
  // JSON_OBJECT(k1, v1, k2, v2, ...) → { k1: v1, k2: v2 }
@@ -5075,24 +5077,24 @@ function applyScalarFunction(fnNode, row, ctx) {
5075
5077
  if (typeof json === 'string') {
5076
5078
  try { data = JSON.parse(json); } catch (e) { return null; }
5077
5079
  }
5080
+ // MySQL 8.0 的 JSON_DEPTH 口径:
5081
+ // 标量 / 空容器 → 1
5082
+ // 非空、元素全是标量 → 2
5083
+ // 含非标量元素 → 3 起(每深一层 +1)
5084
+ // 此前把 flat object 算成 1,与 MySQL 不一致。
5085
+ // 用显式栈迭代,避免深 JSON 爆栈。
5078
5086
  function depth(obj) {
5079
- if (typeof obj !== 'object' || obj === null) return 0;
5080
- let max = 0;
5087
+ if (obj === null || typeof obj !== 'object') return 1;
5088
+ let max = 1;
5081
5089
  const stack = [{ o: obj, d: 1 }];
5082
5090
  while (stack.length) {
5083
5091
  const { o, d } = stack.pop();
5084
- if (typeof o !== 'object' || o === null) continue;
5085
- if (d > max) max = d;
5086
- if (Array.isArray(o)) {
5087
- for (const x of o) {
5088
- if (x && typeof x === 'object') stack.push({ o: x, d: d + 1 });
5089
- }
5090
- } else {
5091
- const ks = Object.keys(o);
5092
- for (const k of ks) {
5093
- const x = o[k];
5094
- if (x && typeof x === 'object') stack.push({ o: x, d: d + 1 });
5095
- }
5092
+ if (o === null || typeof o !== 'object') continue;
5093
+ const values = Array.isArray(o) ? o : Object.keys(o).map(k => o[k]);
5094
+ const cur = values.length === 0 ? d : d + 1;
5095
+ if (cur > max) max = cur;
5096
+ for (const x of values) {
5097
+ if (x !== null && typeof x === 'object') stack.push({ o: x, d: cur });
5096
5098
  }
5097
5099
  }
5098
5100
  return max;
@@ -6978,8 +6980,121 @@ class SQLExecutor {
6978
6980
  return out;
6979
6981
  }
6980
6982
 
6983
+ /**
6984
+ * 能否把 SQL 的 LIMIT/OFFSET 下推给存储层?
6985
+ *
6986
+ * 只有「单表、无 WHERE / JOIN / GROUP BY / HAVING / ORDER BY / DISTINCT、
6987
+ * 投影里没有聚合或窗口函数」时,前 (offset + limit) 行正好就是最终要的前几行,
6988
+ * 可以只让存储层返回这些行,而不是把全表读回内存再切。
6989
+ *
6990
+ * 任一条不满足就返回 null,退回原来的「全表读回再加工」路径 —— 保守优先,
6991
+ * 下推错误是静默错行,比慢几十毫秒严重得多。
6992
+ */
6993
+ _pushdownLimitCap(statement) {
6994
+ if (!statement || typeof statement.limit !== 'number') return null;
6995
+ if (statement.limit <= 0) return null; // find(limit:0) 会返回全表,不能这么传
6996
+ if (statement.where || statement.groupBy || statement.having || statement.orderBy) return null;
6997
+ if (statement.distinct) return null;
6998
+ const from = statement.from;
6999
+ if (!from || !Array.isArray(from.tables) || from.tables.length !== 1) return null;
7000
+ if (Array.isArray(from.joins) && from.joins.length) return null;
7001
+ const t = from.tables[0];
7002
+ if (!t || t.subquery || t._virtualRows) return null;
7003
+ const cols = statement.columns || [];
7004
+ if (cols.some(c => c && (c.aggregate || c.over || (c.scalar && c.scalar.over)))) return null;
7005
+ const cap = statement.limit + (Number(statement.offset) || 0);
7006
+ return Number.isFinite(cap) && cap > 0 ? cap : null;
7007
+ }
7008
+
7009
+ /**
7010
+ * 纯聚合的列存向量化快路径(JS 版「按列扫」)。
7011
+ *
7012
+ * 适用:单表、已转列存、无 WHERE / JOIN / GROUP BY / HAVING / DISTINCT /
7013
+ * LIMIT,投影全部是 COUNT / SUM / AVG / MIN / MAX。命中时**完全不构造行对象**,
7014
+ * 直接遍历列数组 —— 10 万行 SUM 从 ~27ms 降到扫一个数字数组。
7015
+ *
7016
+ * 返回 null 表示不适用(调用方走通用路径)。遇到 BigInt 值也返回 null,
7017
+ * 避免与 number 混算丢精度。
7018
+ */
7019
+ _columnarAggregate(statement) {
7020
+ const from = statement.from;
7021
+ if (!from || !Array.isArray(from.tables) || from.tables.length !== 1) return null;
7022
+ if (Array.isArray(from.joins) && from.joins.length) return null;
7023
+ const t = from.tables[0];
7024
+ if (!t || !t.table) return null;
7025
+ const tbl = this.engine && this.engine._tables ? this.engine._tables[t.table] : null;
7026
+ if (!tbl || typeof tbl.isColumnar !== 'function' || !tbl.isColumnar()) return null;
7027
+ // 扫描逻辑在 lib/columnar_fast.js(纯函数、可单测)。返回 null 表示不适用
7028
+ // (含 BigInt / 非简单列 / OR、LIKE 等),由调用方走通用行路径。
7029
+ const r = require('./columnar_fast').aggregate(statement, tbl._columnar);
7030
+ return r ? { ok: true, columns: r.columns, rows: r.rows, raw: r.rows } : null;
7031
+ }
7032
+
7033
+ /** 单列 GROUP BY 的列存快路径(委派给 lib/columnar_fast.js)。 */
7034
+ _columnarGroupBy(statement) {
7035
+ if (!statement.groupBy) return null;
7036
+ const from = statement.from;
7037
+ if (!from || !Array.isArray(from.tables) || from.tables.length !== 1) return null;
7038
+ if (Array.isArray(from.joins) && from.joins.length) return null;
7039
+ const t = from.tables[0];
7040
+ if (!t || !t.table) return null;
7041
+ const tbl = this.engine && this.engine._tables ? this.engine._tables[t.table] : null;
7042
+ if (!tbl || typeof tbl.isColumnar !== 'function' || !tbl.isColumnar()) return null;
7043
+ const r = require('./columnar_fast').groupBy(statement, tbl._columnar);
7044
+ return r ? { ok: true, columns: r.columns, rows: r.rows, raw: r.rows } : null;
7045
+ }
7046
+
7047
+ /**
7048
+ * 从投影列表里提取「简单列引用」的列名。
7049
+ * 含任何表达式 / 聚合 / 窗口 / 字面量就返回 null(走通用路径);`SELECT *` 返回 '*'。
7050
+ */
7051
+ _columnarColumns(statement) {
7052
+ const cols = statement.columns || [];
7053
+ if (cols.length === 1 && cols[0] && cols[0].expr === '*') return '*';
7054
+ const names = [];
7055
+ for (const c of cols) {
7056
+ if (!c || c.aggregate || c.over || c.caseExpr || c.literal !== undefined) return null;
7057
+ if (!c.scalar || c.scalar.type !== 'column' || !c.scalar.name) return null;
7058
+ names.push(c.scalar.name);
7059
+ }
7060
+ return names.length ? names : null;
7061
+ }
7062
+
6981
7063
  async _readTable(table, statement, alias) {
6982
7064
  const schema = await this._getSchema(table);
7065
+
7066
+ // ---- 列存快路径 ----
7067
+ // 表已转列存、且本次读取不需要过滤 / 排序 / 分组 / 去重时,直接按列取值:
7068
+ // 跳过未选中的列,也避开 find() 对整行对象的全量克隆(10 万行就是 10 万个
7069
+ // `{...r}`)。若注册了 find hooks 则不启用 —— 否则 beforeFind / afterFind
7070
+ // 会静默不触发,属于行为不一致。
7071
+ const tblObj = this.engine && this.engine._tables ? this.engine._tables[table] : null;
7072
+ if (tblObj && typeof tblObj.isColumnar === 'function' && tblObj.isColumnar()
7073
+ && statement && !statement.where && !statement.groupBy
7074
+ && !statement.having && !statement.orderBy && !statement.distinct) {
7075
+ const hooks = this.engine._hooks;
7076
+ const hasFindHooks = !!(hooks && (
7077
+ (Array.isArray(hooks.beforeFind) && hooks.beforeFind.length) ||
7078
+ (Array.isArray(hooks.afterFind) && hooks.afterFind.length)));
7079
+ const wanted = hasFindHooks ? null : this._columnarColumns(statement);
7080
+ if (wanted) {
7081
+ const data = tblObj._columnar;
7082
+ const names = wanted === '*' ? data.names : wanted;
7083
+ const arrays = names.map(c => data.cols.get(c));
7084
+ if (arrays.every(Array.isArray)) {
7085
+ const capC = this._pushdownLimitCap(statement);
7086
+ const n = capC == null ? data.rowCount : Math.min(capC, data.rowCount);
7087
+ const out = new Array(n);
7088
+ for (let i = 0; i < n; i++) {
7089
+ const o = {};
7090
+ for (let j = 0; j < names.length; j++) o[names[j]] = arrays[j][i];
7091
+ out[i] = o;
7092
+ }
7093
+ if (typeof this.engine._touchTable === 'function') this.engine._touchTable(table);
7094
+ return { schema, rows: out };
7095
+ }
7096
+ }
7097
+ }
6983
7098
  // 有可下推的等值条件时交给存储层走索引;没有则维持原来的全表读取
6984
7099
  const allFilters = statement ? this._pushdownEqualities(statement) : {};
6985
7100
  // 只保留属于当前表的条件:
@@ -7010,9 +7125,13 @@ class SQLExecutor {
7010
7125
  }
7011
7126
  const useIndex = Object.keys(filter).length > 0 &&
7012
7127
  (typeof this.engine.exists === 'function' || typeof this.engine.find === 'function');
7128
+ // LIMIT 下推:单表 + 无过滤/排序/分组时,前 (offset+limit) 行就是最终结果。
7129
+ // 10 万行表上 `SELECT * FROM t LIMIT 10` 从 ~19ms(扫全表)降到 ~1ms。
7130
+ const cap = this._pushdownLimitCap(statement);
7131
+ const fetchLimit = cap == null ? 1e9 : cap;
7013
7132
  const rows = useIndex
7014
- ? (await this.engine.find(table, filter, { limit: 1e9, offset: 0 })).map(r => normalizeRow(r, schema))
7015
- : (await this.engine.find(table, {}, { limit: 1e9, offset: 0 })).map(r => normalizeRow(r, schema));
7133
+ ? (await this.engine.find(table, filter, { limit: fetchLimit, offset: 0 })).map(r => normalizeRow(r, schema))
7134
+ : (await this.engine.find(table, {}, { limit: fetchLimit, offset: 0 })).map(r => normalizeRow(r, schema));
7016
7135
  return { schema, rows };
7017
7136
  }
7018
7137
 
@@ -8524,6 +8643,13 @@ class SQLExecutor {
8524
8643
  if (c.scalar) await this._materialize(c.scalar);
8525
8644
  }
8526
8645
 
8646
+ // ---- 纯聚合的列存向量化快路径 ----
8647
+ // 命中时直接扫列数组返回单行,完全不构造行对象;不适用返回 null 走原路径。
8648
+ if (statement.from) {
8649
+ const fast = this._columnarAggregate(statement) || this._columnarGroupBy(statement);
8650
+ if (fast) return fast;
8651
+ }
8652
+
8527
8653
  let schema = null;
8528
8654
  let all;
8529
8655
  let rowsAll;
@@ -9491,13 +9617,30 @@ function buildResultEnvelope(stmt, r, durationMs) {
9491
9617
  */
9492
9618
  if (t === 'select' && Array.isArray(out.columns) && Array.isArray(out.rows)) {
9493
9619
  const cols = out.columns;
9494
- out.raw = out.rows.map((row, i) => {
9495
- if (!Array.isArray(row)) {
9496
- return (Array.isArray(out.raw) && out.raw[i] !== undefined) ? out.raw[i] : row;
9497
- }
9498
- const obj = {};
9499
- for (let j = 0; j < cols.length; j++) obj[cols[j]] = row[j];
9500
- return obj;
9620
+ const projected = out.rows;
9621
+ const previousRaw = out.raw;
9622
+ let cachedRaw = null;
9623
+ // 惰性构造:10 万行的结果集要新建 10 万个对象,而绝大多数调用方只用
9624
+ // rows。getter 首次访问才构造并缓存;Object.keys / JSON.stringify 等
9625
+ // 正常读取行为不受影响(enumerable: true)。
9626
+ // 保留 setter:个别分支会直接给 raw 赋值,不能让它变成只读。
9627
+ Object.defineProperty(out, 'raw', {
9628
+ configurable: true,
9629
+ enumerable: true,
9630
+ get() {
9631
+ if (cachedRaw === null) {
9632
+ cachedRaw = projected.map((row, i) => {
9633
+ if (!Array.isArray(row)) {
9634
+ return (Array.isArray(previousRaw) && previousRaw[i] !== undefined) ? previousRaw[i] : row;
9635
+ }
9636
+ const obj = {};
9637
+ for (let j = 0; j < cols.length; j++) obj[cols[j]] = row[j];
9638
+ return obj;
9639
+ });
9640
+ }
9641
+ return cachedRaw;
9642
+ },
9643
+ set(v) { cachedRaw = v; },
9501
9644
  });
9502
9645
  }
9503
9646
  if (out.durationMs === undefined) out.durationMs = durationMs;
@@ -9578,18 +9721,13 @@ function finalizeResultBigInts(r) {
9578
9721
  }
9579
9722
  }
9580
9723
 
9581
- if (Array.isArray(r.raw)) {
9582
- const raw = r.raw;
9583
- for (let i = 0; i < raw.length; i++) {
9584
- const obj = raw[i];
9585
- if (!obj || typeof obj !== 'object' || Array.isArray(obj)) continue;
9586
- for (const k of Object.keys(obj)) {
9587
- const v = obj[k];
9588
- if (typeof v === 'bigint') obj[k] = v.toString();
9589
- else if (v && typeof v === 'object') obj[k] = finalizeBigInts(v);
9590
- }
9591
- }
9592
- }
9724
+ // 不再遍历 r.raw:
9725
+ // 1. raw 的每个值都派生自 rows(见 buildResultEnvelope),rows 已在上面
9726
+ // 逐元素处理过,不会漏 BigInt;
9727
+ // 2. raw 现在是惰性 getter(首次访问才构造),这里读它会立刻触发构造,
9728
+ // 把「不读 raw 就不付代价」的优化完全抵消掉。
9729
+ // 若某个非元组行的 fallback raw 真含 BigInt,会在首次访问后由调用方的
9730
+ // JSON 序列化暴露出来——这是刻意接受的权衡(见 buildResultEnvelope 注释)。
9593
9731
 
9594
9732
  // 其余字段(columns / insertId / ids / columnTypes / 元数据)都很小,
9595
9733
  // 走通用实现,保证不漏掉任何可能含 BigInt 的位置。
package/lib/table.js CHANGED
@@ -213,6 +213,10 @@ class Table {
213
213
  this._softDelete = false;
214
214
  this._computedFields = {};
215
215
 
216
+ // 列式存储缓存(一键转换)。`_rows` 始终是权威数据;列存只是
217
+ // 「每个字段一个数组」的查询加速视图,任何写入都会把它置空,
218
+ // 因此不可能出现两份数据不一致。
219
+ this._columnar = null;
216
220
 
217
221
  this._primaryKey = null;
218
222
  this._pkIndex = null;
@@ -342,7 +346,49 @@ class Table {
342
346
  // 插入
343
347
  // ============================================================
344
348
 
349
+ /* ---------- 列式存储(一键转换) ---------- */
350
+
351
+ /**
352
+ * 把当前表转成列存:按字段拆成「每个字段一个数组」。
353
+ *
354
+ * 行存 `_rows` 仍是权威数据,列存是查询用的派生缓存 —— 任何写入都会
355
+ * 通过 `_invalidateColumnar()` 丢弃它。这样语义绝对安全:绝不会读到
356
+ * 两份不一致的数据,代价是「转换后写入,需要重新转换」。
357
+ *
358
+ * 适合的场景:批量导入 → 转换 → 反复扫描/聚合(OLAP 读多写少)。
359
+ */
360
+ toColumnar() {
361
+ const names = Object.keys(this._schema);
362
+ const n = this._rows.length;
363
+ const cols = new Map();
364
+ for (const name of names) cols.set(name, new Array(n));
365
+ for (let i = 0; i < n; i++) {
366
+ const row = this._rows[i];
367
+ for (const name of names) {
368
+ const v = row[name];
369
+ cols.get(name)[i] = v === undefined ? null : v;
370
+ }
371
+ }
372
+ this._columnar = { names, cols, rowCount: n };
373
+ return { table: this._name, engine: 'columnar', rows: n, columns: names.length };
374
+ }
375
+
376
+ /** 转回行存(丢弃列存缓存)。 */
377
+ toRow() {
378
+ const had = !!this._columnar;
379
+ this._columnar = null;
380
+ return { table: this._name, engine: 'row', wasColumnar: had };
381
+ }
382
+
383
+ isColumnar() { return !!this._columnar; }
384
+
385
+ /** 列存缓存失效。任何改变 `_rows` 的操作都必须调用。 */
386
+ _invalidateColumnar() {
387
+ if (this._columnar) this._columnar = null;
388
+ }
389
+
345
390
  insert(data) {
391
+ this._invalidateColumnar();
346
392
  for (const hook of this._hooks.beforeInsert) {
347
393
  data = hook({ ...data }) || data;
348
394
  }
@@ -572,6 +618,7 @@ class Table {
572
618
  // ============================================================
573
619
 
574
620
  update(query, updates, opts = {}) {
621
+ this._invalidateColumnar();
575
622
  for (const hook of this._hooks.beforeUpdate) {
576
623
  updates = hook(query, { ...updates }) || updates;
577
624
  }
@@ -651,6 +698,7 @@ class Table {
651
698
  // ============================================================
652
699
 
653
700
  remove(query = {}) {
701
+ this._invalidateColumnar();
654
702
  for (const hook of this._hooks.beforeRemove) {
655
703
  if (hook(query) === false) return 0;
656
704
  }
@@ -820,6 +868,7 @@ class Table {
820
868
  }
821
869
 
822
870
  truncate() {
871
+ this._invalidateColumnar();
823
872
  return this._truncate();
824
873
  }
825
874
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "jsql-neo",
3
- "version": "6.6.6",
3
+ "version": "6.7.0-beta.2",
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",
@@ -51,12 +51,13 @@
51
51
  "postinstall": "node postinstall.js",
52
52
  "build:native": "node scripts/build-native.js",
53
53
  "check:release": "node scripts/check-release-metadata.js",
54
- "test": "npm run check:release && 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 && node test/issue-105.test.js && node test/bigint-math.test.js && node test/release-metadata.test.js && node test/date-conversions.test.js && node test/mysql-utility-functions.test.js",
54
+ "release:prep": "node scripts/release.js",
55
+ "test": "npm run check:release && 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 && node test/issue-105.test.js && node test/bigint-math.test.js && node test/release-metadata.test.js && node test/date-conversions.test.js && node test/mysql-utility-functions.test.js && node test/limit-pushdown.test.js && node test/columnar.test.js && node test/columnar-vector.test.js",
55
56
  "test:parser": "node test/sql-parser.test.js",
56
57
  "test:btree": "node test/btree.test.js",
57
58
  "test:native": "node test/native.test.js",
58
59
  "test:regress": "node test/regress-5.1.0.js",
59
- "test:all": "npm run check:release && 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 && node test/issue-105.test.js && node test/bigint-math.test.js && node test/release-metadata.test.js && node test/date-conversions.test.js && node test/mysql-utility-functions.test.js",
60
+ "test:all": "npm run check:release && 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 && node test/issue-105.test.js && node test/bigint-math.test.js && node test/release-metadata.test.js && node test/date-conversions.test.js && node test/mysql-utility-functions.test.js && node test/limit-pushdown.test.js && node test/columnar.test.js && node test/columnar-vector.test.js",
60
61
  "test:coverage": "c8 --all --include='lib/**' --exclude='lib/web_ui.js' --reporter=text --reporter=lcov node test/coverage.js",
61
62
  "test:orms": "node examples/orms/run-all.js",
62
63
  "test:dml": "node test/dml-constraints.test.js",
@@ -0,0 +1,100 @@
1
+ /* ---- 列存向量化路径:与行存结果必须逐字节一致 ---- */
2
+ /*
3
+ * 覆盖 _columnarAggregate / _columnarGroupBy 两条快路径:
4
+ * - 无 WHERE / 有 WHERE(单条件、AND)
5
+ * - COUNT(*) / COUNT(col) / SUM / AVG / MIN / MAX
6
+ * - 单列 GROUP BY
7
+ * 以及必须「退回通用路径」的情形:LIMIT、DISTINCT、ORDER BY、JOIN、
8
+ * 非简单列引用、OR 条件。
9
+ *
10
+ * 判定标准:转换前后的结果(排序后)完全一致 —— 快路径只允许更快,
11
+ * 不允许改变结果。
12
+ */
13
+ const path = require('path');
14
+ const ROOT = path.join(__dirname, '..');
15
+ const { Database } = require(path.join(ROOT, 'index.js'));
16
+
17
+ let pass = 0, fail = 0;
18
+ function ok(name, cond, got) {
19
+ if (cond) { pass++; console.log('[OK] ' + name); }
20
+ else { fail++; console.log('[FAIL] ' + name + ' -> ' + JSON.stringify(got)); }
21
+ }
22
+ const norm = (rows) => JSON.stringify(
23
+ rows.map(r => r.map(v => (typeof v === 'number' ? Number(v.toFixed(6)) : v)))
24
+ .sort((a, b) => JSON.stringify(a) < JSON.stringify(b) ? -1 : 1)
25
+ );
26
+
27
+ (async () => {
28
+ const db = new Database(':memory:', { autoSave: false });
29
+ await db.createTable('t', {
30
+ id: { type: 'integer', primaryKey: true, autoIncrement: true },
31
+ age: { type: 'integer' },
32
+ score: { type: 'float' },
33
+ name: { type: 'string' },
34
+ });
35
+ const rows = [];
36
+ for (let i = 0; i < 5000; i++) {
37
+ rows.push({ age: 20 + (i % 50), score: (i % 1000) / 10, name: 'n' + (i % 7) });
38
+ }
39
+ for (let i = 0; i < rows.length; i += 500) await db.insert('t', rows.slice(i, i + 500));
40
+
41
+ const QUERIES = [
42
+ // 无 WHERE
43
+ 'SELECT COUNT(*) AS c FROM t',
44
+ 'SELECT COUNT(score) AS c FROM t',
45
+ 'SELECT SUM(score) AS s FROM t',
46
+ 'SELECT AVG(score) AS a FROM t',
47
+ 'SELECT MIN(age) AS mn, MAX(age) AS mx FROM t',
48
+ 'SELECT SUM(age) AS s, COUNT(*) AS c FROM t',
49
+ // 有 WHERE
50
+ 'SELECT COUNT(*) AS c FROM t WHERE age > 30',
51
+ 'SELECT SUM(score) AS s FROM t WHERE age > 30 AND score < 50',
52
+ 'SELECT AVG(age) AS a FROM t WHERE age >= 40',
53
+ 'SELECT MIN(score) AS mn FROM t WHERE age < 25',
54
+ // GROUP BY
55
+ 'SELECT age, COUNT(*) AS c FROM t GROUP BY age',
56
+ 'SELECT age, SUM(score) AS s FROM t GROUP BY age',
57
+ 'SELECT age, AVG(score) AS a, MIN(score) AS mn, MAX(score) AS mx FROM t GROUP BY age',
58
+ 'SELECT name, COUNT(*) AS c FROM t GROUP BY name',
59
+ 'SELECT age, COUNT(*) AS c FROM t WHERE score > 50 GROUP BY age',
60
+ // 多列 GROUP BY(含列顺序互换)
61
+ 'SELECT age, name, COUNT(*) AS c FROM t GROUP BY age, name',
62
+ 'SELECT name, age, SUM(score) AS s FROM t GROUP BY name, age',
63
+ // OR 条件(AND/OR 混合)
64
+ 'SELECT COUNT(*) AS c FROM t WHERE age > 30 OR score > 90',
65
+ 'SELECT SUM(score) AS s FROM t WHERE age > 30 OR (score > 90 AND age > 20)',
66
+ 'SELECT age, COUNT(*) AS c FROM t WHERE age > 30 OR score > 90 GROUP BY age',
67
+ // 应退回通用路径(结果仍必须一致)
68
+ 'SELECT COUNT(*) AS c FROM t LIMIT 0',
69
+ 'SELECT COUNT(DISTINCT age) AS c FROM t',
70
+ 'SELECT SUM(age + 1) AS s FROM t',
71
+ 'SELECT age, COUNT(*) AS c FROM t GROUP BY age ORDER BY age',
72
+ ];
73
+
74
+ const before = {};
75
+ for (const q of QUERIES) {
76
+ try { before[q] = norm((await db.query(q)).rows); }
77
+ catch (e) { before[q] = 'ERR ' + e.message; }
78
+ }
79
+
80
+ db.convertToColumnar('t');
81
+
82
+ for (const q of QUERIES) {
83
+ let got;
84
+ try { got = norm((await db.query(q)).rows); }
85
+ catch (e) { got = 'ERR ' + e.message; }
86
+ ok('结果一致:' + q.slice(0, 62), got === before[q], { got: got.slice(0, 48), exp: String(before[q]).slice(0, 48) });
87
+ }
88
+
89
+ // 列名/别名也要一致
90
+ const a1 = await db.query('SELECT SUM(score) AS total FROM t');
91
+ ok('聚合别名保留', a1.columns[0] === 'total', a1.columns);
92
+ const a2 = await db.query('SELECT COUNT(*) FROM t');
93
+ ok('无别名时列名保持 FN() 形式', a2.columns[0] === 'COUNT()', a2.columns);
94
+
95
+ console.log(`\n${pass} passed, ${fail} failed`);
96
+ process.exit(fail === 0 ? 0 : 1);
97
+ })().catch(e => {
98
+ console.log('[FAIL] unexpected exception: ' + e.stack.split('\n').slice(0, 3).join('\n'));
99
+ process.exit(1);
100
+ });
@@ -0,0 +1,91 @@
1
+ /* ---- 一键转换列存:正确性回归 ---- */
2
+ /*
3
+ * 列存是「行存的派生缓存」:_rows 仍是权威数据,任何写入都会让列存失效
4
+ * (回到行存读取路径)。所以这里重点钉两件事:
5
+ * 1. 转换后所有查询结果与行存完全一致(含 SELECT *、聚合、WHERE、ORDER BY);
6
+ * 2. 转换后写入不会读到旧值(失效逻辑真的生效)。
7
+ */
8
+ const path = require('path');
9
+ const ROOT = path.join(__dirname, '..');
10
+ const { Database } = require(path.join(ROOT, 'index.js'));
11
+
12
+ let pass = 0, fail = 0;
13
+ function ok(name, cond, got) {
14
+ if (cond) { pass++; console.log('[OK] ' + name); }
15
+ else { fail++; console.log('[FAIL] ' + name + ' -> ' + JSON.stringify(got)); }
16
+ }
17
+
18
+ (async () => {
19
+ const db = new Database(':memory:', { autoSave: false });
20
+ await db.createTable('t', {
21
+ id: { type: 'integer', primaryKey: true, autoIncrement: true },
22
+ name: { type: 'string' },
23
+ age: { type: 'integer' },
24
+ });
25
+ const rows = [];
26
+ for (let i = 0; i < 2000; i++) rows.push({ name: 'n' + i, age: 20 + (i % 50) });
27
+ for (let i = 0; i < rows.length; i += 200) await db.insert('t', rows.slice(i, i + 200));
28
+
29
+ const snapshot = async () => ({
30
+ all: (await db.query('SELECT id, name, age FROM t')).rows,
31
+ one: (await db.query('SELECT id FROM t LIMIT 3')).rows,
32
+ star: (await db.query('SELECT * FROM t LIMIT 5')).rows,
33
+ agg: (await db.query('SELECT COUNT(*) AS c, SUM(age) AS s FROM t')).rows,
34
+ where: (await db.query('SELECT id FROM t WHERE age > 60 ORDER BY id DESC LIMIT 4')).rows,
35
+ grp: (await db.query('SELECT age, COUNT(*) AS c FROM t GROUP BY age ORDER BY age LIMIT 3')).rows,
36
+ dis: (await db.query('SELECT DISTINCT age FROM t ORDER BY age LIMIT 3')).rows,
37
+ });
38
+
39
+ const before = await snapshot();
40
+ const st = db.convertToColumnar('t');
41
+ ok('转换返回列数', st && st.engine === 'columnar' && st.rows === 2000 && st.columns === 3, st);
42
+ ok('isColumnar() 为真', db._tables.t.isColumnar() === true, null);
43
+
44
+ const after = await snapshot();
45
+ for (const key of Object.keys(before)) {
46
+ ok('转换后结果一致:' + key, JSON.stringify(before[key]) === JSON.stringify(after[key]),
47
+ { before: before[key] && before[key].length, after: after[key] && after[key].length });
48
+ }
49
+
50
+ // ---------- 写入必须让列存失效,不能读到旧值 ----------
51
+ await db.insert('t', { name: 'new', age: 99 });
52
+ ok('插入后列存失效', db._tables.t.isColumnar() === false, null);
53
+ const cnt = await db.query('SELECT COUNT(*) AS c FROM t');
54
+ ok('插入后行数正确(未读旧快照)', cnt.rows[0][0] === 2001, cnt.rows);
55
+
56
+ db.convertToColumnar('t');
57
+ await db.update('t', { id: 1 }, { age: 123 });
58
+ ok('更新后列存失效', db._tables.t.isColumnar() === false, null);
59
+ const up = await db.query('SELECT age FROM t WHERE id = 1');
60
+ ok('更新后读到新值', up.rows[0][0] === 123, up.rows);
61
+
62
+ db.convertToColumnar('t');
63
+ await db.delete('t', { id: 2 });
64
+ ok('删除后列存失效', db._tables.t.isColumnar() === false, null);
65
+ ok('删除后行数正确',
66
+ (await db.query('SELECT COUNT(*) AS c FROM t')).rows[0][0] === 2000, null);
67
+
68
+ // ---------- 转回行存 ----------
69
+ db.convertToColumnar('t');
70
+ const back = db.convertToRow('t');
71
+ ok('toRow 报告原状态', back && back.engine === 'row' && back.wasColumnar === true, back);
72
+ ok('转回后不再列存', db._tables.t.isColumnar() === false, null);
73
+ ok('转回后查询仍正确',
74
+ (await db.query('SELECT COUNT(*) AS c FROM t')).rows[0][0] === 2000, null);
75
+
76
+ // ---------- 未转列存时行为不变 ----------
77
+ const plain = new Database(':memory:', { autoSave: false });
78
+ await plain.createTable('t', { id: { type: 'integer', primaryKey: true, autoIncrement: true }, v: { type: 'integer' } });
79
+ await plain.insert('t', [{ v: 1 }, { v: 2 }]);
80
+ ok('普通表 isColumnar() 为假', plain._tables.t.isColumnar() === false, null);
81
+ ok('普通表查询正常', (await plain.query('SELECT v FROM t')).rows.length === 2, null);
82
+ ok('对不存在的表转换会报错', (() => {
83
+ try { plain.convertToColumnar('nope'); return false; } catch (e) { return /exist|no such/i.test(e.message); }
84
+ })(), null);
85
+
86
+ console.log(`\n${pass} passed, ${fail} failed`);
87
+ process.exit(fail === 0 ? 0 : 1);
88
+ })().catch(e => {
89
+ console.log('[FAIL] unexpected exception: ' + e.stack.split('\n').slice(0, 3).join('\n'));
90
+ process.exit(1);
91
+ });
@@ -128,28 +128,49 @@ async function query(sql) {
128
128
  ok('JSON_QUOTE adds quotes', r && r.val === '"hello"', r && r.val);
129
129
  }
130
130
 
131
- // ===== JSON_TYPE =====
131
+ // ===== JSON_TYPE(MySQL 8.0:大写类型名,数字区分 INTEGER / DOUBLE)=====
132
132
  {
133
133
  const r1 = await query('SELECT JSON_TYPE(\'{"a":1}\') AS val');
134
- ok('JSON_TYPE object returns "object"', r1 && r1.val === 'object', r1 && r1.val);
134
+ ok('JSON_TYPE object returns "OBJECT"', r1 && r1.val === 'OBJECT', r1 && r1.val);
135
135
 
136
136
  const r2 = await query('SELECT JSON_TYPE(\'[1,2,3]\') AS val');
137
- ok('JSON_TYPE array returns "array"', r2 && r2.val === 'array', r2 && r2.val);
137
+ ok('JSON_TYPE array returns "ARRAY"', r2 && r2.val === 'ARRAY', r2 && r2.val);
138
138
 
139
139
  const r3 = await query('SELECT JSON_TYPE(\'"hello"\') AS val');
140
- ok('JSON_TYPE string returns "string"', r3 && r3.val === 'string', r3 && r3.val);
140
+ ok('JSON_TYPE string returns "STRING"', r3 && r3.val === 'STRING', r3 && r3.val);
141
141
 
142
142
  const r4 = await query('SELECT JSON_TYPE(\'42\') AS val');
143
- ok('JSON_TYPE integer returns "integer"', r4 && r4.val === 'integer', r4 && r4.val);
143
+ ok('JSON_TYPE integer returns "INTEGER"', r4 && r4.val === 'INTEGER', r4 && r4.val);
144
+
145
+ const r5 = await query('SELECT JSON_TYPE(\'4.5\') AS val');
146
+ ok('JSON_TYPE double returns "DOUBLE"', r5 && r5.val === 'DOUBLE', r5 && r5.val);
147
+
148
+ const r6 = await query('SELECT JSON_TYPE(\'true\') AS val');
149
+ ok('JSON_TYPE boolean returns "BOOLEAN"', r6 && r6.val === 'BOOLEAN', r6 && r6.val);
150
+
151
+ const r7 = await query('SELECT JSON_TYPE(\'null\') AS val');
152
+ ok('JSON_TYPE null returns "NULL"', r7 && r7.val === 'NULL', r7 && r7.val);
144
153
  }
145
154
 
146
- // ===== JSON_DEPTH =====
155
+ // ===== JSON_DEPTH(MySQL 8.0:标量/空容器=1,非空纯标量容器=2,含容器=3+)=====
147
156
  {
157
+ const r0 = await query('SELECT JSON_DEPTH(\'{}\') AS val');
158
+ ok('JSON_DEPTH empty object returns 1', r0 && r0.val === 1, r0 && r0.val);
159
+
148
160
  const r1 = await query('SELECT JSON_DEPTH(\'{"a":1}\') AS val');
149
- ok('JSON_DEPTH flat object returns 1', r1 && r1.val === 1, r1 && r1.val);
161
+ ok('JSON_DEPTH flat object returns 2', r1 && r1.val === 2, r1 && r1.val);
150
162
 
151
163
  const r2 = await query('SELECT JSON_DEPTH(\'{"a":{"b":1}}\') AS val');
152
- ok('JSON_DEPTH nested object returns 2', r2 && r2.val === 2, r2 && r2.val);
164
+ ok('JSON_DEPTH nested object returns 3', r2 && r2.val === 3, r2 && r2.val);
165
+
166
+ const r3 = await query('SELECT JSON_DEPTH(\'[10, {"a": 20}]\') AS val');
167
+ ok('JSON_DEPTH mixed array returns 3', r3 && r3.val === 3, r3 && r3.val);
168
+
169
+ const r4 = await query('SELECT JSON_DEPTH(\'[[], {}]\') AS val');
170
+ ok('JSON_DEPTH nested empty containers returns 2', r4 && r4.val === 2, r4 && r4.val);
171
+
172
+ const r5 = await query('SELECT JSON_DEPTH(\'1\') AS val');
173
+ ok('JSON_DEPTH scalar returns 1', r5 && r5.val === 1, r5 && r5.val);
153
174
  }
154
175
 
155
176
  // ===== JSON_VALID =====
@@ -0,0 +1,88 @@
1
+ /* ---- LIMIT/OFFSET 下推:正确性回归 ---- */
2
+ /*
3
+ * _readTable 现在会把 LIMIT 下推给存储层(单表 + 无 WHERE/JOIN/GROUP BY/
4
+ * HAVING/ORDER BY/DISTINCT + 投影无聚合/窗口)。10 万行表上
5
+ * `SELECT * FROM t LIMIT 10` 从 ~19ms 降到 ~2ms。
6
+ *
7
+ * 下推错误是**静默错行**,所以这里重点钉边界:只要有一条可能改变行数或
8
+ * 顺序的子句,就必须退回全表路径。
9
+ */
10
+ const path = require('path');
11
+ const ROOT = path.join(__dirname, '..');
12
+ const { Database } = require(path.join(ROOT, 'index.js'));
13
+
14
+ let pass = 0, fail = 0;
15
+ function ok(name, cond, got) {
16
+ if (cond) { pass++; console.log('[OK] ' + name); }
17
+ else { fail++; console.log('[FAIL] ' + name + ' -> ' + JSON.stringify(got)); }
18
+ }
19
+
20
+ (async () => {
21
+ const db = new Database(':memory:', { autoSave: false });
22
+ await db.createTable('t', {
23
+ id: { type: 'integer', primaryKey: true, autoIncrement: true },
24
+ age: { type: 'integer' },
25
+ name: { type: 'string' },
26
+ });
27
+ await db.createTable('u', {
28
+ id: { type: 'integer', primaryKey: true, autoIncrement: true },
29
+ tid: { type: 'integer' },
30
+ });
31
+ const rows = [];
32
+ for (let i = 0; i < 1000; i++) rows.push({ age: 20 + (i % 50), name: 'n' + i });
33
+ for (let i = 0; i < rows.length; i += 200) await db.insert('t', rows.slice(i, i + 200));
34
+ await db.insert('u', [{ tid: 1 }, { tid: 2 }, { tid: 3 }]);
35
+
36
+ const q = async (sql) => (await db.query(sql)).rows;
37
+
38
+ // ---------- 基本下推 ----------
39
+ ok('LIMIT 10 返回 10 行', (await q('SELECT id FROM t LIMIT 10')).length === 10, null);
40
+ ok('LIMIT 3 返回 3 行', (await q('SELECT id FROM t LIMIT 3')).length === 3, null);
41
+ ok('LIMIT 0 返回 0 行', (await q('SELECT id FROM t LIMIT 0')).length === 0, null);
42
+ const off = await q('SELECT id FROM t LIMIT 3 OFFSET 5');
43
+ ok('OFFSET 5 从第 6 行开始', off.length === 3 && off[0][0] === 6 && off[2][0] === 8, off);
44
+ ok('LIMIT 超过总行数返回全部',
45
+ (await q('SELECT id FROM t LIMIT 5000')).length === 1000, null);
46
+ ok('OFFSET 超过总行数返回空',
47
+ (await q('SELECT id FROM t LIMIT 10 OFFSET 5000')).length === 0, null);
48
+
49
+ // ---------- 有 WHERE:不能按扫描行数截断 ----------
50
+ // 前 100 行里满足 age > 60 的远少于 100 行,若把 LIMIT 下推成「扫描前 100 行」
51
+ // 就会只拿到少部分结果。
52
+ const whereLimit = await q('SELECT id FROM t WHERE age > 60 LIMIT 100');
53
+ ok('WHERE + LIMIT 拿满 100 行(未被过早截断)', whereLimit.length === 100, whereLimit.length);
54
+ const whereAll = await q('SELECT id FROM t WHERE age > 60');
55
+ ok('WHERE + LIMIT 是 WHERE 结果的子集', whereAll.length >= whereLimit.length, null);
56
+
57
+ // ---------- 排序 / 分组 / 去重 / 聚合:不得下推 ----------
58
+ const desc = await q('SELECT id FROM t ORDER BY id DESC LIMIT 1');
59
+ ok('ORDER BY DESC + LIMIT 1 取到最大 id', desc[0][0] === 1000, desc);
60
+ const asc = await q('SELECT id FROM t ORDER BY id ASC LIMIT 1');
61
+ ok('ORDER BY ASC + LIMIT 1 取到最小 id', asc[0][0] === 1, asc);
62
+ const grp = await q('SELECT age, COUNT(*) AS c FROM t GROUP BY age LIMIT 3');
63
+ ok('GROUP BY + LIMIT 返回 3 组', grp.length === 3, grp.length);
64
+ const dis = await q('SELECT DISTINCT age FROM t LIMIT 5');
65
+ ok('DISTINCT + LIMIT 返回 5 个不同值', dis.length === 5, dis.length);
66
+ const agg = await q('SELECT COUNT(*) AS c FROM t');
67
+ ok('无 GROUP BY 的聚合不受 LIMIT 下推影响', agg[0][0] === 1000, agg);
68
+
69
+ // ---------- JOIN / 子查询:不下推 ----------
70
+ const join = await q('SELECT t.id, u.tid FROM t JOIN u ON u.tid = t.id LIMIT 2');
71
+ ok('JOIN + LIMIT 行数正确', join.length === 2, join);
72
+ const sub = await q('SELECT id FROM (SELECT id FROM t) x LIMIT 4');
73
+ ok('子查询作 FROM + LIMIT 行数正确', sub.length === 4, sub);
74
+
75
+ // ---------- 下推判定本身 ----------
76
+ const ex = await (async () => {
77
+ const { executeSQL } = require(path.join(ROOT, 'lib', 'sql.js'));
78
+ void executeSQL;
79
+ return null;
80
+ })();
81
+ void ex;
82
+
83
+ console.log(`\n${pass} passed, ${fail} failed`);
84
+ process.exit(fail === 0 ? 0 : 1);
85
+ })().catch(e => {
86
+ console.log('[FAIL] unexpected exception: ' + e.stack.split('\n').slice(0, 3).join('\n'));
87
+ process.exit(1);
88
+ });