jsql-neo 6.8.27 → 6.9.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.
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.8.27** — stable release · [github.com/vexify-org/JSQL-neo](https://github.com/vexify-org/JSQL-neo) · [jsql.vexify.top](https://jsql.vexify.top)
6
+ > **v6.9.1** — 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)
@@ -172,9 +172,14 @@ await db.start();
172
172
  File mode (`new Database('./data/db.json')`) is **not** an in-memory store that only
173
173
  writes on exit. Every `insert` / `insertMany` / `update` / `updateById` / `remove` /
174
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.
175
+ writes it to the kernel before returning, so a `kill -9` loses nothing that already
176
+ committed. `fsync` is coalesced into a short window (`walSyncInterval`, default 20 ms)
177
+ so bulk single-row writes no longer pay one disk flush per row — set it to `0` for the
178
+ strictest per-write `fsync` behaviour (roughly an order of magnitude slower). Each insert
179
+ still appends its own record; `db.syncWAL()` forces an immediate lightweight `fsync`
180
+ (no snapshot) when you need a durability barrier at an exact point.
181
+ `save()` / `close()` / `stop()` checkpoint the WAL (write a full snapshot, `fsync`, then
182
+ truncate) and always flush any pending window first.
178
183
  WAL is on by default for file mode — pass `wal: false` for the old semantics, or tune
179
184
  auto-checkpointing with `walCheckpointOps` (default 1000, `0` disables). Directory
180
185
  (`mode: 'disk' | 'hybrid'`) and encrypted (`encryptKey`) databases keep it off unless
package/index.d.ts CHANGED
@@ -345,6 +345,7 @@ declare namespace JSQLNeo {
345
345
  versioning?: boolean;
346
346
  wal?: boolean;
347
347
  walCheckpointOps?: number;
348
+ walSyncInterval?: number;
348
349
  isolationLevel?: 'READ_COMMITTED' | 'REPEATABLE_READ';
349
350
  slowQueryThreshold?: number;
350
351
  fileLock?: boolean;
@@ -360,6 +361,8 @@ declare namespace JSQLNeo {
360
361
  constructor(filePath?: string, options?: DatabaseOptions);
361
362
  createTable(name: string, schema: Schema): Promise<unknown>;
362
363
  insert(table: string, data: Record<string, unknown>): Promise<unknown>;
364
+ /** 轻量持久化屏障:只 fsync 已写入的 WAL 记录,不写全量快照。 */
365
+ syncWAL(): this;
363
366
  find(table: string, filter?: Record<string, unknown>): Promise<Row[]>;
364
367
  exists(table: string, filter?: Record<string, unknown>): boolean;
365
368
  prepare(sql: string): PreparedStatement;
package/index.js CHANGED
@@ -1,5 +1,5 @@
1
1
  /**
2
- * JSQL-NEO v6.8.27 — Rust-Powered Embedded Database (WASM + HTTP)
2
+ * JSQL-NEO v6.9.1 — Rust-Powered Embedded Database (WASM + HTTP)
3
3
  *
4
4
  * @example
5
5
  * const jsql = require('jsql-neo');
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' 则固定事务开始时的行快照。
@@ -805,26 +818,43 @@ class Database {
805
818
 
806
819
  /**
807
820
  * 将新增的 WAL 记录追加到磁盘(append-only)
821
+ *
822
+ * 性能设计(此前单条写入 ~1k/s 的根因):
823
+ * 1. 常驻追加句柄 —— 不再每次 open()/close()
824
+ * 2. 一次 write() 批量写出所有待落盘记录(批次内 JSONL 拼接)
825
+ * 3. fsync 合并到 walSyncInterval 时间窗口 —— write() 已完成,进程崩溃不丢;
826
+ * 只是把「每条一次磁盘刷写」摊薄成「窗口内一次」
808
827
  */
809
828
  _flushWAL() {
810
829
  if (!this._walEnabled || !this._walPath || this._walOps.length === 0) return;
830
+ // 只追加尚未落盘的记录
831
+ const pending = this._walOps.slice(this._walFlushedCount);
832
+ if (pending.length === 0) return;
811
833
  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);
834
+ // 路径变化(或句柄已失效)时必须重开:否则会继续写旧 inode。
835
+ if (this._walFd !== null && this._walFdPath !== this._walPath) this._walCloseFd();
836
+ if (!this._walDirReady) {
837
+ const dir = path.dirname(this._walPath);
838
+ if (!fs.existsSync(dir)) fs.mkdirSync(dir, { recursive: true });
839
+ this._walDirReady = true;
840
+ }
841
+ let payload = '';
842
+ for (let i = 0; i < pending.length; i++) {
843
+ payload += bigintJson.stringify(pending[i]) + '\n';
844
+ }
845
+ if (this._walFd === null) {
846
+ this._walFd = fs.openSync(this._walPath, 'a');
847
+ this._walFdPath = this._walPath;
848
+ }
849
+ const buf = Buffer.from(payload, 'utf8');
850
+ let offset = 0;
851
+ while (offset < buf.length) {
852
+ offset += fs.writeSync(this._walFd, buf, offset, buf.length - offset);
825
853
  }
826
854
  this._walFlushedCount = this._walOps.length;
827
855
  this._walError = null;
856
+ this._walNeedsSync = true;
857
+ this._scheduleWALSync();
828
858
  } catch (e) {
829
859
  // #263:WAL 追加失败不能静默吞掉。
830
860
  // WAL 是崩溃安全的前提(README 承诺「kill -9 不会丢已提交的写入」):
@@ -833,10 +863,59 @@ class Database {
833
863
  // 现在至少通过 error 事件暴露出来(与 _flushDirty 的处理一致),
834
864
  // 并记入 _walError 供上层查询。
835
865
  this._walError = e;
866
+ this._walCloseFd();
836
867
  try { this._emit('error', e); } catch (_) { /* 事件监听器自身抛错不影响主流程 */ }
837
868
  }
838
869
  }
839
870
 
871
+ /**
872
+ * 按 walSyncInterval 合并 fsync:
873
+ * - 0 → 立即同步(最严格,等价旧行为)
874
+ * - >0 → 窗口内只 fsync 一次;窗口内已 write() 的记录在进程崩溃后仍可从页缓存恢复
875
+ */
876
+ _scheduleWALSync() {
877
+ if (!this._walNeedsSync) return;
878
+ if (this._walSyncInterval <= 0) {
879
+ this._syncWAL();
880
+ return;
881
+ }
882
+ if (this._walSyncTimer) return;
883
+ this._walSyncTimer = setTimeout(() => {
884
+ this._walSyncTimer = null;
885
+ this._syncWAL();
886
+ }, this._walSyncInterval);
887
+ // 不能让合并窗口的定时器把进程挂住
888
+ if (this._walSyncTimer && this._walSyncTimer.unref) this._walSyncTimer.unref();
889
+ }
890
+
891
+ /** 立即 fsync 尚未落盘刷写的 WAL 数据(幂等)。 */
892
+ _syncWAL() {
893
+ if (!this._walNeedsSync) return;
894
+ if (this._walFd === null) { this._walNeedsSync = false; return; }
895
+ try {
896
+ fs.fsyncSync(this._walFd);
897
+ this._walNeedsSync = false;
898
+ } catch (e) {
899
+ this._walError = e;
900
+ try { this._emit('error', e); } catch (_) { /* ignore */ }
901
+ }
902
+ }
903
+
904
+ /** 关闭常驻 WAL 句柄:先补齐 fsync,再关句柄并复位状态。 */
905
+ _walCloseFd() {
906
+ if (this._walSyncTimer) {
907
+ clearTimeout(this._walSyncTimer);
908
+ this._walSyncTimer = null;
909
+ }
910
+ this._syncWAL();
911
+ if (this._walFd !== null) {
912
+ try { fs.closeSync(this._walFd); } catch (e) { /* 已关闭 / 句柄失效 */ }
913
+ this._walFd = null;
914
+ this._walFdPath = null;
915
+ }
916
+ this._walDirReady = false;
917
+ }
918
+
840
919
  /**
841
920
  * 检查点:数据已由 save() 完整落盘,清空 WAL
842
921
  *
@@ -845,6 +924,9 @@ class Database {
845
924
  */
846
925
  _checkpoint() {
847
926
  if (!this._walEnabled) return;
927
+ // 必须先把常驻句柄里的数据 fsync 并关闭,否则 unlink 后该句柄
928
+ // 仍持有旧 inode,后续写入会落到一个「已被删除」的文件里而静默丢失。
929
+ this._walCloseFd();
848
930
  this._walOps = [];
849
931
  this._walFlushedCount = 0;
850
932
  this._walOpCount = 0;
@@ -2586,6 +2668,18 @@ class Database {
2586
2668
  return this;
2587
2669
  }
2588
2670
 
2671
+ /**
2672
+ * 轻量持久化屏障:只把已写入的 WAL 记录 fsync 到磁盘,不写全量快照。
2673
+ *
2674
+ * 每条记录在写入时已单独 append 并 write() 进内核;默认 fsync 按
2675
+ * `walSyncInterval` 窗口合并。需要「此刻就必须抗掉电」时调用本方法,
2676
+ * 比 flush()/save()(全量快照)轻得多。
2677
+ */
2678
+ syncWAL() {
2679
+ if (this._walEnabled) this._syncWAL();
2680
+ return this;
2681
+ }
2682
+
2589
2683
  _resolveId(table, id) {
2590
2684
  const pk = this._pkOf(table);
2591
2685
  if (pk) {
@@ -2986,6 +3080,9 @@ class Database {
2986
3080
  this._sigInstalled = false;
2987
3081
  Database._uninstallSignalHandler(this);
2988
3082
  }
3083
+ // 兜底:合并窗口内可能还有未 fsync 的 WAL 记录(例如 save() 抛错被吞掉),
3084
+ // 关闭实例前必须补齐,否则掉电会丢失这段已返回成功的写入。
3085
+ this._walCloseFd();
2989
3086
  // #295:stop() 表示本实例停止写入,必须释放文件锁,否则同路径再打开会误报占用
2990
3087
  this._releaseLock();
2991
3088
  return this;
@@ -3221,6 +3318,7 @@ class Database {
3221
3318
  this.save();
3222
3319
  }
3223
3320
  if (this._jsqlFormat) this._jsqlFormat._close();
3321
+ this._walCloseFd();
3224
3322
  this._releaseLock();
3225
3323
  // Bug 3: 清理静态信号处理器,防止关闭后还在响应信号
3226
3324
  if (this._sigInstalled) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "jsql-neo",
3
- "version": "6.8.27",
3
+ "version": "6.9.1",
4
4
  "description": "JSQL-NEO — Rust-powered embedded database with WASM, REST API, B-Tree indexes, WAL, crash recovery",
5
5
  "main": "index.js",
6
6
  "types": "index.d.ts",