jsql-neo 6.8.26 → 6.9.0
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 +7 -4
- package/index.d.ts +23 -5
- package/index.js +1 -1
- package/lib/columnar_fast.js +13 -2
- package/lib/database.js +306 -47
- package/lib/errors.js +2 -0
- package/lib/migrate.js +30 -3
- package/lib/mongo_server.js +42 -9
- package/lib/multiserver.js +4 -1
- package/lib/mysql_server.js +13 -1
- package/lib/pg_server.js +8 -2
- package/lib/redis_server.js +4 -1
- package/lib/sql.js +140 -23
- package/lib/table.js +42 -5
- package/package.json +2 -2
- package/test/columnar-vector.test.js +2 -1
- package/test/issue-259-264.test.js +5 -1
- package/test/issue-329-346.test.js +22 -5
- package/test/issue-445-449.test.js +271 -0
- package/test/issue-450-454.test.js +202 -0
- package/test/issue-455-459.test.js +348 -0
- package/test/issue-460-464.test.js +195 -0
- package/test/issue-465-469.test.js +201 -0
- package/test/issue-471.test.js +150 -0
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
|
|
112
|
-
*
|
|
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
|
-
//
|
|
209
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
382
|
+
payload = JSON.stringify(this._meta, null, 2);
|
|
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);
|
|
358
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.
|
|
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.
|
|
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.
|
|
541
|
-
this._meta.tables[name] = { file, schema: table.
|
|
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);
|
|
@@ -659,6 +734,11 @@ class Database {
|
|
|
659
734
|
*/
|
|
660
735
|
_walWrite(op) {
|
|
661
736
|
if (!this._walEnabled || this._loading) return;
|
|
737
|
+
// #446:活动事务内产生的写入打上事务标签,回放时按 commit 帧判定是否可见。
|
|
738
|
+
if (op.tx === undefined) {
|
|
739
|
+
const tag = this._currentTxTag();
|
|
740
|
+
if (tag !== null) op.tx = tag;
|
|
741
|
+
}
|
|
662
742
|
const entry = {
|
|
663
743
|
...op,
|
|
664
744
|
timestamp: Date.now(),
|
|
@@ -721,11 +801,11 @@ class Database {
|
|
|
721
801
|
_maybeCheckpointWAL() {
|
|
722
802
|
if (!this._walEnabled || this._walCheckpointScheduled) return;
|
|
723
803
|
if (this._walCheckpointOps <= 0 || this._walOpCount < this._walCheckpointOps) return;
|
|
724
|
-
if (this._loading || this._walReplaying || this.
|
|
804
|
+
if (this._loading || this._walReplaying || this.hasActiveTx()) return;
|
|
725
805
|
this._walCheckpointScheduled = true;
|
|
726
806
|
const run = () => {
|
|
727
807
|
this._walCheckpointScheduled = false;
|
|
728
|
-
if (this._loading || this._walReplaying || this.
|
|
808
|
+
if (this._loading || this._walReplaying || this.hasActiveTx()) return;
|
|
729
809
|
try {
|
|
730
810
|
this.save();
|
|
731
811
|
} catch (e) {
|
|
@@ -738,26 +818,43 @@ class Database {
|
|
|
738
818
|
|
|
739
819
|
/**
|
|
740
820
|
* 将新增的 WAL 记录追加到磁盘(append-only)
|
|
821
|
+
*
|
|
822
|
+
* 性能设计(此前单条写入 ~1k/s 的根因):
|
|
823
|
+
* 1. 常驻追加句柄 —— 不再每次 open()/close()
|
|
824
|
+
* 2. 一次 write() 批量写出所有待落盘记录(批次内 JSONL 拼接)
|
|
825
|
+
* 3. fsync 合并到 walSyncInterval 时间窗口 —— write() 已完成,进程崩溃不丢;
|
|
826
|
+
* 只是把「每条一次磁盘刷写」摊薄成「窗口内一次」
|
|
741
827
|
*/
|
|
742
828
|
_flushWAL() {
|
|
743
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;
|
|
744
833
|
try {
|
|
745
|
-
|
|
746
|
-
if (
|
|
747
|
-
|
|
748
|
-
|
|
749
|
-
|
|
750
|
-
|
|
751
|
-
|
|
752
|
-
|
|
753
|
-
|
|
754
|
-
|
|
755
|
-
|
|
756
|
-
|
|
757
|
-
fs.
|
|
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);
|
|
758
853
|
}
|
|
759
854
|
this._walFlushedCount = this._walOps.length;
|
|
760
855
|
this._walError = null;
|
|
856
|
+
this._walNeedsSync = true;
|
|
857
|
+
this._scheduleWALSync();
|
|
761
858
|
} catch (e) {
|
|
762
859
|
// #263:WAL 追加失败不能静默吞掉。
|
|
763
860
|
// WAL 是崩溃安全的前提(README 承诺「kill -9 不会丢已提交的写入」):
|
|
@@ -766,10 +863,59 @@ class Database {
|
|
|
766
863
|
// 现在至少通过 error 事件暴露出来(与 _flushDirty 的处理一致),
|
|
767
864
|
// 并记入 _walError 供上层查询。
|
|
768
865
|
this._walError = e;
|
|
866
|
+
this._walCloseFd();
|
|
769
867
|
try { this._emit('error', e); } catch (_) { /* 事件监听器自身抛错不影响主流程 */ }
|
|
770
868
|
}
|
|
771
869
|
}
|
|
772
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
|
+
|
|
773
919
|
/**
|
|
774
920
|
* 检查点:数据已由 save() 完整落盘,清空 WAL
|
|
775
921
|
*
|
|
@@ -778,6 +924,9 @@ class Database {
|
|
|
778
924
|
*/
|
|
779
925
|
_checkpoint() {
|
|
780
926
|
if (!this._walEnabled) return;
|
|
927
|
+
// 必须先把常驻句柄里的数据 fsync 并关闭,否则 unlink 后该句柄
|
|
928
|
+
// 仍持有旧 inode,后续写入会落到一个「已被删除」的文件里而静默丢失。
|
|
929
|
+
this._walCloseFd();
|
|
781
930
|
this._walOps = [];
|
|
782
931
|
this._walFlushedCount = 0;
|
|
783
932
|
this._walOpCount = 0;
|
|
@@ -888,6 +1037,17 @@ class Database {
|
|
|
888
1037
|
|
|
889
1038
|
this._walReplaying = true;
|
|
890
1039
|
let replayed = 0, failed = 0;
|
|
1040
|
+
// #446:按事务帧聚合回放。先扫描出所有带 commit 帧的事务标签;
|
|
1041
|
+
// 缺少 commit 帧(崩溃时未闭合)的事务,其行变更在恢复时整体丢弃,
|
|
1042
|
+
// 保证 kill -9 后未提交的脏写不会随 WAL 回放复活。
|
|
1043
|
+
const committedTx = new Set();
|
|
1044
|
+
for (const op of ops) {
|
|
1045
|
+
if (op.op === 'commit' && op.tx !== undefined && op.tx !== null) {
|
|
1046
|
+
committedTx.add(String(op.tx));
|
|
1047
|
+
}
|
|
1048
|
+
}
|
|
1049
|
+
const TX_MARKERS = new Set(['begin', 'commit', 'rollback', 'rollbackTo', 'savepoint', 'undo', 'restore', 'import']);
|
|
1050
|
+
const DATA_OPS = new Set(['insert', 'update', 'remove', 'upsertRows', 'removeRows', 'replaceTable']);
|
|
891
1051
|
try {
|
|
892
1052
|
// 逐条按 sequence 顺序回放,保证 insert→update→remove 的相对次序。
|
|
893
1053
|
// insert 不走 _loadRows()(那是整体替换语义),而是直接 push 到 _rows,
|
|
@@ -895,6 +1055,11 @@ class Database {
|
|
|
895
1055
|
const touched = new Set();
|
|
896
1056
|
for (const op of ops) {
|
|
897
1057
|
try {
|
|
1058
|
+
// 事务标记帧本身不改数据状态,回放时跳过。
|
|
1059
|
+
if (TX_MARKERS.has(op.op)) continue;
|
|
1060
|
+
// 未闭合事务的行变更:整批丢弃,不落可见行。
|
|
1061
|
+
if (DATA_OPS.has(op.op) && op.tx !== undefined && op.tx !== null
|
|
1062
|
+
&& !committedTx.has(String(op.tx))) continue;
|
|
898
1063
|
switch (op.op) {
|
|
899
1064
|
case 'insert': {
|
|
900
1065
|
// #259:目录模式下表是懒加载的(_tables 里可能还没有),
|
|
@@ -1389,6 +1554,11 @@ class Database {
|
|
|
1389
1554
|
return { ...(this._corruptTables || {}) };
|
|
1390
1555
|
}
|
|
1391
1556
|
|
|
1557
|
+
/** #453:meta.json 损坏后兜底恢复的排障记录(未损坏时为 null)。 */
|
|
1558
|
+
getMetaCorruption() {
|
|
1559
|
+
return this._metaCorrupt ? { ...this._metaCorrupt } : null;
|
|
1560
|
+
}
|
|
1561
|
+
|
|
1392
1562
|
getTableSchema(name) {
|
|
1393
1563
|
const table = this._ensureTable(name);
|
|
1394
1564
|
if (table) return table._schema;
|
|
@@ -1494,6 +1664,9 @@ class Database {
|
|
|
1494
1664
|
const hasHeader = options.hasHeader !== false;
|
|
1495
1665
|
const skipRows = options.skipRows || 0;
|
|
1496
1666
|
const mapping = options.mapping || null;
|
|
1667
|
+
// #455:strict 模式下不可解析的类型值直接抛错;默认降级为 warnings 并跳过该行,
|
|
1668
|
+
// 不再把非数值整数静默置 0、非真值布尔静默置 false。
|
|
1669
|
+
const strict = options.strict === true;
|
|
1497
1670
|
|
|
1498
1671
|
const content = fs.readFileSync(filePath, 'utf8');
|
|
1499
1672
|
// #184:RFC 4180 允许引号字段内出现换行,不能先按行切分
|
|
@@ -1509,34 +1682,46 @@ class Database {
|
|
|
1509
1682
|
startRow = skipRows;
|
|
1510
1683
|
}
|
|
1511
1684
|
|
|
1685
|
+
const warnings = [];
|
|
1512
1686
|
let count = 0;
|
|
1513
1687
|
for (let i = startRow; i < records.length; i++) {
|
|
1514
1688
|
const values = records[i];
|
|
1515
1689
|
if (values.length === 0) continue;
|
|
1516
1690
|
|
|
1517
1691
|
const data = {};
|
|
1692
|
+
const castCtx = { warnings, row: i };
|
|
1518
1693
|
if (mapping) {
|
|
1519
1694
|
for (const [csvCol, schemaCol] of Object.entries(mapping)) {
|
|
1520
1695
|
const idx = hasHeader ? headers.indexOf(csvCol) : parseInt(csvCol);
|
|
1521
1696
|
if (idx >= 0 && idx < values.length) {
|
|
1522
|
-
data[schemaCol] = this._castValue(values[idx], table._schema[schemaCol]);
|
|
1697
|
+
data[schemaCol] = this._castValue(values[idx], table._schema[schemaCol], { ...castCtx, field: schemaCol });
|
|
1523
1698
|
}
|
|
1524
1699
|
}
|
|
1525
1700
|
} else if (hasHeader) {
|
|
1526
1701
|
for (let j = 0; j < headers.length; j++) {
|
|
1527
1702
|
if (j < values.length && table._schema[headers[j]]) {
|
|
1528
|
-
data[headers[j]] = this._castValue(values[j], table._schema[headers[j]]);
|
|
1703
|
+
data[headers[j]] = this._castValue(values[j], table._schema[headers[j]], { ...castCtx, field: headers[j] });
|
|
1529
1704
|
}
|
|
1530
1705
|
}
|
|
1531
1706
|
}
|
|
1532
1707
|
|
|
1533
1708
|
if (Object.keys(data).length > 0) {
|
|
1534
|
-
|
|
1535
|
-
|
|
1709
|
+
try {
|
|
1710
|
+
table.insert(data);
|
|
1711
|
+
count++;
|
|
1712
|
+
} catch (e) {
|
|
1713
|
+
if (strict) throw e;
|
|
1714
|
+
warnings.push({
|
|
1715
|
+
row: i,
|
|
1716
|
+
code: e.code || e.errno || 'ER_TRUNCATED_WRONG_VALUE',
|
|
1717
|
+
message: e.message,
|
|
1718
|
+
});
|
|
1719
|
+
}
|
|
1536
1720
|
}
|
|
1537
1721
|
}
|
|
1538
1722
|
|
|
1539
|
-
|
|
1723
|
+
// 与 migrate 路径一致:返回 { count, warnings },告警随结果带回上层
|
|
1724
|
+
return { count, warnings };
|
|
1540
1725
|
}
|
|
1541
1726
|
|
|
1542
1727
|
/**
|
|
@@ -1629,12 +1814,39 @@ class Database {
|
|
|
1629
1814
|
return value;
|
|
1630
1815
|
}
|
|
1631
1816
|
|
|
1632
|
-
_castValue(value, schemaDef) {
|
|
1633
|
-
if (!schemaDef
|
|
1634
|
-
|
|
1635
|
-
|
|
1636
|
-
|
|
1637
|
-
|
|
1817
|
+
_castValue(value, schemaDef, ctx) {
|
|
1818
|
+
if (!schemaDef) return value;
|
|
1819
|
+
// 空字段 / NULL:语义与此前一致,不参与类型转换
|
|
1820
|
+
if (value === null || value === undefined || value === '') return value;
|
|
1821
|
+
const type = String(schemaDef.type || '').toLowerCase();
|
|
1822
|
+
const raw = String(value).trim();
|
|
1823
|
+
switch (type) {
|
|
1824
|
+
case 'integer':
|
|
1825
|
+
case 'int':
|
|
1826
|
+
case 'bigint': {
|
|
1827
|
+
// #455:不再 `parseInt(...) || 0` 把解析失败吞成 0;非法整数值记入告警并保留原值,
|
|
1828
|
+
// 由表校验层拒绝(strict 模式下 importCSV 直接抛错)。
|
|
1829
|
+
if (/^[+-]?\d+$/.test(raw)) return parseInt(raw, 10);
|
|
1830
|
+
this._recordCastWarning(ctx, type, value);
|
|
1831
|
+
return value;
|
|
1832
|
+
}
|
|
1833
|
+
case 'number':
|
|
1834
|
+
case 'float':
|
|
1835
|
+
case 'double':
|
|
1836
|
+
case 'real':
|
|
1837
|
+
case 'decimal': {
|
|
1838
|
+
if (raw !== '' && !Number.isNaN(Number(raw))) return Number(raw);
|
|
1839
|
+
this._recordCastWarning(ctx, type, value);
|
|
1840
|
+
return value;
|
|
1841
|
+
}
|
|
1842
|
+
case 'boolean': {
|
|
1843
|
+
// #455:只识别规范真值/假值;其余不可识别的值不再一律归 false,记入告警并保留原值。
|
|
1844
|
+
const low = raw.toLowerCase();
|
|
1845
|
+
if (low === 'true' || low === '1') return true;
|
|
1846
|
+
if (low === 'false' || low === '0') return false;
|
|
1847
|
+
this._recordCastWarning(ctx, type, value);
|
|
1848
|
+
return value;
|
|
1849
|
+
}
|
|
1638
1850
|
case 'array': try { return JSON.parse(value); } catch(e) { return [value]; }
|
|
1639
1851
|
case 'object': try { return JSON.parse(value); } catch(e) { return {}; }
|
|
1640
1852
|
case 'date':
|
|
@@ -1646,6 +1858,17 @@ class Database {
|
|
|
1646
1858
|
}
|
|
1647
1859
|
}
|
|
1648
1860
|
|
|
1861
|
+
_recordCastWarning(ctx, type, value) {
|
|
1862
|
+
if (!ctx || !Array.isArray(ctx.warnings)) return;
|
|
1863
|
+
ctx.warnings.push({
|
|
1864
|
+
row: ctx.row,
|
|
1865
|
+
field: ctx.field,
|
|
1866
|
+
type,
|
|
1867
|
+
value: String(value),
|
|
1868
|
+
message: `Truncated incorrect ${type} value: '${value}'`,
|
|
1869
|
+
});
|
|
1870
|
+
}
|
|
1871
|
+
|
|
1649
1872
|
// ============================================================
|
|
1650
1873
|
// 数据库统计
|
|
1651
1874
|
// ============================================================
|
|
@@ -1827,8 +2050,25 @@ class Database {
|
|
|
1827
2050
|
_restoreTxSnapshot(snap) {
|
|
1828
2051
|
if (!snap) return;
|
|
1829
2052
|
for (const name of Object.keys(this._tables)) {
|
|
1830
|
-
if (
|
|
2053
|
+
if (snap[name]) continue;
|
|
2054
|
+
// #452:事务内 CREATE TABLE 回滚必须彻底撤销。目录模式下只删内存
|
|
2055
|
+
// 表对象会留下 meta 登记与 .jsql 文件,重开后被回滚的表连同未提交
|
|
2056
|
+
// 行一起复活。这里与 _dropTableSync 对齐:清 meta 登记、删表文件、
|
|
2057
|
+
// 摘掉访问器与表名登记。
|
|
2058
|
+
if (this._dirMode) {
|
|
2059
|
+
const meta = this._meta.tables[name];
|
|
2060
|
+
if (meta && meta.file) {
|
|
2061
|
+
try { fs.unlinkSync(path.join(this._filePath, meta.file)); } catch (e) { /* 文件已不存在 */ }
|
|
2062
|
+
}
|
|
2063
|
+
delete this._meta.tables[name];
|
|
2064
|
+
this._dirtyTables.delete(name);
|
|
2065
|
+
}
|
|
2066
|
+
delete this[name];
|
|
2067
|
+
delete this._versions[name];
|
|
2068
|
+
this._tableNames.delete(name);
|
|
2069
|
+
delete this._tables[name];
|
|
1831
2070
|
}
|
|
2071
|
+
if (this._dirMode) this._saveMeta();
|
|
1832
2072
|
for (const [name, entry] of Object.entries(snap)) {
|
|
1833
2073
|
const rows = bigintJson.parse(bigintJson.stringify(entry.rows));
|
|
1834
2074
|
const prev = this._tables[name];
|
|
@@ -1866,6 +2106,16 @@ class Database {
|
|
|
1866
2106
|
return (this._txId !== undefined && !!this._txSnapshot) || !!this._transaction;
|
|
1867
2107
|
}
|
|
1868
2108
|
|
|
2109
|
+
/**
|
|
2110
|
+
* 当前活动事务的 WAL 标签(beginTx 路径用 `tx<n>`,begin 路径用 `b<n>`)。
|
|
2111
|
+
* 无活动事务时返回 null —— 旧 WAL / 自动提交的写入不带事务标记,回放时视为已提交。
|
|
2112
|
+
*/
|
|
2113
|
+
_currentTxTag() {
|
|
2114
|
+
if (this._txId !== undefined && this._txSnapshot) return 'tx' + this._txId;
|
|
2115
|
+
if (this._transaction && this._transaction.txTag) return this._transaction.txTag;
|
|
2116
|
+
return null;
|
|
2117
|
+
}
|
|
2118
|
+
|
|
1869
2119
|
/** 保存点栈(懒建),随事务结束清空 */
|
|
1870
2120
|
_savepointStackRef() {
|
|
1871
2121
|
if (!this._savepointStack) this._savepointStack = [];
|
|
@@ -1881,11 +2131,13 @@ class Database {
|
|
|
1881
2131
|
|
|
1882
2132
|
const level = isolationLevel || this._isolationLevel;
|
|
1883
2133
|
|
|
2134
|
+
this._txFrameSeq = (this._txFrameSeq || 0) + 1;
|
|
1884
2135
|
this._transaction = {
|
|
1885
2136
|
snapshot: null,
|
|
1886
2137
|
autoIncrements: {},
|
|
1887
2138
|
level,
|
|
1888
|
-
startedAt: Date.now()
|
|
2139
|
+
startedAt: Date.now(),
|
|
2140
|
+
txTag: 'b' + this._txFrameSeq
|
|
1889
2141
|
};
|
|
1890
2142
|
|
|
1891
2143
|
if (level === 'REPEATABLE_READ') {
|
|
@@ -1901,12 +2153,12 @@ class Database {
|
|
|
1901
2153
|
}
|
|
1902
2154
|
|
|
1903
2155
|
this._savepointStack = [];
|
|
1904
|
-
this._walWrite({ op: 'begin', level });
|
|
2156
|
+
this._walWrite({ op: 'begin', tx: this._transaction.txTag, level });
|
|
1905
2157
|
}
|
|
1906
2158
|
|
|
1907
2159
|
commit() {
|
|
1908
2160
|
if (!this._transaction) throw createError('ER_NO_TRANSACTION');
|
|
1909
|
-
this._walWrite({ op: 'commit', at: this._transaction.startedAt });
|
|
2161
|
+
this._walWrite({ op: 'commit', tx: this._transaction.txTag, at: this._transaction.startedAt });
|
|
1910
2162
|
// 提交即释放全部保存点 —— 它们随事务一起结束
|
|
1911
2163
|
this._transaction = null;
|
|
1912
2164
|
this._savepointStack = [];
|
|
@@ -1933,7 +2185,7 @@ class Database {
|
|
|
1933
2185
|
}
|
|
1934
2186
|
}
|
|
1935
2187
|
|
|
1936
|
-
this._walWrite({ op: 'rollback', at: this._transaction.startedAt });
|
|
2188
|
+
this._walWrite({ op: 'rollback', tx: this._transaction.txTag, at: this._transaction.startedAt });
|
|
1937
2189
|
this._transaction = null;
|
|
1938
2190
|
this._savepointStack = [];
|
|
1939
2191
|
this._markDirtyLegacy();
|
|
@@ -2025,7 +2277,7 @@ class Database {
|
|
|
2025
2277
|
}
|
|
2026
2278
|
|
|
2027
2279
|
inTransaction() {
|
|
2028
|
-
return
|
|
2280
|
+
return this.hasActiveTx();
|
|
2029
2281
|
}
|
|
2030
2282
|
|
|
2031
2283
|
/**
|
|
@@ -2816,6 +3068,9 @@ class Database {
|
|
|
2816
3068
|
this._sigInstalled = false;
|
|
2817
3069
|
Database._uninstallSignalHandler(this);
|
|
2818
3070
|
}
|
|
3071
|
+
// 兜底:合并窗口内可能还有未 fsync 的 WAL 记录(例如 save() 抛错被吞掉),
|
|
3072
|
+
// 关闭实例前必须补齐,否则掉电会丢失这段已返回成功的写入。
|
|
3073
|
+
this._walCloseFd();
|
|
2819
3074
|
// #295:stop() 表示本实例停止写入,必须释放文件锁,否则同路径再打开会误报占用
|
|
2820
3075
|
this._releaseLock();
|
|
2821
3076
|
return this;
|
|
@@ -2931,7 +3186,7 @@ class Database {
|
|
|
2931
3186
|
for (const [name, table] of Object.entries(this._tables)) {
|
|
2932
3187
|
if (name === '__meta__') continue;
|
|
2933
3188
|
const pkField = Object.keys(table._schema).find(f => table._schema[f].primaryKey);
|
|
2934
|
-
all[name] = { schema: table.
|
|
3189
|
+
all[name] = { schema: table._persistedSchema(), rows: table._rows, pkField };
|
|
2935
3190
|
}
|
|
2936
3191
|
this._jsqlFormat.saveAll(all);
|
|
2937
3192
|
this._jsqlFormat._close();
|
|
@@ -2943,7 +3198,7 @@ class Database {
|
|
|
2943
3198
|
const data = { __schema__: {}, __meta__: { version: this._getCurrentVersion() } };
|
|
2944
3199
|
for (const [name, table] of Object.entries(this._tables)) {
|
|
2945
3200
|
if (name === '__meta__') continue;
|
|
2946
|
-
data.__schema__[name] = table.
|
|
3201
|
+
data.__schema__[name] = table._persistedSchema();
|
|
2947
3202
|
data[name] = table.toJSON();
|
|
2948
3203
|
}
|
|
2949
3204
|
|
|
@@ -3051,6 +3306,7 @@ class Database {
|
|
|
3051
3306
|
this.save();
|
|
3052
3307
|
}
|
|
3053
3308
|
if (this._jsqlFormat) this._jsqlFormat._close();
|
|
3309
|
+
this._walCloseFd();
|
|
3054
3310
|
this._releaseLock();
|
|
3055
3311
|
// Bug 3: 清理静态信号处理器,防止关闭后还在响应信号
|
|
3056
3312
|
if (this._sigInstalled) {
|
|
@@ -3089,10 +3345,12 @@ class Database {
|
|
|
3089
3345
|
// 否则 rollbackTx 还原不了保存点存下来的快照(反之亦然)。
|
|
3090
3346
|
this._txSnapshot = this._captureTxSnapshot();
|
|
3091
3347
|
this._txId = (this._txId || 0) + 1;
|
|
3348
|
+
this._walWrite({ op: 'begin', tx: 'tx' + this._txId });
|
|
3092
3349
|
return this._txId;
|
|
3093
3350
|
}
|
|
3094
3351
|
|
|
3095
3352
|
async commitTx() {
|
|
3353
|
+
this._walWrite({ op: 'commit', tx: 'tx' + this._txId });
|
|
3096
3354
|
this._txSnapshot = null;
|
|
3097
3355
|
this._txId = undefined;
|
|
3098
3356
|
this._savepointStack = []; // 提交即释放全部保存点
|
|
@@ -3105,6 +3363,7 @@ class Database {
|
|
|
3105
3363
|
|
|
3106
3364
|
async rollbackTx() {
|
|
3107
3365
|
const snap = this._txSnapshot;
|
|
3366
|
+
this._walWrite({ op: 'rollback', tx: 'tx' + this._txId });
|
|
3108
3367
|
this._txSnapshot = null;
|
|
3109
3368
|
this._txId = undefined;
|
|
3110
3369
|
this._savepointStack = [];
|
package/lib/errors.js
CHANGED
|
@@ -58,6 +58,8 @@ const ErrorCodes = {
|
|
|
58
58
|
ER_SP_DOES_NOT_EXIST: { code: 1305, msg: "SAVEPOINT %s does not exist" },
|
|
59
59
|
ER_FUNCTION_NOT_EXIST: { code: 1305, msg: "FUNCTION %s does not exist" },
|
|
60
60
|
ER_SUBSELECT_NO_1_ROW: { code: 1242, msg: "Subquery returns more than 1 row" },
|
|
61
|
+
// 标量子查询(单值上下文)返回多列(MySQL 1241)
|
|
62
|
+
ER_OPERAND_COLUMNS: { code: 1241, msg: "Operand should contain 1 column(s)" },
|
|
61
63
|
ER_WRONG_VALUE_COUNT_ON_ROW: { code: 1136, msg: "Column count doesn't match value count at row %s" },
|
|
62
64
|
ER_TRUNCATE_ILLEGAL_FK: { code: 1701, msg: "Cannot truncate a table referenced in a foreign key constraint (%s)" },
|
|
63
65
|
ER_ROW_IS_REFERENCED_2: { code: 1451, msg: "Cannot delete or update a parent row: a foreign key constraint fails (%s)" },
|