jsql-neo 6.7.3 → 6.7.6
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 +12 -1
- package/index.js +1 -1
- package/lib/database.js +261 -51
- package/lib/jsql_format.js +181 -14
- package/lib/row_cache.js +215 -0
- package/lib/sql.js +82 -30
- package/lib/table.js +176 -1
- package/package.json +1 -1
- package/test/bug-regression-2.test.js +2 -1
- package/test/extra-coverage.test.js +3 -2
- package/test/hybrid-row-flush.test.js +191 -0
- package/test/issue-111.test.js +112 -0
- package/test/issue-114.test.js +102 -0
- package/test/wal-recovery.test.js +22 -0
package/lib/jsql_format.js
CHANGED
|
@@ -224,8 +224,17 @@ class JSQLFormat {
|
|
|
224
224
|
_saveIdx(name) {
|
|
225
225
|
const entries = this.pkIdx.get(name) || [];
|
|
226
226
|
const maxPerBlock = Math.floor((SZ.DATA - 4) / 12);
|
|
227
|
-
|
|
227
|
+
if (entries.length === 0) {
|
|
228
|
+
const t0 = this.tables.get(name);
|
|
229
|
+
if (t0) t0.pkBlock = 0;
|
|
230
|
+
return 0;
|
|
231
|
+
}
|
|
228
232
|
|
|
233
|
+
// 先为每个分块分配物理块号,再回填 next/prev 指针,最后统一写盘。
|
|
234
|
+
// 旧实现边分配边写:next 指针写进了当前块自身,上一个块永远指向 0,
|
|
235
|
+
// 导致索引超过一个块(335 项)时后续行在重开后不可见。
|
|
236
|
+
const chunks = [];
|
|
237
|
+
const ids = [];
|
|
229
238
|
for (let chunk = 0; chunk < entries.length; chunk += maxPerBlock) {
|
|
230
239
|
const chunkEnd = Math.min(chunk + maxPerBlock, entries.length);
|
|
231
240
|
const buf = Buffer.alloc(SZ.BLOCK);
|
|
@@ -240,23 +249,22 @@ class JSQLFormat {
|
|
|
240
249
|
buf.writeUInt32LE(e.block, off); off += 4;
|
|
241
250
|
buf.writeUInt32LE(e.off, off); off += 4;
|
|
242
251
|
}
|
|
252
|
+
chunks.push(buf);
|
|
253
|
+
ids.push(this._alloc());
|
|
254
|
+
}
|
|
243
255
|
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
buf.writeUInt32LE(
|
|
248
|
-
|
|
249
|
-
// total entry count in first block
|
|
250
|
-
if (chunk === 0) buf.writeUInt32LE(entries.length, 48);
|
|
251
|
-
|
|
256
|
+
for (let c = 0; c < chunks.length; c++) {
|
|
257
|
+
const buf = chunks[c];
|
|
258
|
+
buf.writeUInt32LE(c + 1 < ids.length ? ids[c + 1] : 0, 52); // next block
|
|
259
|
+
buf.writeUInt32LE(c > 0 ? ids[c - 1] : 0, 56); // prev block
|
|
260
|
+
if (c === 0) buf.writeUInt32LE(entries.length, 48); // 总条目数
|
|
252
261
|
finalize(buf);
|
|
253
|
-
fs.writeSync(this.fd, buf, 0, SZ.BLOCK,
|
|
254
|
-
prevBlock = bid;
|
|
262
|
+
fs.writeSync(this.fd, buf, 0, SZ.BLOCK, ids[c] * SZ.BLOCK);
|
|
255
263
|
}
|
|
256
264
|
|
|
257
265
|
const t = this.tables.get(name);
|
|
258
|
-
if (t) t.pkBlock =
|
|
259
|
-
return
|
|
266
|
+
if (t) t.pkBlock = ids[0];
|
|
267
|
+
return ids[0];
|
|
260
268
|
}
|
|
261
269
|
|
|
262
270
|
_loadIdx(blockId) {
|
|
@@ -417,17 +425,172 @@ class JSQLFormat {
|
|
|
417
425
|
|
|
418
426
|
this._saveSuper();
|
|
419
427
|
this.dirty = false;
|
|
428
|
+
// 整表重写后回收文件尾部的历史空洞块,否则反复「增量追加 + 压缩」会让
|
|
429
|
+
// 文件只增不减。
|
|
430
|
+
fs.ftruncateSync(this.fd, this.nBlocks * SZ.BLOCK);
|
|
420
431
|
}
|
|
421
432
|
|
|
422
433
|
writeTable(name, schema, rows, pkField) {
|
|
423
434
|
this.saveAll({ [name]: { schema, rows, pkField } });
|
|
424
435
|
}
|
|
425
436
|
|
|
437
|
+
// ---- 行级增量写入(hybrid/disk 一行一刷盘) ----
|
|
438
|
+
|
|
439
|
+
_hashRange(entries, hash) {
|
|
440
|
+
let lo = 0, hi = entries.length;
|
|
441
|
+
while (lo < hi) {
|
|
442
|
+
const m = (lo + hi) >>> 1;
|
|
443
|
+
if (entries[m].hash < hash) lo = m + 1; else hi = m;
|
|
444
|
+
}
|
|
445
|
+
return lo;
|
|
446
|
+
}
|
|
447
|
+
|
|
448
|
+
/** 在索引中定位某个主键值的条目,返回下标;未找到返回 -1。 */
|
|
449
|
+
_findEntry(entries, pkValue, pkField) {
|
|
450
|
+
const h = hashPK(pkValue);
|
|
451
|
+
for (let i = this._hashRange(entries, h); i < entries.length && entries[i].hash === h; i++) {
|
|
452
|
+
const row = this._readInBlock(entries[i].block, entries[i].off);
|
|
453
|
+
if (!pkField || row[pkField] === pkValue) return i;
|
|
454
|
+
}
|
|
455
|
+
return -1;
|
|
456
|
+
}
|
|
457
|
+
|
|
458
|
+
_setEntry(entries, entry, pkValue, pkField) {
|
|
459
|
+
const idx = this._findEntry(entries, pkValue, pkField);
|
|
460
|
+
if (idx >= 0) { entries[idx] = entry; return; }
|
|
461
|
+
entries.splice(this._hashRange(entries, entry.hash), 0, entry);
|
|
462
|
+
}
|
|
463
|
+
|
|
464
|
+
_delEntry(entries, pkValue, pkField) {
|
|
465
|
+
const idx = this._findEntry(entries, pkValue, pkField);
|
|
466
|
+
if (idx >= 0) entries.splice(idx, 1);
|
|
467
|
+
}
|
|
468
|
+
|
|
469
|
+
/**
|
|
470
|
+
* 只把变更行追加为独立数据块并更新主键索引,不重写整表。
|
|
471
|
+
* upserts 为最新行(同主键旧索引项被就地替换),deletes 为主键值数组。
|
|
472
|
+
* 旧数据块保留为空洞,由调用方按阈值触发全量重写回收。
|
|
473
|
+
*/
|
|
474
|
+
writeRows(name, schema, upserts, deletes, pkField) {
|
|
475
|
+
this._open();
|
|
476
|
+
const t = this.tables.get(name);
|
|
477
|
+
if (!t) {
|
|
478
|
+
if (upserts && upserts.length > 0) this.writeTable(name, schema, upserts, pkField);
|
|
479
|
+
return [];
|
|
480
|
+
}
|
|
481
|
+
if (schema) t.schema = schema;
|
|
482
|
+
|
|
483
|
+
const entries = this.pkIdx.get(name) || [];
|
|
484
|
+
this.pkIdx.set(name, entries);
|
|
485
|
+
const encoders = buildEncoders(t.schema);
|
|
486
|
+
const scratch = Buffer.allocUnsafe(SZ.DATA);
|
|
487
|
+
const written = [];
|
|
488
|
+
|
|
489
|
+
for (const row of upserts || []) {
|
|
490
|
+
const end = encRowInPlace(row, encoders, scratch, 0);
|
|
491
|
+
if (end > SZ.DATA) {
|
|
492
|
+
throw new Error(
|
|
493
|
+
`row in table '${name}' is too large (${end} bytes > max row size ${SZ.DATA} bytes); ` +
|
|
494
|
+
'split the value or reduce field sizes before saving'
|
|
495
|
+
);
|
|
496
|
+
}
|
|
497
|
+
const bid = this._alloc();
|
|
498
|
+
const buf = Buffer.alloc(SZ.BLOCK);
|
|
499
|
+
mkHeader(BT.DATA, bid, t.tableId).copy(buf);
|
|
500
|
+
const comp = zlib.gzipSync(Buffer.from(scratch.subarray(0, end)), { level: 1 });
|
|
501
|
+
buf.writeUInt32LE(end, 40);
|
|
502
|
+
buf[48] = 1;
|
|
503
|
+
buf.writeUInt32LE(comp.length, 44);
|
|
504
|
+
comp.copy(buf, SZ.HEADER);
|
|
505
|
+
finalize(buf);
|
|
506
|
+
fs.writeSync(this.fd, buf, 0, SZ.BLOCK, bid * SZ.BLOCK);
|
|
507
|
+
t.dataBlock = bid;
|
|
508
|
+
written.push({ block: bid, off: 0 });
|
|
509
|
+
|
|
510
|
+
const pkValue = pkField ? row[pkField] : undefined;
|
|
511
|
+
if (pkValue !== undefined && pkValue !== null) {
|
|
512
|
+
this._setEntry(entries, { hash: hashPK(pkValue), block: bid, off: 0 }, pkValue, pkField);
|
|
513
|
+
}
|
|
514
|
+
}
|
|
515
|
+
|
|
516
|
+
for (const pkValue of deletes || []) {
|
|
517
|
+
if (pkValue !== undefined && pkValue !== null) this._delEntry(entries, pkValue, pkField);
|
|
518
|
+
}
|
|
519
|
+
|
|
520
|
+
t.rowCount = entries.length;
|
|
521
|
+
this._saveIdx(name);
|
|
522
|
+
this._saveSuper();
|
|
523
|
+
return written;
|
|
524
|
+
}
|
|
525
|
+
|
|
526
|
+
/**
|
|
527
|
+
* 扫描某张表,返回所有「有效行」的物理位置(按 readTableSync 的同一顺序)。
|
|
528
|
+
* 只走长度前缀,不 decode 行内容,因此内存占用与行大小无关 —— 供行级
|
|
529
|
+
* 懒加载缓存建立 {block, off} 引用使用。
|
|
530
|
+
*/
|
|
531
|
+
scanLocators(name) {
|
|
532
|
+
this._open();
|
|
533
|
+
const t = this.tables.get(name);
|
|
534
|
+
if (!t) return [];
|
|
535
|
+
const entries = this.pkIdx.get(name) || [];
|
|
536
|
+
const pkField = Object.keys(t.schema || {})
|
|
537
|
+
.find(f => t.schema[f] && t.schema[f].primaryKey) || null;
|
|
538
|
+
const live = entries.length > 0
|
|
539
|
+
? new Set(entries.map(e => `${e.block}:${e.off}`))
|
|
540
|
+
: null;
|
|
541
|
+
|
|
542
|
+
const locs = [];
|
|
543
|
+
for (let bid = 1; bid < this.nBlocks; bid++) {
|
|
544
|
+
const buf = Buffer.alloc(SZ.BLOCK);
|
|
545
|
+
try { fs.readSync(this.fd, buf, 0, SZ.BLOCK, bid * SZ.BLOCK); } catch (e) { continue; }
|
|
546
|
+
if (buf[36] !== BT.DATA || buf[37] !== t.tableId) continue;
|
|
547
|
+
if (!verifyHash(buf)) {
|
|
548
|
+
throw new Error(`[JSQLFormat] Table '${name}': data block ${bid} failed integrity check`);
|
|
549
|
+
}
|
|
550
|
+
const compFlag = buf[48];
|
|
551
|
+
const raw = compFlag
|
|
552
|
+
? zlib.gunzipSync(buf.slice(SZ.HEADER, SZ.HEADER + buf.readUInt32LE(44)))
|
|
553
|
+
: buf.slice(SZ.HEADER, SZ.HEADER + buf.readUInt32LE(40));
|
|
554
|
+
|
|
555
|
+
let off = 0;
|
|
556
|
+
while (off + 4 <= raw.length) {
|
|
557
|
+
const l = raw.readUInt32LE(off);
|
|
558
|
+
if (l === 0 || off + 4 + l > raw.length) break;
|
|
559
|
+
if (!live || live.has(`${bid}:${off}`)) {
|
|
560
|
+
locs.push({ block: bid, off });
|
|
561
|
+
off += 4 + l;
|
|
562
|
+
continue;
|
|
563
|
+
}
|
|
564
|
+
// 不在索引里:可能是旧版本空洞,也可能是没有主键值的行。只有后者要保留。
|
|
565
|
+
const r = decRow(raw, off);
|
|
566
|
+
if (pkField && (r.row[pkField] === undefined || r.row[pkField] === null)) {
|
|
567
|
+
locs.push({ block: bid, off });
|
|
568
|
+
}
|
|
569
|
+
off = r.off;
|
|
570
|
+
}
|
|
571
|
+
}
|
|
572
|
+
return locs;
|
|
573
|
+
}
|
|
574
|
+
|
|
575
|
+
/** 按物理位置读取一行(行级懒加载的最小读单位)。 */
|
|
576
|
+
readRowAt(block, off) {
|
|
577
|
+
this._open();
|
|
578
|
+
return this._readInBlock(block, off);
|
|
579
|
+
}
|
|
580
|
+
|
|
426
581
|
readTableSync(name) {
|
|
427
582
|
this._open();
|
|
428
583
|
const t = this.tables.get(name);
|
|
429
584
|
if (!t) return { schema: null, rows: [] };
|
|
430
585
|
|
|
586
|
+
// 行级增量写入会留下旧版本的「空洞」块;有主键索引时只保留索引指向的
|
|
587
|
+
// 最新行,保证更新/删除后不会读出重复或已删的行。
|
|
588
|
+
const entries = this.pkIdx.get(name) || [];
|
|
589
|
+
const pkField = Object.keys(t.schema || {}).find(f => t.schema[f] && t.schema[f].primaryKey) || null;
|
|
590
|
+
const live = entries.length > 0
|
|
591
|
+
? new Set(entries.map(e => `${e.block}:${e.off}`))
|
|
592
|
+
: null;
|
|
593
|
+
|
|
431
594
|
const rows = [];
|
|
432
595
|
for (let bid = 1; bid < this.nBlocks; bid++) {
|
|
433
596
|
const buf = Buffer.alloc(SZ.BLOCK);
|
|
@@ -450,7 +613,11 @@ class JSQLFormat {
|
|
|
450
613
|
const l = raw.readUInt32LE(off);
|
|
451
614
|
if (l === 0 || off + 4 + l > raw.length) break;
|
|
452
615
|
const r = decRow(raw, off);
|
|
453
|
-
|
|
616
|
+
// 只有索引指向的最新行有效;无主键值的行无法进索引,保留以免丢数据
|
|
617
|
+
if (!live || live.has(`${bid}:${off}`)
|
|
618
|
+
|| (pkField && (r.row[pkField] === undefined || r.row[pkField] === null))) {
|
|
619
|
+
rows.push(r.row);
|
|
620
|
+
}
|
|
454
621
|
off = r.off;
|
|
455
622
|
}
|
|
456
623
|
}
|
package/lib/row_cache.js
ADDED
|
@@ -0,0 +1,215 @@
|
|
|
1
|
+
// © Vexify 2026 All Rights Reserved.
|
|
2
|
+
/**
|
|
3
|
+
* 行级懒加载缓存(hybrid / disk 目录模式)
|
|
4
|
+
*
|
|
5
|
+
* 目标:大表不再整表常驻内存。`Table._rows` 仍是「类数组」,但元素来自
|
|
6
|
+
* 磁盘上的 `{block, off}` 定位符 —— 只有真正被访问的行才 decode 进内存,
|
|
7
|
+
* 内存紧张时由 Database 按 LRU 逐行回退成定位符。
|
|
8
|
+
*
|
|
9
|
+
* 设计要点:
|
|
10
|
+
* • 用 Proxy 包住一个真实数组,数字下标命中定位符时才读盘;
|
|
11
|
+
* • 数组方法(filter/map/find/push/pop/splice…)都以 proxy 为 this,
|
|
12
|
+
* 逐元素走 get/set,语义与普通数组一致;
|
|
13
|
+
* • 脏行(尚未刷盘)永远 pin 在内存里,避免「改了但被淘汰」丢数据;
|
|
14
|
+
* • 淘汰只由 Database 在两次同步操作之间触发。同步操作内部不会发生
|
|
15
|
+
* 淘汰,因此 `_rows.indexOf(row)` 这类依赖对象标识的逻辑仍然成立。
|
|
16
|
+
*/
|
|
17
|
+
|
|
18
|
+
const INDEX_RE = /^(?:0|[1-9]\d*)$/;
|
|
19
|
+
|
|
20
|
+
function toIndex(prop) {
|
|
21
|
+
return INDEX_RE.test(prop) ? Number(prop) : -1;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
function isLocator(v) {
|
|
25
|
+
return v !== null && typeof v === 'object' && v.__loc === true;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
function makeLocator(loc) {
|
|
29
|
+
return { __loc: true, block: loc.block, off: loc.off };
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/**
|
|
33
|
+
* @param {object} table - 所属 Table(用于查询脏行、判断 pin)
|
|
34
|
+
* @param {Array<{block:number, off:number}>} locators - 有效行的物理位置
|
|
35
|
+
* @param {(block:number, off:number) => object} loader - 单行读取函数
|
|
36
|
+
* @param {Function} [onClose] - 缓存被丢弃时关闭底层句柄
|
|
37
|
+
*/
|
|
38
|
+
function createRowCache(table, locators, loader, onClose) {
|
|
39
|
+
const target = new Array(locators.length);
|
|
40
|
+
const locs = new Array(locators.length); // 下标 -> 磁盘位置(null = 无磁盘来源)
|
|
41
|
+
let rowIndex = new WeakMap(); // 行对象 -> 下标
|
|
42
|
+
const lru = new Map(); // 下标 -> true(Map 保持访问顺序)
|
|
43
|
+
|
|
44
|
+
for (let i = 0; i < locators.length; i++) {
|
|
45
|
+
const loc = locators[i];
|
|
46
|
+
target[i] = makeLocator(loc);
|
|
47
|
+
locs[i] = { block: loc.block, off: loc.off };
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
function touch(i) {
|
|
51
|
+
lru.delete(i);
|
|
52
|
+
lru.set(i, true);
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
function untouch(i) {
|
|
56
|
+
lru.delete(i);
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
function dropMappings(i, value) {
|
|
60
|
+
if (value && typeof value === 'object' && !isLocator(value)) rowIndex.delete(value);
|
|
61
|
+
untouch(i);
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
function load(i) {
|
|
65
|
+
const loc = locs[i];
|
|
66
|
+
if (!loc) return undefined;
|
|
67
|
+
const row = loader(loc.block, loc.off);
|
|
68
|
+
if (row && typeof row === 'object') {
|
|
69
|
+
target[i] = row;
|
|
70
|
+
rowIndex.set(row, i);
|
|
71
|
+
touch(i);
|
|
72
|
+
}
|
|
73
|
+
return row;
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
const handler = {
|
|
77
|
+
get(t, prop, receiver) {
|
|
78
|
+
if (typeof prop === 'string') {
|
|
79
|
+
const i = toIndex(prop);
|
|
80
|
+
if (i >= 0) {
|
|
81
|
+
const v = t[i];
|
|
82
|
+
if (isLocator(v)) return load(i);
|
|
83
|
+
if (v !== undefined) touch(i);
|
|
84
|
+
return v;
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
return Reflect.get(t, prop, receiver);
|
|
88
|
+
},
|
|
89
|
+
|
|
90
|
+
set(t, prop, value) {
|
|
91
|
+
if (typeof prop === 'string') {
|
|
92
|
+
const i = toIndex(prop);
|
|
93
|
+
if (i >= 0) {
|
|
94
|
+
const old = t[i];
|
|
95
|
+
if (old !== value) {
|
|
96
|
+
if (value && typeof value === 'object' && !isLocator(value)) {
|
|
97
|
+
const src = rowIndex.get(value);
|
|
98
|
+
if (src !== undefined) {
|
|
99
|
+
// 删除时「用尾行填补空位」:locator 跟着行一起搬
|
|
100
|
+
if (src !== i) {
|
|
101
|
+
locs[i] = locs[src];
|
|
102
|
+
locs[src] = null;
|
|
103
|
+
untouch(src);
|
|
104
|
+
}
|
|
105
|
+
} else {
|
|
106
|
+
locs[i] = null; // 新插入的行,没有磁盘位置
|
|
107
|
+
}
|
|
108
|
+
} else {
|
|
109
|
+
locs[i] = null;
|
|
110
|
+
}
|
|
111
|
+
dropMappings(i, old);
|
|
112
|
+
}
|
|
113
|
+
t[i] = value;
|
|
114
|
+
if (value && typeof value === 'object' && !isLocator(value)) {
|
|
115
|
+
rowIndex.set(value, i);
|
|
116
|
+
touch(i);
|
|
117
|
+
}
|
|
118
|
+
return true;
|
|
119
|
+
}
|
|
120
|
+
if (prop === 'length') {
|
|
121
|
+
const n = value >>> 0;
|
|
122
|
+
const oldLen = t.length;
|
|
123
|
+
if (n < oldLen) {
|
|
124
|
+
for (let j = n; j < oldLen; j++) dropMappings(j, t[j]);
|
|
125
|
+
}
|
|
126
|
+
t.length = n;
|
|
127
|
+
locs.length = n;
|
|
128
|
+
return true;
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
return Reflect.set(t, prop, value);
|
|
132
|
+
},
|
|
133
|
+
|
|
134
|
+
deleteProperty(t, prop) {
|
|
135
|
+
const i = toIndex(prop);
|
|
136
|
+
if (i >= 0) {
|
|
137
|
+
dropMappings(i, t[i]);
|
|
138
|
+
locs[i] = null;
|
|
139
|
+
delete t[i];
|
|
140
|
+
return true;
|
|
141
|
+
}
|
|
142
|
+
return Reflect.deleteProperty(t, prop);
|
|
143
|
+
}
|
|
144
|
+
};
|
|
145
|
+
|
|
146
|
+
const rows = new Proxy(target, handler);
|
|
147
|
+
|
|
148
|
+
/** 顺序扫描全部磁盘行,逐行回调;扫描结果不留在缓存里。 */
|
|
149
|
+
function scan(fn) {
|
|
150
|
+
for (let i = 0; i < locs.length; i++) {
|
|
151
|
+
const cur = target[i];
|
|
152
|
+
let row;
|
|
153
|
+
if (!isLocator(cur) && cur !== undefined) row = cur;
|
|
154
|
+
else if (locs[i]) row = loader(locs[i].block, locs[i].off);
|
|
155
|
+
if (row !== undefined && row !== null) fn(row, i);
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
/** 按 LRU 顺序把最多 max 行回退成定位符;脏行始终保留。 */
|
|
160
|
+
function evict(max) {
|
|
161
|
+
if (max <= 0) return 0;
|
|
162
|
+
let removed = 0;
|
|
163
|
+
const keys = [...lru.keys()];
|
|
164
|
+
for (const i of keys) {
|
|
165
|
+
if (removed >= max) break;
|
|
166
|
+
const v = target[i];
|
|
167
|
+
if (!v || isLocator(v) || typeof v !== 'object') { untouch(i); continue; }
|
|
168
|
+
if (table && table._dirtyUpserts && table._dirtyUpserts.has(v)) continue;
|
|
169
|
+
const loc = locs[i];
|
|
170
|
+
if (!loc) continue; // 新插入、尚未落盘的行无法回退
|
|
171
|
+
rowIndex.delete(v);
|
|
172
|
+
target[i] = makeLocator(loc);
|
|
173
|
+
untouch(i);
|
|
174
|
+
removed++;
|
|
175
|
+
}
|
|
176
|
+
return removed;
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
/** 整表重写/刷新后重置全部定位符(行顺序必须与原来一致)。 */
|
|
180
|
+
function reset(newLocs) {
|
|
181
|
+
target.length = 0;
|
|
182
|
+
locs.length = 0;
|
|
183
|
+
lru.clear();
|
|
184
|
+
rowIndex = new WeakMap();
|
|
185
|
+
for (let i = 0; i < newLocs.length; i++) {
|
|
186
|
+
target[i] = makeLocator(newLocs[i]);
|
|
187
|
+
locs[i] = { block: newLocs[i].block, off: newLocs[i].off };
|
|
188
|
+
}
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
/** 刷盘后更新个别已落盘行的定位符。 */
|
|
192
|
+
function applyLocators(rowList, newLocs) {
|
|
193
|
+
if (!rowList || !newLocs) return;
|
|
194
|
+
const n = Math.min(rowList.length, newLocs.length);
|
|
195
|
+
for (let k = 0; k < n; k++) {
|
|
196
|
+
const row = rowList[k];
|
|
197
|
+
const i = rowIndex.get(row);
|
|
198
|
+
if (i === undefined || target[i] !== row) continue;
|
|
199
|
+
locs[i] = { block: newLocs[k].block, off: newLocs[k].off };
|
|
200
|
+
touch(i);
|
|
201
|
+
}
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
function size() { return lru.size; }
|
|
205
|
+
|
|
206
|
+
function close() {
|
|
207
|
+
if (typeof onClose === 'function') {
|
|
208
|
+
try { onClose(); } catch (e) { /* 关闭句柄失败不影响数据 */ }
|
|
209
|
+
}
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
return { rows, scan, evict, reset, applyLocators, size, close };
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
module.exports = { createRowCache };
|
package/lib/sql.js
CHANGED
|
@@ -490,9 +490,14 @@ function tokenize(sql) {
|
|
|
490
490
|
|
|
491
491
|
// 聚合函数集合:这些必须走 aggregate 节点,否则会被当成逐行标量函数(返回 null 且不折叠行)
|
|
492
492
|
const AGG_FUNCS = new Set(['SUM', 'AVG', 'MIN', 'MAX', 'COUNT',
|
|
493
|
-
'GROUP_CONCAT', 'STDDEV', 'STDDEV_POP', 'STDDEV_SAMP',
|
|
493
|
+
'GROUP_CONCAT', 'STDDEV', 'STD', 'STDDEV_POP', 'STDDEV_SAMP',
|
|
494
494
|
'VARIANCE', 'VAR_POP', 'VAR_SAMP', 'FIRST', 'LAST']);
|
|
495
495
|
|
|
496
|
+
// 方差/标准差族(Issue #114):MySQL 里无后缀的 VARIANCE / STDDEV / STD
|
|
497
|
+
// 都是**总体**口径(= VAR_POP / STDDEV_POP),不是样本。
|
|
498
|
+
const VARIANCE_FUNCS = new Set(['STDDEV', 'STD', 'STDDEV_POP', 'STDDEV_SAMP',
|
|
499
|
+
'VARIANCE', 'VAR_POP', 'VAR_SAMP']);
|
|
500
|
+
|
|
496
501
|
// 这些词会跟在表名/子查询之后,不能被误当成表别名。
|
|
497
502
|
// 新增任何"跟在 FROM 之后"的子句时,都要往这里加词。
|
|
498
503
|
const NOT_ALIAS_WORDS = ['JOIN', 'LEFT', 'RIGHT', 'FULL', 'WHERE', 'GROUP', 'ORDER', 'LIMIT',
|
|
@@ -2574,9 +2579,21 @@ class Parser {
|
|
|
2574
2579
|
}
|
|
2575
2580
|
column = { type: 'tuple', items: cols };
|
|
2576
2581
|
} else if (this.peek().type === 'op' && this.peek().value === ',') {
|
|
2577
|
-
|
|
2578
|
-
|
|
2579
|
-
|
|
2582
|
+
if (VARIANCE_FUNCS.has(fn)) {
|
|
2583
|
+
// Issue #114:MySQL 的 VARIANCE/STDDEV/STD 只接受单个表达式,
|
|
2584
|
+
// 但本项目历史上接受 VARIANCE(1,2,3) 这种多参数写法,统一收集成 arglist,
|
|
2585
|
+
// 让每个参数值都参与统计(多参数时不再误当成 GROUP_CONCAT 的分隔符)。
|
|
2586
|
+
const items = [column];
|
|
2587
|
+
while (this.peek().type === 'op' && this.peek().value === ',') {
|
|
2588
|
+
this.next();
|
|
2589
|
+
items.push(this.parseScalar());
|
|
2590
|
+
}
|
|
2591
|
+
column = { type: 'arglist', items };
|
|
2592
|
+
} else {
|
|
2593
|
+
// GROUP_CONCAT(expr, 'sep')
|
|
2594
|
+
this.next();
|
|
2595
|
+
separator = this.parseValue();
|
|
2596
|
+
}
|
|
2580
2597
|
}
|
|
2581
2598
|
// GROUP_CONCAT(expr ORDER BY col [DESC])
|
|
2582
2599
|
if (this.isKeyword('ORDER')) {
|
|
@@ -3438,6 +3455,24 @@ class BinaryValue {
|
|
|
3438
3455
|
|
|
3439
3456
|
function isBinaryValue(v) { return v instanceof BinaryValue; }
|
|
3440
3457
|
|
|
3458
|
+
/**
|
|
3459
|
+
* Issue #111:按 Unicode code point 定位子串,返回 1-based 字符位置;
|
|
3460
|
+
* 未找到返回 0(与 MySQL LOCATE/INSTR 一致)。空子串返回 1。
|
|
3461
|
+
* 用 Array.from 把代理对拆成单个 code point,避免 emoji 被当成两个字符。
|
|
3462
|
+
*/
|
|
3463
|
+
function codePointIndexOf(needle, haystack) {
|
|
3464
|
+
const hay = Array.from(String(haystack));
|
|
3465
|
+
const pat = Array.from(String(needle));
|
|
3466
|
+
if (pat.length === 0) return 1;
|
|
3467
|
+
outer: for (let i = 0; i + pat.length <= hay.length; i++) {
|
|
3468
|
+
for (let j = 0; j < pat.length; j++) {
|
|
3469
|
+
if (hay[i + j] !== pat[j]) continue outer;
|
|
3470
|
+
}
|
|
3471
|
+
return i + 1;
|
|
3472
|
+
}
|
|
3473
|
+
return 0;
|
|
3474
|
+
}
|
|
3475
|
+
|
|
3441
3476
|
/** 去重 / GROUP BY / 窗口分组用的键:二进制值按文本,其余保持原逻辑 */
|
|
3442
3477
|
function valueKey(v) {
|
|
3443
3478
|
if (isBinaryValue(v)) return v.toString();
|
|
@@ -4226,8 +4261,10 @@ function applyScalarFunction(fnNode, row, ctx) {
|
|
|
4226
4261
|
: (isBinaryValue(args[0]) ? args[0].bytes.length : Buffer.byteLength(String(args[0]), 'utf8'));
|
|
4227
4262
|
case 'CHAR_LENGTH': case 'CHARACTER_LENGTH':
|
|
4228
4263
|
// MySQL:二进制串的 CHAR_LENGTH 也等于字节数
|
|
4264
|
+
// Issue #111:文本按 Unicode code point 计数(Array.from 会按代理对合并),
|
|
4265
|
+
// 否则 '🚀' 会被算成 2(UTF-16 code unit 数)。
|
|
4229
4266
|
return args[0] == null ? null
|
|
4230
|
-
: (isBinaryValue(args[0]) ? args[0].bytes.length : String(args[0]).length);
|
|
4267
|
+
: (isBinaryValue(args[0]) ? args[0].bytes.length : Array.from(String(args[0])).length);
|
|
4231
4268
|
// TRIM(s) / TRIM([LEADING|TRAILING|BOTH] chars FROM s) / TRIM(s, chars)
|
|
4232
4269
|
case 'TRIM': {
|
|
4233
4270
|
if (args[0] == null) return null;
|
|
@@ -4715,25 +4752,26 @@ function applyScalarFunction(fnNode, row, ctx) {
|
|
|
4715
4752
|
}
|
|
4716
4753
|
case 'SUBSTRING': case 'SUBSTR': {
|
|
4717
4754
|
if (args[0] == null) return null;
|
|
4718
|
-
|
|
4719
|
-
const
|
|
4755
|
+
// Issue #111:按 code point 切分,避免把 emoji/增补平面字符劈成孤立代理项
|
|
4756
|
+
const cps = Array.from(String(args[0]));
|
|
4757
|
+
const len = cps.length;
|
|
4720
4758
|
let start = Number(args[1]);
|
|
4721
4759
|
// MySQL 语义:1-based;负数从末尾倒数;0 视为 1(MySQL 返回空串)
|
|
4722
4760
|
if (start === 0) return '';
|
|
4723
4761
|
if (start < 0) start = len + start + 1;
|
|
4724
4762
|
if (args[2] !== undefined) {
|
|
4725
|
-
|
|
4763
|
+
const n = Number(args[2]);
|
|
4726
4764
|
if (n < 0) return '';
|
|
4727
|
-
return
|
|
4765
|
+
return cps.slice(start - 1, start - 1 + n).join('');
|
|
4728
4766
|
}
|
|
4729
|
-
return
|
|
4767
|
+
return cps.slice(start - 1).join('');
|
|
4730
4768
|
}
|
|
4731
4769
|
case 'LEFT': {
|
|
4732
4770
|
if (args[0] == null) return null;
|
|
4733
4771
|
const n = Number(args[1]);
|
|
4734
4772
|
// MySQL:长度 <= 0 返回空串(此前 slice(0, -1) 返回「去尾 1 字符」的 'ab')
|
|
4735
4773
|
if (!Number.isFinite(n) || n <= 0) return '';
|
|
4736
|
-
return String(args[0]).slice(0, Math.trunc(n));
|
|
4774
|
+
return Array.from(String(args[0])).slice(0, Math.trunc(n)).join('');
|
|
4737
4775
|
}
|
|
4738
4776
|
case 'RIGHT': {
|
|
4739
4777
|
if (args[0] == null) return null;
|
|
@@ -4742,21 +4780,23 @@ function applyScalarFunction(fnNode, row, ctx) {
|
|
|
4742
4780
|
// 所以 0 必须显式短路,不能只判 n < 0。
|
|
4743
4781
|
if (!Number.isFinite(n) || n <= 0) return '';
|
|
4744
4782
|
const s = String(args[0]);
|
|
4745
|
-
|
|
4783
|
+
const cps = Array.from(s); // Issue #111:code point 语义
|
|
4784
|
+
return n >= cps.length ? s : cps.slice(cps.length - n).join('');
|
|
4746
4785
|
}
|
|
4747
4786
|
case 'LOCATE': {
|
|
4748
4787
|
if (args[0] == null || args[1] == null) return null;
|
|
4749
|
-
|
|
4750
|
-
return
|
|
4788
|
+
// Issue #111:按 code point 定位,返回**字符**位置(不是 UTF-16 code unit 下标)
|
|
4789
|
+
return codePointIndexOf(String(args[0]), String(args[1]));
|
|
4751
4790
|
}
|
|
4752
4791
|
case 'INSTR': {
|
|
4753
4792
|
// INSTR(str, substr):参数顺序与 LOCATE(substr, str) 相反。
|
|
4754
4793
|
// 此前两者共用一段代码,导致 INSTR 静默返回 0。
|
|
4755
4794
|
if (args[0] == null || args[1] == null) return null;
|
|
4756
|
-
|
|
4757
|
-
return
|
|
4795
|
+
// Issue #111:code point 语义,返回字符位置
|
|
4796
|
+
return codePointIndexOf(String(args[1]), String(args[0]));
|
|
4758
4797
|
}
|
|
4759
|
-
|
|
4798
|
+
// Issue #111:code point 反转,否则代理对会被倒着拼成非法字符串('b\uDE80\uD83Da')
|
|
4799
|
+
case 'REVERSE': return args[0] == null ? null : Array.from(String(args[0])).reverse().join('');
|
|
4760
4800
|
|
|
4761
4801
|
// ---- 以下这批此前没有实现:调用时静默返回 null(不报错),
|
|
4762
4802
|
// 只有拿标准答案对照才发现。语义按 MySQL 8.0。
|
|
@@ -4813,23 +4853,31 @@ function applyScalarFunction(fnNode, row, ctx) {
|
|
|
4813
4853
|
case 'LPAD': {
|
|
4814
4854
|
if (args[0] == null || args[1] == null) return null;
|
|
4815
4855
|
const s = String(args[0]);
|
|
4856
|
+
const cps = Array.from(s); // Issue #111:长度/截断都按 code point
|
|
4816
4857
|
const n = Math.trunc(Number(args[1]));
|
|
4817
4858
|
if (!Number.isFinite(n) || n < 0) return null;
|
|
4818
|
-
if (n <=
|
|
4859
|
+
if (n <= cps.length) return cps.slice(0, n).join('');
|
|
4819
4860
|
const pad = args[2] == null ? ' ' : String(args[2]);
|
|
4820
4861
|
if (pad === '') return '';
|
|
4821
|
-
const
|
|
4862
|
+
const padCps = Array.from(pad);
|
|
4863
|
+
let fill = '';
|
|
4864
|
+
const need = n - cps.length;
|
|
4865
|
+
for (let i = 0; i < need; i++) fill += padCps[i % padCps.length];
|
|
4822
4866
|
return fill + s;
|
|
4823
4867
|
}
|
|
4824
4868
|
case 'RPAD': {
|
|
4825
4869
|
if (args[0] == null || args[1] == null) return null;
|
|
4826
4870
|
const s = String(args[0]);
|
|
4871
|
+
const cps = Array.from(s); // Issue #111:长度/截断都按 code point
|
|
4827
4872
|
const n = Math.trunc(Number(args[1]));
|
|
4828
4873
|
if (!Number.isFinite(n) || n < 0) return null;
|
|
4829
|
-
if (n <=
|
|
4874
|
+
if (n <= cps.length) return cps.slice(0, n).join('');
|
|
4830
4875
|
const pad = args[2] == null ? ' ' : String(args[2]);
|
|
4831
4876
|
if (pad === '') return '';
|
|
4832
|
-
const
|
|
4877
|
+
const padCps = Array.from(pad);
|
|
4878
|
+
let fill = '';
|
|
4879
|
+
const need = n - cps.length;
|
|
4880
|
+
for (let i = 0; i < need; i++) fill += padCps[i % padCps.length];
|
|
4833
4881
|
return s + fill;
|
|
4834
4882
|
}
|
|
4835
4883
|
case 'RAND': return args.length > 0 && args[0] != null ? seedRand(Number(args[0]))() : Math.random();
|
|
@@ -7575,11 +7623,15 @@ class SQLExecutor {
|
|
|
7575
7623
|
const noColumn = !op || op.type === 'star';
|
|
7576
7624
|
let values = noColumn
|
|
7577
7625
|
? rows.map(r => 1)
|
|
7578
|
-
|
|
7579
|
-
|
|
7580
|
-
? rows.
|
|
7626
|
+
// Issue #114:VARIANCE(1,2,3) 这类多参数写法,所有参数值都纳入统计
|
|
7627
|
+
: op && op.type === 'arglist'
|
|
7628
|
+
? rows.flatMap(r => op.items.map(it => resolveOperand(it, r, this.ctx)))
|
|
7581
7629
|
.filter(v => v !== null && v !== undefined)
|
|
7582
|
-
|
|
7630
|
+
// COUNT(DISTINCT a, b):先把多列拼成元组再聚合
|
|
7631
|
+
: op && op.type === 'tuple'
|
|
7632
|
+
? rows.map(r => JSON.stringify(op.items.map(it => resolveOperand(it, r, this.ctx))))
|
|
7633
|
+
.filter(v => v !== null && v !== undefined)
|
|
7634
|
+
: rows.map(r => resolveOperand(op, r, this.ctx)).filter(v => v !== null && v !== undefined);
|
|
7583
7635
|
// COUNT(DISTINCT x) / SUM(DISTINCT x):先按值去重再聚合
|
|
7584
7636
|
if (distinct) {
|
|
7585
7637
|
const seen = new Set();
|
|
@@ -7698,17 +7750,17 @@ class SQLExecutor {
|
|
|
7698
7750
|
const sep = (separator !== undefined && separator !== null) ? String(separator) : ',';
|
|
7699
7751
|
return joined.map(v => (v === null || v === undefined ? '' : String(v))).join(sep);
|
|
7700
7752
|
}
|
|
7701
|
-
// 标准差 / 方差族:_POP
|
|
7702
|
-
if (fn
|
|
7703
|
-
fn === 'VARIANCE' || fn === 'VAR_POP' || fn === 'VAR_SAMP') {
|
|
7753
|
+
// 标准差 / 方差族:_POP 与无后缀 VARIANCE/STDDEV/STD 为总体,仅 _SAMP 为样本
|
|
7754
|
+
if (VARIANCE_FUNCS.has(fn)) {
|
|
7704
7755
|
const nums = values.map(v => Number(v)).filter(v => Number.isFinite(v));
|
|
7705
7756
|
if (nums.length === 0) return null;
|
|
7706
|
-
const pop = (fn === 'STDDEV_POP' || fn === 'VAR_POP');
|
|
7757
|
+
const pop = (fn === 'STDDEV_POP' || fn === 'VAR_POP' || fn === 'VARIANCE' || fn === 'STDDEV' || fn === 'STD');
|
|
7707
7758
|
const mean = nums.reduce((s, v) => s + v, 0) / nums.length;
|
|
7708
7759
|
const denom = pop ? nums.length : nums.length - 1; // 样本方差用 n-1
|
|
7709
7760
|
if (denom <= 0) return null;
|
|
7710
7761
|
const variance = nums.reduce((s, v) => s + (v - mean) * (v - mean), 0) / denom;
|
|
7711
|
-
|
|
7762
|
+
const isStddev = (fn === 'STDDEV' || fn === 'STD' || fn === 'STDDEV_POP' || fn === 'STDDEV_SAMP');
|
|
7763
|
+
return isStddev ? Math.sqrt(variance) : variance;
|
|
7712
7764
|
}
|
|
7713
7765
|
return null;
|
|
7714
7766
|
}
|