jsql-neo 6.8.26 → 6.8.27
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.d.ts +22 -5
- package/index.js +1 -1
- package/lib/columnar_fast.js +13 -2
- package/lib/database.js +204 -31
- 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/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.27** — 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.d.ts
CHANGED
|
@@ -295,6 +295,7 @@ declare namespace JSQLNeo {
|
|
|
295
295
|
allowComments?: boolean;
|
|
296
296
|
safety?: boolean;
|
|
297
297
|
maxStatements?: number;
|
|
298
|
+
allowStacked?: boolean;
|
|
298
299
|
session?: Record<string, unknown>;
|
|
299
300
|
/** 5.5.0+:原生 `?` 占位符绑定值(与 applyParams 的数组入参二选一) */
|
|
300
301
|
params?: unknown[];
|
|
@@ -334,13 +335,29 @@ declare namespace JSQLNeo {
|
|
|
334
335
|
export function transform(ast: unknown, fn: (node: unknown) => unknown): unknown;
|
|
335
336
|
|
|
336
337
|
export interface DatabaseOptions {
|
|
337
|
-
|
|
338
|
-
|
|
339
|
-
|
|
338
|
+
mode?: 'memory' | 'hybrid' | 'disk';
|
|
339
|
+
autoSave?: boolean;
|
|
340
|
+
autoSaveInterval?: number;
|
|
341
|
+
memReserveMB?: number;
|
|
342
|
+
flushInterval?: number;
|
|
343
|
+
evictInterval?: number;
|
|
344
|
+
encryptKey?: string;
|
|
345
|
+
versioning?: boolean;
|
|
346
|
+
wal?: boolean;
|
|
347
|
+
walCheckpointOps?: number;
|
|
348
|
+
isolationLevel?: 'READ_COMMITTED' | 'REPEATABLE_READ';
|
|
349
|
+
slowQueryThreshold?: number;
|
|
350
|
+
fileLock?: boolean;
|
|
351
|
+
}
|
|
352
|
+
|
|
353
|
+
export interface DatastoreOptions {
|
|
354
|
+
filename?: string;
|
|
355
|
+
database?: unknown;
|
|
356
|
+
engine?: unknown;
|
|
340
357
|
}
|
|
341
358
|
|
|
342
359
|
export class Database {
|
|
343
|
-
constructor(options?: DatabaseOptions);
|
|
360
|
+
constructor(filePath?: string, options?: DatabaseOptions);
|
|
344
361
|
createTable(name: string, schema: Schema): Promise<unknown>;
|
|
345
362
|
insert(table: string, data: Record<string, unknown>): Promise<unknown>;
|
|
346
363
|
find(table: string, filter?: Record<string, unknown>): Promise<Row[]>;
|
|
@@ -424,7 +441,7 @@ declare namespace JSQLNeo {
|
|
|
424
441
|
}
|
|
425
442
|
|
|
426
443
|
export class Datastore {
|
|
427
|
-
constructor(options?:
|
|
444
|
+
constructor(options?: DatastoreOptions);
|
|
428
445
|
insert(docs: unknown): Promise<unknown>;
|
|
429
446
|
find(query?: unknown): Promise<unknown[]>;
|
|
430
447
|
update(query: unknown, update: unknown): Promise<number>;
|
package/index.js
CHANGED
package/lib/columnar_fast.js
CHANGED
|
@@ -14,6 +14,17 @@ function colNameOf(node) {
|
|
|
14
14
|
return node.type === 'column' ? node.name : null;
|
|
15
15
|
}
|
|
16
16
|
|
|
17
|
+
/**
|
|
18
|
+
* #469:聚合输出列名,与行存命名规则一致 —— 保留实参 / `*`:
|
|
19
|
+
* COUNT(v)、COUNT(*)、MIN(s),不得退化为 COUNT()。
|
|
20
|
+
*/
|
|
21
|
+
function aggLabel(fn, col) {
|
|
22
|
+
let arg;
|
|
23
|
+
if (col == null || col.type === 'star' || col.type === '*') arg = '*';
|
|
24
|
+
else arg = colNameOf(col) || '*';
|
|
25
|
+
return fn + '(' + arg + ')';
|
|
26
|
+
}
|
|
27
|
+
|
|
17
28
|
/**
|
|
18
29
|
* 把 WHERE 编译成「命中行下标数组」。
|
|
19
30
|
* 只支持 `列 OP 字面量` 以及它们的 AND 组合;其它(OR / LIKE / 函数 / 子查询 /
|
|
@@ -196,7 +207,7 @@ function aggregate(statement, data) {
|
|
|
196
207
|
default: return null;
|
|
197
208
|
}
|
|
198
209
|
outRow.push(v);
|
|
199
|
-
outCols.push(c.alias || (fn
|
|
210
|
+
outCols.push(c.alias || aggLabel(fn, argNode));
|
|
200
211
|
}
|
|
201
212
|
return { type: 'select', columns: outCols, rows: [outRow] };
|
|
202
213
|
}
|
|
@@ -339,7 +350,7 @@ function groupBy(statement, data) {
|
|
|
339
350
|
outRows.push(row);
|
|
340
351
|
}
|
|
341
352
|
const outCols = cols.map(c => c.alias || (c.aggregate
|
|
342
|
-
? String(c.aggregate).toUpperCase()
|
|
353
|
+
? aggLabel(String(c.aggregate).toUpperCase(), c.column)
|
|
343
354
|
: colNameOf(c.scalar || c.expr)));
|
|
344
355
|
|
|
345
356
|
// ORDER BY:在分组结果上排序 —— 组数通常远小于行数,代价很低。
|
package/lib/database.js
CHANGED
|
@@ -201,12 +201,14 @@ class Database {
|
|
|
201
201
|
: null;
|
|
202
202
|
this._walReplaying = false; // 回放中:抑制再次写日志
|
|
203
203
|
this._walReplaySummary = null;
|
|
204
|
+
this._metaCorrupt = null; // #453:meta.json 损坏/兜底恢复的排障记录
|
|
204
205
|
this._walOpCount = 0; // 自上次检查点以来的操作数
|
|
205
206
|
this._walCheckpointOps = options.walCheckpointOps !== undefined ? options.walCheckpointOps : 1000;
|
|
206
207
|
this._walCheckpointScheduled = false;
|
|
207
208
|
|
|
208
|
-
// 事务隔离:默认
|
|
209
|
-
|
|
209
|
+
// 事务隔离:默认 READ_COMMITTED(每条语句读到最新已提交数据);
|
|
210
|
+
// 传 'REPEATABLE_READ' 则固定事务开始时的行快照。
|
|
211
|
+
this._isolationLevel = options.isolationLevel || 'READ_COMMITTED';
|
|
210
212
|
|
|
211
213
|
// JSql 格式 (binary block-based)
|
|
212
214
|
this._jsqlMode = this._filePath && this._filePath.endsWith('.jsql');
|
|
@@ -251,6 +253,10 @@ class Database {
|
|
|
251
253
|
|
|
252
254
|
_initDirStore() {
|
|
253
255
|
if (!this._filePath) throw new Error('hybrid/disk mode requires a directory path');
|
|
256
|
+
// #449:目录模式同样要拿目录级文件锁(`<dir>.lock`),与 legacy 单文件模式一致;
|
|
257
|
+
// 否则同目录两个实例可并存,后 flush 者用陈旧内存快照全量覆写,抹掉前者已提交行。
|
|
258
|
+
// 崩溃残留锁按既有 30s 过期逻辑在 _acquireLock 内接管。
|
|
259
|
+
this._acquireLock();
|
|
254
260
|
fs.mkdirSync(this._filePath, { recursive: true });
|
|
255
261
|
this._metaPath = path.join(this._filePath, 'meta.json');
|
|
256
262
|
this._meta = { version: 1, tables: {} };
|
|
@@ -260,9 +266,11 @@ class Database {
|
|
|
260
266
|
// 格式:{"__enc":"v1","data":"<base64>"};无密钥时按明文 JSON 读(兼容旧库)。
|
|
261
267
|
const rawMeta = fs.readFileSync(this._metaPath, 'utf8');
|
|
262
268
|
let parsed;
|
|
269
|
+
let parseErr = null;
|
|
263
270
|
try {
|
|
264
271
|
parsed = JSON.parse(rawMeta);
|
|
265
272
|
} catch (e) {
|
|
273
|
+
parseErr = e;
|
|
266
274
|
parsed = null;
|
|
267
275
|
}
|
|
268
276
|
if (parsed && parsed.__enc === 'v1' && typeof parsed.data === 'string') {
|
|
@@ -276,6 +284,8 @@ class Database {
|
|
|
276
284
|
]).toString('utf8');
|
|
277
285
|
parsed = JSON.parse(plain);
|
|
278
286
|
}
|
|
287
|
+
// 明文 JSON 半写撕裂:解析失败必须走损坏兜底,不能静默落空注册表。
|
|
288
|
+
if (parseErr) throw parseErr;
|
|
279
289
|
if (parsed && parsed.tables) {
|
|
280
290
|
this._meta = parsed;
|
|
281
291
|
// 清洗 meta 中的 file 字段:拒绝绝对路径/.. 穿越,防恶意 meta.json 写任意位置
|
|
@@ -290,7 +300,9 @@ class Database {
|
|
|
290
300
|
}
|
|
291
301
|
}
|
|
292
302
|
} catch (e) {
|
|
293
|
-
|
|
303
|
+
// #453:解析/解密失败不能静默清空注册表 —— 备份损坏文件、上报 error,
|
|
304
|
+
// 并从目录下的 .jsql 文件重建表登记,避免数据块文件全部成孤儿。
|
|
305
|
+
this._recoverMetaFromFiles(e);
|
|
294
306
|
}
|
|
295
307
|
for (const name of Object.keys(this._meta.tables)) {
|
|
296
308
|
if (this[name] === undefined && !(name in this)) {
|
|
@@ -339,6 +351,7 @@ class Database {
|
|
|
339
351
|
_saveMeta() {
|
|
340
352
|
if (!this._dirMode) return;
|
|
341
353
|
try {
|
|
354
|
+
let payload;
|
|
342
355
|
// #260:启用 encryptKey 时 meta.json 也落密文(表结构/字段名不外泄)
|
|
343
356
|
if (this._encryptKey) {
|
|
344
357
|
const iv = crypto.randomBytes(16);
|
|
@@ -347,20 +360,69 @@ class Database {
|
|
|
347
360
|
cipher.update(JSON.stringify(this._meta, null, 2), 'utf8'),
|
|
348
361
|
cipher.final(),
|
|
349
362
|
]);
|
|
350
|
-
|
|
363
|
+
payload = JSON.stringify({
|
|
351
364
|
__enc: 'v1',
|
|
352
365
|
iv: iv.toString('base64'),
|
|
353
366
|
data: enc.toString('base64'),
|
|
354
367
|
});
|
|
355
|
-
fs.writeFileSync(this._metaPath, payload, 'utf8');
|
|
356
368
|
} else {
|
|
357
|
-
|
|
369
|
+
payload = JSON.stringify(this._meta, null, 2);
|
|
358
370
|
}
|
|
371
|
+
// #453:与 _writeFile 一致的原子写 —— 先写临时文件 + fsync,再 rename
|
|
372
|
+
// 覆盖;崩溃只会留下旧 meta 或新 meta,不会出现写到一半的半份注册表。
|
|
373
|
+
const tmp = this._metaPath + '.tmp';
|
|
374
|
+
const fd = fs.openSync(tmp, 'w');
|
|
375
|
+
try {
|
|
376
|
+
fs.writeFileSync(fd, payload, 'utf8');
|
|
377
|
+
fs.fsyncSync(fd);
|
|
378
|
+
} finally {
|
|
379
|
+
fs.closeSync(fd);
|
|
380
|
+
}
|
|
381
|
+
fs.renameSync(tmp, this._metaPath);
|
|
359
382
|
} catch (e) {
|
|
360
383
|
// 忽略 meta 写入失败
|
|
361
384
|
}
|
|
362
385
|
}
|
|
363
386
|
|
|
387
|
+
/**
|
|
388
|
+
* #453:meta.json 解析/解密失败时的兜底。
|
|
389
|
+
*
|
|
390
|
+
* 此前 catch 直接把注册表重置为 `{version:1,tables:{}}` —— 表数据块
|
|
391
|
+
* 文件还在,引擎却再也找不到表,全部变成孤儿文件,且无任何告警。
|
|
392
|
+
* 这里:先备份损坏文件为 `meta.json.corrupt-<ts>`,再扫描目录下的
|
|
393
|
+
* `.jsql` 文件重建登记,并通过 error 事件对外上报损坏原因。
|
|
394
|
+
*/
|
|
395
|
+
_recoverMetaFromFiles(cause) {
|
|
396
|
+
let backedUp = false;
|
|
397
|
+
try {
|
|
398
|
+
if (fs.existsSync(this._metaPath)) {
|
|
399
|
+
const backup = this._metaPath + '.corrupt-' + Date.now();
|
|
400
|
+
fs.copyFileSync(this._metaPath, backup);
|
|
401
|
+
backedUp = true;
|
|
402
|
+
}
|
|
403
|
+
} catch (e) { /* 备份失败不阻断后续文件扫描 */ }
|
|
404
|
+
this._meta = { version: 1, tables: {} };
|
|
405
|
+
try {
|
|
406
|
+
const files = fs.readdirSync(this._filePath);
|
|
407
|
+
for (const file of files) {
|
|
408
|
+
if (!file.endsWith('.jsql')) continue;
|
|
409
|
+
if (!this._safeTableFile(file)) continue;
|
|
410
|
+
const name = decodeURIComponent(file.slice(0, -5));
|
|
411
|
+
this._meta.tables[name] = { file, schema: {} };
|
|
412
|
+
}
|
|
413
|
+
} catch (e) { /* 目录扫描失败:保持空注册表 */ }
|
|
414
|
+
const reason = cause && cause.message ? cause.message : String(cause);
|
|
415
|
+
const restored = Object.keys(this._meta.tables);
|
|
416
|
+
const err = new Error(
|
|
417
|
+
`meta.json is corrupt (${reason}); rebuilt registry from ${restored.length} table file(s)` +
|
|
418
|
+
(backedUp ? '' : '; corrupt file backup unavailable')
|
|
419
|
+
);
|
|
420
|
+
err.code = 'ER_META_CORRUPT';
|
|
421
|
+
this._metaCorrupt = { error: err.message, code: err.code, at: Date.now(), restored };
|
|
422
|
+
try { this._emit('error', err); } catch (_) { /* 监听器自身抛错不阻塞启动 */ }
|
|
423
|
+
console.error('[jsql-neo] ' + err.message);
|
|
424
|
+
}
|
|
425
|
+
|
|
364
426
|
/**
|
|
365
427
|
* 统一的「表不可用」错误。
|
|
366
428
|
*
|
|
@@ -506,9 +568,9 @@ class Database {
|
|
|
506
568
|
const fmt = new JSQLFormat(path.join(this._filePath, file), this._encryptKey);
|
|
507
569
|
let appendBlocks = 0;
|
|
508
570
|
try {
|
|
509
|
-
const written = fmt.writeRows(name, table.
|
|
571
|
+
const written = fmt.writeRows(name, table._persistedSchema(), dirty.upserts, dirty.deletes, table._primaryKey);
|
|
510
572
|
appendBlocks = fmt.nBlocks;
|
|
511
|
-
this._meta.tables[name] = { file, schema: table.
|
|
573
|
+
this._meta.tables[name] = { file, schema: table._persistedSchema() };
|
|
512
574
|
if (typeof table._applyFlushedLocators === 'function') {
|
|
513
575
|
if (written && written.length === dirty.upserts.length) {
|
|
514
576
|
table._applyFlushedLocators(dirty.upserts, written);
|
|
@@ -537,8 +599,8 @@ class Database {
|
|
|
537
599
|
let keepHandleOpen = false;
|
|
538
600
|
try {
|
|
539
601
|
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.
|
|
602
|
+
fmt.writeTable(name, table._persistedSchema(), table._rows, pkField);
|
|
603
|
+
this._meta.tables[name] = { file, schema: table._persistedSchema() };
|
|
542
604
|
// live 大表首次全量写完后挂上行级 LRU,让后续内存淘汰按行回退。
|
|
543
605
|
if (this._dirMode && !table._rowCache && table._rows.length >= ROW_CACHE_MIN_ROWS) {
|
|
544
606
|
const locators = fmt.scanLocators(name);
|
|
@@ -659,6 +721,11 @@ class Database {
|
|
|
659
721
|
*/
|
|
660
722
|
_walWrite(op) {
|
|
661
723
|
if (!this._walEnabled || this._loading) return;
|
|
724
|
+
// #446:活动事务内产生的写入打上事务标签,回放时按 commit 帧判定是否可见。
|
|
725
|
+
if (op.tx === undefined) {
|
|
726
|
+
const tag = this._currentTxTag();
|
|
727
|
+
if (tag !== null) op.tx = tag;
|
|
728
|
+
}
|
|
662
729
|
const entry = {
|
|
663
730
|
...op,
|
|
664
731
|
timestamp: Date.now(),
|
|
@@ -721,11 +788,11 @@ class Database {
|
|
|
721
788
|
_maybeCheckpointWAL() {
|
|
722
789
|
if (!this._walEnabled || this._walCheckpointScheduled) return;
|
|
723
790
|
if (this._walCheckpointOps <= 0 || this._walOpCount < this._walCheckpointOps) return;
|
|
724
|
-
if (this._loading || this._walReplaying || this.
|
|
791
|
+
if (this._loading || this._walReplaying || this.hasActiveTx()) return;
|
|
725
792
|
this._walCheckpointScheduled = true;
|
|
726
793
|
const run = () => {
|
|
727
794
|
this._walCheckpointScheduled = false;
|
|
728
|
-
if (this._loading || this._walReplaying || this.
|
|
795
|
+
if (this._loading || this._walReplaying || this.hasActiveTx()) return;
|
|
729
796
|
try {
|
|
730
797
|
this.save();
|
|
731
798
|
} catch (e) {
|
|
@@ -888,6 +955,17 @@ class Database {
|
|
|
888
955
|
|
|
889
956
|
this._walReplaying = true;
|
|
890
957
|
let replayed = 0, failed = 0;
|
|
958
|
+
// #446:按事务帧聚合回放。先扫描出所有带 commit 帧的事务标签;
|
|
959
|
+
// 缺少 commit 帧(崩溃时未闭合)的事务,其行变更在恢复时整体丢弃,
|
|
960
|
+
// 保证 kill -9 后未提交的脏写不会随 WAL 回放复活。
|
|
961
|
+
const committedTx = new Set();
|
|
962
|
+
for (const op of ops) {
|
|
963
|
+
if (op.op === 'commit' && op.tx !== undefined && op.tx !== null) {
|
|
964
|
+
committedTx.add(String(op.tx));
|
|
965
|
+
}
|
|
966
|
+
}
|
|
967
|
+
const TX_MARKERS = new Set(['begin', 'commit', 'rollback', 'rollbackTo', 'savepoint', 'undo', 'restore', 'import']);
|
|
968
|
+
const DATA_OPS = new Set(['insert', 'update', 'remove', 'upsertRows', 'removeRows', 'replaceTable']);
|
|
891
969
|
try {
|
|
892
970
|
// 逐条按 sequence 顺序回放,保证 insert→update→remove 的相对次序。
|
|
893
971
|
// insert 不走 _loadRows()(那是整体替换语义),而是直接 push 到 _rows,
|
|
@@ -895,6 +973,11 @@ class Database {
|
|
|
895
973
|
const touched = new Set();
|
|
896
974
|
for (const op of ops) {
|
|
897
975
|
try {
|
|
976
|
+
// 事务标记帧本身不改数据状态,回放时跳过。
|
|
977
|
+
if (TX_MARKERS.has(op.op)) continue;
|
|
978
|
+
// 未闭合事务的行变更:整批丢弃,不落可见行。
|
|
979
|
+
if (DATA_OPS.has(op.op) && op.tx !== undefined && op.tx !== null
|
|
980
|
+
&& !committedTx.has(String(op.tx))) continue;
|
|
898
981
|
switch (op.op) {
|
|
899
982
|
case 'insert': {
|
|
900
983
|
// #259:目录模式下表是懒加载的(_tables 里可能还没有),
|
|
@@ -1389,6 +1472,11 @@ class Database {
|
|
|
1389
1472
|
return { ...(this._corruptTables || {}) };
|
|
1390
1473
|
}
|
|
1391
1474
|
|
|
1475
|
+
/** #453:meta.json 损坏后兜底恢复的排障记录(未损坏时为 null)。 */
|
|
1476
|
+
getMetaCorruption() {
|
|
1477
|
+
return this._metaCorrupt ? { ...this._metaCorrupt } : null;
|
|
1478
|
+
}
|
|
1479
|
+
|
|
1392
1480
|
getTableSchema(name) {
|
|
1393
1481
|
const table = this._ensureTable(name);
|
|
1394
1482
|
if (table) return table._schema;
|
|
@@ -1494,6 +1582,9 @@ class Database {
|
|
|
1494
1582
|
const hasHeader = options.hasHeader !== false;
|
|
1495
1583
|
const skipRows = options.skipRows || 0;
|
|
1496
1584
|
const mapping = options.mapping || null;
|
|
1585
|
+
// #455:strict 模式下不可解析的类型值直接抛错;默认降级为 warnings 并跳过该行,
|
|
1586
|
+
// 不再把非数值整数静默置 0、非真值布尔静默置 false。
|
|
1587
|
+
const strict = options.strict === true;
|
|
1497
1588
|
|
|
1498
1589
|
const content = fs.readFileSync(filePath, 'utf8');
|
|
1499
1590
|
// #184:RFC 4180 允许引号字段内出现换行,不能先按行切分
|
|
@@ -1509,34 +1600,46 @@ class Database {
|
|
|
1509
1600
|
startRow = skipRows;
|
|
1510
1601
|
}
|
|
1511
1602
|
|
|
1603
|
+
const warnings = [];
|
|
1512
1604
|
let count = 0;
|
|
1513
1605
|
for (let i = startRow; i < records.length; i++) {
|
|
1514
1606
|
const values = records[i];
|
|
1515
1607
|
if (values.length === 0) continue;
|
|
1516
1608
|
|
|
1517
1609
|
const data = {};
|
|
1610
|
+
const castCtx = { warnings, row: i };
|
|
1518
1611
|
if (mapping) {
|
|
1519
1612
|
for (const [csvCol, schemaCol] of Object.entries(mapping)) {
|
|
1520
1613
|
const idx = hasHeader ? headers.indexOf(csvCol) : parseInt(csvCol);
|
|
1521
1614
|
if (idx >= 0 && idx < values.length) {
|
|
1522
|
-
data[schemaCol] = this._castValue(values[idx], table._schema[schemaCol]);
|
|
1615
|
+
data[schemaCol] = this._castValue(values[idx], table._schema[schemaCol], { ...castCtx, field: schemaCol });
|
|
1523
1616
|
}
|
|
1524
1617
|
}
|
|
1525
1618
|
} else if (hasHeader) {
|
|
1526
1619
|
for (let j = 0; j < headers.length; j++) {
|
|
1527
1620
|
if (j < values.length && table._schema[headers[j]]) {
|
|
1528
|
-
data[headers[j]] = this._castValue(values[j], table._schema[headers[j]]);
|
|
1621
|
+
data[headers[j]] = this._castValue(values[j], table._schema[headers[j]], { ...castCtx, field: headers[j] });
|
|
1529
1622
|
}
|
|
1530
1623
|
}
|
|
1531
1624
|
}
|
|
1532
1625
|
|
|
1533
1626
|
if (Object.keys(data).length > 0) {
|
|
1534
|
-
|
|
1535
|
-
|
|
1627
|
+
try {
|
|
1628
|
+
table.insert(data);
|
|
1629
|
+
count++;
|
|
1630
|
+
} catch (e) {
|
|
1631
|
+
if (strict) throw e;
|
|
1632
|
+
warnings.push({
|
|
1633
|
+
row: i,
|
|
1634
|
+
code: e.code || e.errno || 'ER_TRUNCATED_WRONG_VALUE',
|
|
1635
|
+
message: e.message,
|
|
1636
|
+
});
|
|
1637
|
+
}
|
|
1536
1638
|
}
|
|
1537
1639
|
}
|
|
1538
1640
|
|
|
1539
|
-
|
|
1641
|
+
// 与 migrate 路径一致:返回 { count, warnings },告警随结果带回上层
|
|
1642
|
+
return { count, warnings };
|
|
1540
1643
|
}
|
|
1541
1644
|
|
|
1542
1645
|
/**
|
|
@@ -1629,12 +1732,39 @@ class Database {
|
|
|
1629
1732
|
return value;
|
|
1630
1733
|
}
|
|
1631
1734
|
|
|
1632
|
-
_castValue(value, schemaDef) {
|
|
1633
|
-
if (!schemaDef
|
|
1634
|
-
|
|
1635
|
-
|
|
1636
|
-
|
|
1637
|
-
|
|
1735
|
+
_castValue(value, schemaDef, ctx) {
|
|
1736
|
+
if (!schemaDef) return value;
|
|
1737
|
+
// 空字段 / NULL:语义与此前一致,不参与类型转换
|
|
1738
|
+
if (value === null || value === undefined || value === '') return value;
|
|
1739
|
+
const type = String(schemaDef.type || '').toLowerCase();
|
|
1740
|
+
const raw = String(value).trim();
|
|
1741
|
+
switch (type) {
|
|
1742
|
+
case 'integer':
|
|
1743
|
+
case 'int':
|
|
1744
|
+
case 'bigint': {
|
|
1745
|
+
// #455:不再 `parseInt(...) || 0` 把解析失败吞成 0;非法整数值记入告警并保留原值,
|
|
1746
|
+
// 由表校验层拒绝(strict 模式下 importCSV 直接抛错)。
|
|
1747
|
+
if (/^[+-]?\d+$/.test(raw)) return parseInt(raw, 10);
|
|
1748
|
+
this._recordCastWarning(ctx, type, value);
|
|
1749
|
+
return value;
|
|
1750
|
+
}
|
|
1751
|
+
case 'number':
|
|
1752
|
+
case 'float':
|
|
1753
|
+
case 'double':
|
|
1754
|
+
case 'real':
|
|
1755
|
+
case 'decimal': {
|
|
1756
|
+
if (raw !== '' && !Number.isNaN(Number(raw))) return Number(raw);
|
|
1757
|
+
this._recordCastWarning(ctx, type, value);
|
|
1758
|
+
return value;
|
|
1759
|
+
}
|
|
1760
|
+
case 'boolean': {
|
|
1761
|
+
// #455:只识别规范真值/假值;其余不可识别的值不再一律归 false,记入告警并保留原值。
|
|
1762
|
+
const low = raw.toLowerCase();
|
|
1763
|
+
if (low === 'true' || low === '1') return true;
|
|
1764
|
+
if (low === 'false' || low === '0') return false;
|
|
1765
|
+
this._recordCastWarning(ctx, type, value);
|
|
1766
|
+
return value;
|
|
1767
|
+
}
|
|
1638
1768
|
case 'array': try { return JSON.parse(value); } catch(e) { return [value]; }
|
|
1639
1769
|
case 'object': try { return JSON.parse(value); } catch(e) { return {}; }
|
|
1640
1770
|
case 'date':
|
|
@@ -1646,6 +1776,17 @@ class Database {
|
|
|
1646
1776
|
}
|
|
1647
1777
|
}
|
|
1648
1778
|
|
|
1779
|
+
_recordCastWarning(ctx, type, value) {
|
|
1780
|
+
if (!ctx || !Array.isArray(ctx.warnings)) return;
|
|
1781
|
+
ctx.warnings.push({
|
|
1782
|
+
row: ctx.row,
|
|
1783
|
+
field: ctx.field,
|
|
1784
|
+
type,
|
|
1785
|
+
value: String(value),
|
|
1786
|
+
message: `Truncated incorrect ${type} value: '${value}'`,
|
|
1787
|
+
});
|
|
1788
|
+
}
|
|
1789
|
+
|
|
1649
1790
|
// ============================================================
|
|
1650
1791
|
// 数据库统计
|
|
1651
1792
|
// ============================================================
|
|
@@ -1827,8 +1968,25 @@ class Database {
|
|
|
1827
1968
|
_restoreTxSnapshot(snap) {
|
|
1828
1969
|
if (!snap) return;
|
|
1829
1970
|
for (const name of Object.keys(this._tables)) {
|
|
1830
|
-
if (
|
|
1971
|
+
if (snap[name]) continue;
|
|
1972
|
+
// #452:事务内 CREATE TABLE 回滚必须彻底撤销。目录模式下只删内存
|
|
1973
|
+
// 表对象会留下 meta 登记与 .jsql 文件,重开后被回滚的表连同未提交
|
|
1974
|
+
// 行一起复活。这里与 _dropTableSync 对齐:清 meta 登记、删表文件、
|
|
1975
|
+
// 摘掉访问器与表名登记。
|
|
1976
|
+
if (this._dirMode) {
|
|
1977
|
+
const meta = this._meta.tables[name];
|
|
1978
|
+
if (meta && meta.file) {
|
|
1979
|
+
try { fs.unlinkSync(path.join(this._filePath, meta.file)); } catch (e) { /* 文件已不存在 */ }
|
|
1980
|
+
}
|
|
1981
|
+
delete this._meta.tables[name];
|
|
1982
|
+
this._dirtyTables.delete(name);
|
|
1983
|
+
}
|
|
1984
|
+
delete this[name];
|
|
1985
|
+
delete this._versions[name];
|
|
1986
|
+
this._tableNames.delete(name);
|
|
1987
|
+
delete this._tables[name];
|
|
1831
1988
|
}
|
|
1989
|
+
if (this._dirMode) this._saveMeta();
|
|
1832
1990
|
for (const [name, entry] of Object.entries(snap)) {
|
|
1833
1991
|
const rows = bigintJson.parse(bigintJson.stringify(entry.rows));
|
|
1834
1992
|
const prev = this._tables[name];
|
|
@@ -1866,6 +2024,16 @@ class Database {
|
|
|
1866
2024
|
return (this._txId !== undefined && !!this._txSnapshot) || !!this._transaction;
|
|
1867
2025
|
}
|
|
1868
2026
|
|
|
2027
|
+
/**
|
|
2028
|
+
* 当前活动事务的 WAL 标签(beginTx 路径用 `tx<n>`,begin 路径用 `b<n>`)。
|
|
2029
|
+
* 无活动事务时返回 null —— 旧 WAL / 自动提交的写入不带事务标记,回放时视为已提交。
|
|
2030
|
+
*/
|
|
2031
|
+
_currentTxTag() {
|
|
2032
|
+
if (this._txId !== undefined && this._txSnapshot) return 'tx' + this._txId;
|
|
2033
|
+
if (this._transaction && this._transaction.txTag) return this._transaction.txTag;
|
|
2034
|
+
return null;
|
|
2035
|
+
}
|
|
2036
|
+
|
|
1869
2037
|
/** 保存点栈(懒建),随事务结束清空 */
|
|
1870
2038
|
_savepointStackRef() {
|
|
1871
2039
|
if (!this._savepointStack) this._savepointStack = [];
|
|
@@ -1881,11 +2049,13 @@ class Database {
|
|
|
1881
2049
|
|
|
1882
2050
|
const level = isolationLevel || this._isolationLevel;
|
|
1883
2051
|
|
|
2052
|
+
this._txFrameSeq = (this._txFrameSeq || 0) + 1;
|
|
1884
2053
|
this._transaction = {
|
|
1885
2054
|
snapshot: null,
|
|
1886
2055
|
autoIncrements: {},
|
|
1887
2056
|
level,
|
|
1888
|
-
startedAt: Date.now()
|
|
2057
|
+
startedAt: Date.now(),
|
|
2058
|
+
txTag: 'b' + this._txFrameSeq
|
|
1889
2059
|
};
|
|
1890
2060
|
|
|
1891
2061
|
if (level === 'REPEATABLE_READ') {
|
|
@@ -1901,12 +2071,12 @@ class Database {
|
|
|
1901
2071
|
}
|
|
1902
2072
|
|
|
1903
2073
|
this._savepointStack = [];
|
|
1904
|
-
this._walWrite({ op: 'begin', level });
|
|
2074
|
+
this._walWrite({ op: 'begin', tx: this._transaction.txTag, level });
|
|
1905
2075
|
}
|
|
1906
2076
|
|
|
1907
2077
|
commit() {
|
|
1908
2078
|
if (!this._transaction) throw createError('ER_NO_TRANSACTION');
|
|
1909
|
-
this._walWrite({ op: 'commit', at: this._transaction.startedAt });
|
|
2079
|
+
this._walWrite({ op: 'commit', tx: this._transaction.txTag, at: this._transaction.startedAt });
|
|
1910
2080
|
// 提交即释放全部保存点 —— 它们随事务一起结束
|
|
1911
2081
|
this._transaction = null;
|
|
1912
2082
|
this._savepointStack = [];
|
|
@@ -1933,7 +2103,7 @@ class Database {
|
|
|
1933
2103
|
}
|
|
1934
2104
|
}
|
|
1935
2105
|
|
|
1936
|
-
this._walWrite({ op: 'rollback', at: this._transaction.startedAt });
|
|
2106
|
+
this._walWrite({ op: 'rollback', tx: this._transaction.txTag, at: this._transaction.startedAt });
|
|
1937
2107
|
this._transaction = null;
|
|
1938
2108
|
this._savepointStack = [];
|
|
1939
2109
|
this._markDirtyLegacy();
|
|
@@ -2025,7 +2195,7 @@ class Database {
|
|
|
2025
2195
|
}
|
|
2026
2196
|
|
|
2027
2197
|
inTransaction() {
|
|
2028
|
-
return
|
|
2198
|
+
return this.hasActiveTx();
|
|
2029
2199
|
}
|
|
2030
2200
|
|
|
2031
2201
|
/**
|
|
@@ -2931,7 +3101,7 @@ class Database {
|
|
|
2931
3101
|
for (const [name, table] of Object.entries(this._tables)) {
|
|
2932
3102
|
if (name === '__meta__') continue;
|
|
2933
3103
|
const pkField = Object.keys(table._schema).find(f => table._schema[f].primaryKey);
|
|
2934
|
-
all[name] = { schema: table.
|
|
3104
|
+
all[name] = { schema: table._persistedSchema(), rows: table._rows, pkField };
|
|
2935
3105
|
}
|
|
2936
3106
|
this._jsqlFormat.saveAll(all);
|
|
2937
3107
|
this._jsqlFormat._close();
|
|
@@ -2943,7 +3113,7 @@ class Database {
|
|
|
2943
3113
|
const data = { __schema__: {}, __meta__: { version: this._getCurrentVersion() } };
|
|
2944
3114
|
for (const [name, table] of Object.entries(this._tables)) {
|
|
2945
3115
|
if (name === '__meta__') continue;
|
|
2946
|
-
data.__schema__[name] = table.
|
|
3116
|
+
data.__schema__[name] = table._persistedSchema();
|
|
2947
3117
|
data[name] = table.toJSON();
|
|
2948
3118
|
}
|
|
2949
3119
|
|
|
@@ -3089,10 +3259,12 @@ class Database {
|
|
|
3089
3259
|
// 否则 rollbackTx 还原不了保存点存下来的快照(反之亦然)。
|
|
3090
3260
|
this._txSnapshot = this._captureTxSnapshot();
|
|
3091
3261
|
this._txId = (this._txId || 0) + 1;
|
|
3262
|
+
this._walWrite({ op: 'begin', tx: 'tx' + this._txId });
|
|
3092
3263
|
return this._txId;
|
|
3093
3264
|
}
|
|
3094
3265
|
|
|
3095
3266
|
async commitTx() {
|
|
3267
|
+
this._walWrite({ op: 'commit', tx: 'tx' + this._txId });
|
|
3096
3268
|
this._txSnapshot = null;
|
|
3097
3269
|
this._txId = undefined;
|
|
3098
3270
|
this._savepointStack = []; // 提交即释放全部保存点
|
|
@@ -3105,6 +3277,7 @@ class Database {
|
|
|
3105
3277
|
|
|
3106
3278
|
async rollbackTx() {
|
|
3107
3279
|
const snap = this._txSnapshot;
|
|
3280
|
+
this._walWrite({ op: 'rollback', tx: 'tx' + this._txId });
|
|
3108
3281
|
this._txSnapshot = null;
|
|
3109
3282
|
this._txId = undefined;
|
|
3110
3283
|
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)" },
|
package/lib/migrate.js
CHANGED
|
@@ -249,6 +249,7 @@ async function importFromJSON(engine, data, opts = {}) {
|
|
|
249
249
|
}
|
|
250
250
|
const created = [];
|
|
251
251
|
let inserted = 0;
|
|
252
|
+
const result = { created, inserted };
|
|
252
253
|
for (const [name, t] of Object.entries(tables)) {
|
|
253
254
|
if (!t || !t.schema) continue;
|
|
254
255
|
if (engine.hasTable(name)) {
|
|
@@ -258,16 +259,33 @@ async function importFromJSON(engine, data, opts = {}) {
|
|
|
258
259
|
await engine.createTable(name, normalizeSchema(t.schema));
|
|
259
260
|
created.push(name);
|
|
260
261
|
if (Array.isArray(t.rows) && t.rows.length > 0) {
|
|
262
|
+
// #454:只保留目标 schema 内的列,schema 外的幽灵字段不得写进存储行。
|
|
263
|
+
const schemaCols = new Set(Object.keys(normalizeSchema(t.schema)));
|
|
264
|
+
const ghostCols = new Set();
|
|
261
265
|
// 分块 insert —— 避免全量 rows.map 先攒再 insert
|
|
262
266
|
const chunkSize = opts.chunkSize != null ? opts.chunkSize : DEFAULT_CHUNK_SIZE;
|
|
263
267
|
for (let i = 0; i < t.rows.length; i += chunkSize) {
|
|
264
|
-
const chunk = t.rows.slice(i, i + chunkSize).map(r =>
|
|
268
|
+
const chunk = t.rows.slice(i, i + chunkSize).map(r => {
|
|
269
|
+
const out = {};
|
|
270
|
+
for (const k of Object.keys(r)) {
|
|
271
|
+
if (schemaCols.has(k)) out[k] = r[k];
|
|
272
|
+
else ghostCols.add(k);
|
|
273
|
+
}
|
|
274
|
+
return out;
|
|
275
|
+
});
|
|
265
276
|
const ids = await engine.insert(name, chunk);
|
|
266
277
|
inserted += Array.isArray(ids) ? ids.length : chunk.length;
|
|
267
278
|
}
|
|
279
|
+
if (ghostCols.size > 0) {
|
|
280
|
+
(result.warnings = result.warnings || []).push({
|
|
281
|
+
kind: 'unknownColumn',
|
|
282
|
+
columns: [...ghostCols].slice(0, 50)
|
|
283
|
+
});
|
|
284
|
+
if (opts.strictColumns) throw new Error(`importFromJSON: columns not in schema: ${[...ghostCols].join(', ')}`);
|
|
285
|
+
}
|
|
268
286
|
}
|
|
269
287
|
}
|
|
270
|
-
return
|
|
288
|
+
return result;
|
|
271
289
|
}
|
|
272
290
|
|
|
273
291
|
/* ---------- CSV ---------- */
|
|
@@ -301,6 +319,9 @@ async function importFromCSV(engine, table, csv, opts = {}) {
|
|
|
301
319
|
}
|
|
302
320
|
await engine.createTable(table, normalizeSchema(schema));
|
|
303
321
|
}
|
|
322
|
+
// #454:按目标表 schema 做白名单投影;schema 外的未知列不得写进存储行。
|
|
323
|
+
const liveSchema = schema || await engine.getTableSchema(table);
|
|
324
|
+
const schemaCols = liveSchema ? new Set(Object.keys(liveSchema)) : new Set();
|
|
304
325
|
const chunkSize = opts.chunkSize != null ? opts.chunkSize : DEFAULT_CHUNK_SIZE;
|
|
305
326
|
let inserted = 0;
|
|
306
327
|
// #362:行宽与表头不一致此前完全静默 —— 多出来的字段被丢掉,缺的列补 NULL,
|
|
@@ -320,7 +341,13 @@ async function importFromCSV(engine, table, csv, opts = {}) {
|
|
|
320
341
|
}
|
|
321
342
|
const row = {};
|
|
322
343
|
for (let j = 0; j < columns.length; j++) {
|
|
323
|
-
|
|
344
|
+
if (liveSchema && !schemaCols.has(columns[j])) {
|
|
345
|
+
// #454:schema 外的幽灵列丢弃,记入 warnings(与 #362 行宽告警同一通道)。
|
|
346
|
+
if (warnings.length < 50) warnings.push({ row: rowNo, kind: 'unknownColumn', column: columns[j] });
|
|
347
|
+
if (opts.strictColumns) throw new Error(`CSV row ${rowNo}: column '${columns[j]}' is not in table schema`);
|
|
348
|
+
continue;
|
|
349
|
+
}
|
|
350
|
+
const type = liveSchema && liveSchema[columns[j]] ? liveSchema[columns[j]].type : 'string';
|
|
324
351
|
row[columns[j]] = parseValue(raw[j], type);
|
|
325
352
|
}
|
|
326
353
|
if (row.id === null || row.id === undefined || row.id === '') delete row.id;
|