jsql-neo 6.7.5 → 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 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.7.5** — 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.6** — stable release · [github.com/vexify-org/JSQL-neo](https://github.com/vexify-org/JSQL-neo) · [jsql.vexify.top](https://jsql.vexify.top)
7
7
 
8
8
  ![Engines](https://img.shields.io/badge/engines-Native%20%7C%20WASM%20%7C%20Pure%20JS-7ee787)
9
9
  ![MySQL](https://img.shields.io/badge/protocol-MySQL%20compatible-1f6feb)
package/index.js CHANGED
@@ -1,5 +1,5 @@
1
1
  /**
2
- * JSQL-NEO v6.7.5 — Rust-Powered Embedded Database (WASM + HTTP)
2
+ * JSQL-NEO v6.7.6 — Rust-Powered Embedded Database (WASM + HTTP)
3
3
  *
4
4
  * @example
5
5
  * const jsql = require('jsql-neo');
package/lib/database.js CHANGED
@@ -295,9 +295,17 @@ class Database {
295
295
  if (!fs.existsSync(file)) return null;
296
296
  try {
297
297
  const fmt = new JSQLFormat(file);
298
- const { rows } = fmt.readTableSync(name);
298
+ fmt._open();
299
299
  const table = new Table(name, meta.schema, this);
300
- if (rows && rows.length > 0) table._loadRows(rows);
300
+ // 行级懒加载:只在内存里保留 {block, off},被访问的行才读盘。
301
+ const locators = fmt.scanLocators(name);
302
+ if (locators.length > 0) {
303
+ table._loadRowRefs(locators, (block, off) => fmt.readRowAt(block, off), fmt);
304
+ } else {
305
+ table._loadRows([]);
306
+ fmt._close();
307
+ }
308
+ if (typeof table._clearDirtyRows === 'function') table._clearDirtyRows();
301
309
  this._tables[name] = table;
302
310
  if (this._versioning) this._versions[name] = [];
303
311
  this._touchTable(name);
@@ -338,7 +346,7 @@ class Database {
338
346
  const names = [...this._dirtyTables];
339
347
  for (const name of names) {
340
348
  try {
341
- this._flushTable(name);
349
+ this._flushTableDelta(name);
342
350
  this._dirtyTables.delete(name);
343
351
  } catch (e) {
344
352
  // 保留脏标记,下次 flush 重试;错误对外传播而非静默
@@ -348,6 +356,53 @@ class Database {
348
356
  this._saveMeta();
349
357
  }
350
358
 
359
+ /**
360
+ * 行级刷盘:只把本表变更过的行追加到表文件,不再整表重写。
361
+ * 无主键表、truncate、schema 变更、回滚等场景退化为全量重写。
362
+ */
363
+ _flushTableDelta(name) {
364
+ const table = this._tables[name];
365
+ if (!table) return;
366
+ const dirty = typeof table._peekDirtyRows === 'function'
367
+ ? table._peekDirtyRows()
368
+ : { all: true, upserts: [], deletes: [] };
369
+
370
+ if (dirty.all) {
371
+ this._flushTable(name);
372
+ return;
373
+ }
374
+ if (dirty.upserts.length === 0 && dirty.deletes.length === 0) {
375
+ table._clearDirtyRows();
376
+ return;
377
+ }
378
+
379
+ const meta = this._meta.tables[name];
380
+ const file = meta && meta.file ? meta.file : encodeURIComponent(name) + '.jsql';
381
+ const fmt = new JSQLFormat(path.join(this._filePath, file));
382
+ let appendBlocks = 0;
383
+ try {
384
+ const written = fmt.writeRows(name, table._schema, dirty.upserts, dirty.deletes, table._primaryKey);
385
+ appendBlocks = fmt.nBlocks;
386
+ this._meta.tables[name] = { file, schema: table._schema };
387
+ if (typeof table._applyFlushedLocators === 'function') {
388
+ if (written && written.length === dirty.upserts.length) {
389
+ table._applyFlushedLocators(dirty.upserts, written);
390
+ } else {
391
+ // 退化成整表写入时行位置全部变化,重建定位符
392
+ table._resetRowLocators(fmt.scanLocators(name));
393
+ }
394
+ }
395
+ table._clearDirtyRows();
396
+ } finally {
397
+ fmt._close();
398
+ }
399
+
400
+ // 空洞块过多时回收:阈值取「行数 2 倍 + 64」,超过则整表重写一次。
401
+ if (appendBlocks > Math.max(64, table._rows.length * 2 + 64)) {
402
+ this._flushTable(name);
403
+ }
404
+ }
405
+
351
406
  _flushTable(name) {
352
407
  const table = this._tables[name];
353
408
  if (!table) return;
@@ -358,6 +413,11 @@ class Database {
358
413
  const pkField = Object.keys(table._schema).find(f => table._schema[f].primaryKey) || null;
359
414
  fmt.writeTable(name, table._schema, table._rows, pkField);
360
415
  this._meta.tables[name] = { file, schema: table._schema };
416
+ // 整表重写改变了每一行的物理位置,用新文件的定位符重置缓存
417
+ if (typeof table._resetRowLocators === 'function') {
418
+ table._resetRowLocators(fmt.scanLocators(name));
419
+ }
420
+ if (typeof table._clearDirtyRows === 'function') table._clearDirtyRows();
361
421
  } finally {
362
422
  fmt._close();
363
423
  }
@@ -385,9 +445,23 @@ class Database {
385
445
  const candidates = Object.keys(this._tables)
386
446
  .filter(n => n !== '__meta__' && !this._versioning && this._meta.tables[n]);
387
447
  candidates.sort((a, b) => (this._lastAccess[a] || 0) - (this._lastAccess[b] || 0));
448
+
449
+ // 先做行级 LRU 淘汰:把冷行回退成磁盘定位符,表结构与索引保持不变。
450
+ // 这一步只在两次同步操作之间触发(定时器回调),不会打断正在进行的查询。
388
451
  for (const name of candidates) {
389
452
  if (budget !== undefined && process.memoryUsage().rss <= budget) break;
390
- try { this._flushTable(name); } catch (e) { continue; }
453
+ const table = this._tables[name];
454
+ if (table && typeof table._evictRows === 'function' && table._rowCache) {
455
+ table._evictRows(Infinity);
456
+ }
457
+ }
458
+
459
+ // 仍超预算时才整表卸载。
460
+ for (const name of candidates) {
461
+ if (budget !== undefined && process.memoryUsage().rss <= budget) break;
462
+ const table = this._tables[name];
463
+ if (table && table._rowCache) continue; // 行级淘汰已足够,保留表对象
464
+ try { this._flushTableDelta(name); } catch (e) { continue; }
391
465
  delete this._tables[name];
392
466
  delete this[name];
393
467
  this._dirtyTables.delete(name);
@@ -719,6 +793,7 @@ class Database {
719
793
  if (typeof t._rebuildPKIndex === 'function') t._rebuildPKIndex();
720
794
  if (typeof t._rebuildAllBTrees === 'function') t._rebuildAllBTrees();
721
795
  for (const field of Object.keys(t._indexes || {})) t.createIndex(field);
796
+ if (typeof t._markAllRowsDirty === 'function') t._markAllRowsDirty();
722
797
  if (t._autoIncrementField) {
723
798
  for (const row of t._rows) {
724
799
  const v = row[t._autoIncrementField];
@@ -1663,6 +1738,7 @@ class Database {
1663
1738
  versions.pop();
1664
1739
  const snapshot = versions[versions.length - 1];
1665
1740
  table._rows = snapshot.rows.map(r => ({ ...r }));
1741
+ if (typeof table._markAllRowsDirty === 'function') table._markAllRowsDirty();
1666
1742
  table._autoIncrement = 0;
1667
1743
  for (const row of table._rows) {
1668
1744
  if (table._autoIncrementField && row[table._autoIncrementField] > table._autoIncrement) {
@@ -1962,6 +2038,14 @@ class Database {
1962
2038
  if (pk) {
1963
2039
  // Issue #44:主键查询值按列类型归一('5' → 5),与索引/insert 保持一致
1964
2040
  const key = typeof table._coerceQueryValue === 'function' ? table._coerceQueryValue(pk, id) : id;
2041
+ // 优先走主键索引:行级懒加载下避免为了取一行而把整表读进内存
2042
+ if (table._pkIndex) {
2043
+ const idx = table._pkIndex.get(key);
2044
+ if (idx !== undefined) {
2045
+ const row = table._rows[idx];
2046
+ if (row && (row[pk] === key || row[pk] === id)) return row;
2047
+ }
2048
+ }
1965
2049
  return table._rows.find(r => r[pk] === key || r[pk] === id) || null;
1966
2050
  }
1967
2051
  // 无主键表:id 是行对象(可能是 find() 返回的浅拷贝)时,用内容匹配代替引用比较。
@@ -2113,10 +2197,20 @@ class Database {
2113
2197
  // 改主键/唯一值时索引必须同步:否则 _pkIndex 还指向旧值,
2114
2198
  // 后续 FK 校验 findOne({id:新值}) 查不到刚更新的父行。
2115
2199
  {
2116
- const rowIndex = table._rows.indexOf(row);
2200
+ // 优先用主键索引定位,避免行级懒加载时 indexOf 把前面的行全部读进内存
2201
+ let rowIndex = -1;
2202
+ if (pk && table._pkIndex) {
2203
+ const oldKey = typeof table._coerceQueryValue === 'function'
2204
+ ? table._coerceQueryValue(pk, row[pk]) : row[pk];
2205
+ const i = table._pkIndex.get(oldKey);
2206
+ if (i !== undefined && table._rows[i] === row) rowIndex = i;
2207
+ }
2208
+ if (rowIndex === -1) rowIndex = table._rows.indexOf(row);
2209
+ const oldPk = pk ? row[pk] : undefined;
2117
2210
  if (rowIndex !== -1) table._removeFromIndexes(rowIndex, row);
2118
2211
  Object.assign(row, validated);
2119
2212
  if (rowIndex !== -1) table._addToIndexes(rowIndex, row);
2213
+ if (typeof table._markRowDirty === 'function') table._markRowDirty(row, oldPk);
2120
2214
  }
2121
2215
  this._walLogUpsert(tableName, [row]);
2122
2216
  this._emit('update', { table: tableName, id, data: validated });
@@ -2138,7 +2232,9 @@ class Database {
2138
2232
  if (row) {
2139
2233
  // CHECK 约束(Issue #70):批量更新同样不能在无校验的情况下写行
2140
2234
  if (typeof table._enforceChecks === 'function') table._enforceChecks({ ...row, ...data });
2235
+ const oldPk = pk ? row[pk] : undefined;
2141
2236
  Object.assign(row, data);
2237
+ if (typeof table._markRowDirty === 'function') table._markRowDirty(row, oldPk);
2142
2238
  count++;
2143
2239
  changed.push(row);
2144
2240
  }
@@ -2207,6 +2303,7 @@ class Database {
2207
2303
  }
2208
2304
  if (targets.length) {
2209
2305
  table._rows = table._rows.filter((_, idx) => !seen.has(idx));
2306
+ if (typeof table._markAllRowsDirty === 'function') table._markAllRowsDirty();
2210
2307
  removed = targets.length;
2211
2308
  }
2212
2309
  table._rebuildPKIndex();
@@ -2229,6 +2326,7 @@ class Database {
2229
2326
  const matched = table._applyFilter(table._getVisibleRows(), filter || {});
2230
2327
  const matchSet = new Set(matched);
2231
2328
  table._rows = table._rows.filter(r => !matchSet.has(r));
2329
+ if (typeof table._markAllRowsDirty === 'function') table._markAllRowsDirty();
2232
2330
  const removed = before - table._rows.length;
2233
2331
  table._rebuildPKIndex();
2234
2332
  table._rebuildAllBTrees();
@@ -2531,6 +2629,10 @@ class Database {
2531
2629
  this._sigInstalled = false;
2532
2630
  Database.removeSignalHandler(this);
2533
2631
  }
2632
+ // 关闭行缓存持有的文件句柄
2633
+ for (const t of Object.values(this._tables)) {
2634
+ if (t && typeof t._detachRowCache === 'function') t._detachRowCache();
2635
+ }
2534
2636
  this._tables = {};
2535
2637
  }
2536
2638
 
@@ -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
- let firstBlock = 0, prevBlock = 0;
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
- const bid = this._alloc();
245
- if (chunk === 0) firstBlock = bid;
246
- if (prevBlock) buf.writeUInt32LE(bid, 52); // next block pointer
247
- buf.writeUInt32LE(prevBlock, 56); // prev block pointer
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, bid * 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 = firstBlock;
259
- return firstBlock;
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
- rows.push(r.row);
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
  }
@@ -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/table.js CHANGED
@@ -6,6 +6,7 @@
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');
11
12
 
@@ -200,7 +201,10 @@ class Table {
200
201
  this._name = name;
201
202
  this._schema = schema;
202
203
  this._db = db;
203
- this._rows = [];
204
+ // 行级懒加载缓存(仅 hybrid/disk 目录模式启用);普通模式下为 null,
205
+ // `_rows` 就是普通数组。
206
+ this._rowCache = null;
207
+ this.__rows = [];
204
208
  this._indexes = {}; // 旧版 hash 索引(兼容)
205
209
  this._btrees = {}; // B-Tree 索引 { fieldName: BTree }
206
210
  this._autoIncrement = 0;
@@ -213,6 +217,13 @@ class Table {
213
217
  this._softDelete = false;
214
218
  this._computedFields = {};
215
219
 
220
+ // 行级脏标记(仅 hybrid/disk 目录模式使用):刷盘时只写变更行,
221
+ // 不再整表重写。`_dirtyUpserts` 存行对象引用(更新是原地修改,
222
+ // 取用时的值即最新值),`_dirtyDeletes` 存被删除的主键值。
223
+ this._dirtyUpserts = new Set();
224
+ this._dirtyDeletes = new Set();
225
+ this._dirtyAll = false;
226
+
216
227
  // 列式存储缓存(一键转换)。`_rows` 始终是权威数据;列存只是
217
228
  // 「每个字段一个数组」的查询加速视图,任何写入都会把它置空,
218
229
  // 因此不可能出现两份数据不一致。
@@ -281,6 +292,95 @@ class Table {
281
292
  this._autoCreateBTrees();
282
293
  }
283
294
 
295
+ // `_rows` 通过访问器暴露:任何整体替换(_loadRows / truncate / WAL 回放)
296
+ // 都会自动丢弃行缓存,避免旧的定位符继续指向已被重写的文件。
297
+ get _rows() {
298
+ return this.__rows;
299
+ }
300
+
301
+ set _rows(rows) {
302
+ this._detachRowCache();
303
+ this.__rows = rows;
304
+ }
305
+
306
+ _detachRowCache() {
307
+ const cache = this._rowCache;
308
+ this._rowCache = null;
309
+ this._rowReader = null;
310
+ if (cache) cache.close();
311
+ }
312
+
313
+ /**
314
+ * 用磁盘定位符初始化行级懒加载。
315
+ * @param {Array<{block:number, off:number}>} locators - 有效行位置(顺序同 readTableSync)
316
+ * @param {(block:number, off:number) => object} loader - 单行读取函数
317
+ * @param {object} [reader] - 底层 JSQLFormat 句柄(缓存丢弃时一并关闭)
318
+ */
319
+ _loadRowRefs(locators, loader, reader) {
320
+ this._detachRowCache();
321
+ const cache = createRowCache(this, locators, loader, () => {
322
+ if (reader && typeof reader._close === 'function') {
323
+ try { reader._close(); } catch (e) { /* 忽略关闭失败 */ }
324
+ }
325
+ });
326
+ this.__rows = cache.rows;
327
+ this._rowCache = cache;
328
+ this._rowReader = reader || null;
329
+ this._rebuildRowMetaStreaming();
330
+ }
331
+
332
+ /** 从磁盘逐行读取并重建主键索引 / B-Tree / 自增计数,不把整表留在内存。 */
333
+ _rebuildRowMetaStreaming() {
334
+ const cache = this._rowCache;
335
+ if (!cache) return;
336
+
337
+ if (this._autoIncrementField) {
338
+ const field = this._autoIncrementField;
339
+ let max = this._autoIncrement;
340
+ cache.scan(row => {
341
+ const v = row[field];
342
+ if (typeof v === 'number' && v > max) max = v;
343
+ });
344
+ this._autoIncrement = max;
345
+ }
346
+
347
+ if (this._pkIndex && this._primaryKey) {
348
+ const field = this._primaryKey;
349
+ this._pkIndex.clear();
350
+ cache.scan((row, i) => {
351
+ const v = row[field];
352
+ if (v !== undefined && v !== null) this._pkIndex.set(v, i);
353
+ });
354
+ }
355
+
356
+ for (const field of Object.keys(this._btrees)) {
357
+ const tree = this._btrees[field];
358
+ tree.clear();
359
+ cache.scan((row, i) => {
360
+ const v = row[field];
361
+ if (v !== undefined && v !== null) tree.insert(v, i);
362
+ });
363
+ }
364
+
365
+ for (const field of Object.keys(this._indexes)) this.createIndex(field);
366
+ }
367
+
368
+ /** 供 Database 在内存压力下按 LRU 逐行淘汰;返回实际淘汰行数。 */
369
+ _evictRows(max) {
370
+ if (!this._rowCache) return 0;
371
+ return this._rowCache.evict(max === undefined ? Infinity : max);
372
+ }
373
+
374
+ /** 整表重写后刷新全部定位符(行顺序不变)。 */
375
+ _resetRowLocators(locators) {
376
+ if (this._rowCache) this._rowCache.reset(locators);
377
+ }
378
+
379
+ /** 行级刷盘后更新被写入行的定位符。 */
380
+ _applyFlushedLocators(rows, locators) {
381
+ if (this._rowCache) this._rowCache.applyLocators(rows, locators);
382
+ }
383
+
284
384
  // P1-2: DDL 后统一刷新 schema 缓存。
285
385
  // dropColumn/renameColumn 过去只改 _cachedSchemaFields,unique/required/numeric/
286
386
  // date/computed 缓存残留旧列 → insertMany 等路径拿到陈旧 schema 直接崩溃或漏校验。
@@ -416,6 +516,7 @@ class Table {
416
516
  }
417
517
  this._db._emitChange('insert', this._name, data);
418
518
  this._db._walLogUpsert(this._name, [data]);
519
+ this._markRowDirty(this._rows[rowIndex]);
419
520
 
420
521
  return data;
421
522
  }
@@ -539,6 +640,7 @@ class Table {
539
640
  }
540
641
  this._db._emitChange('insertMany', this._name, { count: N });
541
642
  this._db._walLogUpsert(this._name, result);
643
+ for (let i = 0; i < N; i++) this._markRowDirty(this._rows[this._rows.length - N + i]);
542
644
  return result;
543
645
  }
544
646
 
@@ -640,6 +742,7 @@ class Table {
640
742
  this._removeFromIndexes(index, oldData);
641
743
  Object.assign(this._rows[index], updates);
642
744
  this._addToIndexes(index, this._rows[index]);
745
+ this._markRowDirty(this._rows[index], this._primaryKey ? oldData[this._primaryKey] : undefined);
643
746
  count++;
644
747
  }
645
748
 
@@ -694,6 +797,7 @@ class Table {
694
797
  }
695
798
  this._db._emitChange('update', this._name, { query: { [this._primaryKey]: id }, updates, count: 1 });
696
799
  this._db._walLogUpsert(this._name, [row]);
800
+ this._markRowDirty(row, oldData[this._primaryKey]);
697
801
  return 1;
698
802
  }
699
803
 
@@ -759,6 +863,11 @@ class Table {
759
863
  }
760
864
  this._db._emitChange('remove', this._name, { query, count });
761
865
  this._db._walLogRemove(this._name, toRemove);
866
+ if (this._primaryKey) {
867
+ for (const row of toRemove) this._markRowDeleted(row[this._primaryKey]);
868
+ } else {
869
+ this._markAllRowsDirty();
870
+ }
762
871
  }
763
872
  return count;
764
873
  }
@@ -821,6 +930,7 @@ class Table {
821
930
  }
822
931
  this._db._emitChange('remove', this._name, { query: { [this._primaryKey]: id }, count: 1 });
823
932
  this._db._walLogRemove(this._name, [row]);
933
+ this._markRowDeleted(row[this._primaryKey]);
824
934
  return 1;
825
935
  }
826
936
 
@@ -846,6 +956,7 @@ class Table {
846
956
  }
847
957
  this._db._emitChange('remove', this._name, { query, count, soft: true });
848
958
  this._db._walLogUpsert(this._name, matched);
959
+ for (const row of matched) this._markRowDirty(row);
849
960
  }
850
961
  return count;
851
962
  }
@@ -892,6 +1003,7 @@ class Table {
892
1003
  this._dirty = true;
893
1004
  this._db._markDirty(this._name);
894
1005
  this._db._walLogReplaceTable(this._name);
1006
+ this._markAllRowsDirty();
895
1007
  return count;
896
1008
  }
897
1009
 
@@ -944,6 +1056,7 @@ class Table {
944
1056
  this._refreshSchemaCache();
945
1057
  this._dirty = true;
946
1058
  this._db._markDirty(this._name);
1059
+ this._markAllRowsDirty(); // schema 变更:整表重写
947
1060
  return this;
948
1061
  }
949
1062
 
@@ -969,6 +1082,7 @@ class Table {
969
1082
  this._refreshSchemaCache();
970
1083
  this._dirty = true;
971
1084
  this._db._markDirty(this._name);
1085
+ this._markAllRowsDirty(); // schema 变更:整表重写
972
1086
  return this;
973
1087
  }
974
1088
 
@@ -1017,6 +1131,7 @@ class Table {
1017
1131
  this._refreshSchemaCache();
1018
1132
  this._dirty = true;
1019
1133
  this._db._markDirty(this._name);
1134
+ this._markAllRowsDirty(); // schema 变更:整表重写
1020
1135
  return this;
1021
1136
  }
1022
1137
 
@@ -1042,6 +1157,7 @@ class Table {
1042
1157
  this._refreshSchemaCache();
1043
1158
  this._dirty = true;
1044
1159
  this._db._markDirty(this._name);
1160
+ this._markAllRowsDirty(); // schema 变更:整表重写
1045
1161
  return this;
1046
1162
  }
1047
1163
 
@@ -1951,6 +2067,57 @@ class Table {
1951
2067
  }
1952
2068
  }
1953
2069
 
2070
+ // ---- 行级脏标记(hybrid/disk 目录模式) ----
2071
+
2072
+ /** 记录一行待刷盘。oldPk 用于主键变更时删除旧索引项。 */
2073
+ _markRowDirty(row, oldPk) {
2074
+ const db = this._db;
2075
+ if (!db || !db._dirMode) return;
2076
+ if (!this._primaryKey) { this._dirtyAll = true; return; }
2077
+ const pk = row[this._primaryKey];
2078
+ if (pk === undefined || pk === null) { this._dirtyAll = true; return; }
2079
+ if (oldPk !== undefined && oldPk !== pk) this._dirtyDeletes.add(oldPk);
2080
+ this._dirtyUpserts.add(row);
2081
+ }
2082
+
2083
+ _markRowDeleted(pkValue) {
2084
+ const db = this._db;
2085
+ if (!db || !db._dirMode) return;
2086
+ if (!this._primaryKey || pkValue === undefined || pkValue === null) {
2087
+ this._dirtyAll = true;
2088
+ return;
2089
+ }
2090
+ this._dirtyDeletes.add(pkValue);
2091
+ for (const r of this._dirtyUpserts) {
2092
+ if (r[this._primaryKey] === pkValue) this._dirtyUpserts.delete(r);
2093
+ }
2094
+ }
2095
+
2096
+ /** 整表脏(无主键表、truncate、回滚/恢复快照等),下次刷盘走全量重写。 */
2097
+ _markAllRowsDirty() {
2098
+ const db = this._db;
2099
+ if (!db || !db._dirMode) return;
2100
+ this._dirtyAll = true;
2101
+ this._dirtyUpserts.clear();
2102
+ this._dirtyDeletes.clear();
2103
+ }
2104
+
2105
+ _peekDirtyRows() {
2106
+ const all = this._dirtyAll || !this._primaryKey
2107
+ || this._dirtyUpserts.size > this._rows.length; // 批量改写过多时全量更划算
2108
+ return {
2109
+ all,
2110
+ upserts: all ? [] : [...this._dirtyUpserts],
2111
+ deletes: all ? [] : [...this._dirtyDeletes]
2112
+ };
2113
+ }
2114
+
2115
+ _clearDirtyRows() {
2116
+ this._dirtyAll = false;
2117
+ this._dirtyUpserts.clear();
2118
+ this._dirtyDeletes.clear();
2119
+ }
2120
+
1954
2121
  _loadRows(rows) {
1955
2122
  this._rows = rows;
1956
2123
  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.6",
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",
@@ -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
+ })();