jsql-neo 6.8.14 → 6.8.15
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 +1 -1
- package/index.js +1 -1
- package/lib/database.js +207 -36
- package/lib/jsql_format.js +84 -24
- package/lib/sqlite_worker.js +9 -2
- package/package.json +3 -3
- package/test/issue-259-264.test.js +163 -0
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.
|
|
6
|
+
> **v6.8.15** — 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
|

|
|
9
9
|

|
package/index.js
CHANGED
package/lib/database.js
CHANGED
|
@@ -190,6 +190,15 @@ class Database {
|
|
|
190
190
|
this._walPath = this._filePath ? this._filePath + '.wal' : null;
|
|
191
191
|
this._walOps = []; // WAL 操作日志(内存镜像)
|
|
192
192
|
this._walFlushedCount = 0; // 已落盘记录数(append-only 增量追加用)
|
|
193
|
+
this._walError = null; // #263:最近一次 WAL 落盘失败(供上层查询)
|
|
194
|
+
// #260:目录模式的静态加密(与 legacy 单文件模式语义一致)。
|
|
195
|
+
// _aesKey 是由用户密钥派生的 32 字节 AES-256 密钥。
|
|
196
|
+
this._aesKey = this._encryptKey
|
|
197
|
+
? crypto.scryptSync(
|
|
198
|
+
Buffer.from(String(this._encryptKey), 'utf8'),
|
|
199
|
+
Buffer.from('jsql-neo-static-encryption-v1', 'utf8'),
|
|
200
|
+
32)
|
|
201
|
+
: null;
|
|
193
202
|
this._walReplaying = false; // 回放中:抑制再次写日志
|
|
194
203
|
this._walReplaySummary = null;
|
|
195
204
|
this._walOpCount = 0; // 自上次检查点以来的操作数
|
|
@@ -201,7 +210,7 @@ class Database {
|
|
|
201
210
|
|
|
202
211
|
// JSql 格式 (binary block-based)
|
|
203
212
|
this._jsqlMode = this._filePath && this._filePath.endsWith('.jsql');
|
|
204
|
-
this._jsqlFormat = this._jsqlMode ? new JSQLFormat(this._filePath) : null;
|
|
213
|
+
this._jsqlFormat = this._jsqlMode ? new JSQLFormat(this._filePath, this._encryptKey) : null;
|
|
205
214
|
|
|
206
215
|
// 文件锁
|
|
207
216
|
this._fileLockEnabled = options.fileLock === true && !this._memoryMode;
|
|
@@ -247,7 +256,26 @@ class Database {
|
|
|
247
256
|
this._meta = { version: 1, tables: {} };
|
|
248
257
|
try {
|
|
249
258
|
if (fs.existsSync(this._metaPath)) {
|
|
250
|
-
|
|
259
|
+
// #260:meta.json 在启用 encryptKey 时也是密文。
|
|
260
|
+
// 格式:{"__enc":"v1","data":"<base64>"};无密钥时按明文 JSON 读(兼容旧库)。
|
|
261
|
+
const rawMeta = fs.readFileSync(this._metaPath, 'utf8');
|
|
262
|
+
let parsed;
|
|
263
|
+
try {
|
|
264
|
+
parsed = JSON.parse(rawMeta);
|
|
265
|
+
} catch (e) {
|
|
266
|
+
parsed = null;
|
|
267
|
+
}
|
|
268
|
+
if (parsed && parsed.__enc === 'v1' && typeof parsed.data === 'string') {
|
|
269
|
+
if (!this._encryptKey) {
|
|
270
|
+
throw new Error('meta.json is encrypted but no encryptKey was provided');
|
|
271
|
+
}
|
|
272
|
+
const dec = crypto.createDecipheriv('aes-256-cbc', this._aesKey, Buffer.from(parsed.iv, 'base64'));
|
|
273
|
+
const plain = Buffer.concat([
|
|
274
|
+
dec.update(Buffer.from(parsed.data, 'base64')),
|
|
275
|
+
dec.final(),
|
|
276
|
+
]).toString('utf8');
|
|
277
|
+
parsed = JSON.parse(plain);
|
|
278
|
+
}
|
|
251
279
|
if (parsed && parsed.tables) {
|
|
252
280
|
this._meta = parsed;
|
|
253
281
|
// 清洗 meta 中的 file 字段:拒绝绝对路径/.. 穿越,防恶意 meta.json 写任意位置
|
|
@@ -273,6 +301,19 @@ class Database {
|
|
|
273
301
|
});
|
|
274
302
|
}
|
|
275
303
|
}
|
|
304
|
+
// #259:目录模式(hybrid/disk)显式开启 wal:true 后,写入路径会往
|
|
305
|
+
// `<dir>.wal` 追加并 fsync,但此前**从不回放** —— 只写不读,
|
|
306
|
+
// 崩溃时尚未刷入 .jsql 的提交全部丢失。
|
|
307
|
+
// 这里在启动时回放 WAL,把已 fsync 的提交恢复出来。
|
|
308
|
+
if (this._walEnabled && this._walPath && fs.existsSync(this._walPath)) {
|
|
309
|
+
try {
|
|
310
|
+
this._recoverFromWAL();
|
|
311
|
+
} catch (e) {
|
|
312
|
+
// 回放失败不能静默:记录下来供 getWALInfo() 排障
|
|
313
|
+
this._walReplaySummary = { replayed: 0, failed: 1, error: e.message, at: Date.now() };
|
|
314
|
+
try { this._emit('error', e); } catch (_) { /* ignore */ }
|
|
315
|
+
}
|
|
316
|
+
}
|
|
276
317
|
this._startMonitor();
|
|
277
318
|
}
|
|
278
319
|
|
|
@@ -298,12 +339,49 @@ class Database {
|
|
|
298
339
|
_saveMeta() {
|
|
299
340
|
if (!this._dirMode) return;
|
|
300
341
|
try {
|
|
301
|
-
|
|
342
|
+
// #260:启用 encryptKey 时 meta.json 也落密文(表结构/字段名不外泄)
|
|
343
|
+
if (this._encryptKey) {
|
|
344
|
+
const iv = crypto.randomBytes(16);
|
|
345
|
+
const cipher = crypto.createCipheriv('aes-256-cbc', this._aesKey, iv);
|
|
346
|
+
const enc = Buffer.concat([
|
|
347
|
+
cipher.update(JSON.stringify(this._meta, null, 2), 'utf8'),
|
|
348
|
+
cipher.final(),
|
|
349
|
+
]);
|
|
350
|
+
const payload = JSON.stringify({
|
|
351
|
+
__enc: 'v1',
|
|
352
|
+
iv: iv.toString('base64'),
|
|
353
|
+
data: enc.toString('base64'),
|
|
354
|
+
});
|
|
355
|
+
fs.writeFileSync(this._metaPath, payload, 'utf8');
|
|
356
|
+
} else {
|
|
357
|
+
fs.writeFileSync(this._metaPath, JSON.stringify(this._meta, null, 2), 'utf8');
|
|
358
|
+
}
|
|
302
359
|
} catch (e) {
|
|
303
360
|
// 忽略 meta 写入失败
|
|
304
361
|
}
|
|
305
362
|
}
|
|
306
363
|
|
|
364
|
+
/**
|
|
365
|
+
* 统一的「表不可用」错误。
|
|
366
|
+
*
|
|
367
|
+
* #262:区分「表不存在」与「表文件损坏」。损坏的表文件加载失败后,
|
|
368
|
+
* 若一律报 ER_NO_SUCH_TABLE,运维看到的是「表没了」,而 meta.json 里
|
|
369
|
+
* 明明还登记着它 —— 极易被误判为「数据被删」。现在报 ER_TABLE_CORRUPT
|
|
370
|
+
* 并带上原始原因。
|
|
371
|
+
*/
|
|
372
|
+
_noSuchTable(name) {
|
|
373
|
+
const corrupt = this._corruptTables && this._corruptTables[name];
|
|
374
|
+
if (corrupt) {
|
|
375
|
+
const err = new Error(corrupt.message);
|
|
376
|
+
err.code = 'ER_TABLE_CORRUPT';
|
|
377
|
+
err.errno = corrupt.errno || 1815;
|
|
378
|
+
err.sqlState = 'HY000';
|
|
379
|
+
err.cause = corrupt.cause;
|
|
380
|
+
return err;
|
|
381
|
+
}
|
|
382
|
+
return createError('ER_NO_SUCH_TABLE', name);
|
|
383
|
+
}
|
|
384
|
+
|
|
307
385
|
_touchTable(name) {
|
|
308
386
|
this._lastAccess[name] = Date.now();
|
|
309
387
|
}
|
|
@@ -316,7 +394,7 @@ class Database {
|
|
|
316
394
|
const file = this._tableFile(name);
|
|
317
395
|
if (!fs.existsSync(file)) return null;
|
|
318
396
|
try {
|
|
319
|
-
const fmt = new JSQLFormat(file);
|
|
397
|
+
const fmt = new JSQLFormat(file, this._encryptKey);
|
|
320
398
|
fmt._open();
|
|
321
399
|
const table = new Table(name, meta.schema, this);
|
|
322
400
|
// 行级懒加载:只在内存里保留 {block, off},被访问的行才读盘。
|
|
@@ -333,6 +411,21 @@ class Database {
|
|
|
333
411
|
this._touchTable(name);
|
|
334
412
|
return table;
|
|
335
413
|
} catch (e) {
|
|
414
|
+
// #262:加载失败不能静默吞掉。
|
|
415
|
+
// 此前 catch 里直接 return null —— 表文件损坏时表「从查询中消失」,
|
|
416
|
+
// 而 meta.json 仍登记着它,getTables()/hasTable() 报存在、
|
|
417
|
+
// count()/find() 全报缺表,形成自相矛盾的「幽灵表」且无任何告警。
|
|
418
|
+
// 现在:记录损坏状态、发出 error 事件,并让后续查询明确报出损坏原因。
|
|
419
|
+
const err = new Error(
|
|
420
|
+
`Table '${name}' failed to load from '${file}': ${e.message}`
|
|
421
|
+
);
|
|
422
|
+
err.code = 'ER_TABLE_CORRUPT';
|
|
423
|
+
err.errno = 1815;
|
|
424
|
+
err.sqlState = 'HY000';
|
|
425
|
+
err.cause = e;
|
|
426
|
+
this._corruptTables = this._corruptTables || {};
|
|
427
|
+
this._corruptTables[name] = err;
|
|
428
|
+
try { this._emit('error', err); } catch (_) { /* 监听器自身抛错不影响主流程 */ }
|
|
336
429
|
return null;
|
|
337
430
|
}
|
|
338
431
|
}
|
|
@@ -410,7 +503,7 @@ class Database {
|
|
|
410
503
|
|
|
411
504
|
const meta = this._meta.tables[name];
|
|
412
505
|
const file = meta && meta.file ? meta.file : encodeURIComponent(name) + '.jsql';
|
|
413
|
-
const fmt = new JSQLFormat(path.join(this._filePath, file));
|
|
506
|
+
const fmt = new JSQLFormat(path.join(this._filePath, file), this._encryptKey);
|
|
414
507
|
let appendBlocks = 0;
|
|
415
508
|
try {
|
|
416
509
|
const written = fmt.writeRows(name, table._schema, dirty.upserts, dirty.deletes, table._primaryKey);
|
|
@@ -440,7 +533,7 @@ class Database {
|
|
|
440
533
|
if (!table) return;
|
|
441
534
|
const meta = this._meta.tables[name];
|
|
442
535
|
let file = meta && meta.file ? meta.file : encodeURIComponent(name) + '.jsql';
|
|
443
|
-
const fmt = new JSQLFormat(path.join(this._filePath, file));
|
|
536
|
+
const fmt = new JSQLFormat(path.join(this._filePath, file), this._encryptKey);
|
|
444
537
|
let keepHandleOpen = false;
|
|
445
538
|
try {
|
|
446
539
|
const pkField = Object.keys(table._schema).find(f => table._schema[f].primaryKey) || null;
|
|
@@ -664,8 +757,16 @@ class Database {
|
|
|
664
757
|
fs.closeSync(fd);
|
|
665
758
|
}
|
|
666
759
|
this._walFlushedCount = this._walOps.length;
|
|
760
|
+
this._walError = null;
|
|
667
761
|
} catch (e) {
|
|
668
|
-
// WAL
|
|
762
|
+
// #263:WAL 追加失败不能静默吞掉。
|
|
763
|
+
// WAL 是崩溃安全的前提(README 承诺「kill -9 不会丢已提交的写入」):
|
|
764
|
+
// 磁盘满 / 权限不足 / inode 耗尽时若继续返回成功,
|
|
765
|
+
// 进程崩溃后这批提交就彻底丢失,且事后没有任何线索。
|
|
766
|
+
// 现在至少通过 error 事件暴露出来(与 _flushDirty 的处理一致),
|
|
767
|
+
// 并记入 _walError 供上层查询。
|
|
768
|
+
this._walError = e;
|
|
769
|
+
try { this._emit('error', e); } catch (_) { /* 事件监听器自身抛错不影响主流程 */ }
|
|
669
770
|
}
|
|
670
771
|
}
|
|
671
772
|
|
|
@@ -720,6 +821,25 @@ class Database {
|
|
|
720
821
|
return defs;
|
|
721
822
|
}
|
|
722
823
|
|
|
824
|
+
/**
|
|
825
|
+
* WAL 回放时定位目标表(#259)。
|
|
826
|
+
*
|
|
827
|
+
* 目录模式(hybrid/disk)的表是**懒加载**的:meta.json 里登记了表名,
|
|
828
|
+
* 但 `this._tables` 里要等第一次访问才通过 _ensureTable 加载。
|
|
829
|
+
* 回放直接取 `this._tables[op.table]` 会拿到 undefined,
|
|
830
|
+
* 于是 WAL 里的行被写进一个凭空新建的空表(原表数据被覆盖)。
|
|
831
|
+
* 这里统一走 _ensureTable,把已存在的表真正加载出来。
|
|
832
|
+
*/
|
|
833
|
+
_walTargetTable(name) {
|
|
834
|
+
if (!name) return null;
|
|
835
|
+
if (this._tables[name]) return this._tables[name];
|
|
836
|
+
if (this._dirMode && this._meta && this._meta.tables && this._meta.tables[name]) {
|
|
837
|
+
const loaded = this._ensureTable(name);
|
|
838
|
+
if (loaded) return loaded;
|
|
839
|
+
}
|
|
840
|
+
return null;
|
|
841
|
+
}
|
|
842
|
+
|
|
723
843
|
_recoverFromWAL() {
|
|
724
844
|
if (!this._walEnabled || !this._walPath || !fs.existsSync(this._walPath)) return;
|
|
725
845
|
|
|
@@ -777,7 +897,10 @@ class Database {
|
|
|
777
897
|
try {
|
|
778
898
|
switch (op.op) {
|
|
779
899
|
case 'insert': {
|
|
780
|
-
|
|
900
|
+
// #259:目录模式下表是懒加载的(_tables 里可能还没有),
|
|
901
|
+
// 回放前必须先把它加载出来,否则 WAL 里的行会落到一个
|
|
902
|
+
// 凭空新建的空表上。
|
|
903
|
+
let t = op.table && this._walTargetTable(op.table);
|
|
781
904
|
if (!t && op.table && Array.isArray(op.rows) && op.rows.length > 0) {
|
|
782
905
|
this._createTableSync(op.table, this._inferWalSchema(op.rows));
|
|
783
906
|
t = this._tables[op.table];
|
|
@@ -797,7 +920,8 @@ class Database {
|
|
|
797
920
|
break;
|
|
798
921
|
}
|
|
799
922
|
case 'upsertRows': {
|
|
800
|
-
|
|
923
|
+
// #259:同上 —— 目录模式先加载已存在的表
|
|
924
|
+
let t = op.table && this._walTargetTable(op.table);
|
|
801
925
|
if (!t && op.table && Array.isArray(op.rows) && op.rows.length > 0) {
|
|
802
926
|
this._createTableSync(op.table, this._inferWalSchema(op.rows));
|
|
803
927
|
t = this._tables[op.table];
|
|
@@ -814,7 +938,7 @@ class Database {
|
|
|
814
938
|
break;
|
|
815
939
|
}
|
|
816
940
|
case 'removeRows': {
|
|
817
|
-
const t = op.table && this.
|
|
941
|
+
const t = op.table && this._walTargetTable(op.table);
|
|
818
942
|
if (!t || !op.pk || !Array.isArray(op.ids)) { failed++; break; }
|
|
819
943
|
const gone = new Set(op.ids.map(String));
|
|
820
944
|
t._rows = t._rows.filter(r => !r || !gone.has(String(r[op.pk])));
|
|
@@ -823,7 +947,7 @@ class Database {
|
|
|
823
947
|
break;
|
|
824
948
|
}
|
|
825
949
|
case 'replaceTable': {
|
|
826
|
-
let t = op.table && this.
|
|
950
|
+
let t = op.table && this._walTargetTable(op.table);
|
|
827
951
|
if (!t && op.table && Array.isArray(op.rows) && op.rows.length > 0) {
|
|
828
952
|
this._createTableSync(op.table, this._inferWalSchema(op.rows));
|
|
829
953
|
t = this._tables[op.table];
|
|
@@ -835,7 +959,7 @@ class Database {
|
|
|
835
959
|
break;
|
|
836
960
|
}
|
|
837
961
|
case 'update': {
|
|
838
|
-
const t = this.
|
|
962
|
+
const t = this._walTargetTable(op.table);
|
|
839
963
|
if (!t || !op.pk || op.row === undefined) { failed++; break; }
|
|
840
964
|
const cur = t._rows.find(r => r[op.pk] === op.id);
|
|
841
965
|
if (!cur) { failed++; break; }
|
|
@@ -845,7 +969,7 @@ class Database {
|
|
|
845
969
|
break;
|
|
846
970
|
}
|
|
847
971
|
case 'remove': {
|
|
848
|
-
const t = this.
|
|
972
|
+
const t = this._walTargetTable(op.table);
|
|
849
973
|
if (!t || !op.pk) { failed++; break; }
|
|
850
974
|
const before = t._rows.length;
|
|
851
975
|
t._rows = t._rows.filter(r => r[op.pk] !== op.id);
|
|
@@ -915,8 +1039,22 @@ class Database {
|
|
|
915
1039
|
_replayWalOp(op) {
|
|
916
1040
|
switch (op.op) {
|
|
917
1041
|
case 'createTable':
|
|
1042
|
+
// #259:目录模式下的两种情形:
|
|
1043
|
+
// a) 表文件已落盘 → 懒加载表对象即可(_walTargetTable)
|
|
1044
|
+
// b) meta.json 已登记但 .jsql 未落盘(崩溃发生在首次刷盘前)
|
|
1045
|
+
// → 需要按 WAL 里的 schema 重建表,否则行数据无处安放。
|
|
1046
|
+
// _createTableSync 会因「meta 里已登记」抛 ER_TABLE_EXISTS_ERROR,
|
|
1047
|
+
// 这里先清掉那条陈旧的 meta 登记再重建。
|
|
918
1048
|
if (op.table && !this._tables[op.table]) {
|
|
919
|
-
this.
|
|
1049
|
+
const existing = this._walTargetTable(op.table);
|
|
1050
|
+
if (!existing) {
|
|
1051
|
+
if (this._dirMode && this._meta && this._meta.tables
|
|
1052
|
+
&& this._meta.tables[op.table]
|
|
1053
|
+
&& !fs.existsSync(this._tableFile(op.table))) {
|
|
1054
|
+
delete this._meta.tables[op.table];
|
|
1055
|
+
}
|
|
1056
|
+
this._createTableSync(op.table, op.schema || {});
|
|
1057
|
+
}
|
|
920
1058
|
}
|
|
921
1059
|
return true;
|
|
922
1060
|
|
|
@@ -1180,17 +1318,39 @@ class Database {
|
|
|
1180
1318
|
}
|
|
1181
1319
|
|
|
1182
1320
|
hasTable(name) {
|
|
1183
|
-
|
|
1321
|
+
// #262:损坏的表不再报告为「存在」—— 否则 meta 说在、查询说缺表,
|
|
1322
|
+
// 两种状态互相矛盾且没有任何告警。
|
|
1323
|
+
if (this._corruptTables && this._corruptTables[name]) return false;
|
|
1324
|
+
if (this._tables[name]) return true;
|
|
1325
|
+
if (!this._dirMode || !this._meta.tables[name]) return false;
|
|
1326
|
+
// 主动探测:首次访问前损坏状态还没记录,这里触发一次加载判定
|
|
1327
|
+
this._ensureTable(name);
|
|
1328
|
+
return !(this._corruptTables && this._corruptTables[name]);
|
|
1184
1329
|
}
|
|
1185
1330
|
|
|
1186
1331
|
getTables() {
|
|
1187
1332
|
const names = new Set(Object.keys(this._tables));
|
|
1188
1333
|
if (this._dirMode) {
|
|
1189
|
-
for (const name of Object.keys(this._meta.tables))
|
|
1334
|
+
for (const name of Object.keys(this._meta.tables)) {
|
|
1335
|
+
// #262:跳过已确认损坏的表,避免列出「查不到」的幽灵表
|
|
1336
|
+
if (this._corruptTables && this._corruptTables[name]) continue;
|
|
1337
|
+
// 主动探测损坏状态,保证 getTables 与实际可查询状态一致
|
|
1338
|
+
this._ensureTable(name);
|
|
1339
|
+
if (this._corruptTables && this._corruptTables[name]) continue;
|
|
1340
|
+
names.add(name);
|
|
1341
|
+
}
|
|
1190
1342
|
}
|
|
1191
1343
|
return [...names];
|
|
1192
1344
|
}
|
|
1193
1345
|
|
|
1346
|
+
/**
|
|
1347
|
+
* 列出损坏的表及其原因(#262)。
|
|
1348
|
+
* @returns {Object<string, Error>} tableName -> 加载错误
|
|
1349
|
+
*/
|
|
1350
|
+
getCorruptTables() {
|
|
1351
|
+
return { ...(this._corruptTables || {}) };
|
|
1352
|
+
}
|
|
1353
|
+
|
|
1194
1354
|
getTableSchema(name) {
|
|
1195
1355
|
const table = this._ensureTable(name);
|
|
1196
1356
|
if (table) return table._schema;
|
|
@@ -1290,7 +1450,7 @@ class Database {
|
|
|
1290
1450
|
*/
|
|
1291
1451
|
importCSV(filePath, tableName, options = {}) {
|
|
1292
1452
|
const table = this._ensureTable(tableName);
|
|
1293
|
-
if (!table) throw
|
|
1453
|
+
if (!table) throw this._noSuchTable(tableName);
|
|
1294
1454
|
|
|
1295
1455
|
const delimiter = options.delimiter || ',';
|
|
1296
1456
|
const hasHeader = options.hasHeader !== false;
|
|
@@ -1346,7 +1506,7 @@ class Database {
|
|
|
1346
1506
|
*/
|
|
1347
1507
|
exportCSV(filePath, tableName, query = {}, options = {}) {
|
|
1348
1508
|
const table = this._ensureTable(tableName);
|
|
1349
|
-
if (!table) throw
|
|
1509
|
+
if (!table) throw this._noSuchTable(tableName);
|
|
1350
1510
|
|
|
1351
1511
|
const delimiter = options.delimiter || ',';
|
|
1352
1512
|
const rows = table._applyFilter(table._rows, query);
|
|
@@ -1885,7 +2045,7 @@ class Database {
|
|
|
1885
2045
|
const versions = this._versions[tableName];
|
|
1886
2046
|
if (!versions || versions.length < 2) throw createError('ER_NOT_SUPPORTED', 'No versions to undo');
|
|
1887
2047
|
const table = this._ensureTable(tableName);
|
|
1888
|
-
if (!table) throw
|
|
2048
|
+
if (!table) throw this._noSuchTable(tableName);
|
|
1889
2049
|
|
|
1890
2050
|
for (let i = 0; i < steps && versions.length > 1; i++) {
|
|
1891
2051
|
versions.pop();
|
|
@@ -2091,6 +2251,17 @@ class Database {
|
|
|
2091
2251
|
for (const fn of this._eventListeners) {
|
|
2092
2252
|
try { fn(eventName, data); } catch (e) { /* ignore */ }
|
|
2093
2253
|
}
|
|
2254
|
+
// #263:'error' 事件同时投递给 on('error', fn) 注册的钩子。
|
|
2255
|
+
// on() 走 registerHook(进 _hooks),onEvent() 走 _eventListeners ——
|
|
2256
|
+
// 此前只有后者能收到错误,db.on('error', ...) 永远静默。
|
|
2257
|
+
if (eventName === 'error') {
|
|
2258
|
+
const hooks = this._hooks && this._hooks.error;
|
|
2259
|
+
if (hooks && hooks.length) {
|
|
2260
|
+
for (const entry of hooks) {
|
|
2261
|
+
try { entry.fn(data); } catch (e) { /* ignore */ }
|
|
2262
|
+
}
|
|
2263
|
+
}
|
|
2264
|
+
}
|
|
2094
2265
|
}
|
|
2095
2266
|
|
|
2096
2267
|
_runHooks(hookName, args) {
|
|
@@ -2157,7 +2328,7 @@ class Database {
|
|
|
2157
2328
|
|
|
2158
2329
|
async insert(tableName, data) {
|
|
2159
2330
|
const table = this._ensureTable(tableName);
|
|
2160
|
-
if (!table) throw
|
|
2331
|
+
if (!table) throw this._noSuchTable(tableName);
|
|
2161
2332
|
// #303:beforeInsert 可返回「修改后 data」(PLUGINS.md 契约)。
|
|
2162
2333
|
// 钩子返回值通过 args 数组原地写回,这里必须读回被替换后的 arr。
|
|
2163
2334
|
const hookArgs = [tableName, Array.isArray(data) ? data : [data]];
|
|
@@ -2217,7 +2388,7 @@ class Database {
|
|
|
2217
2388
|
|
|
2218
2389
|
async find(tableName, filter, opts = {}) {
|
|
2219
2390
|
const table = this._ensureTable(tableName);
|
|
2220
|
-
if (!table) throw
|
|
2391
|
+
if (!table) throw this._noSuchTable(tableName);
|
|
2221
2392
|
if (!(await this._runHooks('beforeFind', [tableName, { filter, opts }]))) return [];
|
|
2222
2393
|
const { limit, offset = 0 } = opts;
|
|
2223
2394
|
// P1-4: 软删除模式下不得泄露已删除行——只看可见行
|
|
@@ -2241,20 +2412,20 @@ class Database {
|
|
|
2241
2412
|
*/
|
|
2242
2413
|
convertToColumnar(tableName) {
|
|
2243
2414
|
const table = this._ensureTable(tableName);
|
|
2244
|
-
if (!table) throw
|
|
2415
|
+
if (!table) throw this._noSuchTable(tableName);
|
|
2245
2416
|
return table.toColumnar();
|
|
2246
2417
|
}
|
|
2247
2418
|
|
|
2248
2419
|
/** 把表转回行存(丢弃列存缓存)。 */
|
|
2249
2420
|
convertToRow(tableName) {
|
|
2250
2421
|
const table = this._ensureTable(tableName);
|
|
2251
|
-
if (!table) throw
|
|
2422
|
+
if (!table) throw this._noSuchTable(tableName);
|
|
2252
2423
|
return table.toRow();
|
|
2253
2424
|
}
|
|
2254
2425
|
|
|
2255
2426
|
exists(tableName, filter = {}) {
|
|
2256
2427
|
const table = this._ensureTable(tableName);
|
|
2257
|
-
if (!table) throw
|
|
2428
|
+
if (!table) throw this._noSuchTable(tableName);
|
|
2258
2429
|
this._touchTable(tableName);
|
|
2259
2430
|
return table.exists(filter);
|
|
2260
2431
|
}
|
|
@@ -2273,7 +2444,7 @@ class Database {
|
|
|
2273
2444
|
|
|
2274
2445
|
async findById(tableName, id) {
|
|
2275
2446
|
const table = this._ensureTable(tableName);
|
|
2276
|
-
if (!table) throw
|
|
2447
|
+
if (!table) throw this._noSuchTable(tableName);
|
|
2277
2448
|
if (!(await this._runHooks('beforeFind', [tableName, { id }]))) return null;
|
|
2278
2449
|
const row = this._resolveId(table, id);
|
|
2279
2450
|
// P1-4: 软删除行对普通读取不可见
|
|
@@ -2287,7 +2458,7 @@ class Database {
|
|
|
2287
2458
|
|
|
2288
2459
|
async findByIds(tableName, ids) {
|
|
2289
2460
|
const table = this._ensureTable(tableName);
|
|
2290
|
-
if (!table) throw
|
|
2461
|
+
if (!table) throw this._noSuchTable(tableName);
|
|
2291
2462
|
if (!(await this._runHooks('beforeFind', [tableName, { ids }]))) return null;
|
|
2292
2463
|
// P1-4: 过滤掉软删除行;P1-11: 返回浅拷贝
|
|
2293
2464
|
const rows = ids.map(id => this._resolveId(table, id)).filter(r => r !== null && !r._deleted).map(r => ({ ...r }));
|
|
@@ -2302,7 +2473,7 @@ class Database {
|
|
|
2302
2473
|
|
|
2303
2474
|
async count(tableName) {
|
|
2304
2475
|
const table = this._ensureTable(tableName);
|
|
2305
|
-
if (!table) throw
|
|
2476
|
+
if (!table) throw this._noSuchTable(tableName);
|
|
2306
2477
|
if (!(await this._runHooks('beforeCount', [tableName]))) return undefined;
|
|
2307
2478
|
// P1-4: 软删除模式下只统计可见行
|
|
2308
2479
|
const n = table._softDelete ? table._getVisibleRows().length : table._rows.length;
|
|
@@ -2313,7 +2484,7 @@ class Database {
|
|
|
2313
2484
|
|
|
2314
2485
|
async updateById(tableName, id, data) {
|
|
2315
2486
|
const table = this._ensureTable(tableName);
|
|
2316
|
-
if (!table) throw
|
|
2487
|
+
if (!table) throw this._noSuchTable(tableName);
|
|
2317
2488
|
// #303:beforeUpdate 可返回「修改后 data」(PLUGINS.md 契约),
|
|
2318
2489
|
// 写回后必须用改写后的值继续。
|
|
2319
2490
|
const hookArgs = [tableName, id, data];
|
|
@@ -2398,7 +2569,7 @@ class Database {
|
|
|
2398
2569
|
|
|
2399
2570
|
async updateByIds(tableName, entries) {
|
|
2400
2571
|
const table = this._ensureTable(tableName);
|
|
2401
|
-
if (!table) throw
|
|
2572
|
+
if (!table) throw this._noSuchTable(tableName);
|
|
2402
2573
|
const pairs = entries.map(([id, data]) => [id, data]);
|
|
2403
2574
|
if (!(await this._runHooks('beforeUpdate', [tableName, pairs]))) return;
|
|
2404
2575
|
const pk = this._pkOf(table);
|
|
@@ -2425,7 +2596,7 @@ class Database {
|
|
|
2425
2596
|
|
|
2426
2597
|
async removeById(tableName, id) {
|
|
2427
2598
|
const table = this._ensureTable(tableName);
|
|
2428
|
-
if (!table) throw
|
|
2599
|
+
if (!table) throw this._noSuchTable(tableName);
|
|
2429
2600
|
if (!(await this._runHooks('beforeDelete', [tableName, id]))) return;
|
|
2430
2601
|
if (table._primaryKey) {
|
|
2431
2602
|
const removed = table.removeById(id);
|
|
@@ -2451,7 +2622,7 @@ class Database {
|
|
|
2451
2622
|
|
|
2452
2623
|
async removeByIds(tableName, ids) {
|
|
2453
2624
|
const table = this._ensureTable(tableName);
|
|
2454
|
-
if (!table) throw
|
|
2625
|
+
if (!table) throw this._noSuchTable(tableName);
|
|
2455
2626
|
if (!(await this._runHooks('beforeDelete', [tableName, ids]))) return;
|
|
2456
2627
|
let removed = 0;
|
|
2457
2628
|
if (table._primaryKey) {
|
|
@@ -2496,7 +2667,7 @@ class Database {
|
|
|
2496
2667
|
|
|
2497
2668
|
async removeWhere(tableName, filter) {
|
|
2498
2669
|
const table = this._ensureTable(tableName);
|
|
2499
|
-
if (!table) throw
|
|
2670
|
+
if (!table) throw this._noSuchTable(tableName);
|
|
2500
2671
|
if (!(await this._runHooks('beforeDelete', [tableName, [filter]]))) return { ok: true, count: 0 };
|
|
2501
2672
|
const before = table._rows.length;
|
|
2502
2673
|
// P1-4: 只匹配可见行(软删除行已“不存在”,不应被硬删操作波及)
|
|
@@ -2517,7 +2688,7 @@ class Database {
|
|
|
2517
2688
|
|
|
2518
2689
|
async insertMany(tableName, items) {
|
|
2519
2690
|
const table = this._ensureTable(tableName);
|
|
2520
|
-
if (!table) throw
|
|
2691
|
+
if (!table) throw this._noSuchTable(tableName);
|
|
2521
2692
|
const arr = Array.isArray(items) ? items : [items];
|
|
2522
2693
|
if (!(await this._runHooks('beforeInsert', [tableName, arr]))) return [];
|
|
2523
2694
|
const inserted = table.insertMany(arr);
|
|
@@ -2530,7 +2701,7 @@ class Database {
|
|
|
2530
2701
|
|
|
2531
2702
|
async update(tableName, query, updates) {
|
|
2532
2703
|
const table = this._ensureTable(tableName);
|
|
2533
|
-
if (!table) throw
|
|
2704
|
+
if (!table) throw this._noSuchTable(tableName);
|
|
2534
2705
|
if (!(await this._runHooks('beforeUpdate', [tableName, query, updates]))) return 0;
|
|
2535
2706
|
const count = table.update(query, updates);
|
|
2536
2707
|
// WAL 由 Table.update() 记录
|
|
@@ -2542,7 +2713,7 @@ class Database {
|
|
|
2542
2713
|
|
|
2543
2714
|
async delete(tableName, query = {}) {
|
|
2544
2715
|
const table = this._ensureTable(tableName);
|
|
2545
|
-
if (!table) throw
|
|
2716
|
+
if (!table) throw this._noSuchTable(tableName);
|
|
2546
2717
|
if (!(await this._runHooks('beforeDelete', [tableName, query]))) return 0;
|
|
2547
2718
|
// WAL 由 Table.remove() 记录
|
|
2548
2719
|
const count = table.remove(query);
|
|
@@ -2554,7 +2725,7 @@ class Database {
|
|
|
2554
2725
|
|
|
2555
2726
|
truncate(tableName) {
|
|
2556
2727
|
const table = this._ensureTable(tableName);
|
|
2557
|
-
if (!table) throw
|
|
2728
|
+
if (!table) throw this._noSuchTable(tableName);
|
|
2558
2729
|
// #206:被外键引用的父表禁止 TRUNCATE(MySQL 1701),也不应触发级联
|
|
2559
2730
|
if (this._foreignReferencingRows(tableName).length > 0) {
|
|
2560
2731
|
throw createError('ER_TRUNCATE_ILLEGAL_FK', tableName);
|
package/lib/jsql_format.js
CHANGED
|
@@ -11,6 +11,45 @@ const SZ = {
|
|
|
11
11
|
DATA: 4096 - 64
|
|
12
12
|
};
|
|
13
13
|
|
|
14
|
+
// ---------------------------------------------------------------------------
|
|
15
|
+
// 静态加密(Issue #260)
|
|
16
|
+
//
|
|
17
|
+
// 目录模式(hybrid/disk)的 `.jsql` 数据块此前只做 gzip,明文可直接解压看到。
|
|
18
|
+
// `encryptKey` 只在 legacy 单文件模式生效,目录模式静默忽略密钥 —— 用户以为
|
|
19
|
+
// 落盘已加密,实际裸奔。
|
|
20
|
+
//
|
|
21
|
+
// 现在把目录模式的数据块也加密:
|
|
22
|
+
// 写:原始行字节 → gzip → AES-256-CBC 加密 → 落盘
|
|
23
|
+
// 读:落盘字节 → AES-256-CBC 解密 → gunzip
|
|
24
|
+
//
|
|
25
|
+
// 布局:块头 [49] = 加密标记(0 未加密 / 1 已加密);
|
|
26
|
+
// 密文区 = IV(16 字节) + 密文本体。
|
|
27
|
+
// IV 每次随机生成,随密文一起落盘。
|
|
28
|
+
// ---------------------------------------------------------------------------
|
|
29
|
+
|
|
30
|
+
/** 由用户密钥派生 32 字节 AES-256 密钥(scrypt,固定 salt 以便同一密钥可重复解密)。 */
|
|
31
|
+
function deriveAesKey(encryptKey) {
|
|
32
|
+
const raw = Buffer.from(String(encryptKey), 'utf8');
|
|
33
|
+
return crypto.scryptSync(raw, Buffer.from('jsql-neo-static-encryption-v1', 'utf8'), 32);
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/** 加密一段数据,返回 IV(16) + 密文。 */
|
|
37
|
+
function encryptBlock(data, key) {
|
|
38
|
+
const iv = crypto.randomBytes(16);
|
|
39
|
+
const cipher = crypto.createCipheriv('aes-256-cbc', key, iv);
|
|
40
|
+
const enc = Buffer.concat([cipher.update(data), cipher.final()]);
|
|
41
|
+
return Buffer.concat([iv, enc]);
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/** 解密 IV(16) + 密文。 */
|
|
45
|
+
function decryptBlock(payload, key) {
|
|
46
|
+
if (payload.length < 16) throw new Error('encrypted block too short');
|
|
47
|
+
const iv = payload.subarray(0, 16);
|
|
48
|
+
const body = payload.subarray(16);
|
|
49
|
+
const decipher = crypto.createDecipheriv('aes-256-cbc', key, iv);
|
|
50
|
+
return Buffer.concat([decipher.update(body), decipher.final()]);
|
|
51
|
+
}
|
|
52
|
+
|
|
14
53
|
const BT = { FREE: 0, DATA: 1, IDX: 2 };
|
|
15
54
|
|
|
16
55
|
const TYPE = { NUL:0, BOL:1, I32:2, F64:3, STR:4, BUF:5, ARR:6, OBJ:7, I64:8, DATE:9, OID:10 };
|
|
@@ -177,7 +216,7 @@ function verifyHash(buf) {
|
|
|
177
216
|
}
|
|
178
217
|
|
|
179
218
|
class JSQLFormat {
|
|
180
|
-
constructor(path) {
|
|
219
|
+
constructor(path, encryptKey) {
|
|
181
220
|
this.path = path;
|
|
182
221
|
this.fd = null;
|
|
183
222
|
this.tables = new Map();
|
|
@@ -186,6 +225,37 @@ class JSQLFormat {
|
|
|
186
225
|
this.dirty = false;
|
|
187
226
|
this.open = false;
|
|
188
227
|
this._nextTableId = 1;
|
|
228
|
+
// #260:目录模式的静态加密密钥(未提供则为 null,即不加密)
|
|
229
|
+
this._encryptKey = encryptKey ? deriveAesKey(encryptKey) : null;
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
/** 块头 [49] 加密标记 */
|
|
233
|
+
static get ENC_FLAG_OFF() { return 49; }
|
|
234
|
+
|
|
235
|
+
/**
|
|
236
|
+
* 把块内载荷编码成落盘字节:gzip → (可选)加密。
|
|
237
|
+
* 返回 { payload, compLen, encFlag }
|
|
238
|
+
*/
|
|
239
|
+
_encodeBlockPayload(raw) {
|
|
240
|
+
const comp = zlib.gzipSync(raw, { level: 1 });
|
|
241
|
+
if (!this._encryptKey) {
|
|
242
|
+
return { payload: comp, compLen: comp.length, encFlag: 0 };
|
|
243
|
+
}
|
|
244
|
+
const payload = encryptBlock(comp, this._encryptKey);
|
|
245
|
+
return { payload, compLen: payload.length, encFlag: 1 };
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
/**
|
|
249
|
+
* 解析块内载荷: (可选)解密 → gunzip。
|
|
250
|
+
*/
|
|
251
|
+
_decodeBlockPayload(buf) {
|
|
252
|
+
const compFlag = buf[48];
|
|
253
|
+
const encFlag = buf[JSQLFormat.ENC_FLAG_OFF];
|
|
254
|
+
const dataLen = compFlag ? buf.readUInt32LE(44) : buf.readUInt32LE(40);
|
|
255
|
+
let payload = buf.slice(SZ.HEADER, SZ.HEADER + dataLen);
|
|
256
|
+
if (encFlag) payload = decryptBlock(payload, this._encryptKey);
|
|
257
|
+
if (!compFlag) return payload;
|
|
258
|
+
return zlib.gunzipSync(payload);
|
|
189
259
|
}
|
|
190
260
|
|
|
191
261
|
_open() {
|
|
@@ -426,13 +496,15 @@ class JSQLFormat {
|
|
|
426
496
|
// Compress and write blocks
|
|
427
497
|
for (let i = 0; i < p.rawBlocks.length; i++) {
|
|
428
498
|
const bid = p.blockIds[i];
|
|
429
|
-
|
|
499
|
+
// #260:gzip 后加密(目录模式静态加密)
|
|
500
|
+
const { payload, compLen, encFlag } = this._encodeBlockPayload(p.rawBlocks[i]);
|
|
430
501
|
const block = Buffer.alloc(SZ.BLOCK);
|
|
431
502
|
mkHeader(BT.DATA, bid, p.tableId).copy(block);
|
|
432
503
|
block.writeUInt32LE(p.rawBlocks[i].length, 40);
|
|
433
504
|
block[48] = 1;
|
|
434
|
-
block.
|
|
435
|
-
|
|
505
|
+
block[JSQLFormat.ENC_FLAG_OFF] = encFlag;
|
|
506
|
+
block.writeUInt32LE(compLen, 44);
|
|
507
|
+
payload.copy(block, SZ.HEADER);
|
|
436
508
|
finalize(block);
|
|
437
509
|
fs.writeSync(this.fd, block, 0, SZ.BLOCK, bid * SZ.BLOCK);
|
|
438
510
|
}
|
|
@@ -519,11 +591,13 @@ class JSQLFormat {
|
|
|
519
591
|
const bid = this._alloc();
|
|
520
592
|
const buf = Buffer.alloc(SZ.BLOCK);
|
|
521
593
|
mkHeader(BT.DATA, bid, t.tableId).copy(buf);
|
|
522
|
-
|
|
594
|
+
// #260:gzip 后加密(目录模式静态加密)
|
|
595
|
+
const { payload, compLen, encFlag } = this._encodeBlockPayload(Buffer.from(scratch.subarray(0, end)));
|
|
523
596
|
buf.writeUInt32LE(end, 40);
|
|
524
597
|
buf[48] = 1;
|
|
525
|
-
buf.
|
|
526
|
-
|
|
598
|
+
buf[JSQLFormat.ENC_FLAG_OFF] = encFlag;
|
|
599
|
+
buf.writeUInt32LE(compLen, 44);
|
|
600
|
+
payload.copy(buf, SZ.HEADER);
|
|
527
601
|
finalize(buf);
|
|
528
602
|
fs.writeSync(this.fd, buf, 0, SZ.BLOCK, bid * SZ.BLOCK);
|
|
529
603
|
t.dataBlock = bid;
|
|
@@ -569,10 +643,7 @@ class JSQLFormat {
|
|
|
569
643
|
if (!verifyHash(buf)) {
|
|
570
644
|
throw new Error(`[JSQLFormat] Table '${name}': data block ${bid} failed integrity check`);
|
|
571
645
|
}
|
|
572
|
-
const
|
|
573
|
-
const raw = compFlag
|
|
574
|
-
? zlib.gunzipSync(buf.slice(SZ.HEADER, SZ.HEADER + buf.readUInt32LE(44)))
|
|
575
|
-
: buf.slice(SZ.HEADER, SZ.HEADER + buf.readUInt32LE(40));
|
|
646
|
+
const raw = this._decodeBlockPayload(buf);
|
|
576
647
|
|
|
577
648
|
let off = 0;
|
|
578
649
|
while (off + 4 <= raw.length) {
|
|
@@ -625,10 +696,7 @@ class JSQLFormat {
|
|
|
625
696
|
throw new Error(`[JSQLFormat] Table '${name}': data block ${bid} failed integrity check`);
|
|
626
697
|
}
|
|
627
698
|
|
|
628
|
-
const
|
|
629
|
-
const raw = compFlag
|
|
630
|
-
? zlib.gunzipSync(buf.slice(SZ.HEADER, SZ.HEADER + buf.readUInt32LE(44)))
|
|
631
|
-
: buf.slice(SZ.HEADER, SZ.HEADER + buf.readUInt32LE(40));
|
|
699
|
+
const raw = this._decodeBlockPayload(buf);
|
|
632
700
|
|
|
633
701
|
let off = 0;
|
|
634
702
|
while (off + 4 <= raw.length) {
|
|
@@ -689,15 +757,7 @@ class JSQLFormat {
|
|
|
689
757
|
_readInBlock(blockId, off) {
|
|
690
758
|
const buf = Buffer.alloc(SZ.BLOCK);
|
|
691
759
|
fs.readSync(this.fd, buf, 0, SZ.BLOCK, blockId * SZ.BLOCK);
|
|
692
|
-
const
|
|
693
|
-
const compSz = buf.readUInt32LE(44);
|
|
694
|
-
const dataSz = buf.readUInt32LE(40);
|
|
695
|
-
let raw;
|
|
696
|
-
if (compFlag) {
|
|
697
|
-
raw = zlib.gunzipSync(buf.slice(SZ.HEADER, SZ.HEADER + compSz));
|
|
698
|
-
} else {
|
|
699
|
-
raw = buf.slice(SZ.HEADER, SZ.HEADER + dataSz);
|
|
700
|
-
}
|
|
760
|
+
const raw = this._decodeBlockPayload(buf);
|
|
701
761
|
const r = decRow(raw, off);
|
|
702
762
|
return r.row;
|
|
703
763
|
}
|
package/lib/sqlite_worker.js
CHANGED
|
@@ -106,18 +106,24 @@ function toRows(result) {
|
|
|
106
106
|
|
|
107
107
|
let _lastInsertId = 0;
|
|
108
108
|
|
|
109
|
-
async function executeStatement(sql, params) {
|
|
109
|
+
async function executeStatement(sql, params, extraOpts) {
|
|
110
110
|
if (params && typeof params === 'object' && !Array.isArray(params)) {
|
|
111
111
|
sql = applyParams(sql, params);
|
|
112
112
|
params = null;
|
|
113
113
|
}
|
|
114
114
|
const result = await executeSQL(db, sql, params, {
|
|
115
|
+
// #264:better-sqlite3 的 db.exec() 设计上就是执行一条或多条 SQL
|
|
116
|
+
// (常用于跑建表脚本 / BEGIN;…;COMMIT;)。sqlite 兼容层的 exec 必须
|
|
117
|
+
// 走 allowStacked —— 否则迁移过来的多语句脚本直接被安全策略拦掉。
|
|
118
|
+
// prepare()/run()/get()/all() 等单语句路径保持拦截(allowStacked 为 false)。
|
|
119
|
+
allowStacked: false,
|
|
115
120
|
session: {
|
|
116
121
|
get lastInsertId() { return _lastInsertId; },
|
|
117
122
|
set lastInsertId(v) { _lastInsertId = Number(v); },
|
|
118
123
|
},
|
|
119
124
|
functions: userFunctions,
|
|
120
125
|
aggregates: userAggregates,
|
|
126
|
+
...(extraOpts || {}),
|
|
121
127
|
});
|
|
122
128
|
if (result && result.type === 'insert' && result.insertId !== null && result.insertId !== undefined) {
|
|
123
129
|
_lastInsertId = Number(result.insertId);
|
|
@@ -157,7 +163,8 @@ async function handleOp(op, args) {
|
|
|
157
163
|
break;
|
|
158
164
|
}
|
|
159
165
|
case 'exec': {
|
|
160
|
-
|
|
166
|
+
// #264:exec 固定允许堆叠多语句(better-sqlite3 语义)
|
|
167
|
+
result = await executeStatement(args[0], args[1], { allowStacked: true });
|
|
161
168
|
break;
|
|
162
169
|
}
|
|
163
170
|
case 'run': {
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "jsql-neo",
|
|
3
|
-
"version": "6.8.
|
|
3
|
+
"version": "6.8.15",
|
|
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",
|
|
@@ -52,12 +52,12 @@
|
|
|
52
52
|
"build:native": "node scripts/build-native.js",
|
|
53
53
|
"check:release": "node scripts/check-release-metadata.js",
|
|
54
54
|
"release:prep": "node scripts/release.js",
|
|
55
|
-
"test": "npm run check:release && node test/smoke.js && node test/result-raw.test.js && node test/native-install.test.js && node test/native-cli.test.js && node test/finalize-bigint.test.js && node test/native.test.js && node test/json-functions.test.js && node test/sql-parser.test.js && node test/readme-audit.test.js && node test/query-opt.test.js && node test/wal-recovery.test.js && node test/mysql-compat-hijack.test.js && node test/dml-constraints.test.js && node test/star-nag.test.js && node test/plugin-xql.test.js && node test/bug-regression-2.test.js && node test/issue-34-35-36.test.js && node test/issue-g4.test.js && node test/issue-38.test.js && node test/issue-39.test.js && node test/issue-40.test.js && node test/issue-44.test.js && node test/issue-45.test.js && node test/issue-46.test.js && node test/issue-47.test.js && node test/issue-48.test.js && node test/issue-50.test.js && node test/issue-51.test.js && node test/issue-52.test.js && node test/issue-53.test.js && node test/issue-54.test.js && node test/issue-55.test.js && node test/issue-56.test.js && node test/issue-57.test.js && node test/issue-58.test.js && node test/issue-59.test.js && node test/issue-60.test.js && node test/issue-63-68.test.js && node test/network-policy.test.js && node test/issue-69-70.test.js && node test/issue-71-72.test.js && node test/issue-73-76.test.js && node test/issue-77-84.test.js && node test/issue-86-99.test.js && node test/issue-101-103.test.js && node test/issue-105.test.js && node test/issue-118-136.test.js && node test/issue-127.test.js && node test/issue-138-156.test.js && node test/issue-157-161.test.js && node test/issue-162-179.test.js && node test/issue-181-186.test.js && node test/issue-187.test.js && node test/issue-188-237.test.js && node test/issue-238-241.test.js && node test/bigint-math.test.js && node test/release-metadata.test.js && node test/date-conversions.test.js && node test/mysql-utility-functions.test.js && node test/limit-pushdown.test.js && node test/columnar.test.js && node test/columnar-vector.test.js && node test/cast-rounding.test.js && node test/convert-subquery.test.js && node test/mongo-persistence.test.js && node test/mongo-objectid.test.js && node test/mongo-arrays.test.js && node test/issue-117.test.js && node test/issue-314-321.test.js && node test/issue-312-320.test.js && node test/issue-243-289.test.js && node test/issue-284-292.test.js && node test/issue-301-305.test.js && node test/issue-248-252.test.js",
|
|
55
|
+
"test": "npm run check:release && node test/smoke.js && node test/result-raw.test.js && node test/native-install.test.js && node test/native-cli.test.js && node test/finalize-bigint.test.js && node test/native.test.js && node test/json-functions.test.js && node test/sql-parser.test.js && node test/readme-audit.test.js && node test/query-opt.test.js && node test/wal-recovery.test.js && node test/mysql-compat-hijack.test.js && node test/dml-constraints.test.js && node test/star-nag.test.js && node test/plugin-xql.test.js && node test/bug-regression-2.test.js && node test/issue-34-35-36.test.js && node test/issue-g4.test.js && node test/issue-38.test.js && node test/issue-39.test.js && node test/issue-40.test.js && node test/issue-44.test.js && node test/issue-45.test.js && node test/issue-46.test.js && node test/issue-47.test.js && node test/issue-48.test.js && node test/issue-50.test.js && node test/issue-51.test.js && node test/issue-52.test.js && node test/issue-53.test.js && node test/issue-54.test.js && node test/issue-55.test.js && node test/issue-56.test.js && node test/issue-57.test.js && node test/issue-58.test.js && node test/issue-59.test.js && node test/issue-60.test.js && node test/issue-63-68.test.js && node test/network-policy.test.js && node test/issue-69-70.test.js && node test/issue-71-72.test.js && node test/issue-73-76.test.js && node test/issue-77-84.test.js && node test/issue-86-99.test.js && node test/issue-101-103.test.js && node test/issue-105.test.js && node test/issue-118-136.test.js && node test/issue-127.test.js && node test/issue-138-156.test.js && node test/issue-157-161.test.js && node test/issue-162-179.test.js && node test/issue-181-186.test.js && node test/issue-187.test.js && node test/issue-188-237.test.js && node test/issue-238-241.test.js && node test/bigint-math.test.js && node test/release-metadata.test.js && node test/date-conversions.test.js && node test/mysql-utility-functions.test.js && node test/limit-pushdown.test.js && node test/columnar.test.js && node test/columnar-vector.test.js && node test/cast-rounding.test.js && node test/convert-subquery.test.js && node test/mongo-persistence.test.js && node test/mongo-objectid.test.js && node test/mongo-arrays.test.js && node test/issue-117.test.js && node test/issue-314-321.test.js && node test/issue-312-320.test.js && node test/issue-243-289.test.js && node test/issue-284-292.test.js && node test/issue-301-305.test.js && node test/issue-248-252.test.js && node test/issue-259-264.test.js",
|
|
56
56
|
"test:parser": "node test/sql-parser.test.js",
|
|
57
57
|
"test:btree": "node test/btree.test.js",
|
|
58
58
|
"test:native": "node test/native.test.js",
|
|
59
59
|
"test:regress": "node test/regress-5.1.0.js",
|
|
60
|
-
"test:all": "npm run check:release && node test/smoke.js && node test/result-raw.test.js && node test/native-install.test.js && node test/native-cli.test.js && node test/finalize-bigint.test.js && node test/sql-parser.test.js && node test/readme-audit.test.js && node test/native.test.js && node test/native-multi-instance.test.js && node test/wal-recovery.test.js && node test/mysql-compat-hijack.test.js && node test/wasm.test.js && node test/coverage.js && node test/regress-5.1.0.js && node test/join.test.js && node test/btree.test.js && node test/dml-constraints.test.js && node test/savepoint.test.js && node test/alter-table.test.js && node test/null-semantics.test.js && node test/identifier-keywords.test.js && node test/issue-34-35-36.test.js && node test/sql-semantics.test.js && node test/extra-coverage.test.js && node test/filter-compile.test.js && node test/recursive-cte.test.js && node test/index-ddl.test.js && node test/mongo-group.test.js && node test/multiprotocol.test.js && node test/issue-g4.test.js && node test/issue-38.test.js && node test/issue-39.test.js && node test/issue-40.test.js && node test/issue-44.test.js && node test/issue-45.test.js && node test/issue-46.test.js && node test/issue-47.test.js && node test/issue-48.test.js && node test/issue-50.test.js && node test/issue-51.test.js && node test/issue-52.test.js && node test/issue-53.test.js && node test/issue-54.test.js && node test/issue-55.test.js && node test/issue-56.test.js && node test/issue-57.test.js && node test/issue-58.test.js && node test/issue-59.test.js && node test/issue-60.test.js && node test/issue-63-68.test.js && node test/network-policy.test.js && node test/issue-69-70.test.js && node test/issue-71-72.test.js && node test/issue-77-84.test.js && node test/issue-86-99.test.js && node test/issue-101-103.test.js && node test/issue-105.test.js && node test/issue-118-136.test.js && node test/issue-127.test.js && node test/issue-138-156.test.js && node test/issue-157-161.test.js && node test/issue-162-179.test.js && node test/issue-181-186.test.js && node test/issue-187.test.js && node test/issue-188-237.test.js && node test/issue-238-241.test.js && node test/bigint-math.test.js && node test/release-metadata.test.js && node test/date-conversions.test.js && node test/mysql-utility-functions.test.js && node test/limit-pushdown.test.js && node test/columnar.test.js && node test/columnar-vector.test.js && node test/cast-rounding.test.js && node test/convert-subquery.test.js && node test/mongo-persistence.test.js && node test/mongo-objectid.test.js && node test/mongo-arrays.test.js && node test/issue-117.test.js && node test/issue-314-321.test.js && node test/issue-312-320.test.js && node test/issue-243-289.test.js && node test/issue-284-292.test.js && node test/issue-301-305.test.js && node test/issue-248-252.test.js",
|
|
60
|
+
"test:all": "npm run check:release && node test/smoke.js && node test/result-raw.test.js && node test/native-install.test.js && node test/native-cli.test.js && node test/finalize-bigint.test.js && node test/sql-parser.test.js && node test/readme-audit.test.js && node test/native.test.js && node test/native-multi-instance.test.js && node test/wal-recovery.test.js && node test/mysql-compat-hijack.test.js && node test/wasm.test.js && node test/coverage.js && node test/regress-5.1.0.js && node test/join.test.js && node test/btree.test.js && node test/dml-constraints.test.js && node test/savepoint.test.js && node test/alter-table.test.js && node test/null-semantics.test.js && node test/identifier-keywords.test.js && node test/issue-34-35-36.test.js && node test/sql-semantics.test.js && node test/extra-coverage.test.js && node test/filter-compile.test.js && node test/recursive-cte.test.js && node test/index-ddl.test.js && node test/mongo-group.test.js && node test/multiprotocol.test.js && node test/issue-g4.test.js && node test/issue-38.test.js && node test/issue-39.test.js && node test/issue-40.test.js && node test/issue-44.test.js && node test/issue-45.test.js && node test/issue-46.test.js && node test/issue-47.test.js && node test/issue-48.test.js && node test/issue-50.test.js && node test/issue-51.test.js && node test/issue-52.test.js && node test/issue-53.test.js && node test/issue-54.test.js && node test/issue-55.test.js && node test/issue-56.test.js && node test/issue-57.test.js && node test/issue-58.test.js && node test/issue-59.test.js && node test/issue-60.test.js && node test/issue-63-68.test.js && node test/network-policy.test.js && node test/issue-69-70.test.js && node test/issue-71-72.test.js && node test/issue-77-84.test.js && node test/issue-86-99.test.js && node test/issue-101-103.test.js && node test/issue-105.test.js && node test/issue-118-136.test.js && node test/issue-127.test.js && node test/issue-138-156.test.js && node test/issue-157-161.test.js && node test/issue-162-179.test.js && node test/issue-181-186.test.js && node test/issue-187.test.js && node test/issue-188-237.test.js && node test/issue-238-241.test.js && node test/bigint-math.test.js && node test/release-metadata.test.js && node test/date-conversions.test.js && node test/mysql-utility-functions.test.js && node test/limit-pushdown.test.js && node test/columnar.test.js && node test/columnar-vector.test.js && node test/cast-rounding.test.js && node test/convert-subquery.test.js && node test/mongo-persistence.test.js && node test/mongo-objectid.test.js && node test/mongo-arrays.test.js && node test/issue-117.test.js && node test/issue-314-321.test.js && node test/issue-312-320.test.js && node test/issue-243-289.test.js && node test/issue-284-292.test.js && node test/issue-301-305.test.js && node test/issue-248-252.test.js && node test/issue-259-264.test.js",
|
|
61
61
|
"test:coverage": "c8 --all --include='lib/**' --exclude='lib/web_ui.js' --reporter=text --reporter=lcov node test/coverage.js",
|
|
62
62
|
"test:orms": "node examples/orms/run-all.js",
|
|
63
63
|
"test:dml": "node test/dml-constraints.test.js",
|
|
@@ -0,0 +1,163 @@
|
|
|
1
|
+
/* ---- 回归:#259 / #260 / #262 / #263 / #264 ---- */
|
|
2
|
+
/*
|
|
3
|
+
* #259 目录模式(hybrid/disk)显式开启 wal:true 后,WAL 已追加落盘,
|
|
4
|
+
* 但重开库从不回放 WAL:崩溃时尚未刷入 .jsql 的提交全部丢失。
|
|
5
|
+
* #260 encryptKey 在目录模式被静默忽略:.jsql 数据块仅 gzip、可直接解压回明文,
|
|
6
|
+
* meta.json 也是明文。
|
|
7
|
+
* #262 目录模式 .jsql 表文件损坏后被 _ensureTable 静默吞掉:表从查询中消失,
|
|
8
|
+
* 但 meta.json 仍把它列为幽灵表,无任何损坏告警。
|
|
9
|
+
* #263 WAL 追加失败被空 catch 静默吞掉:主流程照常返回成功、无 error 事件。
|
|
10
|
+
* #264 sqlite 兼容层 db.exec() 多语句被安全策略拦截。
|
|
11
|
+
*/
|
|
12
|
+
const path = require('path');
|
|
13
|
+
const fs = require('fs');
|
|
14
|
+
const os = require('os');
|
|
15
|
+
const zlib = require('zlib');
|
|
16
|
+
const ROOT = path.join(__dirname, '..');
|
|
17
|
+
const Database = require(path.join(ROOT, 'lib/database.js'));
|
|
18
|
+
const SqliteCompat = require(path.join(ROOT, 'lib/sqlite_compat.js'));
|
|
19
|
+
|
|
20
|
+
let pass = 0, fail = 0;
|
|
21
|
+
function ok(name, cond, got) {
|
|
22
|
+
if (cond) { pass++; console.log('[OK] ' + name); }
|
|
23
|
+
else { fail++; console.log('[FAIL] ' + name + ' -> ' + JSON.stringify(got)); }
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
function tmpdir(prefix) {
|
|
27
|
+
return fs.mkdtempSync(path.join(os.tmpdir(), prefix));
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
(async () => {
|
|
31
|
+
// ================= #259 目录模式 WAL 回放 =================
|
|
32
|
+
{
|
|
33
|
+
const dir = tmpdir('jsql-waldir-');
|
|
34
|
+
const db = new Database(dir, { mode: 'disk', wal: true, flushInterval: 1e9 });
|
|
35
|
+
await db.createTable('t', { id: { type: 'integer', primaryKey: true }, v: { type: 'string' } });
|
|
36
|
+
await db.insert('t', { id: 1, v: 'hello-wal' });
|
|
37
|
+
const wal = dir + '.wal';
|
|
38
|
+
ok('目录模式 WAL 文件已落盘', fs.existsSync(wal), wal);
|
|
39
|
+
// 不 flush/close —— 模拟后台刷盘前进程崩溃
|
|
40
|
+
const db2 = new Database(dir, { mode: 'disk', wal: true, flushInterval: 1e9 });
|
|
41
|
+
ok('重开后 WAL 被回放(replayed > 0)',
|
|
42
|
+
db2._walReplaySummary && db2._walReplaySummary.replayed > 0, db2._walReplaySummary);
|
|
43
|
+
const rows = await db2.find('t', {});
|
|
44
|
+
ok('崩溃前已提交的插入被恢复',
|
|
45
|
+
rows.length === 1 && rows[0].v === 'hello-wal', rows);
|
|
46
|
+
db2.close();
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
// hybrid 模式同样要能回放
|
|
50
|
+
{
|
|
51
|
+
const dir = tmpdir('jsql-walhyb-');
|
|
52
|
+
const db = new Database(dir, { mode: 'hybrid', wal: true, flushInterval: 1e9 });
|
|
53
|
+
await db.createTable('h', { id: { type: 'integer', primaryKey: true }, v: { type: 'string' } });
|
|
54
|
+
await db.insert('h', { id: 1, v: 'hyb' });
|
|
55
|
+
const db2 = new Database(dir, { mode: 'hybrid', wal: true, flushInterval: 1e9 });
|
|
56
|
+
const rows = await db2.find('h', {});
|
|
57
|
+
ok('hybrid 模式 WAL 回放同样生效',
|
|
58
|
+
rows.length === 1 && rows[0].v === 'hyb', rows);
|
|
59
|
+
db2.close();
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
// ================= #260 目录模式加密 =================
|
|
63
|
+
{
|
|
64
|
+
const SECRET = 'TOP-SECRET-PLAINTEXT-777';
|
|
65
|
+
const dir = tmpdir('jsql-encdir-');
|
|
66
|
+
const KEY = '0123456789abcdef'; // 16 字节
|
|
67
|
+
const db = new Database(dir, { mode: 'disk', encryptKey: KEY, flushInterval: 0 });
|
|
68
|
+
await db.createTable('secret', { id: { type: 'integer', primaryKey: true }, note: { type: 'string' } });
|
|
69
|
+
await db.insert('secret', { id: 1, note: SECRET });
|
|
70
|
+
await db.flush();
|
|
71
|
+
db.close();
|
|
72
|
+
|
|
73
|
+
// 直接扫描 .jsql 数据块、gunzip 后搜明文(不使用任何密钥)
|
|
74
|
+
const buf = fs.readFileSync(path.join(dir, 'secret.jsql'));
|
|
75
|
+
let decoded = '';
|
|
76
|
+
for (let bid = 1; bid * 4096 < buf.length; bid++) {
|
|
77
|
+
const blk = buf.subarray(bid * 4096, bid * 4096 + 4096);
|
|
78
|
+
const compLen = blk.readUInt32LE(44);
|
|
79
|
+
if (!compLen) continue;
|
|
80
|
+
try { decoded += zlib.gunzipSync(blk.subarray(64, 64 + compLen)).toString('utf8'); } catch (e) { /* 密文解不开 */ }
|
|
81
|
+
}
|
|
82
|
+
ok('目录模式 .jsql 不含可直接解压的明文', !decoded.includes(SECRET), decoded.slice(0, 40));
|
|
83
|
+
ok('meta.json 也是密文(不含字段名)',
|
|
84
|
+
!fs.readFileSync(path.join(dir, 'meta.json'), 'utf8').includes('note'), null);
|
|
85
|
+
|
|
86
|
+
// 同密钥重开能正确解密读回
|
|
87
|
+
const db2 = new Database(dir, { mode: 'disk', encryptKey: KEY, flushInterval: 0 });
|
|
88
|
+
const rows = await db2.find('secret', {});
|
|
89
|
+
ok('同密钥重开能解密读回原值',
|
|
90
|
+
rows.length === 1 && rows[0].note === SECRET, rows);
|
|
91
|
+
db2.close();
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
// ================= #262 表文件损坏显式报错 =================
|
|
95
|
+
{
|
|
96
|
+
const dir = tmpdir('jsql-torn-');
|
|
97
|
+
const db = new Database(dir, { mode: 'hybrid' });
|
|
98
|
+
await db.createTable('t', { id: { type: 'integer', primaryKey: true }, v: { type: 'string' } });
|
|
99
|
+
await db.insertMany('t', [{ id: 1, v: 'a' }, { id: 2, v: 'b' }]);
|
|
100
|
+
await db.flush();
|
|
101
|
+
db.close();
|
|
102
|
+
// 模拟崩溃半写:破坏表文件头部 magic
|
|
103
|
+
const file = path.join(dir, 't.jsql');
|
|
104
|
+
const buf = fs.readFileSync(file);
|
|
105
|
+
buf.write('XXXX', 0, 'utf8');
|
|
106
|
+
fs.writeFileSync(file, buf);
|
|
107
|
+
|
|
108
|
+
const errs = [];
|
|
109
|
+
const db2 = new Database(dir, { mode: 'hybrid' });
|
|
110
|
+
db2.on('error', (e) => errs.push(e.message));
|
|
111
|
+
ok('损坏表不再被 getTables 列为存在(无幽灵表)',
|
|
112
|
+
!db2.getTables().includes('t'), db2.getTables());
|
|
113
|
+
ok('hasTable 对损坏表返回 false', db2.hasTable('t') === false, db2.hasTable('t'));
|
|
114
|
+
ok('损坏表被记录到 getCorruptTables', Object.keys(db2.getCorruptTables()).includes('t'), null);
|
|
115
|
+
let qErr = null;
|
|
116
|
+
try { await db2.count('t'); } catch (e) { qErr = e; }
|
|
117
|
+
ok('查询损坏表报 ER_TABLE_CORRUPT(不再是含糊的缺表)',
|
|
118
|
+
qErr && qErr.code === 'ER_TABLE_CORRUPT', qErr && qErr.code);
|
|
119
|
+
ok('损坏时有 error 事件可见', errs.length > 0, errs);
|
|
120
|
+
db2.close();
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
// ================= #263 WAL 落盘失败不静默 =================
|
|
124
|
+
{
|
|
125
|
+
const dir = tmpdir('jsql-walerr-');
|
|
126
|
+
const file = path.join(dir, 'db.json');
|
|
127
|
+
const db = new Database(file, { wal: true, autoSave: false });
|
|
128
|
+
const errs = [];
|
|
129
|
+
db.on('error', (e) => errs.push(e.message));
|
|
130
|
+
await db.createTable('t', { id: { type: 'integer', primaryKey: true }, v: { type: 'string' } });
|
|
131
|
+
// 让 WAL 路径指向一个目录 → openSync(...,'a') 必然失败
|
|
132
|
+
const walAsDir = path.join(dir, 'wal-as-dir');
|
|
133
|
+
fs.mkdirSync(walAsDir, { recursive: true });
|
|
134
|
+
db._walPath = walAsDir;
|
|
135
|
+
await db.insert('t', { id: 1, v: 'x' });
|
|
136
|
+
ok('WAL 落盘失败时发出 error 事件', errs.length > 0, errs);
|
|
137
|
+
ok('WAL 落盘失败被记入 _walError', !!db._walError, null);
|
|
138
|
+
db.close();
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
// ================= #264 sqlite exec 多语句 =================
|
|
142
|
+
{
|
|
143
|
+
const db = new SqliteCompat(':memory:');
|
|
144
|
+
db.exec('CREATE TABLE u (x INTEGER)');
|
|
145
|
+
let multiErr = null;
|
|
146
|
+
try { db.exec('INSERT INTO u VALUES (1); INSERT INTO u VALUES (2);'); }
|
|
147
|
+
catch (e) { multiErr = e; }
|
|
148
|
+
ok('sqlite db.exec() 支持多语句', !multiErr, multiErr && multiErr.message);
|
|
149
|
+
const cnt = db.prepare('SELECT COUNT(*) AS c FROM u').get();
|
|
150
|
+
ok('多语句 exec 全部生效(count = 2)', cnt && cnt.c === 2, cnt);
|
|
151
|
+
// prepare 单语句路径不受影响(实际执行时仍拦截堆叠语句)
|
|
152
|
+
let prepErr = null;
|
|
153
|
+
try { db.prepare('SELECT 1; SELECT 2').all(); } catch (e) { prepErr = e; }
|
|
154
|
+
ok('prepare().all() 单语句路径仍拦截堆叠语句', !!prepErr, prepErr && prepErr.message);
|
|
155
|
+
db.close();
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
console.log(`\n${pass} passed, ${fail} failed`);
|
|
159
|
+
process.exit(fail === 0 ? 0 : 1);
|
|
160
|
+
})().catch(e => {
|
|
161
|
+
console.log('[FAIL] unexpected exception: ' + (e.stack || e).split('\n').slice(0, 4).join('\n'));
|
|
162
|
+
process.exit(1);
|
|
163
|
+
});
|