jsql-neo 6.8.26 → 6.10.1

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.
Files changed (141) hide show
  1. package/README.md +9 -4
  2. package/bin/jsql-server-control.js +58 -14
  3. package/index.d.ts +25 -5
  4. package/index.js +1 -1
  5. package/lib/bigint_json.js +13 -1
  6. package/lib/btree.js +12 -3
  7. package/lib/cache.js +12 -1
  8. package/lib/columnar_fast.js +13 -2
  9. package/lib/database.js +477 -68
  10. package/lib/errors.js +2 -0
  11. package/lib/migrate.js +186 -75
  12. package/lib/mod.js +41 -12
  13. package/lib/mongo_server.js +688 -254
  14. package/lib/multiserver.js +4 -1
  15. package/lib/mysql_compat.js +54 -11
  16. package/lib/mysql_server.js +261 -66
  17. package/lib/nedb_compat.js +7 -1
  18. package/lib/objectid.js +14 -6
  19. package/lib/pg_server.js +393 -11
  20. package/lib/plugin.js +34 -3
  21. package/lib/query.js +12 -6
  22. package/lib/redis_server.js +105 -42
  23. package/lib/sql.js +585 -70
  24. package/lib/table.js +153 -46
  25. package/lib/tui.js +24 -8
  26. package/lib/web_ui.js +33 -2
  27. package/package.json +2 -2
  28. package/test/alter-table.test.js +11 -5
  29. package/test/columnar-vector.test.js +2 -1
  30. package/test/compat-v1.test.js +1 -1
  31. package/test/extra-coverage.test.js +6 -7
  32. package/test/issue-258-300.test.js +6 -0
  33. package/test/issue-259-264.test.js +5 -1
  34. package/test/issue-312-320.test.js +11 -4
  35. package/test/issue-326.test.js +42 -0
  36. package/test/issue-327-418.test.js +1 -1
  37. package/test/issue-329-346.test.js +22 -5
  38. package/test/issue-336.test.js +56 -0
  39. package/test/issue-353.test.js +34 -0
  40. package/test/issue-356.test.js +27 -0
  41. package/test/issue-357-365.test.js +1 -1
  42. package/test/issue-361.test.js +55 -0
  43. package/test/issue-370.test.js +43 -0
  44. package/test/issue-373.test.js +40 -0
  45. package/test/issue-374.test.js +62 -0
  46. package/test/issue-378.test.js +39 -0
  47. package/test/issue-379.test.js +39 -0
  48. package/test/issue-38.test.js +2 -2
  49. package/test/issue-380.test.js +27 -0
  50. package/test/issue-383-402.test.js +4 -3
  51. package/test/issue-392.test.js +25 -0
  52. package/test/issue-397.test.js +44 -0
  53. package/test/issue-403.test.js +47 -0
  54. package/test/issue-404.test.js +58 -0
  55. package/test/issue-407.test.js +40 -0
  56. package/test/issue-408.test.js +92 -0
  57. package/test/issue-409.test.js +32 -0
  58. package/test/issue-410.test.js +36 -0
  59. package/test/issue-411.test.js +38 -0
  60. package/test/issue-412.test.js +50 -0
  61. package/test/issue-414.test.js +46 -0
  62. package/test/issue-417.test.js +56 -0
  63. package/test/issue-420.test.js +87 -0
  64. package/test/issue-421.test.js +30 -0
  65. package/test/issue-422.test.js +33 -0
  66. package/test/issue-424.test.js +44 -0
  67. package/test/issue-425.test.js +22 -0
  68. package/test/issue-426.test.js +22 -0
  69. package/test/issue-427.test.js +36 -0
  70. package/test/issue-429.test.js +38 -0
  71. package/test/issue-431.test.js +41 -0
  72. package/test/issue-432.test.js +37 -0
  73. package/test/issue-436.test.js +47 -0
  74. package/test/issue-445-449.test.js +278 -0
  75. package/test/issue-450-454.test.js +202 -0
  76. package/test/issue-455-459.test.js +351 -0
  77. package/test/issue-460-464.test.js +195 -0
  78. package/test/issue-465-469.test.js +201 -0
  79. package/test/issue-471.test.js +150 -0
  80. package/test/issue-474.test.js +59 -0
  81. package/test/issue-475.test.js +38 -0
  82. package/test/issue-476.test.js +50 -0
  83. package/test/issue-477.test.js +54 -0
  84. package/test/issue-478.test.js +52 -0
  85. package/test/issue-479.test.js +44 -0
  86. package/test/issue-481.test.js +51 -0
  87. package/test/issue-482.test.js +36 -0
  88. package/test/issue-483.test.js +57 -0
  89. package/test/issue-486.test.js +69 -0
  90. package/test/issue-487.test.js +54 -0
  91. package/test/issue-488.test.js +69 -0
  92. package/test/issue-490.test.js +20 -0
  93. package/test/issue-491.test.js +21 -0
  94. package/test/issue-492.test.js +19 -0
  95. package/test/issue-493.test.js +30 -0
  96. package/test/issue-494.test.js +82 -0
  97. package/test/issue-495.test.js +86 -0
  98. package/test/issue-496.test.js +98 -0
  99. package/test/issue-497.test.js +29 -0
  100. package/test/issue-498.test.js +32 -0
  101. package/test/issue-499.test.js +41 -0
  102. package/test/issue-500.test.js +39 -0
  103. package/test/issue-503.test.js +43 -0
  104. package/test/issue-504.test.js +83 -0
  105. package/test/issue-505.test.js +29 -0
  106. package/test/issue-529.test.js +39 -0
  107. package/test/issue-530.test.js +69 -0
  108. package/test/issue-536.test.js +46 -0
  109. package/test/issue-537.test.js +52 -0
  110. package/test/issue-539.test.js +65 -0
  111. package/test/issue-540.test.js +31 -0
  112. package/test/issue-546.test.js +68 -0
  113. package/test/issue-547.test.js +27 -0
  114. package/test/issue-548.test.js +68 -0
  115. package/test/issue-549.test.js +26 -0
  116. package/test/issue-550.test.js +52 -0
  117. package/test/issue-551.test.js +34 -0
  118. package/test/issue-552.test.js +30 -0
  119. package/test/issue-553.test.js +29 -0
  120. package/test/issue-554.test.js +29 -0
  121. package/test/issue-555.test.js +22 -0
  122. package/test/issue-556.test.js +25 -0
  123. package/test/issue-565.test.js +32 -0
  124. package/test/issue-566.test.js +30 -0
  125. package/test/issue-567.test.js +56 -0
  126. package/test/issue-568.test.js +46 -0
  127. package/test/issue-569.test.js +25 -0
  128. package/test/issue-570.test.js +30 -0
  129. package/test/issue-571.test.js +32 -0
  130. package/test/issue-572.test.js +64 -0
  131. package/test/issue-573.test.js +71 -0
  132. package/test/issue-574.test.js +63 -0
  133. package/test/issue-581.test.js +46 -0
  134. package/test/issue-59.test.js +17 -4
  135. package/test/issue-69-70.test.js +1 -1
  136. package/test/issue-mysql-harness.js +260 -0
  137. package/test/issue-pg5-helper.js +135 -0
  138. package/test/mongo-arrays.test.js +63 -0
  139. package/test/mongo-objectid.test.js +2 -2
  140. package/test/mongo-persistence.test.js +3 -3
  141. package/test/wal-recovery.test.js +17 -9
package/lib/database.js CHANGED
@@ -108,9 +108,12 @@ class Database {
108
108
  * @param {boolean} options.pretty - JSON 是否格式化(默认 true,仅旧文件模式)
109
109
  * @param {string} options.encryptKey - 加密密钥(16/24/32 字节),启用 AES-256-CBC
110
110
  * @param {boolean} options.versioning - 是否启用版本历史(默认 false)
111
- * @param {boolean} options.wal - 是否启用 WAL(默认 true:文件模式每次写入立即 append+fsync;
112
- * 内存模式自动禁用;传 false 关闭;目录 hybrid/disk 模式与加密库默认关闭)
111
+ * @param {boolean} options.wal - 是否启用 WAL(默认 true:文件模式写入立即 append 到内核,fsync 按
112
+ * walSyncInterval 合并;内存模式自动禁用;传 false 关闭;目录 hybrid/disk 模式与加密库默认关闭)
113
113
  * @param {number} options.walCheckpointOps - WAL 累积多少条后自动做一次快照检查点(默认 1000,0 禁用)
114
+ * @param {number} options.walSyncInterval - WAL fsync 合并窗口 ms(默认 20)。写入仍立即 write() 到内核,
115
+ * 进程崩溃 / kill -9 不丢已提交写入;fsync 按窗口合并以摊薄磁盘刷写成本(掉电最多丢一个窗口,
116
+ * 等价 SQLite WAL 的 synchronous=NORMAL)。传 0 恢复「每条写入立即 fsync」的严格模式。
114
117
  * @param {string} options.isolationLevel - 事务隔离级别 'READ_COMMITTED' | 'REPEATABLE_READ'(默认 'READ_COMMITTED')
115
118
  * @param {number} options.slowQueryThreshold - 慢查询阈值 ms(默认 100,0 记录全部,<0 禁用)
116
119
  * @param {boolean} options.fileLock - 是否启用文件锁(默认 false)
@@ -201,12 +204,24 @@ class Database {
201
204
  : null;
202
205
  this._walReplaying = false; // 回放中:抑制再次写日志
203
206
  this._walReplaySummary = null;
207
+ this._metaCorrupt = null; // #453:meta.json 损坏/兜底恢复的排障记录
204
208
  this._walOpCount = 0; // 自上次检查点以来的操作数
205
209
  this._walCheckpointOps = options.walCheckpointOps !== undefined ? options.walCheckpointOps : 1000;
206
210
  this._walCheckpointScheduled = false;
207
-
208
- // 事务隔离:默认 REPEATABLE_READ(begin 时保存行快照,rollback 可回滚)
209
- this._isolationLevel = options.isolationLevel || 'REPEATABLE_READ';
211
+ // 落盘策略:write() 立即执行(进程崩溃/ kill -9 安全),fsync 合并到时间窗口内批量执行。
212
+ // 逐条 fsync 是此前单条写入只有 ~1k/s 的根因;合并后吞吐提升一个数量级,
213
+ // 同时保留「已提交写入在进程崩溃后不丢」的承诺(掉电窗口外的数据仍在页缓存里)。
214
+ this._walSyncInterval = options.walSyncInterval !== undefined ? Number(options.walSyncInterval) : 20;
215
+ if (!(this._walSyncInterval >= 0)) this._walSyncInterval = 20;
216
+ this._walFd = null; // 常驻追加句柄(避免每次 open/close 的系统调用)
217
+ this._walFdPath = null; // 句柄绑定的路径(路径变化时需重开,不能写到旧 inode)
218
+ this._walDirReady = false; // 目录已确保存在(避免每次 existsSync)
219
+ this._walNeedsSync = false; // 有已 write() 但尚未 fsync 的数据
220
+ this._walSyncTimer = null;
221
+
222
+ // 事务隔离:默认 READ_COMMITTED(每条语句读到最新已提交数据);
223
+ // 传 'REPEATABLE_READ' 则固定事务开始时的行快照。
224
+ this._isolationLevel = options.isolationLevel || 'READ_COMMITTED';
210
225
 
211
226
  // JSql 格式 (binary block-based)
212
227
  this._jsqlMode = this._filePath && this._filePath.endsWith('.jsql');
@@ -251,6 +266,10 @@ class Database {
251
266
 
252
267
  _initDirStore() {
253
268
  if (!this._filePath) throw new Error('hybrid/disk mode requires a directory path');
269
+ // #449:目录模式同样要拿目录级文件锁(`<dir>.lock`),与 legacy 单文件模式一致;
270
+ // 否则同目录两个实例可并存,后 flush 者用陈旧内存快照全量覆写,抹掉前者已提交行。
271
+ // 崩溃残留锁按既有 30s 过期逻辑在 _acquireLock 内接管。
272
+ this._acquireLock();
254
273
  fs.mkdirSync(this._filePath, { recursive: true });
255
274
  this._metaPath = path.join(this._filePath, 'meta.json');
256
275
  this._meta = { version: 1, tables: {} };
@@ -260,9 +279,11 @@ class Database {
260
279
  // 格式:{"__enc":"v1","data":"<base64>"};无密钥时按明文 JSON 读(兼容旧库)。
261
280
  const rawMeta = fs.readFileSync(this._metaPath, 'utf8');
262
281
  let parsed;
282
+ let parseErr = null;
263
283
  try {
264
284
  parsed = JSON.parse(rawMeta);
265
285
  } catch (e) {
286
+ parseErr = e;
266
287
  parsed = null;
267
288
  }
268
289
  if (parsed && parsed.__enc === 'v1' && typeof parsed.data === 'string') {
@@ -276,6 +297,8 @@ class Database {
276
297
  ]).toString('utf8');
277
298
  parsed = JSON.parse(plain);
278
299
  }
300
+ // 明文 JSON 半写撕裂:解析失败必须走损坏兜底,不能静默落空注册表。
301
+ if (parseErr) throw parseErr;
279
302
  if (parsed && parsed.tables) {
280
303
  this._meta = parsed;
281
304
  // 清洗 meta 中的 file 字段:拒绝绝对路径/.. 穿越,防恶意 meta.json 写任意位置
@@ -290,7 +313,9 @@ class Database {
290
313
  }
291
314
  }
292
315
  } catch (e) {
293
- this._meta = { version: 1, tables: {} };
316
+ // #453:解析/解密失败不能静默清空注册表 —— 备份损坏文件、上报 error,
317
+ // 并从目录下的 .jsql 文件重建表登记,避免数据块文件全部成孤儿。
318
+ this._recoverMetaFromFiles(e);
294
319
  }
295
320
  for (const name of Object.keys(this._meta.tables)) {
296
321
  if (this[name] === undefined && !(name in this)) {
@@ -339,6 +364,7 @@ class Database {
339
364
  _saveMeta() {
340
365
  if (!this._dirMode) return;
341
366
  try {
367
+ let payload;
342
368
  // #260:启用 encryptKey 时 meta.json 也落密文(表结构/字段名不外泄)
343
369
  if (this._encryptKey) {
344
370
  const iv = crypto.randomBytes(16);
@@ -347,20 +373,69 @@ class Database {
347
373
  cipher.update(JSON.stringify(this._meta, null, 2), 'utf8'),
348
374
  cipher.final(),
349
375
  ]);
350
- const payload = JSON.stringify({
376
+ payload = JSON.stringify({
351
377
  __enc: 'v1',
352
378
  iv: iv.toString('base64'),
353
379
  data: enc.toString('base64'),
354
380
  });
355
- fs.writeFileSync(this._metaPath, payload, 'utf8');
356
381
  } else {
357
- fs.writeFileSync(this._metaPath, JSON.stringify(this._meta, null, 2), 'utf8');
382
+ payload = JSON.stringify(this._meta, null, 2);
358
383
  }
384
+ // #453:与 _writeFile 一致的原子写 —— 先写临时文件 + fsync,再 rename
385
+ // 覆盖;崩溃只会留下旧 meta 或新 meta,不会出现写到一半的半份注册表。
386
+ const tmp = this._metaPath + '.tmp';
387
+ const fd = fs.openSync(tmp, 'w');
388
+ try {
389
+ fs.writeFileSync(fd, payload, 'utf8');
390
+ fs.fsyncSync(fd);
391
+ } finally {
392
+ fs.closeSync(fd);
393
+ }
394
+ fs.renameSync(tmp, this._metaPath);
359
395
  } catch (e) {
360
396
  // 忽略 meta 写入失败
361
397
  }
362
398
  }
363
399
 
400
+ /**
401
+ * #453:meta.json 解析/解密失败时的兜底。
402
+ *
403
+ * 此前 catch 直接把注册表重置为 `{version:1,tables:{}}` —— 表数据块
404
+ * 文件还在,引擎却再也找不到表,全部变成孤儿文件,且无任何告警。
405
+ * 这里:先备份损坏文件为 `meta.json.corrupt-<ts>`,再扫描目录下的
406
+ * `.jsql` 文件重建登记,并通过 error 事件对外上报损坏原因。
407
+ */
408
+ _recoverMetaFromFiles(cause) {
409
+ let backedUp = false;
410
+ try {
411
+ if (fs.existsSync(this._metaPath)) {
412
+ const backup = this._metaPath + '.corrupt-' + Date.now();
413
+ fs.copyFileSync(this._metaPath, backup);
414
+ backedUp = true;
415
+ }
416
+ } catch (e) { /* 备份失败不阻断后续文件扫描 */ }
417
+ this._meta = { version: 1, tables: {} };
418
+ try {
419
+ const files = fs.readdirSync(this._filePath);
420
+ for (const file of files) {
421
+ if (!file.endsWith('.jsql')) continue;
422
+ if (!this._safeTableFile(file)) continue;
423
+ const name = decodeURIComponent(file.slice(0, -5));
424
+ this._meta.tables[name] = { file, schema: {} };
425
+ }
426
+ } catch (e) { /* 目录扫描失败:保持空注册表 */ }
427
+ const reason = cause && cause.message ? cause.message : String(cause);
428
+ const restored = Object.keys(this._meta.tables);
429
+ const err = new Error(
430
+ `meta.json is corrupt (${reason}); rebuilt registry from ${restored.length} table file(s)` +
431
+ (backedUp ? '' : '; corrupt file backup unavailable')
432
+ );
433
+ err.code = 'ER_META_CORRUPT';
434
+ this._metaCorrupt = { error: err.message, code: err.code, at: Date.now(), restored };
435
+ try { this._emit('error', err); } catch (_) { /* 监听器自身抛错不阻塞启动 */ }
436
+ console.error('[jsql-neo] ' + err.message);
437
+ }
438
+
364
439
  /**
365
440
  * 统一的「表不可用」错误。
366
441
  *
@@ -506,9 +581,9 @@ class Database {
506
581
  const fmt = new JSQLFormat(path.join(this._filePath, file), this._encryptKey);
507
582
  let appendBlocks = 0;
508
583
  try {
509
- const written = fmt.writeRows(name, table._schema, dirty.upserts, dirty.deletes, table._primaryKey);
584
+ const written = fmt.writeRows(name, table._persistedSchema(), dirty.upserts, dirty.deletes, table._primaryKey);
510
585
  appendBlocks = fmt.nBlocks;
511
- this._meta.tables[name] = { file, schema: table._schema };
586
+ this._meta.tables[name] = { file, schema: table._persistedSchema() };
512
587
  if (typeof table._applyFlushedLocators === 'function') {
513
588
  if (written && written.length === dirty.upserts.length) {
514
589
  table._applyFlushedLocators(dirty.upserts, written);
@@ -537,8 +612,8 @@ class Database {
537
612
  let keepHandleOpen = false;
538
613
  try {
539
614
  const pkField = Object.keys(table._schema).find(f => table._schema[f].primaryKey) || null;
540
- fmt.writeTable(name, table._schema, table._rows, pkField);
541
- this._meta.tables[name] = { file, schema: table._schema };
615
+ fmt.writeTable(name, table._persistedSchema(), table._rows, pkField);
616
+ this._meta.tables[name] = { file, schema: table._persistedSchema() };
542
617
  // live 大表首次全量写完后挂上行级 LRU,让后续内存淘汰按行回退。
543
618
  if (this._dirMode && !table._rowCache && table._rows.length >= ROW_CACHE_MIN_ROWS) {
544
619
  const locators = fmt.scanLocators(name);
@@ -618,7 +693,20 @@ class Database {
618
693
  if (e.code === 'EEXIST') {
619
694
  try {
620
695
  const lockTime = fs.statSync(this._lockPath).mtimeMs;
621
- if (Date.now() - lockTime > 30000) {
696
+ // #550:SIGKILL 后锁文件残留且 mtime 仍然很新;回读锁内 PID
697
+ // 做存活探测,持锁进程已退出(或 PID 无效)时立即接管,
698
+ // 不必等满 30 秒陈旧阈值才能重开。
699
+ let holderPid = null;
700
+ try {
701
+ const raw = fs.readFileSync(this._lockPath, 'utf8').trim();
702
+ if (/^\d+$/.test(raw)) holderPid = Number(raw);
703
+ } catch (_) { /* 锁文件短暂不可读:按无有效持有者处理 */ }
704
+ let holderAlive = false;
705
+ if (holderPid !== null && holderPid > 0) {
706
+ try { process.kill(holderPid, 0); holderAlive = true; }
707
+ catch (pe) { holderAlive = (pe.code === 'EPERM'); }
708
+ }
709
+ if (Date.now() - lockTime > 30000 || !holderAlive) {
622
710
  fs.unlinkSync(this._lockPath);
623
711
  this._lockFd = fs.openSync(this._lockPath, 'wx');
624
712
  fs.writeSync(this._lockFd, String(process.pid), null, 'utf8');
@@ -636,14 +724,19 @@ class Database {
636
724
 
637
725
  _releaseLock() {
638
726
  if (!this._fileLockEnabled || !this._lockFd) return;
727
+ const fd = this._lockFd;
728
+ this._lockFd = null;
639
729
  try {
640
730
  if (fs.existsSync(this._lockPath)) {
641
731
  fs.unlinkSync(this._lockPath);
642
732
  }
643
- this._lockFd = null;
644
733
  } catch (e) {
645
734
  // 忽略
646
735
  }
736
+ // 必须 closeSync:不关 fd 的话,Windows 上被 unlink 的锁文件停留在
737
+ // delete-pending(目录项残留,任何后续 rmSync/lstat 都 EPERM,Node 18/20
738
+ // 的 CI 因此整片挂掉);POSIX 上则每次 open/close 泄漏一枚 fd。
739
+ try { fs.closeSync(fd); } catch (_) { /* 已关闭 / 句柄失效 */ }
647
740
  }
648
741
 
649
742
  // ============================================================
@@ -659,6 +752,11 @@ class Database {
659
752
  */
660
753
  _walWrite(op) {
661
754
  if (!this._walEnabled || this._loading) return;
755
+ // #446:活动事务内产生的写入打上事务标签,回放时按 commit 帧判定是否可见。
756
+ if (op.tx === undefined) {
757
+ const tag = this._currentTxTag();
758
+ if (tag !== null) op.tx = tag;
759
+ }
662
760
  const entry = {
663
761
  ...op,
664
762
  timestamp: Date.now(),
@@ -682,11 +780,15 @@ class Database {
682
780
  if (!t || !Array.isArray(rows) || rows.length === 0) return;
683
781
  if (t._primaryKey) {
684
782
  const pk = t._primaryKey;
685
- const out = rows.filter(r => r && r[pk] !== undefined && r[pk] !== null).map(r => ({ ...r }));
783
+ // 不复制行对象:WAL 在本次调用内同步序列化落盘,
784
+ // 批量插入几十万行时浅拷贝本身就是一笔可观开销。
785
+ const out = rows.filter(r => r && r[pk] !== undefined && r[pk] !== null);
686
786
  if (out.length === 0) return;
687
787
  this._walWrite({ op: 'upsertRows', table: tableName, pk, rows: out });
688
788
  } else {
689
- this._walLogReplaceTable(tableName);
789
+ // 无主键表此前退化成「每次批量插入都写整表镜像」——100 万行会写出几百 MB 的 O(n²) 日志。
790
+ // 改为只追加本批新增行(append-only),回放时顺序 push 即可。
791
+ this._walWrite({ op: 'insert', table: tableName, rows });
690
792
  }
691
793
  }
692
794
 
@@ -711,7 +813,7 @@ class Database {
711
813
  if (!this._walEnabled || this._walReplaying || this._loading) return;
712
814
  const t = this._tables[tableName];
713
815
  if (!t) return;
714
- this._walWrite({ op: 'replaceTable', table: tableName, rows: t._rows.map(r => ({ ...r })) });
816
+ this._walWrite({ op: 'replaceTable', table: tableName, rows: t._rows });
715
817
  }
716
818
 
717
819
  /**
@@ -721,11 +823,11 @@ class Database {
721
823
  _maybeCheckpointWAL() {
722
824
  if (!this._walEnabled || this._walCheckpointScheduled) return;
723
825
  if (this._walCheckpointOps <= 0 || this._walOpCount < this._walCheckpointOps) return;
724
- if (this._loading || this._walReplaying || this._transaction) return;
826
+ if (this._loading || this._walReplaying || this.hasActiveTx()) return;
725
827
  this._walCheckpointScheduled = true;
726
828
  const run = () => {
727
829
  this._walCheckpointScheduled = false;
728
- if (this._loading || this._walReplaying || this._transaction) return;
830
+ if (this._loading || this._walReplaying || this.hasActiveTx()) return;
729
831
  try {
730
832
  this.save();
731
833
  } catch (e) {
@@ -738,26 +840,43 @@ class Database {
738
840
 
739
841
  /**
740
842
  * 将新增的 WAL 记录追加到磁盘(append-only)
843
+ *
844
+ * 性能设计(此前单条写入 ~1k/s 的根因):
845
+ * 1. 常驻追加句柄 —— 不再每次 open()/close()
846
+ * 2. 一次 write() 批量写出所有待落盘记录(批次内 JSONL 拼接)
847
+ * 3. fsync 合并到 walSyncInterval 时间窗口 —— write() 已完成,进程崩溃不丢;
848
+ * 只是把「每条一次磁盘刷写」摊薄成「窗口内一次」
741
849
  */
742
850
  _flushWAL() {
743
851
  if (!this._walEnabled || !this._walPath || this._walOps.length === 0) return;
852
+ // 只追加尚未落盘的记录
853
+ const pending = this._walOps.slice(this._walFlushedCount);
854
+ if (pending.length === 0) return;
744
855
  try {
745
- const dir = path.dirname(this._walPath);
746
- if (!fs.existsSync(dir)) fs.mkdirSync(dir, { recursive: true });
747
- // 只追加尚未落盘的记录
748
- const pending = this._walOps.slice(this._walFlushedCount);
749
- if (pending.length === 0) return;
750
- const lines = pending.map(o => bigintJson.stringify(o)).join('\n') + '\n';
751
- const fd = fs.openSync(this._walPath, 'a');
752
- try {
753
- fs.writeSync(fd, lines, null, 'utf8');
754
- // 崩溃安全性:确保数据真正落到磁盘而不仅在页缓存
755
- try { fs.fsyncSync(fd); } catch (e) { /* 某些文件系统不支持 fsync */ }
756
- } finally {
757
- fs.closeSync(fd);
856
+ // 路径变化(或句柄已失效)时必须重开:否则会继续写旧 inode。
857
+ if (this._walFd !== null && this._walFdPath !== this._walPath) this._walCloseFd();
858
+ if (!this._walDirReady) {
859
+ const dir = path.dirname(this._walPath);
860
+ if (!fs.existsSync(dir)) fs.mkdirSync(dir, { recursive: true });
861
+ this._walDirReady = true;
862
+ }
863
+ let payload = '';
864
+ for (let i = 0; i < pending.length; i++) {
865
+ payload += bigintJson.stringify(pending[i]) + '\n';
866
+ }
867
+ if (this._walFd === null) {
868
+ this._walFd = fs.openSync(this._walPath, 'a');
869
+ this._walFdPath = this._walPath;
870
+ }
871
+ const buf = Buffer.from(payload, 'utf8');
872
+ let offset = 0;
873
+ while (offset < buf.length) {
874
+ offset += fs.writeSync(this._walFd, buf, offset, buf.length - offset);
758
875
  }
759
876
  this._walFlushedCount = this._walOps.length;
760
877
  this._walError = null;
878
+ this._walNeedsSync = true;
879
+ this._scheduleWALSync();
761
880
  } catch (e) {
762
881
  // #263:WAL 追加失败不能静默吞掉。
763
882
  // WAL 是崩溃安全的前提(README 承诺「kill -9 不会丢已提交的写入」):
@@ -766,10 +885,59 @@ class Database {
766
885
  // 现在至少通过 error 事件暴露出来(与 _flushDirty 的处理一致),
767
886
  // 并记入 _walError 供上层查询。
768
887
  this._walError = e;
888
+ this._walCloseFd();
769
889
  try { this._emit('error', e); } catch (_) { /* 事件监听器自身抛错不影响主流程 */ }
770
890
  }
771
891
  }
772
892
 
893
+ /**
894
+ * 按 walSyncInterval 合并 fsync:
895
+ * - 0 → 立即同步(最严格,等价旧行为)
896
+ * - >0 → 窗口内只 fsync 一次;窗口内已 write() 的记录在进程崩溃后仍可从页缓存恢复
897
+ */
898
+ _scheduleWALSync() {
899
+ if (!this._walNeedsSync) return;
900
+ if (this._walSyncInterval <= 0) {
901
+ this._syncWAL();
902
+ return;
903
+ }
904
+ if (this._walSyncTimer) return;
905
+ this._walSyncTimer = setTimeout(() => {
906
+ this._walSyncTimer = null;
907
+ this._syncWAL();
908
+ }, this._walSyncInterval);
909
+ // 不能让合并窗口的定时器把进程挂住
910
+ if (this._walSyncTimer && this._walSyncTimer.unref) this._walSyncTimer.unref();
911
+ }
912
+
913
+ /** 立即 fsync 尚未落盘刷写的 WAL 数据(幂等)。 */
914
+ _syncWAL() {
915
+ if (!this._walNeedsSync) return;
916
+ if (this._walFd === null) { this._walNeedsSync = false; return; }
917
+ try {
918
+ fs.fsyncSync(this._walFd);
919
+ this._walNeedsSync = false;
920
+ } catch (e) {
921
+ this._walError = e;
922
+ try { this._emit('error', e); } catch (_) { /* ignore */ }
923
+ }
924
+ }
925
+
926
+ /** 关闭常驻 WAL 句柄:先补齐 fsync,再关句柄并复位状态。 */
927
+ _walCloseFd() {
928
+ if (this._walSyncTimer) {
929
+ clearTimeout(this._walSyncTimer);
930
+ this._walSyncTimer = null;
931
+ }
932
+ this._syncWAL();
933
+ if (this._walFd !== null) {
934
+ try { fs.closeSync(this._walFd); } catch (e) { /* 已关闭 / 句柄失效 */ }
935
+ this._walFd = null;
936
+ this._walFdPath = null;
937
+ }
938
+ this._walDirReady = false;
939
+ }
940
+
773
941
  /**
774
942
  * 检查点:数据已由 save() 完整落盘,清空 WAL
775
943
  *
@@ -778,6 +946,9 @@ class Database {
778
946
  */
779
947
  _checkpoint() {
780
948
  if (!this._walEnabled) return;
949
+ // 必须先把常驻句柄里的数据 fsync 并关闭,否则 unlink 后该句柄
950
+ // 仍持有旧 inode,后续写入会落到一个「已被删除」的文件里而静默丢失。
951
+ this._walCloseFd();
781
952
  this._walOps = [];
782
953
  this._walFlushedCount = 0;
783
954
  this._walOpCount = 0;
@@ -888,13 +1059,50 @@ class Database {
888
1059
 
889
1060
  this._walReplaying = true;
890
1061
  let replayed = 0, failed = 0;
1062
+ // #446:按事务帧聚合回放。先扫描出所有带 commit 帧的事务标签;
1063
+ // 缺少 commit 帧(崩溃时未闭合)的事务,其行变更在恢复时整体丢弃,
1064
+ // 保证 kill -9 后未提交的脏写不会随 WAL 回放复活。
1065
+ const committedTx = new Set();
1066
+ for (const op of ops) {
1067
+ if (op.op === 'commit' && op.tx !== undefined && op.tx !== null) {
1068
+ committedTx.add(String(op.tx));
1069
+ }
1070
+ }
1071
+ const TX_MARKERS = new Set(['begin', 'commit', 'rollback', 'rollbackTo', 'savepoint', 'undo', 'restore', 'import']);
1072
+ const DATA_OPS = new Set(['insert', 'update', 'remove', 'upsertRows', 'removeRows', 'replaceTable']);
891
1073
  try {
892
1074
  // 逐条按 sequence 顺序回放,保证 insert→update→remove 的相对次序。
893
1075
  // insert 不走 _loadRows()(那是整体替换语义),而是直接 push 到 _rows,
894
1076
  // 再在末尾统一重建索引;否则逐条回放会互相覆盖。
895
1077
  const touched = new Set();
1078
+ // 回放热路径:按表缓存 pk -> 行下标,避免逐行 findIndex 造成 O(n²)。
1079
+ // 一次 20 万行的批量 upsert 回放在旧实现里会退化成 400 亿次比较(几乎等于挂死)。
1080
+ const replayIdx = new Map(); // table -> Map(pkField -> Map(pkKey -> rowIndex))
1081
+ const pkKeyOf = (v) => typeof v + ':' + String(v);
1082
+ const idxMapOf = (t, pkField) => {
1083
+ let byField = replayIdx.get(t);
1084
+ if (!byField) { byField = new Map(); replayIdx.set(t, byField); }
1085
+ let m = byField.get(pkField);
1086
+ if (!m) {
1087
+ m = new Map();
1088
+ for (let i = 0; i < t._rows.length; i++) {
1089
+ const row = t._rows[i];
1090
+ if (row && row[pkField] !== undefined && row[pkField] !== null) {
1091
+ m.set(pkKeyOf(row[pkField]), i);
1092
+ }
1093
+ }
1094
+ byField.set(pkField, m);
1095
+ }
1096
+ return m;
1097
+ };
1098
+ const invalidateIdx = (t) => { replayIdx.delete(t); };
896
1099
  for (const op of ops) {
897
1100
  try {
1101
+ // 事务标记帧本身不改数据状态,回放时跳过。
1102
+ if (TX_MARKERS.has(op.op)) continue;
1103
+ // 未闭合事务的行变更:整批丢弃,不落可见行。
1104
+ if (DATA_OPS.has(op.op) && op.tx !== undefined && op.tx !== null
1105
+ && !committedTx.has(String(op.tx))) continue;
898
1106
  switch (op.op) {
899
1107
  case 'insert': {
900
1108
  // #259:目录模式下表是懒加载的(_tables 里可能还没有),
@@ -907,11 +1115,15 @@ class Database {
907
1115
  }
908
1116
  if (!t || !Array.isArray(op.rows) || op.rows.length === 0) { failed++; break; }
909
1117
  const pk = t._primaryKey;
1118
+ const idm = pk ? idxMapOf(t, pk) : null;
910
1119
  for (const __e of op.rows) {
1120
+ if (!__e) continue;
911
1121
  // 幂等:快照已包含该行时覆盖而不是重复插入
912
- if (pk && __e && __e[pk] !== undefined) {
913
- const ai = t._rows.findIndex(r => r && r[pk] === __e[pk]);
914
- if (ai >= 0) { t._rows[ai] = __e; continue; }
1122
+ if (idm && __e[pk] !== undefined && __e[pk] !== null) {
1123
+ const k = pkKeyOf(__e[pk]);
1124
+ const ai = idm.get(k);
1125
+ if (ai !== undefined) { t._rows[ai] = __e; continue; }
1126
+ idm.set(k, t._rows.length);
915
1127
  }
916
1128
  t._rows.push(__e);
917
1129
  }
@@ -927,11 +1139,17 @@ class Database {
927
1139
  t = this._tables[op.table];
928
1140
  }
929
1141
  if (!t || !op.pk || !Array.isArray(op.rows)) { failed++; break; }
1142
+ const idm = idxMapOf(t, op.pk);
930
1143
  for (const __r of op.rows) {
931
1144
  if (!__r || typeof __r !== 'object') continue;
932
- const ai = t._rows.findIndex(r => r && String(r[op.pk]) === String(__r[op.pk]));
933
- if (ai >= 0) t._rows[ai] = { ...__r };
934
- else t._rows.push({ ...__r });
1145
+ const k = pkKeyOf(__r[op.pk]);
1146
+ const ai = idm.get(k);
1147
+ if (ai !== undefined) {
1148
+ t._rows[ai] = { ...__r };
1149
+ } else {
1150
+ idm.set(k, t._rows.length);
1151
+ t._rows.push({ ...__r });
1152
+ }
935
1153
  }
936
1154
  touched.add(t);
937
1155
  replayed++;
@@ -942,6 +1160,7 @@ class Database {
942
1160
  if (!t || !op.pk || !Array.isArray(op.ids)) { failed++; break; }
943
1161
  const gone = new Set(op.ids.map(String));
944
1162
  t._rows = t._rows.filter(r => !r || !gone.has(String(r[op.pk])));
1163
+ invalidateIdx(t);
945
1164
  touched.add(t);
946
1165
  replayed++;
947
1166
  break;
@@ -954,6 +1173,7 @@ class Database {
954
1173
  }
955
1174
  if (!t || !Array.isArray(op.rows)) { failed++; break; }
956
1175
  t._rows = op.rows.map(r => ({ ...r }));
1176
+ invalidateIdx(t);
957
1177
  touched.add(t);
958
1178
  replayed++;
959
1179
  break;
@@ -973,6 +1193,7 @@ class Database {
973
1193
  if (!t || !op.pk) { failed++; break; }
974
1194
  const before = t._rows.length;
975
1195
  t._rows = t._rows.filter(r => r[op.pk] !== op.id);
1196
+ invalidateIdx(t);
976
1197
  if (t._rows.length === before) { failed++; break; }
977
1198
  touched.add(t);
978
1199
  replayed++;
@@ -1389,6 +1610,11 @@ class Database {
1389
1610
  return { ...(this._corruptTables || {}) };
1390
1611
  }
1391
1612
 
1613
+ /** #453:meta.json 损坏后兜底恢复的排障记录(未损坏时为 null)。 */
1614
+ getMetaCorruption() {
1615
+ return this._metaCorrupt ? { ...this._metaCorrupt } : null;
1616
+ }
1617
+
1392
1618
  getTableSchema(name) {
1393
1619
  const table = this._ensureTable(name);
1394
1620
  if (table) return table._schema;
@@ -1494,6 +1720,9 @@ class Database {
1494
1720
  const hasHeader = options.hasHeader !== false;
1495
1721
  const skipRows = options.skipRows || 0;
1496
1722
  const mapping = options.mapping || null;
1723
+ // #455:strict 模式下不可解析的类型值直接抛错;默认降级为 warnings 并跳过该行,
1724
+ // 不再把非数值整数静默置 0、非真值布尔静默置 false。
1725
+ const strict = options.strict === true;
1497
1726
 
1498
1727
  const content = fs.readFileSync(filePath, 'utf8');
1499
1728
  // #184:RFC 4180 允许引号字段内出现换行,不能先按行切分
@@ -1509,34 +1738,46 @@ class Database {
1509
1738
  startRow = skipRows;
1510
1739
  }
1511
1740
 
1741
+ const warnings = [];
1512
1742
  let count = 0;
1513
1743
  for (let i = startRow; i < records.length; i++) {
1514
1744
  const values = records[i];
1515
1745
  if (values.length === 0) continue;
1516
1746
 
1517
1747
  const data = {};
1748
+ const castCtx = { warnings, row: i };
1518
1749
  if (mapping) {
1519
1750
  for (const [csvCol, schemaCol] of Object.entries(mapping)) {
1520
1751
  const idx = hasHeader ? headers.indexOf(csvCol) : parseInt(csvCol);
1521
1752
  if (idx >= 0 && idx < values.length) {
1522
- data[schemaCol] = this._castValue(values[idx], table._schema[schemaCol]);
1753
+ data[schemaCol] = this._castValue(values[idx], table._schema[schemaCol], { ...castCtx, field: schemaCol });
1523
1754
  }
1524
1755
  }
1525
1756
  } else if (hasHeader) {
1526
1757
  for (let j = 0; j < headers.length; j++) {
1527
1758
  if (j < values.length && table._schema[headers[j]]) {
1528
- data[headers[j]] = this._castValue(values[j], table._schema[headers[j]]);
1759
+ data[headers[j]] = this._castValue(values[j], table._schema[headers[j]], { ...castCtx, field: headers[j] });
1529
1760
  }
1530
1761
  }
1531
1762
  }
1532
1763
 
1533
1764
  if (Object.keys(data).length > 0) {
1534
- table.insert(data);
1535
- count++;
1765
+ try {
1766
+ table.insert(data);
1767
+ count++;
1768
+ } catch (e) {
1769
+ if (strict) throw e;
1770
+ warnings.push({
1771
+ row: i,
1772
+ code: e.code || e.errno || 'ER_TRUNCATED_WRONG_VALUE',
1773
+ message: e.message,
1774
+ });
1775
+ }
1536
1776
  }
1537
1777
  }
1538
1778
 
1539
- return count;
1779
+ // 与 migrate 路径一致:返回 { count, warnings },告警随结果带回上层
1780
+ return { count, warnings };
1540
1781
  }
1541
1782
 
1542
1783
  /**
@@ -1629,12 +1870,39 @@ class Database {
1629
1870
  return value;
1630
1871
  }
1631
1872
 
1632
- _castValue(value, schemaDef) {
1633
- if (!schemaDef || !value) return value;
1634
- switch (schemaDef.type) {
1635
- case 'integer': return parseInt(value, 10) || 0;
1636
- case 'number': return parseFloat(value) || 0;
1637
- case 'boolean': return value.toLowerCase() === 'true' || value === '1';
1873
+ _castValue(value, schemaDef, ctx) {
1874
+ if (!schemaDef) return value;
1875
+ // 空字段 / NULL:语义与此前一致,不参与类型转换
1876
+ if (value === null || value === undefined || value === '') return value;
1877
+ const type = String(schemaDef.type || '').toLowerCase();
1878
+ const raw = String(value).trim();
1879
+ switch (type) {
1880
+ case 'integer':
1881
+ case 'int':
1882
+ case 'bigint': {
1883
+ // #455:不再 `parseInt(...) || 0` 把解析失败吞成 0;非法整数值记入告警并保留原值,
1884
+ // 由表校验层拒绝(strict 模式下 importCSV 直接抛错)。
1885
+ if (/^[+-]?\d+$/.test(raw)) return parseInt(raw, 10);
1886
+ this._recordCastWarning(ctx, type, value);
1887
+ return value;
1888
+ }
1889
+ case 'number':
1890
+ case 'float':
1891
+ case 'double':
1892
+ case 'real':
1893
+ case 'decimal': {
1894
+ if (raw !== '' && !Number.isNaN(Number(raw))) return Number(raw);
1895
+ this._recordCastWarning(ctx, type, value);
1896
+ return value;
1897
+ }
1898
+ case 'boolean': {
1899
+ // #455:只识别规范真值/假值;其余不可识别的值不再一律归 false,记入告警并保留原值。
1900
+ const low = raw.toLowerCase();
1901
+ if (low === 'true' || low === '1') return true;
1902
+ if (low === 'false' || low === '0') return false;
1903
+ this._recordCastWarning(ctx, type, value);
1904
+ return value;
1905
+ }
1638
1906
  case 'array': try { return JSON.parse(value); } catch(e) { return [value]; }
1639
1907
  case 'object': try { return JSON.parse(value); } catch(e) { return {}; }
1640
1908
  case 'date':
@@ -1646,6 +1914,17 @@ class Database {
1646
1914
  }
1647
1915
  }
1648
1916
 
1917
+ _recordCastWarning(ctx, type, value) {
1918
+ if (!ctx || !Array.isArray(ctx.warnings)) return;
1919
+ ctx.warnings.push({
1920
+ row: ctx.row,
1921
+ field: ctx.field,
1922
+ type,
1923
+ value: String(value),
1924
+ message: `Truncated incorrect ${type} value: '${value}'`,
1925
+ });
1926
+ }
1927
+
1649
1928
  // ============================================================
1650
1929
  // 数据库统计
1651
1930
  // ============================================================
@@ -1827,8 +2106,25 @@ class Database {
1827
2106
  _restoreTxSnapshot(snap) {
1828
2107
  if (!snap) return;
1829
2108
  for (const name of Object.keys(this._tables)) {
1830
- if (!snap[name]) delete this._tables[name];
2109
+ if (snap[name]) continue;
2110
+ // #452:事务内 CREATE TABLE 回滚必须彻底撤销。目录模式下只删内存
2111
+ // 表对象会留下 meta 登记与 .jsql 文件,重开后被回滚的表连同未提交
2112
+ // 行一起复活。这里与 _dropTableSync 对齐:清 meta 登记、删表文件、
2113
+ // 摘掉访问器与表名登记。
2114
+ if (this._dirMode) {
2115
+ const meta = this._meta.tables[name];
2116
+ if (meta && meta.file) {
2117
+ try { fs.unlinkSync(path.join(this._filePath, meta.file)); } catch (e) { /* 文件已不存在 */ }
2118
+ }
2119
+ delete this._meta.tables[name];
2120
+ this._dirtyTables.delete(name);
2121
+ }
2122
+ delete this[name];
2123
+ delete this._versions[name];
2124
+ this._tableNames.delete(name);
2125
+ delete this._tables[name];
1831
2126
  }
2127
+ if (this._dirMode) this._saveMeta();
1832
2128
  for (const [name, entry] of Object.entries(snap)) {
1833
2129
  const rows = bigintJson.parse(bigintJson.stringify(entry.rows));
1834
2130
  const prev = this._tables[name];
@@ -1866,6 +2162,16 @@ class Database {
1866
2162
  return (this._txId !== undefined && !!this._txSnapshot) || !!this._transaction;
1867
2163
  }
1868
2164
 
2165
+ /**
2166
+ * 当前活动事务的 WAL 标签(beginTx 路径用 `tx<n>`,begin 路径用 `b<n>`)。
2167
+ * 无活动事务时返回 null —— 旧 WAL / 自动提交的写入不带事务标记,回放时视为已提交。
2168
+ */
2169
+ _currentTxTag() {
2170
+ if (this._txId !== undefined && this._txSnapshot) return 'tx' + this._txId;
2171
+ if (this._transaction && this._transaction.txTag) return this._transaction.txTag;
2172
+ return null;
2173
+ }
2174
+
1869
2175
  /** 保存点栈(懒建),随事务结束清空 */
1870
2176
  _savepointStackRef() {
1871
2177
  if (!this._savepointStack) this._savepointStack = [];
@@ -1881,11 +2187,13 @@ class Database {
1881
2187
 
1882
2188
  const level = isolationLevel || this._isolationLevel;
1883
2189
 
2190
+ this._txFrameSeq = (this._txFrameSeq || 0) + 1;
1884
2191
  this._transaction = {
1885
2192
  snapshot: null,
1886
2193
  autoIncrements: {},
1887
2194
  level,
1888
- startedAt: Date.now()
2195
+ startedAt: Date.now(),
2196
+ txTag: 'b' + this._txFrameSeq
1889
2197
  };
1890
2198
 
1891
2199
  if (level === 'REPEATABLE_READ') {
@@ -1901,12 +2209,12 @@ class Database {
1901
2209
  }
1902
2210
 
1903
2211
  this._savepointStack = [];
1904
- this._walWrite({ op: 'begin', level });
2212
+ this._walWrite({ op: 'begin', tx: this._transaction.txTag, level });
1905
2213
  }
1906
2214
 
1907
2215
  commit() {
1908
2216
  if (!this._transaction) throw createError('ER_NO_TRANSACTION');
1909
- this._walWrite({ op: 'commit', at: this._transaction.startedAt });
2217
+ this._walWrite({ op: 'commit', tx: this._transaction.txTag, at: this._transaction.startedAt });
1910
2218
  // 提交即释放全部保存点 —— 它们随事务一起结束
1911
2219
  this._transaction = null;
1912
2220
  this._savepointStack = [];
@@ -1933,7 +2241,7 @@ class Database {
1933
2241
  }
1934
2242
  }
1935
2243
 
1936
- this._walWrite({ op: 'rollback', at: this._transaction.startedAt });
2244
+ this._walWrite({ op: 'rollback', tx: this._transaction.txTag, at: this._transaction.startedAt });
1937
2245
  this._transaction = null;
1938
2246
  this._savepointStack = [];
1939
2247
  this._markDirtyLegacy();
@@ -2025,7 +2333,7 @@ class Database {
2025
2333
  }
2026
2334
 
2027
2335
  inTransaction() {
2028
- return !!this._transaction;
2336
+ return this.hasActiveTx();
2029
2337
  }
2030
2338
 
2031
2339
  /**
@@ -2096,6 +2404,9 @@ class Database {
2096
2404
  table._autoIncrement = row[table._autoIncrementField];
2097
2405
  }
2098
2406
  }
2407
+ // #549:行序被快照整体替换后 `_pkIndex` 仍指向删除阶段的下标,
2408
+ // 必须和 B-Tree / 二级索引一起重建,否则主键点查命中错误行。
2409
+ if (typeof table._rebuildPKIndex === 'function') table._rebuildPKIndex();
2099
2410
  table._rebuildAllBTrees();
2100
2411
  for (const field of Object.keys(table._indexes)) {
2101
2412
  table.createIndex(field);
@@ -2416,6 +2727,18 @@ class Database {
2416
2727
  return this;
2417
2728
  }
2418
2729
 
2730
+ /**
2731
+ * 轻量持久化屏障:只把已写入的 WAL 记录 fsync 到磁盘,不写全量快照。
2732
+ *
2733
+ * 每条记录在写入时已单独 append 并 write() 进内核;默认 fsync 按
2734
+ * `walSyncInterval` 窗口合并。需要「此刻就必须抗掉电」时调用本方法,
2735
+ * 比 flush()/save()(全量快照)轻得多。
2736
+ */
2737
+ syncWAL() {
2738
+ if (this._walEnabled) this._syncWAL();
2739
+ return this;
2740
+ }
2741
+
2419
2742
  _resolveId(table, id) {
2420
2743
  const pk = this._pkOf(table);
2421
2744
  if (pk) {
@@ -2489,7 +2812,15 @@ class Database {
2489
2812
  async query(sql, paramsOrOpts, opts) {
2490
2813
  const { executeSQL } = require('./sql');
2491
2814
  if (!(await this._runHooks('beforeQuery', [sql, paramsOrOpts, opts]))) return null;
2492
- const result = await executeSQL(this, sql, paramsOrOpts, opts);
2815
+ // #581:SQL 的 UPDATE 必须拒绝未知 SET 列;mongo 等 API 允许动态加列,
2816
+ // 因此只在 SQL 执行期间开启严格列校验(计数器支持嵌套调用)。
2817
+ this._sqlStrictColumns = (this._sqlStrictColumns || 0) + 1;
2818
+ let result;
2819
+ try {
2820
+ result = await executeSQL(this, sql, paramsOrOpts, opts);
2821
+ } finally {
2822
+ this._sqlStrictColumns--;
2823
+ }
2493
2824
  await this._runHooks('afterQuery', [sql, paramsOrOpts, opts, result]);
2494
2825
  return result;
2495
2826
  }
@@ -2556,10 +2887,26 @@ class Database {
2556
2887
  const row = this._resolveId(table, id);
2557
2888
  // P1-4: 软删除行不可更新
2558
2889
  if (!row || row._deleted) return null;
2890
+ // #581:SQL UPDATE 的 SET 左侧列必须属于目标表(与 INSERT 的未知列
2891
+ // 校验对齐)。只在 SQL 执行路径开启,mongo 等 API 仍可动态加列。
2892
+ if (this._sqlStrictColumns > 0) {
2893
+ const schema = table._schema || {};
2894
+ for (const field of Object.keys(data || {})) {
2895
+ if (!Object.prototype.hasOwnProperty.call(schema, field)) {
2896
+ throw createError('ER_BAD_FIELD_ERROR', field, 'field list');
2897
+ }
2898
+ }
2899
+ }
2559
2900
  // 改主键/唯一列时要先确认新值不与其它行冲突。
2560
2901
  // 注意:UNIQUE 列记录在 table._cachedUniqueFields(不是 _indexes),
2561
2902
  // 逐行比对即可,未建索引时也能正确拦截。
2562
2903
  const pk = this._pkOf(table);
2904
+ // #548:主键改写时记下旧值,调用方需为旧主键补一条 WAL removeRows,
2905
+ // 否则崩溃回放只会追加新行,旧主键成为幽灵行复活。
2906
+ const pkChanged = !!(pk
2907
+ && Object.prototype.hasOwnProperty.call(validated, pk)
2908
+ && validated[pk] !== row[pk]);
2909
+ let oldPk;
2563
2910
  const uniq = (table._cachedUniqueFields || []).filter(f => f !== pk);
2564
2911
  for (const field of [pk, ...uniq]) {
2565
2912
  if (!field || !Object.prototype.hasOwnProperty.call(validated, field)) continue;
@@ -2604,13 +2951,13 @@ class Database {
2604
2951
  if (i !== undefined && table._rows[i] === row) rowIndex = i;
2605
2952
  }
2606
2953
  if (rowIndex === -1) rowIndex = table._rows.indexOf(row);
2607
- const oldPk = pk ? row[pk] : undefined;
2954
+ oldPk = pk ? row[pk] : undefined;
2608
2955
  if (rowIndex !== -1) table._removeFromIndexes(rowIndex, row);
2609
2956
  Object.assign(row, validated);
2610
2957
  if (rowIndex !== -1) table._addToIndexes(rowIndex, row);
2611
2958
  if (typeof table._markRowDirty === 'function') table._markRowDirty(row, oldPk);
2612
2959
  }
2613
- return { row, validated };
2960
+ return { row, validated, oldPk: pkChanged ? oldPk : undefined };
2614
2961
  }
2615
2962
 
2616
2963
  async updateById(tableName, id, data) {
@@ -2623,7 +2970,11 @@ class Database {
2623
2970
  data = hookArgs[2];
2624
2971
  const applied = this._applyUpdateToRow(table, id, data);
2625
2972
  if (!applied) return { ok: false, error: 'not found' };
2626
- const { row, validated } = applied;
2973
+ const { row, validated, oldPk } = applied;
2974
+ // #548:先撤销旧主键,再写入新行;否则回放后旧键复活成幽灵行。
2975
+ if (oldPk !== undefined) {
2976
+ this._walLogRemove(tableName, [{ [this._pkOf(table)]: oldPk }]);
2977
+ }
2627
2978
  this._walLogUpsert(tableName, [row]);
2628
2979
  this._emit('update', { table: tableName, id, data: validated });
2629
2980
  await this._runHooks('afterUpdate', [tableName, id, validated, { ok: true }]);
@@ -2638,13 +2989,17 @@ class Database {
2638
2989
  if (!(await this._runHooks('beforeUpdate', [tableName, pairs]))) return { ok: false, count: 0, error: 'aborted' }; // #383
2639
2990
  let count = 0;
2640
2991
  const changed = [];
2992
+ const oldPkRows = [];
2993
+ const pk = this._pkOf(table);
2641
2994
  for (const [id, data] of pairs) {
2642
2995
  const applied = this._applyUpdateToRow(table, id, data);
2643
2996
  if (applied) {
2644
2997
  changed.push(applied.row);
2998
+ if (applied.oldPk !== undefined && pk) oldPkRows.push({ [pk]: applied.oldPk });
2645
2999
  count++;
2646
3000
  }
2647
3001
  }
3002
+ if (oldPkRows.length) this._walLogRemove(tableName, oldPkRows);
2648
3003
  if (changed.length) this._walLogUpsert(tableName, changed);
2649
3004
  this._emit('update', { table: tableName, entries: pairs, result: { ok: true, count } });
2650
3005
  await this._runHooks('afterUpdate', [tableName, pairs, { ok: true, count }]);
@@ -2796,6 +3151,15 @@ class Database {
2796
3151
  return count;
2797
3152
  }
2798
3153
 
3154
+ /** 关闭懒加载行缓存持有的各表 .jsql 句柄(flush 路径 keepHandleOpen 故意留着)。
3155
+ * 不关的话:Windows 上 stop/close 后目录删不掉(delete-pending 残留,CI 实测
3156
+ * ENOTEMPTY/EPERM),POSIX 上每次泄漏一枚 fd。 */
3157
+ _closeRowCaches() {
3158
+ for (const t of Object.values(this._tables)) {
3159
+ if (t && typeof t._detachRowCache === 'function') t._detachRowCache();
3160
+ }
3161
+ }
3162
+
2799
3163
  async stop() {
2800
3164
  await this._runHooks('onStop', []);
2801
3165
  this._emit('stop', {});
@@ -2808,6 +3172,7 @@ class Database {
2808
3172
  this._saveMeta();
2809
3173
  this._checkpoint();
2810
3174
  } catch (e) {}
3175
+ this._closeRowCaches();
2811
3176
  } else if (!this._memoryMode) {
2812
3177
  // 正常关闭时做一次快照检查点,缩短下次启动的回放时间
2813
3178
  try { this.save(); } catch (e) {}
@@ -2816,6 +3181,9 @@ class Database {
2816
3181
  this._sigInstalled = false;
2817
3182
  Database._uninstallSignalHandler(this);
2818
3183
  }
3184
+ // 兜底:合并窗口内可能还有未 fsync 的 WAL 记录(例如 save() 抛错被吞掉),
3185
+ // 关闭实例前必须补齐,否则掉电会丢失这段已返回成功的写入。
3186
+ this._walCloseFd();
2819
3187
  // #295:stop() 表示本实例停止写入,必须释放文件锁,否则同路径再打开会误报占用
2820
3188
  this._releaseLock();
2821
3189
  return this;
@@ -2897,9 +3265,31 @@ class Database {
2897
3265
  }
2898
3266
  const json = this._readFile(filePath);
2899
3267
  const data = bigintJson.parse(json);
3268
+ if (!data || typeof data !== 'object' || Array.isArray(data)) {
3269
+ throw createError('ER_PARSE_ERROR', 'Backup must be an object keyed by table name');
3270
+ }
3271
+ // #536:先整体校验,非数组行集合必须在写入任何目标表之前被拒绝,
3272
+ // 否则字符串会被当成可迭代行集合展开成逐字符垃圾行。
2900
3273
  for (const [name, rows] of Object.entries(data)) {
2901
- if (this._tables[name]) {
2902
- this._tables[name]._loadRows(rows);
3274
+ if (!Array.isArray(rows)) {
3275
+ throw createError('ER_PARSE_ERROR', `Invalid rows for table '${name}': expected an array`);
3276
+ }
3277
+ }
3278
+ for (const [name, rows] of Object.entries(data)) {
3279
+ let table = this._tables[name];
3280
+ if (!table) {
3281
+ // #540:备份专属的表此前被静默跳过;按行推断一个最小 schema 建表。
3282
+ table = this._createTableSync(name, this._inferWalSchema(rows));
3283
+ }
3284
+ table._loadRows(rows);
3285
+ // #546:整表替换必须写行级 WAL;只有 restore 标记时回放是 no-op,
3286
+ // kill -9 后导入行会被旧快照覆盖。
3287
+ this._walLogReplaceTable(name);
3288
+ }
3289
+ // #540:目标库中备份里没有的表也要清理,恢复结果才是备份的完整快照。
3290
+ for (const name of Object.keys(this._tables)) {
3291
+ if (name !== '__meta__' && !Object.prototype.hasOwnProperty.call(data, name)) {
3292
+ this._dropTableSync(name);
2903
3293
  }
2904
3294
  }
2905
3295
  this._walWrite({ op: 'restore', from: filePath });
@@ -2931,7 +3321,7 @@ class Database {
2931
3321
  for (const [name, table] of Object.entries(this._tables)) {
2932
3322
  if (name === '__meta__') continue;
2933
3323
  const pkField = Object.keys(table._schema).find(f => table._schema[f].primaryKey);
2934
- all[name] = { schema: table._schema, rows: table._rows, pkField };
3324
+ all[name] = { schema: table._persistedSchema(), rows: table._rows, pkField };
2935
3325
  }
2936
3326
  this._jsqlFormat.saveAll(all);
2937
3327
  this._jsqlFormat._close();
@@ -2943,7 +3333,7 @@ class Database {
2943
3333
  const data = { __schema__: {}, __meta__: { version: this._getCurrentVersion() } };
2944
3334
  for (const [name, table] of Object.entries(this._tables)) {
2945
3335
  if (name === '__meta__') continue;
2946
- data.__schema__[name] = table._schema;
3336
+ data.__schema__[name] = table._persistedSchema();
2947
3337
  data[name] = table.toJSON();
2948
3338
  }
2949
3339
 
@@ -2963,10 +3353,11 @@ class Database {
2963
3353
  this._jsqlFormat._open();
2964
3354
  for (const [name, t] of this._jsqlFormat.tables) {
2965
3355
  if (!this._tables[name]) this._createTableSync(name, t.schema);
2966
- if (t.rowCount > 0) {
2967
- const { rows } = this._jsqlFormat.readTableSync(name);
2968
- this._tables[name]._loadRows(rows);
2969
- }
3356
+ // #547:无主键表没有 pkEntries,rowCount 恒为 0,但行确实写在
3357
+ // 数据块里。readTableSync 在无索引时按表 ID 扫描全部数据块,
3358
+ // 因此不能再用 rowCount>0 作为是否加载行的门槛。
3359
+ const { rows } = this._jsqlFormat.readTableSync(name);
3360
+ this._tables[name]._loadRows(rows);
2970
3361
  }
2971
3362
  // WAL 恢复(此前 .jsql 分支提前 return,导致崩溃后数据全丢)
2972
3363
  this._recoverFromWAL();
@@ -3044,6 +3435,7 @@ class Database {
3044
3435
  try {
3045
3436
  this._flushDirty();
3046
3437
  this._saveMeta();
3438
+ this._closeRowCaches();
3047
3439
  } catch (e) {
3048
3440
  this._emit('error', e);
3049
3441
  }
@@ -3051,6 +3443,7 @@ class Database {
3051
3443
  this.save();
3052
3444
  }
3053
3445
  if (this._jsqlFormat) this._jsqlFormat._close();
3446
+ this._walCloseFd();
3054
3447
  this._releaseLock();
3055
3448
  // Bug 3: 清理静态信号处理器,防止关闭后还在响应信号
3056
3449
  if (this._sigInstalled) {
@@ -3074,9 +3467,19 @@ class Database {
3074
3467
  }
3075
3468
 
3076
3469
  import(data) {
3470
+ if (!data || typeof data !== 'object' || Array.isArray(data)) {
3471
+ throw createError('ER_PARSE_ERROR', 'Import data must be an object keyed by table name');
3472
+ }
3473
+ // #536:与 restore 同一口径,非数组行集合在写表前拒绝。
3474
+ for (const [name, rows] of Object.entries(data)) {
3475
+ if (!Array.isArray(rows)) {
3476
+ throw createError('ER_PARSE_ERROR', `Invalid rows for table '${name}': expected an array`);
3477
+ }
3478
+ }
3077
3479
  for (const [name, rows] of Object.entries(data)) {
3078
3480
  if (this._tables[name]) {
3079
3481
  this._tables[name]._loadRows(rows);
3482
+ this._walLogReplaceTable(name);
3080
3483
  }
3081
3484
  }
3082
3485
  this._walWrite({ op: 'import', tables: Object.keys(data) });
@@ -3084,15 +3487,20 @@ class Database {
3084
3487
  }
3085
3488
 
3086
3489
  async beginTx() {
3490
+ // #356:与 begin() 的 ER_TRANSACTION_ACTIVE 守卫对齐。活跃事务中再开
3491
+ // 事务会覆盖外层 _txSnapshot,使外层写入在回滚后残留。
3492
+ if (this.hasActiveTx()) throw createError('ER_TRANSACTION_ACTIVE');
3087
3493
  this._savepointStack = [];
3088
3494
  // 与保存点共用同一套快照函数,两边形状必须一致,
3089
3495
  // 否则 rollbackTx 还原不了保存点存下来的快照(反之亦然)。
3090
3496
  this._txSnapshot = this._captureTxSnapshot();
3091
3497
  this._txId = (this._txId || 0) + 1;
3498
+ this._walWrite({ op: 'begin', tx: 'tx' + this._txId });
3092
3499
  return this._txId;
3093
3500
  }
3094
3501
 
3095
3502
  async commitTx() {
3503
+ this._walWrite({ op: 'commit', tx: 'tx' + this._txId });
3096
3504
  this._txSnapshot = null;
3097
3505
  this._txId = undefined;
3098
3506
  this._savepointStack = []; // 提交即释放全部保存点
@@ -3105,6 +3513,7 @@ class Database {
3105
3513
 
3106
3514
  async rollbackTx() {
3107
3515
  const snap = this._txSnapshot;
3516
+ this._walWrite({ op: 'rollback', tx: 'tx' + this._txId });
3108
3517
  this._txSnapshot = null;
3109
3518
  this._txId = undefined;
3110
3519
  this._savepointStack = [];