jsql-neo 6.8.27 → 6.10.2

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 (139) hide show
  1. package/README.md +9 -4
  2. package/bin/jsql-server-control.js +58 -14
  3. package/index.d.ts +3 -0
  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/database.js +272 -36
  9. package/lib/jsql_format.js +22 -9
  10. package/lib/migrate.js +184 -98
  11. package/lib/mod.js +48 -13
  12. package/lib/mongo_server.js +652 -246
  13. package/lib/mysql_compat.js +54 -11
  14. package/lib/mysql_server.js +248 -65
  15. package/lib/nedb_compat.js +7 -1
  16. package/lib/objectid.js +14 -6
  17. package/lib/pg_server.js +385 -9
  18. package/lib/plugin.js +34 -3
  19. package/lib/query.js +12 -6
  20. package/lib/redis_server.js +102 -42
  21. package/lib/sql.js +446 -48
  22. package/lib/table.js +111 -41
  23. package/lib/tui.js +28 -9
  24. package/lib/web_ui.js +33 -2
  25. package/package.json +4 -4
  26. package/test/alter-table.test.js +11 -5
  27. package/test/compat-v1.test.js +1 -1
  28. package/test/extra-coverage.test.js +6 -7
  29. package/test/issue-258-300.test.js +6 -0
  30. package/test/issue-312-320.test.js +11 -4
  31. package/test/issue-326.test.js +42 -0
  32. package/test/issue-327-418.test.js +1 -1
  33. package/test/issue-336.test.js +56 -0
  34. package/test/issue-353.test.js +34 -0
  35. package/test/issue-356.test.js +27 -0
  36. package/test/issue-357-365.test.js +1 -1
  37. package/test/issue-361.test.js +55 -0
  38. package/test/issue-370.test.js +43 -0
  39. package/test/issue-373.test.js +40 -0
  40. package/test/issue-374.test.js +62 -0
  41. package/test/issue-378.test.js +39 -0
  42. package/test/issue-379.test.js +39 -0
  43. package/test/issue-38.test.js +2 -2
  44. package/test/issue-380.test.js +27 -0
  45. package/test/issue-383-402.test.js +4 -3
  46. package/test/issue-384.test.js +41 -0
  47. package/test/issue-392.test.js +25 -0
  48. package/test/issue-397.test.js +44 -0
  49. package/test/issue-403.test.js +47 -0
  50. package/test/issue-404.test.js +58 -0
  51. package/test/issue-407.test.js +40 -0
  52. package/test/issue-408.test.js +92 -0
  53. package/test/issue-409.test.js +32 -0
  54. package/test/issue-410.test.js +36 -0
  55. package/test/issue-411.test.js +38 -0
  56. package/test/issue-412.test.js +50 -0
  57. package/test/issue-414.test.js +46 -0
  58. package/test/issue-417.test.js +56 -0
  59. package/test/issue-420.test.js +87 -0
  60. package/test/issue-421.test.js +30 -0
  61. package/test/issue-422.test.js +33 -0
  62. package/test/issue-424.test.js +44 -0
  63. package/test/issue-425.test.js +22 -0
  64. package/test/issue-426.test.js +22 -0
  65. package/test/issue-427.test.js +36 -0
  66. package/test/issue-429.test.js +38 -0
  67. package/test/issue-431.test.js +41 -0
  68. package/test/issue-432.test.js +37 -0
  69. package/test/issue-436.test.js +47 -0
  70. package/test/issue-445-449.test.js +14 -7
  71. package/test/issue-455-459.test.js +6 -3
  72. package/test/issue-474.test.js +59 -0
  73. package/test/issue-475.test.js +38 -0
  74. package/test/issue-476.test.js +50 -0
  75. package/test/issue-477.test.js +54 -0
  76. package/test/issue-478.test.js +52 -0
  77. package/test/issue-479.test.js +44 -0
  78. package/test/issue-480.test.js +42 -0
  79. package/test/issue-481.test.js +51 -0
  80. package/test/issue-482.test.js +36 -0
  81. package/test/issue-483.test.js +57 -0
  82. package/test/issue-485.test.js +47 -0
  83. package/test/issue-486.test.js +69 -0
  84. package/test/issue-487.test.js +54 -0
  85. package/test/issue-488.test.js +69 -0
  86. package/test/issue-490.test.js +20 -0
  87. package/test/issue-491.test.js +21 -0
  88. package/test/issue-492.test.js +19 -0
  89. package/test/issue-493.test.js +30 -0
  90. package/test/issue-494.test.js +82 -0
  91. package/test/issue-495.test.js +86 -0
  92. package/test/issue-496.test.js +98 -0
  93. package/test/issue-497.test.js +29 -0
  94. package/test/issue-498.test.js +32 -0
  95. package/test/issue-499.test.js +41 -0
  96. package/test/issue-500.test.js +39 -0
  97. package/test/issue-501-506.test.js +29 -0
  98. package/test/issue-502.test.js +18 -0
  99. package/test/issue-503.test.js +43 -0
  100. package/test/issue-504.test.js +83 -0
  101. package/test/issue-505.test.js +29 -0
  102. package/test/issue-529.test.js +39 -0
  103. package/test/issue-530.test.js +69 -0
  104. package/test/issue-536.test.js +46 -0
  105. package/test/issue-537.test.js +52 -0
  106. package/test/issue-539.test.js +65 -0
  107. package/test/issue-540.test.js +31 -0
  108. package/test/issue-545.test.js +38 -0
  109. package/test/issue-546.test.js +68 -0
  110. package/test/issue-547.test.js +27 -0
  111. package/test/issue-548.test.js +68 -0
  112. package/test/issue-549.test.js +26 -0
  113. package/test/issue-550.test.js +52 -0
  114. package/test/issue-551.test.js +34 -0
  115. package/test/issue-552.test.js +30 -0
  116. package/test/issue-553.test.js +29 -0
  117. package/test/issue-554.test.js +29 -0
  118. package/test/issue-555.test.js +22 -0
  119. package/test/issue-556.test.js +25 -0
  120. package/test/issue-565.test.js +32 -0
  121. package/test/issue-566.test.js +30 -0
  122. package/test/issue-567.test.js +56 -0
  123. package/test/issue-568.test.js +46 -0
  124. package/test/issue-569.test.js +25 -0
  125. package/test/issue-570.test.js +30 -0
  126. package/test/issue-571.test.js +32 -0
  127. package/test/issue-572.test.js +64 -0
  128. package/test/issue-573.test.js +71 -0
  129. package/test/issue-574.test.js +63 -0
  130. package/test/issue-581.test.js +46 -0
  131. package/test/issue-59.test.js +17 -4
  132. package/test/issue-69-70.test.js +1 -1
  133. package/test/issue-mysql-harness.js +260 -0
  134. package/test/issue-pg5-helper.js +135 -0
  135. package/test/mongo-arrays.test.js +63 -0
  136. package/test/mongo-objectid.test.js +2 -2
  137. package/test/mongo-persistence.test.js +3 -3
  138. package/test/mongo-update-dates.test.js +128 -0
  139. 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)
@@ -205,6 +208,16 @@ class Database {
205
208
  this._walOpCount = 0; // 自上次检查点以来的操作数
206
209
  this._walCheckpointOps = options.walCheckpointOps !== undefined ? options.walCheckpointOps : 1000;
207
210
  this._walCheckpointScheduled = false;
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;
208
221
 
209
222
  // 事务隔离:默认 READ_COMMITTED(每条语句读到最新已提交数据);
210
223
  // 传 'REPEATABLE_READ' 则固定事务开始时的行快照。
@@ -680,7 +693,20 @@ class Database {
680
693
  if (e.code === 'EEXIST') {
681
694
  try {
682
695
  const lockTime = fs.statSync(this._lockPath).mtimeMs;
683
- 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) {
684
710
  fs.unlinkSync(this._lockPath);
685
711
  this._lockFd = fs.openSync(this._lockPath, 'wx');
686
712
  fs.writeSync(this._lockFd, String(process.pid), null, 'utf8');
@@ -698,14 +724,19 @@ class Database {
698
724
 
699
725
  _releaseLock() {
700
726
  if (!this._fileLockEnabled || !this._lockFd) return;
727
+ const fd = this._lockFd;
728
+ this._lockFd = null;
701
729
  try {
702
730
  if (fs.existsSync(this._lockPath)) {
703
731
  fs.unlinkSync(this._lockPath);
704
732
  }
705
- this._lockFd = null;
706
733
  } catch (e) {
707
734
  // 忽略
708
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 (_) { /* 已关闭 / 句柄失效 */ }
709
740
  }
710
741
 
711
742
  // ============================================================
@@ -749,11 +780,15 @@ class Database {
749
780
  if (!t || !Array.isArray(rows) || rows.length === 0) return;
750
781
  if (t._primaryKey) {
751
782
  const pk = t._primaryKey;
752
- 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);
753
786
  if (out.length === 0) return;
754
787
  this._walWrite({ op: 'upsertRows', table: tableName, pk, rows: out });
755
788
  } else {
756
- this._walLogReplaceTable(tableName);
789
+ // 无主键表此前退化成「每次批量插入都写整表镜像」——100 万行会写出几百 MB 的 O(n²) 日志。
790
+ // 改为只追加本批新增行(append-only),回放时顺序 push 即可。
791
+ this._walWrite({ op: 'insert', table: tableName, rows });
757
792
  }
758
793
  }
759
794
 
@@ -778,7 +813,7 @@ class Database {
778
813
  if (!this._walEnabled || this._walReplaying || this._loading) return;
779
814
  const t = this._tables[tableName];
780
815
  if (!t) return;
781
- this._walWrite({ op: 'replaceTable', table: tableName, rows: t._rows.map(r => ({ ...r })) });
816
+ this._walWrite({ op: 'replaceTable', table: tableName, rows: t._rows });
782
817
  }
783
818
 
784
819
  /**
@@ -805,26 +840,43 @@ class Database {
805
840
 
806
841
  /**
807
842
  * 将新增的 WAL 记录追加到磁盘(append-only)
843
+ *
844
+ * 性能设计(此前单条写入 ~1k/s 的根因):
845
+ * 1. 常驻追加句柄 —— 不再每次 open()/close()
846
+ * 2. 一次 write() 批量写出所有待落盘记录(批次内 JSONL 拼接)
847
+ * 3. fsync 合并到 walSyncInterval 时间窗口 —— write() 已完成,进程崩溃不丢;
848
+ * 只是把「每条一次磁盘刷写」摊薄成「窗口内一次」
808
849
  */
809
850
  _flushWAL() {
810
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;
811
855
  try {
812
- const dir = path.dirname(this._walPath);
813
- if (!fs.existsSync(dir)) fs.mkdirSync(dir, { recursive: true });
814
- // 只追加尚未落盘的记录
815
- const pending = this._walOps.slice(this._walFlushedCount);
816
- if (pending.length === 0) return;
817
- const lines = pending.map(o => bigintJson.stringify(o)).join('\n') + '\n';
818
- const fd = fs.openSync(this._walPath, 'a');
819
- try {
820
- fs.writeSync(fd, lines, null, 'utf8');
821
- // 崩溃安全性:确保数据真正落到磁盘而不仅在页缓存
822
- try { fs.fsyncSync(fd); } catch (e) { /* 某些文件系统不支持 fsync */ }
823
- } finally {
824
- 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);
825
875
  }
826
876
  this._walFlushedCount = this._walOps.length;
827
877
  this._walError = null;
878
+ this._walNeedsSync = true;
879
+ this._scheduleWALSync();
828
880
  } catch (e) {
829
881
  // #263:WAL 追加失败不能静默吞掉。
830
882
  // WAL 是崩溃安全的前提(README 承诺「kill -9 不会丢已提交的写入」):
@@ -833,10 +885,59 @@ class Database {
833
885
  // 现在至少通过 error 事件暴露出来(与 _flushDirty 的处理一致),
834
886
  // 并记入 _walError 供上层查询。
835
887
  this._walError = e;
888
+ this._walCloseFd();
836
889
  try { this._emit('error', e); } catch (_) { /* 事件监听器自身抛错不影响主流程 */ }
837
890
  }
838
891
  }
839
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
+
840
941
  /**
841
942
  * 检查点:数据已由 save() 完整落盘,清空 WAL
842
943
  *
@@ -845,6 +946,9 @@ class Database {
845
946
  */
846
947
  _checkpoint() {
847
948
  if (!this._walEnabled) return;
949
+ // 必须先把常驻句柄里的数据 fsync 并关闭,否则 unlink 后该句柄
950
+ // 仍持有旧 inode,后续写入会落到一个「已被删除」的文件里而静默丢失。
951
+ this._walCloseFd();
848
952
  this._walOps = [];
849
953
  this._walFlushedCount = 0;
850
954
  this._walOpCount = 0;
@@ -971,6 +1075,27 @@ class Database {
971
1075
  // insert 不走 _loadRows()(那是整体替换语义),而是直接 push 到 _rows,
972
1076
  // 再在末尾统一重建索引;否则逐条回放会互相覆盖。
973
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); };
974
1099
  for (const op of ops) {
975
1100
  try {
976
1101
  // 事务标记帧本身不改数据状态,回放时跳过。
@@ -990,11 +1115,15 @@ class Database {
990
1115
  }
991
1116
  if (!t || !Array.isArray(op.rows) || op.rows.length === 0) { failed++; break; }
992
1117
  const pk = t._primaryKey;
1118
+ const idm = pk ? idxMapOf(t, pk) : null;
993
1119
  for (const __e of op.rows) {
1120
+ if (!__e) continue;
994
1121
  // 幂等:快照已包含该行时覆盖而不是重复插入
995
- if (pk && __e && __e[pk] !== undefined) {
996
- const ai = t._rows.findIndex(r => r && r[pk] === __e[pk]);
997
- 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);
998
1127
  }
999
1128
  t._rows.push(__e);
1000
1129
  }
@@ -1010,11 +1139,17 @@ class Database {
1010
1139
  t = this._tables[op.table];
1011
1140
  }
1012
1141
  if (!t || !op.pk || !Array.isArray(op.rows)) { failed++; break; }
1142
+ const idm = idxMapOf(t, op.pk);
1013
1143
  for (const __r of op.rows) {
1014
1144
  if (!__r || typeof __r !== 'object') continue;
1015
- const ai = t._rows.findIndex(r => r && String(r[op.pk]) === String(__r[op.pk]));
1016
- if (ai >= 0) t._rows[ai] = { ...__r };
1017
- 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
+ }
1018
1153
  }
1019
1154
  touched.add(t);
1020
1155
  replayed++;
@@ -1025,6 +1160,7 @@ class Database {
1025
1160
  if (!t || !op.pk || !Array.isArray(op.ids)) { failed++; break; }
1026
1161
  const gone = new Set(op.ids.map(String));
1027
1162
  t._rows = t._rows.filter(r => !r || !gone.has(String(r[op.pk])));
1163
+ invalidateIdx(t);
1028
1164
  touched.add(t);
1029
1165
  replayed++;
1030
1166
  break;
@@ -1037,6 +1173,7 @@ class Database {
1037
1173
  }
1038
1174
  if (!t || !Array.isArray(op.rows)) { failed++; break; }
1039
1175
  t._rows = op.rows.map(r => ({ ...r }));
1176
+ invalidateIdx(t);
1040
1177
  touched.add(t);
1041
1178
  replayed++;
1042
1179
  break;
@@ -1056,6 +1193,7 @@ class Database {
1056
1193
  if (!t || !op.pk) { failed++; break; }
1057
1194
  const before = t._rows.length;
1058
1195
  t._rows = t._rows.filter(r => r[op.pk] !== op.id);
1196
+ invalidateIdx(t);
1059
1197
  if (t._rows.length === before) { failed++; break; }
1060
1198
  touched.add(t);
1061
1199
  replayed++;
@@ -2266,6 +2404,9 @@ class Database {
2266
2404
  table._autoIncrement = row[table._autoIncrementField];
2267
2405
  }
2268
2406
  }
2407
+ // #549:行序被快照整体替换后 `_pkIndex` 仍指向删除阶段的下标,
2408
+ // 必须和 B-Tree / 二级索引一起重建,否则主键点查命中错误行。
2409
+ if (typeof table._rebuildPKIndex === 'function') table._rebuildPKIndex();
2269
2410
  table._rebuildAllBTrees();
2270
2411
  for (const field of Object.keys(table._indexes)) {
2271
2412
  table.createIndex(field);
@@ -2586,6 +2727,18 @@ class Database {
2586
2727
  return this;
2587
2728
  }
2588
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
+
2589
2742
  _resolveId(table, id) {
2590
2743
  const pk = this._pkOf(table);
2591
2744
  if (pk) {
@@ -2659,7 +2812,15 @@ class Database {
2659
2812
  async query(sql, paramsOrOpts, opts) {
2660
2813
  const { executeSQL } = require('./sql');
2661
2814
  if (!(await this._runHooks('beforeQuery', [sql, paramsOrOpts, opts]))) return null;
2662
- 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
+ }
2663
2824
  await this._runHooks('afterQuery', [sql, paramsOrOpts, opts, result]);
2664
2825
  return result;
2665
2826
  }
@@ -2726,10 +2887,26 @@ class Database {
2726
2887
  const row = this._resolveId(table, id);
2727
2888
  // P1-4: 软删除行不可更新
2728
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
+ }
2729
2900
  // 改主键/唯一列时要先确认新值不与其它行冲突。
2730
2901
  // 注意:UNIQUE 列记录在 table._cachedUniqueFields(不是 _indexes),
2731
2902
  // 逐行比对即可,未建索引时也能正确拦截。
2732
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;
2733
2910
  const uniq = (table._cachedUniqueFields || []).filter(f => f !== pk);
2734
2911
  for (const field of [pk, ...uniq]) {
2735
2912
  if (!field || !Object.prototype.hasOwnProperty.call(validated, field)) continue;
@@ -2774,13 +2951,13 @@ class Database {
2774
2951
  if (i !== undefined && table._rows[i] === row) rowIndex = i;
2775
2952
  }
2776
2953
  if (rowIndex === -1) rowIndex = table._rows.indexOf(row);
2777
- const oldPk = pk ? row[pk] : undefined;
2954
+ oldPk = pk ? row[pk] : undefined;
2778
2955
  if (rowIndex !== -1) table._removeFromIndexes(rowIndex, row);
2779
2956
  Object.assign(row, validated);
2780
2957
  if (rowIndex !== -1) table._addToIndexes(rowIndex, row);
2781
2958
  if (typeof table._markRowDirty === 'function') table._markRowDirty(row, oldPk);
2782
2959
  }
2783
- return { row, validated };
2960
+ return { row, validated, oldPk: pkChanged ? oldPk : undefined };
2784
2961
  }
2785
2962
 
2786
2963
  async updateById(tableName, id, data) {
@@ -2793,7 +2970,11 @@ class Database {
2793
2970
  data = hookArgs[2];
2794
2971
  const applied = this._applyUpdateToRow(table, id, data);
2795
2972
  if (!applied) return { ok: false, error: 'not found' };
2796
- 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
+ }
2797
2978
  this._walLogUpsert(tableName, [row]);
2798
2979
  this._emit('update', { table: tableName, id, data: validated });
2799
2980
  await this._runHooks('afterUpdate', [tableName, id, validated, { ok: true }]);
@@ -2808,13 +2989,17 @@ class Database {
2808
2989
  if (!(await this._runHooks('beforeUpdate', [tableName, pairs]))) return { ok: false, count: 0, error: 'aborted' }; // #383
2809
2990
  let count = 0;
2810
2991
  const changed = [];
2992
+ const oldPkRows = [];
2993
+ const pk = this._pkOf(table);
2811
2994
  for (const [id, data] of pairs) {
2812
2995
  const applied = this._applyUpdateToRow(table, id, data);
2813
2996
  if (applied) {
2814
2997
  changed.push(applied.row);
2998
+ if (applied.oldPk !== undefined && pk) oldPkRows.push({ [pk]: applied.oldPk });
2815
2999
  count++;
2816
3000
  }
2817
3001
  }
3002
+ if (oldPkRows.length) this._walLogRemove(tableName, oldPkRows);
2818
3003
  if (changed.length) this._walLogUpsert(tableName, changed);
2819
3004
  this._emit('update', { table: tableName, entries: pairs, result: { ok: true, count } });
2820
3005
  await this._runHooks('afterUpdate', [tableName, pairs, { ok: true, count }]);
@@ -2966,6 +3151,15 @@ class Database {
2966
3151
  return count;
2967
3152
  }
2968
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
+
2969
3163
  async stop() {
2970
3164
  await this._runHooks('onStop', []);
2971
3165
  this._emit('stop', {});
@@ -2978,6 +3172,7 @@ class Database {
2978
3172
  this._saveMeta();
2979
3173
  this._checkpoint();
2980
3174
  } catch (e) {}
3175
+ this._closeRowCaches();
2981
3176
  } else if (!this._memoryMode) {
2982
3177
  // 正常关闭时做一次快照检查点,缩短下次启动的回放时间
2983
3178
  try { this.save(); } catch (e) {}
@@ -2986,6 +3181,9 @@ class Database {
2986
3181
  this._sigInstalled = false;
2987
3182
  Database._uninstallSignalHandler(this);
2988
3183
  }
3184
+ // 兜底:合并窗口内可能还有未 fsync 的 WAL 记录(例如 save() 抛错被吞掉),
3185
+ // 关闭实例前必须补齐,否则掉电会丢失这段已返回成功的写入。
3186
+ this._walCloseFd();
2989
3187
  // #295:stop() 表示本实例停止写入,必须释放文件锁,否则同路径再打开会误报占用
2990
3188
  this._releaseLock();
2991
3189
  return this;
@@ -3067,9 +3265,31 @@ class Database {
3067
3265
  }
3068
3266
  const json = this._readFile(filePath);
3069
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
+ // 否则字符串会被当成可迭代行集合展开成逐字符垃圾行。
3070
3273
  for (const [name, rows] of Object.entries(data)) {
3071
- if (this._tables[name]) {
3072
- 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);
3073
3293
  }
3074
3294
  }
3075
3295
  this._walWrite({ op: 'restore', from: filePath });
@@ -3133,10 +3353,11 @@ class Database {
3133
3353
  this._jsqlFormat._open();
3134
3354
  for (const [name, t] of this._jsqlFormat.tables) {
3135
3355
  if (!this._tables[name]) this._createTableSync(name, t.schema);
3136
- if (t.rowCount > 0) {
3137
- const { rows } = this._jsqlFormat.readTableSync(name);
3138
- this._tables[name]._loadRows(rows);
3139
- }
3356
+ // #547:无主键表没有 pkEntries,rowCount 恒为 0,但行确实写在
3357
+ // 数据块里。readTableSync 在无索引时按表 ID 扫描全部数据块,
3358
+ // 因此不能再用 rowCount>0 作为是否加载行的门槛。
3359
+ const { rows } = this._jsqlFormat.readTableSync(name);
3360
+ this._tables[name]._loadRows(rows);
3140
3361
  }
3141
3362
  // WAL 恢复(此前 .jsql 分支提前 return,导致崩溃后数据全丢)
3142
3363
  this._recoverFromWAL();
@@ -3214,6 +3435,7 @@ class Database {
3214
3435
  try {
3215
3436
  this._flushDirty();
3216
3437
  this._saveMeta();
3438
+ this._closeRowCaches();
3217
3439
  } catch (e) {
3218
3440
  this._emit('error', e);
3219
3441
  }
@@ -3221,6 +3443,7 @@ class Database {
3221
3443
  this.save();
3222
3444
  }
3223
3445
  if (this._jsqlFormat) this._jsqlFormat._close();
3446
+ this._walCloseFd();
3224
3447
  this._releaseLock();
3225
3448
  // Bug 3: 清理静态信号处理器,防止关闭后还在响应信号
3226
3449
  if (this._sigInstalled) {
@@ -3244,9 +3467,19 @@ class Database {
3244
3467
  }
3245
3468
 
3246
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
+ }
3247
3479
  for (const [name, rows] of Object.entries(data)) {
3248
3480
  if (this._tables[name]) {
3249
3481
  this._tables[name]._loadRows(rows);
3482
+ this._walLogReplaceTable(name);
3250
3483
  }
3251
3484
  }
3252
3485
  this._walWrite({ op: 'import', tables: Object.keys(data) });
@@ -3254,6 +3487,9 @@ class Database {
3254
3487
  }
3255
3488
 
3256
3489
  async beginTx() {
3490
+ // #356:与 begin() 的 ER_TRANSACTION_ACTIVE 守卫对齐。活跃事务中再开
3491
+ // 事务会覆盖外层 _txSnapshot,使外层写入在回滚后残留。
3492
+ if (this.hasActiveTx()) throw createError('ER_TRANSACTION_ACTIVE');
3257
3493
  this._savepointStack = [];
3258
3494
  // 与保存点共用同一套快照函数,两边形状必须一致,
3259
3495
  // 否则 rollbackTx 还原不了保存点存下来的快照(反之亦然)。
@@ -161,19 +161,24 @@ function encRowInPlace(row, encoders, scratch, offStart) {
161
161
  // Build reusable field encoders from schema
162
162
  // 无 schema 的表(如 Mongo collection 以 {} 建表):字段从行数据本身取并集。
163
163
  // 否则 0 个编码器会把每一行刷成 4 字节空桩,重载时一行都读不回来。
164
+ // 有 schema 时以 schema 字段为底、再并入行里出现的未知字段:Mongo 集合的
165
+ // schema 是首份文档推断出来的(_inferSchema),后续更新新增的字段不在其中,
166
+ // 若按 schema 硬裁会把新字段静默丢弃(内存可见、重载即消失)。
164
167
  // shortcut: 某行缺的字段重载后变 null(不区分「缺字段」和「值为 null」),需要严格区分时再升级
165
168
  function buildEncoders(schema, rows) {
166
169
  const skip = f => f !== '_softDelete'; // _softDelete 是 schema 配置键,不会是数据字段
167
- const schemaFields = Object.keys(schema || {}).filter(skip);
168
- if (schemaFields.length > 0) {
169
- return schemaFields.map(name => ({ name, nameEnc: enc(name) }));
170
- }
171
170
  const seen = new Set();
171
+ const fields = [];
172
+ for (const name of Object.keys(schema || {})) {
173
+ if (skip(name) && !seen.has(name)) { seen.add(name); fields.push(name); }
174
+ }
172
175
  for (const row of rows || []) {
173
176
  if (!row) continue;
174
- for (const f of Object.keys(row)) if (skip(f)) seen.add(f);
177
+ for (const f of Object.keys(row)) {
178
+ if (skip(f) && !seen.has(f)) { seen.add(f); fields.push(f); }
179
+ }
175
180
  }
176
- return [...seen].map(name => ({ name, nameEnc: enc(name) }));
181
+ return fields.map(name => ({ name, nameEnc: enc(name) }));
177
182
  }
178
183
 
179
184
  const encRow = encRowInPlace;
@@ -431,10 +436,17 @@ class JSQLFormat {
431
436
 
432
437
  for (const [name, info] of Object.entries(allTables)) {
433
438
  const { schema, rows, pkField } = info;
434
- if (!rows || rows.length === 0) continue;
435
-
439
+ // #545:空表也要登记到 superblock,否则重开后 DDL 静默消失。
440
+ // 之前 rows.length===0 直接 continue,表名/schema 既不进 superblock 也不写索引块。
436
441
  const tableId = this._nextTableId++;
437
442
  this.tables.set(name, { schema, rowCount:0, pkBlock:0, dataBlock:0, tableId });
443
+ if (!rows || rows.length === 0) {
444
+ // #545:空表也要写一个空数据块,让 _load 能从 superblock 重建出这张表。
445
+ // 走下面的统一 phase2 编码路径(含 gzip/加密/finalize 校验),
446
+ // 不能直接写裸块,否则校验和不通过。
447
+ pending.push({ name, tableId, rawBlocks: [Buffer.alloc(0)], blockIds: [this._alloc()], pkEntries: [] });
448
+ continue;
449
+ }
438
450
 
439
451
  const pkEntries = [];
440
452
  const rawBlocks = [];
@@ -576,7 +588,8 @@ class JSQLFormat {
576
588
 
577
589
  const entries = this.pkIdx.get(name) || [];
578
590
  this.pkIdx.set(name, entries);
579
- const encoders = buildEncoders(t.schema);
591
+ // upserts 也要传给 buildEncoders:schema 之外的行字段不能被静默裁掉
592
+ const encoders = buildEncoders(t.schema, upserts);
580
593
  const scratch = Buffer.allocUnsafe(SZ.DATA);
581
594
  const written = [];
582
595