jsql-neo 6.7.5 → 6.7.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/table.js CHANGED
@@ -6,8 +6,10 @@
6
6
 
7
7
  const Query = require('./query');
8
8
  const BTree = require('./btree');
9
+ const { createRowCache } = require('./row_cache');
9
10
  const { validateDateType, now } = require('./date-types');
10
11
  const { createError, JSQL_Error } = require('./errors');
12
+ const { ObjectId, valuesEqual, arrayIncludesValue } = require('./objectid');
11
13
 
12
14
  // ---------------------------------------------------------------------------
13
15
  // DEFAULT 表达式求值(Issue #72)
@@ -200,7 +202,10 @@ class Table {
200
202
  this._name = name;
201
203
  this._schema = schema;
202
204
  this._db = db;
203
- this._rows = [];
205
+ // 行级懒加载缓存(仅 hybrid/disk 目录模式启用);普通模式下为 null,
206
+ // `_rows` 就是普通数组。
207
+ this._rowCache = null;
208
+ this.__rows = [];
204
209
  this._indexes = {}; // 旧版 hash 索引(兼容)
205
210
  this._btrees = {}; // B-Tree 索引 { fieldName: BTree }
206
211
  this._autoIncrement = 0;
@@ -213,6 +218,13 @@ class Table {
213
218
  this._softDelete = false;
214
219
  this._computedFields = {};
215
220
 
221
+ // 行级脏标记(仅 hybrid/disk 目录模式使用):刷盘时只写变更行,
222
+ // 不再整表重写。`_dirtyUpserts` 存行对象引用(更新是原地修改,
223
+ // 取用时的值即最新值),`_dirtyDeletes` 存被删除的主键值。
224
+ this._dirtyUpserts = new Set();
225
+ this._dirtyDeletes = new Set();
226
+ this._dirtyAll = false;
227
+
216
228
  // 列式存储缓存(一键转换)。`_rows` 始终是权威数据;列存只是
217
229
  // 「每个字段一个数组」的查询加速视图,任何写入都会把它置空,
218
230
  // 因此不可能出现两份数据不一致。
@@ -281,6 +293,95 @@ class Table {
281
293
  this._autoCreateBTrees();
282
294
  }
283
295
 
296
+ // `_rows` 通过访问器暴露:任何整体替换(_loadRows / truncate / WAL 回放)
297
+ // 都会自动丢弃行缓存,避免旧的定位符继续指向已被重写的文件。
298
+ get _rows() {
299
+ return this.__rows;
300
+ }
301
+
302
+ set _rows(rows) {
303
+ this._detachRowCache();
304
+ this.__rows = rows;
305
+ }
306
+
307
+ _detachRowCache() {
308
+ const cache = this._rowCache;
309
+ this._rowCache = null;
310
+ this._rowReader = null;
311
+ if (cache) cache.close();
312
+ }
313
+
314
+ /**
315
+ * 用磁盘定位符初始化行级懒加载。
316
+ * @param {Array<{block:number, off:number}>} locators - 有效行位置(顺序同 readTableSync)
317
+ * @param {(block:number, off:number) => object} loader - 单行读取函数
318
+ * @param {object} [reader] - 底层 JSQLFormat 句柄(缓存丢弃时一并关闭)
319
+ */
320
+ _loadRowRefs(locators, loader, reader) {
321
+ this._detachRowCache();
322
+ const cache = createRowCache(this, locators, loader, () => {
323
+ if (reader && typeof reader._close === 'function') {
324
+ try { reader._close(); } catch (e) { /* 忽略关闭失败 */ }
325
+ }
326
+ });
327
+ this.__rows = cache.rows;
328
+ this._rowCache = cache;
329
+ this._rowReader = reader || null;
330
+ this._rebuildRowMetaStreaming();
331
+ }
332
+
333
+ /** 从磁盘逐行读取并重建主键索引 / B-Tree / 自增计数,不把整表留在内存。 */
334
+ _rebuildRowMetaStreaming() {
335
+ const cache = this._rowCache;
336
+ if (!cache) return;
337
+
338
+ if (this._autoIncrementField) {
339
+ const field = this._autoIncrementField;
340
+ let max = this._autoIncrement;
341
+ cache.scan(row => {
342
+ const v = row[field];
343
+ if (typeof v === 'number' && v > max) max = v;
344
+ });
345
+ this._autoIncrement = max;
346
+ }
347
+
348
+ if (this._pkIndex && this._primaryKey) {
349
+ const field = this._primaryKey;
350
+ this._pkIndex.clear();
351
+ cache.scan((row, i) => {
352
+ const v = row[field];
353
+ if (v !== undefined && v !== null) this._pkIndex.set(v, i);
354
+ });
355
+ }
356
+
357
+ for (const field of Object.keys(this._btrees)) {
358
+ const tree = this._btrees[field];
359
+ tree.clear();
360
+ cache.scan((row, i) => {
361
+ const v = row[field];
362
+ if (v !== undefined && v !== null) tree.insert(v, i);
363
+ });
364
+ }
365
+
366
+ for (const field of Object.keys(this._indexes)) this.createIndex(field);
367
+ }
368
+
369
+ /** 供 Database 在内存压力下按 LRU 逐行淘汰;返回实际淘汰行数。 */
370
+ _evictRows(max) {
371
+ if (!this._rowCache) return 0;
372
+ return this._rowCache.evict(max === undefined ? Infinity : max);
373
+ }
374
+
375
+ /** 整表重写后刷新全部定位符(行顺序不变)。 */
376
+ _resetRowLocators(locators) {
377
+ if (this._rowCache) this._rowCache.reset(locators);
378
+ }
379
+
380
+ /** 行级刷盘后更新被写入行的定位符。 */
381
+ _applyFlushedLocators(rows, locators) {
382
+ if (this._rowCache) this._rowCache.applyLocators(rows, locators);
383
+ }
384
+
284
385
  // P1-2: DDL 后统一刷新 schema 缓存。
285
386
  // dropColumn/renameColumn 过去只改 _cachedSchemaFields,unique/required/numeric/
286
387
  // date/computed 缓存残留旧列 → insertMany 等路径拿到陈旧 schema 直接崩溃或漏校验。
@@ -416,6 +517,7 @@ class Table {
416
517
  }
417
518
  this._db._emitChange('insert', this._name, data);
418
519
  this._db._walLogUpsert(this._name, [data]);
520
+ this._markRowDirty(this._rows[rowIndex]);
419
521
 
420
522
  return data;
421
523
  }
@@ -539,6 +641,7 @@ class Table {
539
641
  }
540
642
  this._db._emitChange('insertMany', this._name, { count: N });
541
643
  this._db._walLogUpsert(this._name, result);
644
+ for (let i = 0; i < N; i++) this._markRowDirty(this._rows[this._rows.length - N + i]);
542
645
  return result;
543
646
  }
544
647
 
@@ -640,6 +743,7 @@ class Table {
640
743
  this._removeFromIndexes(index, oldData);
641
744
  Object.assign(this._rows[index], updates);
642
745
  this._addToIndexes(index, this._rows[index]);
746
+ this._markRowDirty(this._rows[index], this._primaryKey ? oldData[this._primaryKey] : undefined);
643
747
  count++;
644
748
  }
645
749
 
@@ -694,6 +798,7 @@ class Table {
694
798
  }
695
799
  this._db._emitChange('update', this._name, { query: { [this._primaryKey]: id }, updates, count: 1 });
696
800
  this._db._walLogUpsert(this._name, [row]);
801
+ this._markRowDirty(row, oldData[this._primaryKey]);
697
802
  return 1;
698
803
  }
699
804
 
@@ -759,6 +864,11 @@ class Table {
759
864
  }
760
865
  this._db._emitChange('remove', this._name, { query, count });
761
866
  this._db._walLogRemove(this._name, toRemove);
867
+ if (this._primaryKey) {
868
+ for (const row of toRemove) this._markRowDeleted(row[this._primaryKey]);
869
+ } else {
870
+ this._markAllRowsDirty();
871
+ }
762
872
  }
763
873
  return count;
764
874
  }
@@ -821,6 +931,7 @@ class Table {
821
931
  }
822
932
  this._db._emitChange('remove', this._name, { query: { [this._primaryKey]: id }, count: 1 });
823
933
  this._db._walLogRemove(this._name, [row]);
934
+ this._markRowDeleted(row[this._primaryKey]);
824
935
  return 1;
825
936
  }
826
937
 
@@ -846,6 +957,7 @@ class Table {
846
957
  }
847
958
  this._db._emitChange('remove', this._name, { query, count, soft: true });
848
959
  this._db._walLogUpsert(this._name, matched);
960
+ for (const row of matched) this._markRowDirty(row);
849
961
  }
850
962
  return count;
851
963
  }
@@ -892,6 +1004,7 @@ class Table {
892
1004
  this._dirty = true;
893
1005
  this._db._markDirty(this._name);
894
1006
  this._db._walLogReplaceTable(this._name);
1007
+ this._markAllRowsDirty();
895
1008
  return count;
896
1009
  }
897
1010
 
@@ -944,6 +1057,7 @@ class Table {
944
1057
  this._refreshSchemaCache();
945
1058
  this._dirty = true;
946
1059
  this._db._markDirty(this._name);
1060
+ this._markAllRowsDirty(); // schema 变更:整表重写
947
1061
  return this;
948
1062
  }
949
1063
 
@@ -969,6 +1083,7 @@ class Table {
969
1083
  this._refreshSchemaCache();
970
1084
  this._dirty = true;
971
1085
  this._db._markDirty(this._name);
1086
+ this._markAllRowsDirty(); // schema 变更:整表重写
972
1087
  return this;
973
1088
  }
974
1089
 
@@ -1017,6 +1132,7 @@ class Table {
1017
1132
  this._refreshSchemaCache();
1018
1133
  this._dirty = true;
1019
1134
  this._db._markDirty(this._name);
1135
+ this._markAllRowsDirty(); // schema 变更:整表重写
1020
1136
  return this;
1021
1137
  }
1022
1138
 
@@ -1042,6 +1158,7 @@ class Table {
1042
1158
  this._refreshSchemaCache();
1043
1159
  this._dirty = true;
1044
1160
  this._db._markDirty(this._name);
1161
+ this._markAllRowsDirty(); // schema 变更:整表重写
1045
1162
  return this;
1046
1163
  }
1047
1164
 
@@ -1528,7 +1645,7 @@ class Table {
1528
1645
 
1529
1646
  const value = this._resolvePath(row, field);
1530
1647
 
1531
- if (condition !== null && typeof condition === 'object' && !Array.isArray(condition) && !(condition instanceof RegExp)) {
1648
+ if (condition !== null && typeof condition === 'object' && !Array.isArray(condition) && !(condition instanceof RegExp) && !(condition instanceof ObjectId)) {
1532
1649
  const keys = Object.keys(condition);
1533
1650
  const isOperator = keys.every(k => k.startsWith('$'));
1534
1651
  if (isOperator && keys.length > 0) {
@@ -1543,7 +1660,7 @@ class Table {
1543
1660
  }
1544
1661
  }
1545
1662
  } else {
1546
- if (value !== condition) return false;
1663
+ if (!valuesEqual(value, condition)) return false;
1547
1664
  }
1548
1665
  }
1549
1666
  return true;
@@ -1551,14 +1668,14 @@ class Table {
1551
1668
 
1552
1669
  _matchOperator(value, op, target) {
1553
1670
  switch (op) {
1554
- case '$eq': return value === target;
1555
- case '$ne': return value !== target;
1671
+ case '$eq': return valuesEqual(value, target);
1672
+ case '$ne': return !valuesEqual(value, target);
1556
1673
  case '$gt': return value > target;
1557
1674
  case '$gte': return value >= target;
1558
1675
  case '$lt': return value < target;
1559
1676
  case '$lte': return value <= target;
1560
- case '$in': return Array.isArray(target) && target.includes(value);
1561
- case '$nin': return Array.isArray(target) && !target.includes(value);
1677
+ case '$in': return Array.isArray(target) && arrayIncludesValue(target, value);
1678
+ case '$nin': return Array.isArray(target) && !arrayIncludesValue(target, value);
1562
1679
  case '$like':
1563
1680
  if (typeof value !== 'string' || typeof target !== 'string') return false;
1564
1681
  {
@@ -1951,6 +2068,57 @@ class Table {
1951
2068
  }
1952
2069
  }
1953
2070
 
2071
+ // ---- 行级脏标记(hybrid/disk 目录模式) ----
2072
+
2073
+ /** 记录一行待刷盘。oldPk 用于主键变更时删除旧索引项。 */
2074
+ _markRowDirty(row, oldPk) {
2075
+ const db = this._db;
2076
+ if (!db || !db._dirMode) return;
2077
+ if (!this._primaryKey) { this._dirtyAll = true; return; }
2078
+ const pk = row[this._primaryKey];
2079
+ if (pk === undefined || pk === null) { this._dirtyAll = true; return; }
2080
+ if (oldPk !== undefined && oldPk !== pk) this._dirtyDeletes.add(oldPk);
2081
+ this._dirtyUpserts.add(row);
2082
+ }
2083
+
2084
+ _markRowDeleted(pkValue) {
2085
+ const db = this._db;
2086
+ if (!db || !db._dirMode) return;
2087
+ if (!this._primaryKey || pkValue === undefined || pkValue === null) {
2088
+ this._dirtyAll = true;
2089
+ return;
2090
+ }
2091
+ this._dirtyDeletes.add(pkValue);
2092
+ for (const r of this._dirtyUpserts) {
2093
+ if (r[this._primaryKey] === pkValue) this._dirtyUpserts.delete(r);
2094
+ }
2095
+ }
2096
+
2097
+ /** 整表脏(无主键表、truncate、回滚/恢复快照等),下次刷盘走全量重写。 */
2098
+ _markAllRowsDirty() {
2099
+ const db = this._db;
2100
+ if (!db || !db._dirMode) return;
2101
+ this._dirtyAll = true;
2102
+ this._dirtyUpserts.clear();
2103
+ this._dirtyDeletes.clear();
2104
+ }
2105
+
2106
+ _peekDirtyRows() {
2107
+ const all = this._dirtyAll || !this._primaryKey
2108
+ || this._dirtyUpserts.size > this._rows.length; // 批量改写过多时全量更划算
2109
+ return {
2110
+ all,
2111
+ upserts: all ? [] : [...this._dirtyUpserts],
2112
+ deletes: all ? [] : [...this._dirtyDeletes]
2113
+ };
2114
+ }
2115
+
2116
+ _clearDirtyRows() {
2117
+ this._dirtyAll = false;
2118
+ this._dirtyUpserts.clear();
2119
+ this._dirtyDeletes.clear();
2120
+ }
2121
+
1954
2122
  _loadRows(rows) {
1955
2123
  this._rows = rows;
1956
2124
  if (this._autoIncrementField) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "jsql-neo",
3
- "version": "6.7.5",
3
+ "version": "6.7.7",
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",
@@ -52,12 +52,12 @@
52
52
  "build:native": "node scripts/build-native.js",
53
53
  "check:release": "node scripts/check-release-metadata.js",
54
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 && node test/cast-rounding.test.js && node test/convert-subquery.test.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 && node test/cast-rounding.test.js && node test/convert-subquery.test.js && node test/mongo-persistence.test.js && node test/mongo-objectid.test.js",
56
56
  "test:parser": "node test/sql-parser.test.js",
57
57
  "test:btree": "node test/btree.test.js",
58
58
  "test:native": "node test/native.test.js",
59
59
  "test:regress": "node test/regress-5.1.0.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 && node test/cast-rounding.test.js && node test/convert-subquery.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 && node test/cast-rounding.test.js && node test/convert-subquery.test.js && node test/mongo-persistence.test.js && node test/mongo-objectid.test.js",
61
61
  "test:coverage": "c8 --all --include='lib/**' --exclude='lib/web_ui.js' --reporter=text --reporter=lcov node test/coverage.js",
62
62
  "test:orms": "node examples/orms/run-all.js",
63
63
  "test:dml": "node test/dml-constraints.test.js",
@@ -0,0 +1,191 @@
1
+ /*
2
+ * hybrid/disk 模式行级刷盘回归测试
3
+ *
4
+ * 背景:此前 hybrid 的刷盘单位是「整表」——任何一行变更都会把整张表
5
+ * 重写一遍(write amplification),内存里也整表常驻。
6
+ *
7
+ * 现在:Table 按行记录脏标记(_dirtyUpserts/_dirtyDeletes),
8
+ * Database._flushTableDelta() 只把变更行追加到表文件并更新主键索引,
9
+ * 无主键表 / truncate / schema 变更 / 回滚仍走整表重写。
10
+ */
11
+ const fs = require('fs');
12
+ const os = require('os');
13
+ const path = require('path');
14
+ const Database = require('../lib/database.js');
15
+
16
+ let pass = 0, fail = 0;
17
+ function ok(name, cond, extra) {
18
+ if (cond) { pass++; console.log('[OK] ' + name); }
19
+ else { fail++; console.log('[FAIL] ' + name + (extra !== undefined ? ' → ' + JSON.stringify(extra) : '')); }
20
+ }
21
+
22
+ function tmpDir(tag) {
23
+ return fs.mkdtempSync(path.join(os.tmpdir(), 'jsql-rowflush-' + tag + '-'));
24
+ }
25
+
26
+ const SCHEMA = {
27
+ id: { type: 'integer', primaryKey: true },
28
+ v: { type: 'string' },
29
+ n: { type: 'integer' }
30
+ };
31
+
32
+ (async () => {
33
+ console.log('--- 1. 单行更新只追加该行,不整表重写 ---');
34
+ {
35
+ const dir = tmpDir('delta');
36
+ let db = new Database(dir, { mode: 'hybrid' });
37
+ await db.createTable('t', SCHEMA);
38
+ await db.insertMany('t', Array.from({ length: 300 }, (_, i) => ({ id: i + 1, v: 'v' + i, n: i })));
39
+ await db.flush();
40
+
41
+ const file = path.join(dir, 't.jsql');
42
+ const before = fs.statSync(file).size;
43
+ await db.updateById('t', 42, { n: 9999 });
44
+ await db.flush();
45
+ const after = fs.statSync(file).size;
46
+ db.close();
47
+
48
+ ok('增量写入远小于整表大小', after - before > 0 && after - before < before,
49
+ { before, after });
50
+
51
+ db = new Database(dir, { mode: 'hybrid' });
52
+ const row = await db.findById('t', 42);
53
+ ok('重开后更新已持久化', row && row.n === 9999, row);
54
+ ok('行数不变', (await db.count('t')) === 300);
55
+ db.close();
56
+ }
57
+
58
+ console.log('--- 2. 删除一行:重开不复活、不重复 ---');
59
+ {
60
+ const dir = tmpDir('delete');
61
+ let db = new Database(dir, { mode: 'hybrid' });
62
+ await db.createTable('t', SCHEMA);
63
+ await db.insertMany('t', [{ id: 1, v: 'a', n: 1 }, { id: 2, v: 'b', n: 2 }, { id: 3, v: 'c', n: 3 }]);
64
+ await db.flush();
65
+ await db.removeById('t', 2);
66
+ await db.flush();
67
+ db.close();
68
+
69
+ db = new Database(dir, { mode: 'hybrid' });
70
+ const rows = await db.find('t', {});
71
+ const ids = rows.map(r => r.id).sort();
72
+ ok('删除的行不复活', (await db.findById('t', 2)) === null);
73
+ ok('剩余行正确且无重复', JSON.stringify(ids) === JSON.stringify([1, 3]), ids);
74
+ db.close();
75
+ }
76
+
77
+ console.log('--- 3. 主键更新后旧主键不残留 ---');
78
+ {
79
+ const dir = tmpDir('pkchange');
80
+ let db = new Database(dir, { mode: 'hybrid' });
81
+ await db.createTable('t', SCHEMA);
82
+ await db.insertMany('t', [{ id: 1, v: 'a', n: 1 }, { id: 2, v: 'b', n: 2 }]);
83
+ await db.flush();
84
+ await db.updateById('t', 1, { id: 10 });
85
+ await db.flush();
86
+ db.close();
87
+
88
+ db = new Database(dir, { mode: 'hybrid' });
89
+ const oldRow = await db.findById('t', 1);
90
+ const newRow = await db.findById('t', 10);
91
+ ok('旧主键已不可见', oldRow === null, oldRow);
92
+ ok('新主键可查到', newRow && newRow.v === 'a', newRow);
93
+ ok('总行数仍为 2', (await db.count('t')) === 2);
94
+ db.close();
95
+ }
96
+
97
+ console.log('--- 4. 无主键表回退整表重写,语义不变 ---');
98
+ {
99
+ const dir = tmpDir('nopk');
100
+ let db = new Database(dir, { mode: 'hybrid' });
101
+ await db.createTable('log', { v: { type: 'string' } });
102
+ await db.insert('log', { v: 'a' });
103
+ await db.insert('log', { v: 'b' });
104
+ await db.flush();
105
+ await db.removeWhere('log', { v: 'a' });
106
+ await db.flush();
107
+ db.close();
108
+
109
+ db = new Database(dir, { mode: 'hybrid' });
110
+ const rows = await db.find('log', {});
111
+ ok('无主键表删除已持久化', rows.length === 1 && rows[0].v === 'b', rows);
112
+ db.close();
113
+ }
114
+
115
+ console.log('--- 5. 反复更新触发压缩后数据仍正确 ---');
116
+ {
117
+ const dir = tmpDir('compact');
118
+ let db = new Database(dir, { mode: 'hybrid' });
119
+ await db.createTable('t', SCHEMA);
120
+ await db.insertMany('t', [{ id: 1, n: 0 }, { id: 2, n: 0 }]);
121
+ await db.flush();
122
+ const file = path.join(dir, 't.jsql');
123
+ const baseSize = fs.statSync(file).size;
124
+ for (let i = 1; i <= 200; i++) {
125
+ await db.updateById('t', 1, { n: i });
126
+ await db.flush();
127
+ }
128
+ const grownSize = fs.statSync(file).size;
129
+ db.close();
130
+
131
+ db = new Database(dir, { mode: 'hybrid' });
132
+ const row = await db.findById('t', 1);
133
+ ok('压缩后最新值正确', row && row.n === 200, row);
134
+ ok('压缩后行数正确', (await db.count('t')) === 2);
135
+ ok('文件未无限膨胀', grownSize < baseSize * 60, { baseSize, grownSize });
136
+ db.close();
137
+ }
138
+
139
+ console.log('--- 6. 删除后重新插入同主键 ---');
140
+ {
141
+ const dir = tmpDir('reinsert');
142
+ let db = new Database(dir, { mode: 'hybrid' });
143
+ await db.createTable('t', SCHEMA);
144
+ await db.insert('t', { id: 1, v: 'old', n: 1 });
145
+ await db.flush();
146
+ await db.removeById('t', 1);
147
+ await db.flush();
148
+ await db.insert('t', { id: 1, v: 'new', n: 2 });
149
+ await db.flush();
150
+ db.close();
151
+
152
+ db = new Database(dir, { mode: 'hybrid' });
153
+ const row = await db.findById('t', 1);
154
+ ok('重新插入的行是唯一一行', row && row.v === 'new' && (await db.count('t')) === 1, row);
155
+ db.close();
156
+ }
157
+
158
+ console.log('--- 7. 重开后按行懒加载 + 逐行淘汰 ---');
159
+ {
160
+ const dir = tmpDir('lazy');
161
+ let db = new Database(dir, { mode: 'hybrid' });
162
+ await db.createTable('t', SCHEMA);
163
+ // 400 行超过单个索引块的容量(335 项),同时覆盖索引分块读取
164
+ await db.insertMany('t', Array.from({ length: 400 }, (_, i) => ({ id: i + 1, v: 'v' + i, n: i })));
165
+ await db.flush();
166
+ db.close();
167
+
168
+ db = new Database(dir, { mode: 'hybrid' });
169
+ const table = db._ensureTable('t');
170
+ ok('重开后行数完整(索引跨块)', table._rows.length === 400 && (await db.count('t')) === 400,
171
+ table._rows.length);
172
+ ok('打开时不把整表读入内存', table._rowCache.size() === 0, table._rowCache.size());
173
+
174
+ const row = await db.findById('t', 200);
175
+ ok('按主键只加载命中的一行', row && row.n === 199 && table._rowCache.size() === 1,
176
+ { row, cached: table._rowCache.size() });
177
+
178
+ await db.updateById('t', 200, { n: 8888 });
179
+ await db.flush();
180
+ table._evictRows(Infinity);
181
+ ok('淘汰后按需重读仍是新值',
182
+ (await db.findById('t', 200)).n === 8888 && table._rowCache.size() === 1);
183
+
184
+ table._evictRows(Infinity);
185
+ ok('淘汰后行数不变', (await db.count('t')) === 400 && table._rowCache.size() === 0);
186
+ db.close();
187
+ }
188
+
189
+ console.log(`\n${pass} passed, ${fail} failed`);
190
+ if (fail > 0) process.exit(1);
191
+ })();