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 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.3** — stable release · [github.com/vexify-org/JSQL-neo](https://github.com/vexify-org/JSQL-neo) · [jsql.vexify.top](https://jsql.vexify.top)
6
+ > **v6.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)
@@ -169,6 +169,17 @@ await db.start();
169
169
  | Disk | `new Database('./data/app')` | Production persistence |
170
170
  | Hybrid | `new Database('./data', { autoSave: true, saveInterval: 3000 })` | Performance + durability |
171
171
 
172
+ File mode (`new Database('./data/db.json')`) is **not** an in-memory store that only
173
+ writes on exit. Every `insert` / `insertMany` / `update` / `updateById` / `remove` /
174
+ `removeById` / `softDelete` / `truncate` appends one JSONL record to `<file>.wal` and
175
+ `fsync`s it before returning, so a `kill -9` loses nothing that already committed.
176
+ `save()` / `close()` / `stop()` only checkpoint (write a full snapshot, then truncate
177
+ the WAL); they are no longer the moment data first reaches disk.
178
+ WAL is on by default for file mode — pass `wal: false` for the old semantics, or tune
179
+ auto-checkpointing with `walCheckpointOps` (default 1000, `0` disables). Directory
180
+ (`mode: 'disk' | 'hybrid'`) and encrypted (`encryptKey`) databases keep it off unless
181
+ you opt in with `wal: true`, because the WAL is plaintext.
182
+
172
183
  ---
173
184
 
174
185
  ## Query results
package/index.js CHANGED
@@ -1,5 +1,5 @@
1
1
  /**
2
- * JSQL-NEO v6.7.3 — 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
@@ -103,7 +103,9 @@ class Database {
103
103
  * @param {boolean} options.pretty - JSON 是否格式化(默认 true,仅旧文件模式)
104
104
  * @param {string} options.encryptKey - 加密密钥(16/24/32 字节),启用 AES-256-CBC
105
105
  * @param {boolean} options.versioning - 是否启用版本历史(默认 false)
106
- * @param {boolean} options.wal - 是否启用 WAL 模式(默认 false,内存模式自动禁用)
106
+ * @param {boolean} options.wal - 是否启用 WAL(默认 true:文件模式每次写入立即 append+fsync;
107
+ * 内存模式自动禁用;传 false 关闭;目录 hybrid/disk 模式与加密库默认关闭)
108
+ * @param {number} options.walCheckpointOps - WAL 累积多少条后自动做一次快照检查点(默认 1000,0 禁用)
107
109
  * @param {string} options.isolationLevel - 事务隔离级别 'READ_COMMITTED' | 'REPEATABLE_READ'(默认 'READ_COMMITTED')
108
110
  * @param {number} options.slowQueryThreshold - 慢查询阈值 ms(默认 100,0 记录全部,<0 禁用)
109
111
  * @param {boolean} options.fileLock - 是否启用文件锁(默认 false)
@@ -157,13 +159,20 @@ class Database {
157
159
  this._attached = {}; // 附加数据库 { name: db }
158
160
  this._changeStream = null; // 变更流
159
161
 
160
- // WAL(Write-Ahead Logging)
161
- this._walEnabled = options.wal === true && !this._memoryMode;
162
+ // WAL(Write-Ahead Logging):文件模式下默认开启,每次写入立即追加并 fsync,
163
+ // 不再依赖「内存中改完、退出时 save()」的旧语义。
164
+ if (this._memoryMode) this._walEnabled = false;
165
+ else if (this._dirMode) this._walEnabled = options.wal === true;
166
+ else if (this._encryptKey) this._walEnabled = options.wal === true; // WAL 为明文,加密库需显式开启
167
+ else this._walEnabled = options.wal !== false;
162
168
  this._walPath = this._filePath ? this._filePath + '.wal' : null;
163
169
  this._walOps = []; // WAL 操作日志(内存镜像)
164
170
  this._walFlushedCount = 0; // 已落盘记录数(append-only 增量追加用)
165
171
  this._walReplaying = false; // 回放中:抑制再次写日志
166
172
  this._walReplaySummary = null;
173
+ this._walOpCount = 0; // 自上次检查点以来的操作数
174
+ this._walCheckpointOps = options.walCheckpointOps !== undefined ? options.walCheckpointOps : 1000;
175
+ this._walCheckpointScheduled = false;
167
176
 
168
177
  // 事务隔离:默认 REPEATABLE_READ(begin 时保存行快照,rollback 可回滚)
169
178
  this._isolationLevel = options.isolationLevel || 'REPEATABLE_READ';
@@ -286,9 +295,17 @@ class Database {
286
295
  if (!fs.existsSync(file)) return null;
287
296
  try {
288
297
  const fmt = new JSQLFormat(file);
289
- const { rows } = fmt.readTableSync(name);
298
+ fmt._open();
290
299
  const table = new Table(name, meta.schema, this);
291
- 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();
292
309
  this._tables[name] = table;
293
310
  if (this._versioning) this._versions[name] = [];
294
311
  this._touchTable(name);
@@ -329,7 +346,7 @@ class Database {
329
346
  const names = [...this._dirtyTables];
330
347
  for (const name of names) {
331
348
  try {
332
- this._flushTable(name);
349
+ this._flushTableDelta(name);
333
350
  this._dirtyTables.delete(name);
334
351
  } catch (e) {
335
352
  // 保留脏标记,下次 flush 重试;错误对外传播而非静默
@@ -339,6 +356,53 @@ class Database {
339
356
  this._saveMeta();
340
357
  }
341
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
+
342
406
  _flushTable(name) {
343
407
  const table = this._tables[name];
344
408
  if (!table) return;
@@ -349,6 +413,11 @@ class Database {
349
413
  const pkField = Object.keys(table._schema).find(f => table._schema[f].primaryKey) || null;
350
414
  fmt.writeTable(name, table._schema, table._rows, pkField);
351
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();
352
421
  } finally {
353
422
  fmt._close();
354
423
  }
@@ -376,9 +445,23 @@ class Database {
376
445
  const candidates = Object.keys(this._tables)
377
446
  .filter(n => n !== '__meta__' && !this._versioning && this._meta.tables[n]);
378
447
  candidates.sort((a, b) => (this._lastAccess[a] || 0) - (this._lastAccess[b] || 0));
448
+
449
+ // 先做行级 LRU 淘汰:把冷行回退成磁盘定位符,表结构与索引保持不变。
450
+ // 这一步只在两次同步操作之间触发(定时器回调),不会打断正在进行的查询。
379
451
  for (const name of candidates) {
380
452
  if (budget !== undefined && process.memoryUsage().rss <= budget) break;
381
- 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; }
382
465
  delete this._tables[name];
383
466
  delete this[name];
384
467
  this._dirtyTables.delete(name);
@@ -441,23 +524,89 @@ class Database {
441
524
  * append-only 下崩溃最多丢失最后一行(已 fsync 过的行不会丢)。
442
525
  */
443
526
  _walWrite(op) {
444
- if (!this._walEnabled) return;
527
+ if (!this._walEnabled || this._loading) return;
445
528
  const entry = {
446
529
  ...op,
447
530
  timestamp: Date.now(),
448
531
  sequence: this._walOps.length + 1
449
532
  };
450
533
  this._walOps.push(entry);
534
+ this._walOpCount++;
451
535
  // 恢复过程中重放操作不能再次写 WAL,否则会无限增长
452
536
  if (this._walReplaying) return;
453
537
  this._flushWAL();
538
+ this._maybeCheckpointWAL();
539
+ }
540
+
541
+ /**
542
+ * 记录「写入后的行」:有主键时按主键幂等 upsert,无主键时退化为整表镜像。
543
+ * 这样任何写入都立刻落到 WAL,崩溃后按序回放即可恢复。
544
+ */
545
+ _walLogUpsert(tableName, rows) {
546
+ if (!this._walEnabled || this._walReplaying || this._loading) return;
547
+ const t = this._tables[tableName];
548
+ if (!t || !Array.isArray(rows) || rows.length === 0) return;
549
+ if (t._primaryKey) {
550
+ const pk = t._primaryKey;
551
+ const out = rows.filter(r => r && r[pk] !== undefined && r[pk] !== null).map(r => ({ ...r }));
552
+ if (out.length === 0) return;
553
+ this._walWrite({ op: 'upsertRows', table: tableName, pk, rows: out });
554
+ } else {
555
+ this._walLogReplaceTable(tableName);
556
+ }
557
+ }
558
+
559
+ /** 记录删除:有主键时只记主键列表,无主键时记录整表镜像。 */
560
+ _walLogRemove(tableName, removedRows) {
561
+ if (!this._walEnabled || this._walReplaying || this._loading) return;
562
+ const t = this._tables[tableName];
563
+ if (!t) return;
564
+ if (t._primaryKey && Array.isArray(removedRows) && removedRows.length) {
565
+ const pk = t._primaryKey;
566
+ const ids = removedRows.map(r => r && r[pk]).filter(v => v !== undefined && v !== null);
567
+ if (ids.length) {
568
+ this._walWrite({ op: 'removeRows', table: tableName, pk, ids });
569
+ return;
570
+ }
571
+ }
572
+ this._walLogReplaceTable(tableName);
573
+ }
574
+
575
+ /** 无主键表 / truncate / 结构变化:写入该表的完整行镜像。 */
576
+ _walLogReplaceTable(tableName) {
577
+ if (!this._walEnabled || this._walReplaying || this._loading) return;
578
+ const t = this._tables[tableName];
579
+ if (!t) return;
580
+ this._walWrite({ op: 'replaceTable', table: tableName, rows: t._rows.map(r => ({ ...r })) });
581
+ }
582
+
583
+ /**
584
+ * WAL 增长到阈值后自动做一次快照检查点,避免日志无限膨胀。
585
+ * 事务进行中不检查点,否则未提交的数据会进入快照。
586
+ */
587
+ _maybeCheckpointWAL() {
588
+ if (!this._walEnabled || this._walCheckpointScheduled) return;
589
+ if (this._walCheckpointOps <= 0 || this._walOpCount < this._walCheckpointOps) return;
590
+ if (this._loading || this._walReplaying || this._transaction) return;
591
+ this._walCheckpointScheduled = true;
592
+ const run = () => {
593
+ this._walCheckpointScheduled = false;
594
+ if (this._loading || this._walReplaying || this._transaction) return;
595
+ try {
596
+ this.save();
597
+ } catch (e) {
598
+ // 快照失败时保留 WAL,数据仍可恢复
599
+ }
600
+ };
601
+ if (typeof setImmediate === 'function') setImmediate(run);
602
+ else setTimeout(run, 0);
454
603
  }
455
604
 
456
605
  /**
457
606
  * 将新增的 WAL 记录追加到磁盘(append-only)
458
607
  */
459
608
  _flushWAL() {
460
- if (!this._walEnabled || this._walOps.length === 0) return;
609
+ if (!this._walEnabled || !this._walPath || this._walOps.length === 0) return;
461
610
  try {
462
611
  const dir = path.dirname(this._walPath);
463
612
  if (!fs.existsSync(dir)) fs.mkdirSync(dir, { recursive: true });
@@ -489,6 +638,7 @@ class Database {
489
638
  if (!this._walEnabled) return;
490
639
  this._walOps = [];
491
640
  this._walFlushedCount = 0;
641
+ this._walOpCount = 0;
492
642
  try {
493
643
  if (this._walPath && fs.existsSync(this._walPath)) {
494
644
  fs.unlinkSync(this._walPath);
@@ -567,7 +717,45 @@ class Database {
567
717
  case 'insert': {
568
718
  const t = op.table && this._tables[op.table];
569
719
  if (!t || !Array.isArray(op.rows) || op.rows.length === 0) { failed++; break; }
570
- for (const __e of op.rows) t._rows.push(__e);
720
+ const pk = t._primaryKey;
721
+ for (const __e of op.rows) {
722
+ // 幂等:快照已包含该行时覆盖而不是重复插入
723
+ if (pk && __e && __e[pk] !== undefined) {
724
+ const ai = t._rows.findIndex(r => r && r[pk] === __e[pk]);
725
+ if (ai >= 0) { t._rows[ai] = __e; continue; }
726
+ }
727
+ t._rows.push(__e);
728
+ }
729
+ touched.add(t);
730
+ replayed++;
731
+ break;
732
+ }
733
+ case 'upsertRows': {
734
+ const t = op.table && this._tables[op.table];
735
+ if (!t || !op.pk || !Array.isArray(op.rows)) { failed++; break; }
736
+ for (const __r of op.rows) {
737
+ if (!__r || typeof __r !== 'object') continue;
738
+ const ai = t._rows.findIndex(r => r && String(r[op.pk]) === String(__r[op.pk]));
739
+ if (ai >= 0) t._rows[ai] = { ...__r };
740
+ else t._rows.push({ ...__r });
741
+ }
742
+ touched.add(t);
743
+ replayed++;
744
+ break;
745
+ }
746
+ case 'removeRows': {
747
+ const t = op.table && this._tables[op.table];
748
+ if (!t || !op.pk || !Array.isArray(op.ids)) { failed++; break; }
749
+ const gone = new Set(op.ids.map(String));
750
+ t._rows = t._rows.filter(r => !r || !gone.has(String(r[op.pk])));
751
+ touched.add(t);
752
+ replayed++;
753
+ break;
754
+ }
755
+ case 'replaceTable': {
756
+ const t = op.table && this._tables[op.table];
757
+ if (!t || !Array.isArray(op.rows)) { failed++; break; }
758
+ t._rows = op.rows.map(r => ({ ...r }));
571
759
  touched.add(t);
572
760
  replayed++;
573
761
  break;
@@ -605,6 +793,7 @@ class Database {
605
793
  if (typeof t._rebuildPKIndex === 'function') t._rebuildPKIndex();
606
794
  if (typeof t._rebuildAllBTrees === 'function') t._rebuildAllBTrees();
607
795
  for (const field of Object.keys(t._indexes || {})) t.createIndex(field);
796
+ if (typeof t._markAllRowsDirty === 'function') t._markAllRowsDirty();
608
797
  if (t._autoIncrementField) {
609
798
  for (const row of t._rows) {
610
799
  const v = row[t._autoIncrementField];
@@ -679,6 +868,9 @@ class Database {
679
868
  case 'insert':
680
869
  case 'update':
681
870
  case 'remove':
871
+ case 'upsertRows':
872
+ case 'removeRows':
873
+ case 'replaceTable':
682
874
  // 数据类操作由 _recoverFromWAL 按序直接处理(需维护表内行序),
683
875
  // 不走这里。
684
876
  return false;
@@ -688,6 +880,8 @@ class Database {
688
880
  case 'begin':
689
881
  case 'commit':
690
882
  case 'rollback':
883
+ case 'rollbackTo':
884
+ case 'savepoint':
691
885
  case 'undo':
692
886
  case 'restore':
693
887
  case 'import':
@@ -1375,6 +1569,11 @@ class Database {
1375
1569
 
1376
1570
  if (this._transaction.snapshot) {
1377
1571
  this._restoreTxSnapshot(this._transaction.snapshot);
1572
+ // 回滚后的状态必须重新写入 WAL:否则 WAL 里已记录的写入
1573
+ // 会在崩溃重放时被重新应用,回滚等于没做。
1574
+ for (const name of Object.keys(this._transaction.snapshot)) {
1575
+ if (this._tables[name]) this._walLogReplaceTable(name);
1576
+ }
1378
1577
  } else {
1379
1578
  // READ_COMMITTED:没有行快照,只能退回自增值
1380
1579
  for (const [name, table] of Object.entries(this._tables)) {
@@ -1429,6 +1628,9 @@ class Database {
1429
1628
  const list = this._requireSavepoints(name, 'ROLLBACK TO SAVEPOINT');
1430
1629
  const idx = this._findSavepoint(list, name);
1431
1630
  this._restoreTxSnapshot(list[idx].snap);
1631
+ for (const tableName of Object.keys(list[idx].snap)) {
1632
+ if (this._tables[tableName]) this._walLogReplaceTable(tableName);
1633
+ }
1432
1634
  list.length = idx + 1;
1433
1635
  this._walWrite({ op: 'rollbackTo', name });
1434
1636
  this._markDirtyLegacy();
@@ -1536,6 +1738,7 @@ class Database {
1536
1738
  versions.pop();
1537
1739
  const snapshot = versions[versions.length - 1];
1538
1740
  table._rows = snapshot.rows.map(r => ({ ...r }));
1741
+ if (typeof table._markAllRowsDirty === 'function') table._markAllRowsDirty();
1539
1742
  table._autoIncrement = 0;
1540
1743
  for (const row of table._rows) {
1541
1744
  if (table._autoIncrementField && row[table._autoIncrementField] > table._autoIncrement) {
@@ -1806,17 +2009,11 @@ class Database {
1806
2009
  if (!(await this._runHooks('beforeInsert', [tableName, arr]))) return [];
1807
2010
  const pk = this._pkOf(table);
1808
2011
  const ids = [];
1809
- const logged = [];
1810
2012
  for (const row of arr) {
1811
2013
  const r = table.insert(row);
1812
- const id = pk ? r[pk] : table._rows.length;
1813
- ids.push(id);
1814
- // 记录落库后的完整行(含自增主键),保证回放能还原真实数据
1815
- if (pk) logged.push({ ...r });
1816
- else logged.push(r);
1817
- }
1818
- // 有主键才可幂等回放;无主键表回放会重复插行,故不记录
1819
- if (pk) this._walWrite({ op: 'insert', table: tableName, rows: logged });
2014
+ ids.push(pk ? r[pk] : table._rows.length);
2015
+ }
2016
+ // WAL 已由 Table.insert() 在写入瞬间逐条落盘(含无主键表的整表镜像)
1820
2017
  this._emit('insert', { table: tableName, count: arr.length, ids });
1821
2018
  await this._runHooks('afterInsert', [tableName, arr, ids]);
1822
2019
  this._markDirty(tableName);
@@ -1828,6 +2025,7 @@ class Database {
1828
2025
  if (this._dirMode) {
1829
2026
  this._flushDirty();
1830
2027
  this._saveMeta();
2028
+ this._checkpoint();
1831
2029
  } else if (!this._memoryMode) {
1832
2030
  this.save();
1833
2031
  }
@@ -1840,6 +2038,14 @@ class Database {
1840
2038
  if (pk) {
1841
2039
  // Issue #44:主键查询值按列类型归一('5' → 5),与索引/insert 保持一致
1842
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
+ }
1843
2049
  return table._rows.find(r => r[pk] === key || r[pk] === id) || null;
1844
2050
  }
1845
2051
  // 无主键表:id 是行对象(可能是 find() 返回的浅拷贝)时,用内容匹配代替引用比较。
@@ -1991,12 +2197,22 @@ class Database {
1991
2197
  // 改主键/唯一值时索引必须同步:否则 _pkIndex 还指向旧值,
1992
2198
  // 后续 FK 校验 findOne({id:新值}) 查不到刚更新的父行。
1993
2199
  {
1994
- 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;
1995
2210
  if (rowIndex !== -1) table._removeFromIndexes(rowIndex, row);
1996
2211
  Object.assign(row, validated);
1997
2212
  if (rowIndex !== -1) table._addToIndexes(rowIndex, row);
2213
+ if (typeof table._markRowDirty === 'function') table._markRowDirty(row, oldPk);
1998
2214
  }
1999
- if (pk) this._walWrite({ op: 'update', table: tableName, pk, id, row: { ...validated } });
2215
+ this._walLogUpsert(tableName, [row]);
2000
2216
  this._emit('update', { table: tableName, id, data: validated });
2001
2217
  await this._runHooks('afterUpdate', [tableName, id, validated, { ok: true }]);
2002
2218
  this._markDirty(tableName);
@@ -2010,16 +2226,20 @@ class Database {
2010
2226
  if (!(await this._runHooks('beforeUpdate', [tableName, pairs]))) return;
2011
2227
  const pk = this._pkOf(table);
2012
2228
  let count = 0;
2229
+ const changed = [];
2013
2230
  for (const [id, data] of pairs) {
2014
2231
  const row = this._resolveId(table, id);
2015
2232
  if (row) {
2016
2233
  // CHECK 约束(Issue #70):批量更新同样不能在无校验的情况下写行
2017
2234
  if (typeof table._enforceChecks === 'function') table._enforceChecks({ ...row, ...data });
2235
+ const oldPk = pk ? row[pk] : undefined;
2018
2236
  Object.assign(row, data);
2237
+ if (typeof table._markRowDirty === 'function') table._markRowDirty(row, oldPk);
2019
2238
  count++;
2020
- if (pk) this._walWrite({ op: 'update', table: tableName, pk, id, row: { ...data } });
2239
+ changed.push(row);
2021
2240
  }
2022
2241
  }
2242
+ if (changed.length) this._walLogUpsert(tableName, changed);
2023
2243
  this._emit('update', { table: tableName, entries: pairs, result: { ok: true, count } });
2024
2244
  await this._runHooks('afterUpdate', [tableName, pairs, { ok: true, count }]);
2025
2245
  this._markDirty(tableName);
@@ -2033,7 +2253,7 @@ class Database {
2033
2253
  if (table._primaryKey) {
2034
2254
  const removed = table.removeById(id);
2035
2255
  if (removed === 0) return { ok: false, error: 'not found' };
2036
- this._walWrite({ op: 'remove', table: tableName, pk: table._primaryKey, id });
2256
+ // WAL 由 Table.removeById() 记录
2037
2257
  this._emit('delete', { table: tableName, id });
2038
2258
  await this._runHooks('afterDelete', [tableName, id, { ok: true }]);
2039
2259
  this._markDirty(tableName);
@@ -2045,6 +2265,7 @@ class Database {
2045
2265
  table._rebuildPKIndex();
2046
2266
  table._rebuildAllBTrees();
2047
2267
  for (const field of Object.keys(table._indexes)) table.createIndex(field);
2268
+ this._walLogReplaceTable(tableName);
2048
2269
  this._emit('delete', { table: tableName, id });
2049
2270
  await this._runHooks('afterDelete', [tableName, id, { ok: true }]);
2050
2271
  this._markDirty(tableName);
@@ -2082,11 +2303,13 @@ class Database {
2082
2303
  }
2083
2304
  if (targets.length) {
2084
2305
  table._rows = table._rows.filter((_, idx) => !seen.has(idx));
2306
+ if (typeof table._markAllRowsDirty === 'function') table._markAllRowsDirty();
2085
2307
  removed = targets.length;
2086
2308
  }
2087
2309
  table._rebuildPKIndex();
2088
2310
  table._rebuildAllBTrees();
2089
2311
  for (const field of Object.keys(table._indexes)) table.createIndex(field);
2312
+ if (removed > 0) this._walLogReplaceTable(tableName);
2090
2313
  }
2091
2314
  this._emit('delete', { table: tableName, ids, result: { ok: true, count: removed } });
2092
2315
  await this._runHooks('afterDelete', [tableName, ids, { ok: true, count: removed }]);
@@ -2103,10 +2326,12 @@ class Database {
2103
2326
  const matched = table._applyFilter(table._getVisibleRows(), filter || {});
2104
2327
  const matchSet = new Set(matched);
2105
2328
  table._rows = table._rows.filter(r => !matchSet.has(r));
2329
+ if (typeof table._markAllRowsDirty === 'function') table._markAllRowsDirty();
2106
2330
  const removed = before - table._rows.length;
2107
2331
  table._rebuildPKIndex();
2108
2332
  table._rebuildAllBTrees();
2109
2333
  for (const field of Object.keys(table._indexes)) table.createIndex(field);
2334
+ if (removed > 0) this._walLogRemove(tableName, matched);
2110
2335
  this._emit('delete', { table: tableName, ids: [], result: { ok: true, count: removed } });
2111
2336
  await this._runHooks('afterDelete', [tableName, [filter], { ok: true, count: removed }]);
2112
2337
  this._markDirty(tableName);
@@ -2119,10 +2344,7 @@ class Database {
2119
2344
  const arr = Array.isArray(items) ? items : [items];
2120
2345
  if (!(await this._runHooks('beforeInsert', [tableName, arr]))) return [];
2121
2346
  const inserted = table.insertMany(arr);
2122
- // P1-6: insertMany 不写 WAL——崩溃恢复时丢失这些操作
2123
- if (table._primaryKey && inserted.length > 0) {
2124
- this._walWrite({ op: 'insert', table: tableName, rows: inserted });
2125
- }
2347
+ // WAL 由 Table.insertMany() 记录
2126
2348
  this._emit('insert', { table: tableName, count: arr.length });
2127
2349
  await this._runHooks('afterInsert', [tableName, arr, inserted]);
2128
2350
  this._markDirty(tableName);
@@ -2134,14 +2356,7 @@ class Database {
2134
2356
  if (!table) throw createError('ER_NO_SUCH_TABLE', tableName);
2135
2357
  if (!(await this._runHooks('beforeUpdate', [tableName, query, updates]))) return 0;
2136
2358
  const count = table.update(query, updates);
2137
- // P1-6: update 不写 WAL——崩溃恢复时丢失这些操作
2138
- if (table._primaryKey && count > 0) {
2139
- const updatedRows = table.find(query);
2140
- for (const row of updatedRows) {
2141
- const id = row[table._primaryKey];
2142
- if (id !== undefined) this._walWrite({ op: 'update', table: tableName, pk: table._primaryKey, id, row: { ...row } });
2143
- }
2144
- }
2359
+ // WAL 由 Table.update() 记录
2145
2360
  this._emit('update', { table: tableName, query, count });
2146
2361
  await this._runHooks('afterUpdate', [tableName, query, updates, count]);
2147
2362
  this._markDirty(tableName);
@@ -2152,14 +2367,7 @@ class Database {
2152
2367
  const table = this._ensureTable(tableName);
2153
2368
  if (!table) throw createError('ER_NO_SUCH_TABLE', tableName);
2154
2369
  if (!(await this._runHooks('beforeDelete', [tableName, query]))) return 0;
2155
- // P1-6: delete 不写 WAL——崩溃恢复时丢失这些操作
2156
- if (table._primaryKey) {
2157
- const toDelete = table.find(query);
2158
- for (const row of toDelete) {
2159
- const id = row[table._primaryKey];
2160
- if (id !== undefined) this._walWrite({ op: 'remove', table: tableName, pk: table._primaryKey, id });
2161
- }
2162
- }
2370
+ // WAL 由 Table.remove() 记录
2163
2371
  const count = table.remove(query);
2164
2372
  this._emit('delete', { table: tableName, query, count });
2165
2373
  await this._runHooks('afterDelete', [tableName, query, count]);
@@ -2170,14 +2378,7 @@ class Database {
2170
2378
  truncate(tableName) {
2171
2379
  const table = this._ensureTable(tableName);
2172
2380
  if (!table) throw createError('ER_NO_SUCH_TABLE', tableName);
2173
- // P1-6: truncate 不写 WAL——崩溃恢复时丢失这些操作
2174
- if (table._primaryKey) {
2175
- const toDelete = table.find({});
2176
- for (const row of toDelete) {
2177
- const id = row[table._primaryKey];
2178
- if (id !== undefined) this._walWrite({ op: 'remove', table: tableName, pk: table._primaryKey, id });
2179
- }
2180
- }
2381
+ // WAL 由 Table.truncate() 记录整表镜像
2181
2382
  const count = table.truncate();
2182
2383
  this._emit('delete', { table: tableName, count });
2183
2384
  this._markDirty(tableName);
@@ -2194,7 +2395,11 @@ class Database {
2194
2395
  try {
2195
2396
  this._flushDirty();
2196
2397
  this._saveMeta();
2398
+ this._checkpoint();
2197
2399
  } catch (e) {}
2400
+ } else if (!this._memoryMode) {
2401
+ // 正常关闭时做一次快照检查点,缩短下次启动的回放时间
2402
+ try { this.save(); } catch (e) {}
2198
2403
  }
2199
2404
  if (this._sigInstalled) {
2200
2405
  this._sigInstalled = false;
@@ -2304,6 +2509,7 @@ class Database {
2304
2509
  if (this._dirMode) {
2305
2510
  this._flushDirty();
2306
2511
  this._saveMeta();
2512
+ this._checkpoint();
2307
2513
  return;
2308
2514
  }
2309
2515
 
@@ -2423,6 +2629,10 @@ class Database {
2423
2629
  this._sigInstalled = false;
2424
2630
  Database.removeSignalHandler(this);
2425
2631
  }
2632
+ // 关闭行缓存持有的文件句柄
2633
+ for (const t of Object.values(this._tables)) {
2634
+ if (t && typeof t._detachRowCache === 'function') t._detachRowCache();
2635
+ }
2426
2636
  this._tables = {};
2427
2637
  }
2428
2638