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/lib/table.js CHANGED
@@ -1118,15 +1118,36 @@ class Table {
1118
1118
 
1119
1119
  restore(query = {}) {
1120
1120
  if (!this._softDelete) throw createError('ER_NOT_SUPPORTED', 'Soft delete is not enabled');
1121
- const matched = this._applyFilter(this._rows, { ...query, _deleted: true });
1121
+ // #450:restore 要匹配的恰恰是被可见性过滤跳过的 _deleted 行;
1122
+ // _applyFilter 在软删除模式下先剔除所有 _deleted 行,走它恒匹配为空。
1123
+ // 这里直接在全量行上按 query 匹配软删除行,再对称地撤下索引、清标记、重新登记。
1124
+ const match = this._compileMatcher(query);
1125
+ const matched = [];
1126
+ for (const row of this._rows) {
1127
+ if (!row._deleted) continue;
1128
+ if (match(row)) matched.push(row);
1129
+ }
1130
+ let count = 0;
1122
1131
  for (const row of matched) {
1123
1132
  const index = this._rows.indexOf(row);
1124
- if (index !== -1) {
1125
- delete this._rows[index]._deleted;
1126
- delete this._rows[index]._deletedAt;
1133
+ if (index === -1) continue;
1134
+ this._removeFromIndexes(index, row);
1135
+ delete row._deleted;
1136
+ delete row._deletedAt;
1137
+ this._addToIndexes(index, row);
1138
+ count++;
1139
+ }
1140
+ if (count > 0) {
1141
+ this._dirty = true;
1142
+ this._db._markDirty(this._name);
1143
+ for (const hook of this._hooks.afterRemove) {
1144
+ hook(query, count);
1127
1145
  }
1146
+ this._db._emitChange('restore', this._name, { query, count });
1147
+ this._db._walLogUpsert(this._name, matched);
1148
+ for (const row of matched) this._markRowDirty(row);
1128
1149
  }
1129
- return matched.length;
1150
+ return count;
1130
1151
  }
1131
1152
 
1132
1153
  truncate() {
@@ -1368,6 +1389,22 @@ class Table {
1368
1389
  };
1369
1390
  }
1370
1391
 
1392
+ /**
1393
+ * #451:落盘用的 schema 快照。复合唯一组不落在任何单列定义里,
1394
+ * 必须随 schema 一起持久化(meta / jsql 头 / legacy 快照),
1395
+ * 否则重启后 _uniqueIndexes 为空、重复组合键被静默接受。
1396
+ * 重载时构造器从 schema.__uniqueGroups__ 重建 _uniqueIndexes。
1397
+ */
1398
+ _persistedSchema() {
1399
+ const out = { ...this._schema };
1400
+ const groups = (this._uniqueIndexes || [])
1401
+ .filter(u => u.columns && u.columns.length >= 2 && u.name !== 'PRIMARY')
1402
+ .map(u => u.columns.slice());
1403
+ if (groups.length > 0) out.__uniqueGroups__ = groups;
1404
+ else delete out.__uniqueGroups__;
1405
+ return out;
1406
+ }
1407
+
1371
1408
  selectInto(newTableName, newSchema, query = {}) {
1372
1409
  const rows = this._applyFilterOptimized(this._getVisibleRows(), query);
1373
1410
  this._db.createTable(newTableName, newSchema);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "jsql-neo",
3
- "version": "6.8.26",
3
+ "version": "6.9.0",
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,7 +52,7 @@
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 && node test/issue-259-264.test.js && node test/issue-255-270.test.js && node test/issue-253-269.test.js && node test/issue-280-310.test.js && node test/issue-272-311.test.js && node test/issue-279-306.test.js && node test/issue-271-283.test.js && node test/issue-265-307.test.js && node test/issue-258-300.test.js && node test/issue-247-295-277.test.js && node test/issue-322-325.test.js && node test/issue-357-365.test.js && node test/issue-372-387.test.js && node test/issue-383-402.test.js && node test/issue-369-394.test.js && node test/issue-352-386.test.js && node test/issue-395-430.test.js && node test/btree.test.js && node test/regress-5.1.0.js && node test/native-multi-instance.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/savepoint.test.js && node test/alter-table.test.js && node test/null-semantics.test.js && node test/identifier-keywords.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/coverage.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/savepoint.test.js && node test/alter-table.test.js && node test/identifier-keywords.test.js && node test/null-semantics.test.js && node test/sql-semantics.test.js && node test/filter-compile.test.js && node test/compat-v1.test.js && node test/issue-327-418.test.js && node test/issue-341-419.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 && node test/issue-255-270.test.js && node test/issue-253-269.test.js && node test/issue-280-310.test.js && node test/issue-272-311.test.js && node test/issue-279-306.test.js && node test/issue-271-283.test.js && node test/issue-265-307.test.js && node test/issue-258-300.test.js && node test/issue-247-295-277.test.js && node test/issue-322-325.test.js && node test/issue-357-365.test.js && node test/issue-372-387.test.js && node test/issue-383-402.test.js && node test/issue-369-394.test.js && node test/issue-352-386.test.js && node test/issue-395-430.test.js && node test/btree.test.js && node test/regress-5.1.0.js && node test/native-multi-instance.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/savepoint.test.js && node test/alter-table.test.js && node test/null-semantics.test.js && node test/identifier-keywords.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/coverage.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/savepoint.test.js && node test/alter-table.test.js && node test/identifier-keywords.test.js && node test/null-semantics.test.js && node test/sql-semantics.test.js && node test/filter-compile.test.js && node test/compat-v1.test.js && node test/issue-327-418.test.js && node test/issue-341-419.test.js && node test/issue-450-454.test.js && node test/issue-445-449.test.js && node test/issue-460-464.test.js && node test/issue-455-459.test.js && node test/issue-465-469.test.js && node test/issue-471.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",
@@ -121,7 +121,8 @@ const norm = (rows) => JSON.stringify(
121
121
  const a1 = await db.query('SELECT SUM(score) AS total FROM t');
122
122
  ok('聚合别名保留', a1.columns[0] === 'total', a1.columns);
123
123
  const a2 = await db.query('SELECT COUNT(*) FROM t');
124
- ok('无别名时列名保持 FN() 形式', a2.columns[0] === 'COUNT()', a2.columns);
124
+ // #469:列存快路径列名与行存一致 —— 保留 `*`,不再退化为 COUNT()。
125
+ ok('无别名时列名与行存一致(COUNT(*))', a2.columns[0] === 'COUNT(*)', a2.columns);
125
126
 
126
127
  console.log(`\n${pass} passed, ${fail} failed`);
127
128
  process.exit(fail === 0 ? 0 : 1);
@@ -36,7 +36,10 @@ function tmpdir(prefix) {
36
36
  await db.insert('t', { id: 1, v: 'hello-wal' });
37
37
  const wal = dir + '.wal';
38
38
  ok('目录模式 WAL 文件已落盘', fs.existsSync(wal), wal);
39
- // 不 flush/close —— 模拟后台刷盘前进程崩溃
39
+ // 不 flush/close —— 模拟后台刷盘前进程崩溃。
40
+ // #449:目录模式现在持有目录级文件锁,进程崩溃后由 OS 释放锁;
41
+ // 同进程内重开前需显式释放首个实例持有的锁,模拟崩溃后的锁清理。
42
+ db._releaseLock();
40
43
  const db2 = new Database(dir, { mode: 'disk', wal: true, flushInterval: 1e9 });
41
44
  ok('重开后 WAL 被回放(replayed > 0)',
42
45
  db2._walReplaySummary && db2._walReplaySummary.replayed > 0, db2._walReplaySummary);
@@ -52,6 +55,7 @@ function tmpdir(prefix) {
52
55
  const db = new Database(dir, { mode: 'hybrid', wal: true, flushInterval: 1e9 });
53
56
  await db.createTable('h', { id: { type: 'integer', primaryKey: true }, v: { type: 'string' } });
54
57
  await db.insert('h', { id: 1, v: 'hyb' });
58
+ db._releaseLock();
55
59
  const db2 = new Database(dir, { mode: 'hybrid', wal: true, flushInterval: 1e9 });
56
60
  const rows = await db2.find('h', {});
57
61
  ok('hybrid 模式 WAL 回放同样生效',
@@ -64,8 +64,9 @@ function opMsg(doc) {
64
64
  {
65
65
  const srv = createMongoServer({ dataDir: ':memory:' });
66
66
  await new Promise((r) => srv.listen(r));
67
+ const port = srv._server.address().port;
67
68
  const call = (doc) => new Promise((res) => {
68
- const s = net.connect(srv._server.address().port, '127.0.0.1', () => s.write(opMsg(doc)));
69
+ const s = net.connect(port, '127.0.0.1', () => s.write(opMsg(doc)));
69
70
  const c = [];
70
71
  s.on('data', (d) => {
71
72
  c.push(d);
@@ -73,6 +74,20 @@ function opMsg(doc) {
73
74
  if (b.length >= 16 && b.length >= b.readInt32LE(0)) { res(bsonReadDocument(b.slice(21), 0).value); s.end(); }
74
75
  });
75
76
  });
77
+ // #459:游标绑定创建连接,find/getMore 必须走同一条 socket
78
+ const callOn = (sock, doc) => new Promise((res) => {
79
+ const c = [];
80
+ const onData = (d) => {
81
+ c.push(d);
82
+ const b = Buffer.concat(c);
83
+ if (b.length >= 16 && b.length >= b.readInt32LE(0)) {
84
+ sock.removeListener('data', onData);
85
+ res(bsonReadDocument(b.slice(21), 0).value);
86
+ }
87
+ };
88
+ sock.on('data', onData);
89
+ sock.write(opMsg(doc));
90
+ });
76
91
  await call({ insert: 'af', documents: [{ n: 1 }, { n: 2 }], $db: 'test' });
77
92
  const add = await call({ aggregate: 'af', pipeline: [{ $addFields: { z: 5 } }], cursor: {}, $db: 'test' });
78
93
  ok('#328 $addFields 保留原字段并新增字段',
@@ -83,14 +98,16 @@ function opMsg(doc) {
83
98
  const bogus = await call({ aggregate: 'af', pipeline: [{ $bogus: {} }], cursor: {}, $db: 'test' });
84
99
  ok('#328 未知 stage 仍报 40324', bogus.ok === 0 && bogus.code === 40324, bogus);
85
100
 
86
- // #339 getMore 支持扩展 JSON 的 $numberLong 游标 id
87
- await call({ insert: 'cur', documents: [{ n: 1 }, { n: 2 }, { n: 3 }], $db: 'test' });
88
- const find = await call({ find: 'cur', batchSize: 2, $db: 'test' });
101
+ // #339 getMore 支持扩展 JSON 的 $numberLong 游标 id(find/getMore 同一连接)
102
+ const sock = net.connect(port, '127.0.0.1');
103
+ await callOn(sock, { insert: 'cur', documents: [{ n: 1 }, { n: 2 }, { n: 3 }], $db: 'test' });
104
+ const find = await callOn(sock, { find: 'cur', batchSize: 2, $db: 'test' });
89
105
  const rawId = find.cursor.id;
90
106
  const id = rawId && typeof rawId === 'object' ? (rawId.$long ?? rawId.$numberLong) : rawId;
91
- const more = await call({ getMore: { $numberLong: String(id) }, collection: 'cur', batchSize: 2, $db: 'test' });
107
+ const more = await callOn(sock, { getMore: { $numberLong: String(id) }, collection: 'cur', batchSize: 2, $db: 'test' });
92
108
  ok('#339 getMore 接受 $numberLong 形态游标 id',
93
109
  more.ok === 1 && more.cursor && more.cursor.nextBatch.length === 1, more);
110
+ sock.end();
94
111
  srv.close();
95
112
  }
96
113
 
@@ -0,0 +1,271 @@
1
+ /*
2
+ * Regression tests for issues #445–#449.
3
+ * node test/issue-445-449.test.js
4
+ *
5
+ * 覆盖:
6
+ * #445 递归 CTE 递归项内 JOIN 自引用不展开(INNER / LEFT JOIN 层级遍历)
7
+ * #446 未提交事务写入经 WAL 在 SIGKILL 后回放复活(真实子进程崩溃重启)
8
+ * #447 活动 beginTx 期间自动 checkpoint 固化未提交行
9
+ * #448 窗口聚合静默丢弃 DISTINCT
10
+ * #449 disk/hybrid 目录模式从不获取文件锁
11
+ *
12
+ * 用例断言用户可见行为:SQL 结果、恢复后行集、错误码/错误消息、实例打开结果,
13
+ * 不直接断言内部字段。
14
+ */
15
+ const fs = require('fs');
16
+ const os = require('os');
17
+ const path = require('path');
18
+ const { spawnSync } = require('child_process');
19
+
20
+ const ROOT = path.join(__dirname, '..');
21
+ const { Database } = require(path.join(ROOT, 'index.js'));
22
+
23
+ let passed = 0, failed = 0;
24
+ function ok(name, cond, extra) {
25
+ if (cond) { passed++; console.log('[OK]', name); }
26
+ else { failed++; console.log('[FAIL]', name, extra !== undefined ? '→ ' + JSON.stringify(extra) : ''); }
27
+ }
28
+
29
+ const SCHEMA = { id: { type: 'integer', primaryKey: true }, v: { type: 'string' } };
30
+
31
+ function tmpDir(tag) {
32
+ return fs.mkdtempSync(path.join(os.tmpdir(), 'jsql-445-449-' + tag + '-'));
33
+ }
34
+
35
+ // ---------------------------------------------------------------------------
36
+ // #445 递归 CTE:递归项以 JOIN 形式引用 CTE 自身
37
+ // ---------------------------------------------------------------------------
38
+ async function testRecursiveCteJoin() {
39
+ console.log('\n--- #445 递归 CTE JOIN 自引用 ---');
40
+ const db = new Database(':memory:');
41
+ try {
42
+ await db.query("CREATE TABLE e (id INT, mgr INT, name TEXT)");
43
+ await db.query("INSERT INTO e VALUES (1,NULL,'CEO'),(2,1,'A'),(3,1,'B'),(4,2,'C')");
44
+
45
+ const inner = `WITH RECURSIVE hier(id, name, depth) AS (
46
+ SELECT id, name, 1 FROM e WHERE mgr IS NULL
47
+ UNION ALL
48
+ SELECT e.id, e.name, h.depth+1 FROM e JOIN hier h ON e.mgr = h.id
49
+ ) SELECT id, name, depth FROM hier ORDER BY id`;
50
+ const rInner = await db.query(inner);
51
+ const expected = [[1, 'CEO', 1], [2, 'A', 2], [3, 'B', 2], [4, 'C', 3]];
52
+ ok('INNER JOIN 自引用逐层展开(锚点 + 两层子女)',
53
+ JSON.stringify(rInner.rows) === JSON.stringify(expected), rInner.rows);
54
+
55
+ // LEFT JOIN 自引用:已匹配的子女节点必须出现,且结果有界、
56
+ // 不会每轮重复累积到行数上限。
57
+ const left = `WITH RECURSIVE hier(id, name, depth) AS (
58
+ SELECT id, name, 1 FROM e WHERE mgr IS NULL
59
+ UNION ALL
60
+ SELECT e.id, e.name, h.depth+1 FROM e LEFT JOIN hier h ON e.mgr = h.id
61
+ ) SELECT id, name, depth FROM hier ORDER BY id, depth`;
62
+ const rLeft = await db.query(left);
63
+ const ids = rLeft.rows.map(x => x[0]);
64
+ ok('LEFT JOIN 自引用:根/子女/孙节点均出现',
65
+ [1, 2, 3, 4].every(id => ids.includes(id)), rLeft.rows.map(x => x.slice(0, 2)));
66
+ ok('LEFT JOIN 自引用:结果有界(未累积到行数上限)',
67
+ rLeft.rows.length < 10000, rLeft.rows.length);
68
+ } catch (e) {
69
+ ok('递归 CTE JOIN 用例未抛错', false, String(e && e.message).slice(0, 120));
70
+ } finally {
71
+ await db.stop();
72
+ }
73
+ }
74
+
75
+ // ---------------------------------------------------------------------------
76
+ // #448 窗口聚合 DISTINCT
77
+ // ---------------------------------------------------------------------------
78
+ async function testWindowDistinct() {
79
+ console.log('\n--- #448 窗口聚合 DISTINCT ---');
80
+ const db = new Database(':memory:');
81
+ try {
82
+ await db.query("CREATE TABLE w (id INT, dept TEXT, sal INT)");
83
+ await db.query("INSERT INTO w VALUES (1,'x',100),(2,'x',200),(3,'x',200),(4,'y',150),(5,'y',250),(6,'y',250)");
84
+ const r = await db.query("SELECT dept, COUNT(DISTINCT sal) OVER (PARTITION BY dept) c, SUM(DISTINCT sal) OVER (PARTITION BY dept) s FROM w ORDER BY id");
85
+ const expected = [['x', 2, 300], ['x', 2, 300], ['x', 2, 300], ['y', 2, 400], ['y', 2, 400], ['y', 2, 400]];
86
+ ok('COUNT(DISTINCT) / SUM(DISTINCT) 窗口按分区去重',
87
+ JSON.stringify(r.rows) === JSON.stringify(expected), r.rows);
88
+ } catch (e) {
89
+ ok('窗口 DISTINCT 用例未抛错', false, String(e && e.message).slice(0, 120));
90
+ } finally {
91
+ await db.stop();
92
+ }
93
+ }
94
+
95
+ // ---------------------------------------------------------------------------
96
+ // #447 活动 beginTx 期间自动 checkpoint 不固化未提交行
97
+ // ---------------------------------------------------------------------------
98
+ async function testCheckpointDuringTx() {
99
+ console.log('\n--- #447 活动事务期间 checkpoint ---');
100
+ const dir = tmpDir('cptx');
101
+ const file = path.join(dir, 'db.json');
102
+ const db = new Database(file, { walCheckpointOps: 2 });
103
+ try {
104
+ await db.createTable('t', SCHEMA);
105
+ await db.insert('t', { id: 1, v: 'committed' });
106
+ await db.save();
107
+
108
+ await db.beginTx();
109
+ await db.insert('t', { id: 2, v: 'uncommitted-A' });
110
+ await db.insert('t', { id: 3, v: 'uncommitted-B' });
111
+ // 等待 setImmediate 调度的自动 checkpoint 跑完
112
+ await new Promise(r => setTimeout(r, 300));
113
+
114
+ const snap = JSON.parse(fs.readFileSync(file, 'utf8'));
115
+ const snapRows = snap.t || [];
116
+ ok('主快照不含未提交行',
117
+ snapRows.length === 1 && snapRows[0].id === 1, snapRows);
118
+ ok('WAL 未被 checkpoint 清空', fs.existsSync(file + '.wal'));
119
+ ok('inTransaction() 识别 beginTx 路径', db.inTransaction() === true);
120
+
121
+ await db.rollbackTx();
122
+ } catch (e) {
123
+ ok('事务 checkpoint 用例未抛错', false, String(e && e.message).slice(0, 120));
124
+ } finally {
125
+ db.close();
126
+ fs.rmSync(dir, { recursive: true, force: true });
127
+ }
128
+ }
129
+
130
+ // ---------------------------------------------------------------------------
131
+ // #446 未提交事务写入在 SIGKILL 后不随 WAL 回放复活(真实子进程崩溃重启)
132
+ // ---------------------------------------------------------------------------
133
+ function writeChildCrashScript() {
134
+ const script = path.join(tmpDir('child'), 'midtx-child.js');
135
+ fs.writeFileSync(script, `
136
+ const jsql = require(${JSON.stringify(path.join(ROOT, 'index.js'))});
137
+ const file = process.argv[2];
138
+ (async () => {
139
+ const db = new jsql.Database(file, { walCheckpointOps: 0 });
140
+ await db.beginTx();
141
+ await db.insert('t', { id: 2, v: 'uncommitted' });
142
+ console.log('child inserted');
143
+ setTimeout(() => process.kill(process.pid, 'SIGKILL'), 200);
144
+ })().catch(e => { console.error('ERR', e); process.exit(1); });
145
+ `);
146
+ return script;
147
+ }
148
+
149
+ function writeChildCommitScript() {
150
+ const script = path.join(tmpDir('childc'), 'commit-child.js');
151
+ fs.writeFileSync(script, `
152
+ const jsql = require(${JSON.stringify(path.join(ROOT, 'index.js'))});
153
+ const file = process.argv[2];
154
+ (async () => {
155
+ const db = new jsql.Database(file, { walCheckpointOps: 0 });
156
+ await db.beginTx();
157
+ await db.insert('t', { id: 2, v: 'committed-tx' });
158
+ await db.commitTx();
159
+ setTimeout(() => process.kill(process.pid, 'SIGKILL'), 200);
160
+ })().catch(e => { console.error('ERR', e); process.exit(1); });
161
+ `);
162
+ return script;
163
+ }
164
+
165
+ async function seedFile(file) {
166
+ const seed = new Database(file, { walCheckpointOps: 0 });
167
+ await seed.createTable('t', SCHEMA);
168
+ await seed.insert('t', { id: 1, v: 'committed' });
169
+ await seed.save();
170
+ seed.close();
171
+ }
172
+
173
+ async function testUncommittedTxNoResurrect() {
174
+ console.log('\n--- #446 SIGKILL 后未提交事务不复活 ---');
175
+ const dir = tmpDir('midtx');
176
+ const file = path.join(dir, 'db.json');
177
+ await seedFile(file);
178
+
179
+ const childScript = writeChildCrashScript();
180
+ const ch = spawnSync('node', [childScript, file], { encoding: 'utf8' });
181
+ ok('子进程被 SIGKILL 终止', ch.signal === 'SIGKILL', { status: ch.status, signal: ch.signal });
182
+
183
+ try { fs.unlinkSync(file + '.lock'); } catch (_) { /* 崩溃残留锁由测试侧清理 */ }
184
+
185
+ const db2 = new Database(file, { walCheckpointOps: 0 });
186
+ const rows = await db2.find('t');
187
+ ok('崩溃重开后只剩已提交行(未提交行不复活)',
188
+ rows.length === 1 && rows[0].id === 1 && rows[0].v === 'committed', rows);
189
+ db2.close();
190
+ fs.rmSync(dir, { recursive: true, force: true });
191
+ }
192
+
193
+ async function testCommittedTxSurvivesCrash() {
194
+ console.log('\n--- #446 已提交事务崩溃后仍恢复 ---');
195
+ const dir = tmpDir('ctxtx');
196
+ const file = path.join(dir, 'db.json');
197
+ await seedFile(file);
198
+
199
+ const childScript = writeChildCommitScript();
200
+ const ch = spawnSync('node', [childScript, file], { encoding: 'utf8' });
201
+ ok('提交事务子进程被 SIGKILL 终止', ch.signal === 'SIGKILL', { status: ch.status, signal: ch.signal });
202
+
203
+ try { fs.unlinkSync(file + '.lock'); } catch (_) { /* ignore */ }
204
+
205
+ const db2 = new Database(file, { walCheckpointOps: 0 });
206
+ const rows = await db2.find('t');
207
+ ok('崩溃重开后已提交事务的行仍然存在',
208
+ rows.length === 2 && rows[0].id === 1 && rows[1].id === 2, rows);
209
+ db2.close();
210
+ fs.rmSync(dir, { recursive: true, force: true });
211
+ }
212
+
213
+ // ---------------------------------------------------------------------------
214
+ // #449 disk/hybrid 目录模式文件锁
215
+ // ---------------------------------------------------------------------------
216
+ async function testDirModeFileLock() {
217
+ console.log('\n--- #449 目录模式文件锁 ---');
218
+ const dir = tmpDir('dirlock');
219
+ try {
220
+ const dbA = new Database(dir, { mode: 'disk', flushInterval: 0 });
221
+ await dbA.createTable('t', SCHEMA);
222
+ await dbA.insert('t', { id: 1, v: 'seed' });
223
+ await dbA.flush();
224
+
225
+ // 同目录第二个实例必须被拒绝(锁冲突)
226
+ let bErr = null;
227
+ let dbB = null;
228
+ try { dbB = new Database(dir, { mode: 'disk', flushInterval: 0 }); }
229
+ catch (e) { bErr = e; }
230
+ ok('同目录第二个实例被文件锁拒绝',
231
+ !!bErr && (bErr.code === 1205 || bErr.code === 'ER_LOCK_WAIT_TIMEOUT' || /locked/i.test(bErr.message || '')),
232
+ bErr && (bErr.code || bErr.message));
233
+
234
+ dbA.close();
235
+
236
+ // 锁释放后第二个实例可正常打开并读到已提交行
237
+ const dbC = new Database(dir, { mode: 'disk', flushInterval: 0 });
238
+ const rows = await dbC.find('t');
239
+ ok('锁释放后实例可打开并读到已提交行', rows.length === 1 && rows[0].v === 'seed', rows);
240
+ dbC.close();
241
+
242
+ // 崩溃残留的过期锁(>30s)可被新实例接管
243
+ const staleDir = tmpDir('stale');
244
+ fs.writeFileSync(path.join(staleDir, '.lock'), '99999');
245
+ const old = (Date.now() - 31000) / 1000;
246
+ fs.utimesSync(path.join(staleDir, '.lock'), old, old);
247
+ const dbD = new Database(staleDir, { mode: 'disk', flushInterval: 0 });
248
+ await dbD.createTable('t', SCHEMA);
249
+ await dbD.insert('t', { id: 1, v: 'takeover' });
250
+ await dbD.flush();
251
+ ok('过期残留锁被新实例接管', (await dbD.find('t')).length === 1);
252
+ dbD.close();
253
+ fs.rmSync(staleDir, { recursive: true, force: true });
254
+ } catch (e) {
255
+ ok('目录锁用例未抛错', false, String(e && e.message).slice(0, 120));
256
+ } finally {
257
+ fs.rmSync(dir, { recursive: true, force: true });
258
+ }
259
+ }
260
+
261
+ (async () => {
262
+ await testRecursiveCteJoin();
263
+ await testWindowDistinct();
264
+ await testCheckpointDuringTx();
265
+ await testUncommittedTxNoResurrect();
266
+ await testCommittedTxSurvivesCrash();
267
+ await testDirModeFileLock();
268
+
269
+ console.log(`\n${passed} passed, ${failed} failed`);
270
+ process.exit(failed === 0 ? 0 : 1);
271
+ })().catch(e => { console.error('FATAL', e); process.exit(1); });
@@ -0,0 +1,202 @@
1
+ /*
2
+ * 回归测试:#450 #451 #452 #453 #454
3
+ *
4
+ * 口径:全部走公共 API(require('../index.js') 导出的 Database / migrate),
5
+ * 真实目录库 / 真实重启,不直接断言私有类内部字段。
6
+ *
7
+ * #450 [P2] Table.restore() 永远匹配不到软删除行(恢复过滤先跳过 _deleted 行)。
8
+ * #451 [P2] 复合 CREATE UNIQUE INDEX (a,b) 不写回 schema,重启后唯一组丢失。
9
+ * #452 [P2] 目录模式事务内 CREATE TABLE 回滚后,表连同未提交行复活。
10
+ * #453 [P2] meta.json 直接 writeFileSync,撕裂后静默清空注册表、表文件成孤儿。
11
+ * #454 [P2] CSV/JSON 导入不按目标 schema 过滤未知列,幽灵字段被持久化。
12
+ */
13
+ const fs = require('fs');
14
+ const os = require('os');
15
+ const path = require('path');
16
+ const assert = require('assert');
17
+ const ROOT = path.join(__dirname, '..');
18
+ const { Database } = require(path.join(ROOT, 'index.js'));
19
+ const migrate = require(path.join(ROOT, 'lib/migrate.js'));
20
+
21
+ let passed = 0, failed = 0;
22
+
23
+ async function t(name, fn) {
24
+ try { await fn(); passed++; console.log(`ok - ${name}`); }
25
+ catch (e) { failed++; console.error(`not ok - ${name}\n ${e && e.message}`); }
26
+ }
27
+
28
+ function tmpDir(tag) {
29
+ return fs.mkdtempSync(path.join(os.tmpdir(), 'jsql-450-454-' + tag + '-'));
30
+ }
31
+
32
+ (async () => {
33
+ // #450:软删除行可以被 restore 恢复,恢复后重新出现在普通查询结果中。
34
+ await t('#450 restore 能匹配并恢复软删除行', async () => {
35
+ const db = new Database(':memory:');
36
+ try {
37
+ await db.createTable('t', {
38
+ id: { type: 'integer', primaryKey: true },
39
+ email: { type: 'string' },
40
+ _softDelete: true
41
+ });
42
+ await db.insert('t', { id: 1, email: 'a@x.com' });
43
+
44
+ db.t.removeSoft({ id: 1 });
45
+ // 恢复前:软删除行不出现在普通查询结果中
46
+ assert.deepEqual(await db.find('t', {}), []);
47
+
48
+ const restored = db.t.restore({ id: 1 });
49
+ assert.strictEqual(restored, 1);
50
+
51
+ const rows = await db.find('t', {});
52
+ assert.strictEqual(rows.length, 1);
53
+ assert.strictEqual(rows[0].id, 1);
54
+ assert.strictEqual(rows[0].email, 'a@x.com');
55
+ } finally {
56
+ db.close();
57
+ }
58
+ });
59
+
60
+ // #451:复合唯一索引随 schema 落盘,重开后重复组合键仍被拒绝。
61
+ await t('#451 复合唯一索引重启后仍生效', async () => {
62
+ const dir = tmpDir('451');
63
+ const file = path.join(dir, 'db.jsql');
64
+ let db = new Database(file);
65
+ await db.query('CREATE TABLE t (a INT, b INT)');
66
+ await db.query('CREATE UNIQUE INDEX idx_ab ON t (a, b)');
67
+ await db.insert('t', { a: 1, b: 1 });
68
+ db.save();
69
+ db.close();
70
+
71
+ // 重开库
72
+ db = new Database(file);
73
+ try {
74
+ // 不重复的组合键可以正常写入
75
+ await db.insert('t', { a: 2, b: 2 });
76
+ let dupErr = null;
77
+ try {
78
+ await db.insert('t', { a: 1, b: 1 });
79
+ } catch (e) {
80
+ dupErr = e;
81
+ }
82
+ assert(dupErr, '重开后重复组合键应被拒绝');
83
+ assert.strictEqual(dupErr.code, 1062); // ER_DUP_ENTRY
84
+ } finally {
85
+ db.close();
86
+ }
87
+ });
88
+
89
+ // #452:目录模式事务内建表回滚后,meta 登记与 .jsql 文件都不残留,重开不复活。
90
+ await t('#452 目录 DDL 回滚后被回滚的表不复活', async () => {
91
+ const dir = tmpDir('452');
92
+ let db = new Database(dir, { mode: 'disk', flushInterval: 0 });
93
+ await db.createTable('parent', { id: { type: 'integer', primaryKey: true }, v: { type: 'string' } });
94
+ await db.insert('parent', { id: 1, v: 'seed' });
95
+ await db.flush();
96
+
97
+ await db.beginTx();
98
+ await db.createTable('ghost', { id: { type: 'integer', primaryKey: true }, v: { type: 'string' } });
99
+ await db.insert('ghost', { id: 1, v: 'uncommitted' });
100
+ await db.flush();
101
+ await db.rollbackTx();
102
+
103
+ // 回滚后内存与 meta 都不应残留 ghost
104
+ assert.deepEqual(db.getTables().slice().sort(), ['parent']);
105
+ assert.strictEqual(db.hasTable('ghost'), false);
106
+ db.close();
107
+
108
+ // 重开目录库:ghost 不得复活,已提交的 parent 不受影响
109
+ db = new Database(dir, { mode: 'disk', flushInterval: 0 });
110
+ try {
111
+ assert.strictEqual(db.hasTable('ghost'), false);
112
+ assert.deepEqual(db.getTables().slice().sort(), ['parent']);
113
+ const parentRows = await db.find('parent', {});
114
+ assert.strictEqual(parentRows.length, 1);
115
+ assert.strictEqual(parentRows[0].v, 'seed');
116
+ } finally {
117
+ db.close();
118
+ }
119
+ });
120
+
121
+ // #453:meta.json 撕裂/损坏后不静默清空注册表,从 .jsql 文件重建登记,表仍可查询。
122
+ await t('#453 meta 损坏后从表文件重建登记,不致表失联', async () => {
123
+ const dir = tmpDir('453');
124
+ const db0 = new Database(dir, { mode: 'disk', flushInterval: 0 });
125
+ await db0.createTable('t', { id: { type: 'integer', primaryKey: true }, v: { type: 'string' } });
126
+ await db0.insert('t', { id: 1, v: 'hello' });
127
+ await db0.flush();
128
+ db0.close();
129
+
130
+ // 模拟半写撕裂:把 meta.json 截断到一半
131
+ const metaPath = path.join(dir, 'meta.json');
132
+ const raw = fs.readFileSync(metaPath, 'utf8');
133
+ fs.writeFileSync(metaPath, raw.slice(0, Math.floor(raw.length / 2)));
134
+
135
+ const db = new Database(dir, { mode: 'disk', flushInterval: 0 });
136
+ const errors = [];
137
+ db.on('error', e => errors.push(e));
138
+ await new Promise(r => setImmediate(r));
139
+
140
+ try {
141
+ assert.strictEqual(db.hasTable('t'), true);
142
+ const rows = await db.find('t', {});
143
+ assert.strictEqual(rows.length, 1);
144
+ assert.strictEqual(rows[0].v, 'hello');
145
+ // 排障记录可见:损坏原因 + 重建出的表
146
+ const corrupt = db.getMetaCorruption();
147
+ assert(corrupt, '应记录 meta 损坏兜底恢复记录');
148
+ assert.deepEqual(corrupt.restored, ['t']);
149
+ // 损坏原件已备份,不是直接丢弃
150
+ const backups = fs.readdirSync(dir).filter(f => f.startsWith('meta.json.corrupt-'));
151
+ assert(backups.length >= 1, '损坏 meta 应备份为 meta.json.corrupt-<ts>');
152
+ } finally {
153
+ db.close();
154
+ }
155
+
156
+ // 正常路径行为不变:完好 meta 不报损坏
157
+ const dir2 = tmpDir('453-ok');
158
+ const db2 = new Database(dir2, { mode: 'disk', flushInterval: 0 });
159
+ try {
160
+ await db2.createTable('x', { id: { type: 'integer', primaryKey: true } });
161
+ assert.strictEqual(db2.getMetaCorruption(), null);
162
+ } finally {
163
+ db2.close();
164
+ }
165
+ });
166
+
167
+ // #454:CSV / JSON 导入只保留目标 schema 内的列,未知列不写进存储行。
168
+ await t('#454 导入按目标 schema 过滤未知列', async () => {
169
+ // CSV 路径:目标表只有 id/name,CSV 多带一列 ghost
170
+ const db = new Database(':memory:');
171
+ try {
172
+ await db.createTable('d', { id: { type: 'integer' }, name: { type: 'string' } });
173
+ const csvRes = await migrate.importFromCSV(db, 'd', 'id,name,ghost\n1,alice,xyz\n');
174
+ const csvRows = await db.find('d', {});
175
+ assert.strictEqual(csvRows.length, 1);
176
+ assert.deepEqual(Object.keys(csvRows[0]).sort(), ['id', 'name']);
177
+ assert(csvRes.warnings && csvRes.warnings.some(w => w.kind === 'unknownColumn'));
178
+ } finally {
179
+ db.close();
180
+ }
181
+
182
+ // JSON 路径:行内携带 schema 中不存在的 extra 字段
183
+ const db2 = new Database(':memory:');
184
+ try {
185
+ const jsonRes = await migrate.importFromJSON(db2, {
186
+ g: {
187
+ schema: { id: 'integer', name: 'string' },
188
+ rows: [{ id: 1, name: 'a', extra: 'ghost' }]
189
+ }
190
+ });
191
+ const jsonRows = await db2.find('g', {});
192
+ assert.strictEqual(jsonRows.length, 1);
193
+ assert.deepEqual(Object.keys(jsonRows[0]).sort(), ['id', 'name']);
194
+ assert(jsonRes.warnings && jsonRes.warnings.some(w => w.kind === 'unknownColumn'));
195
+ } finally {
196
+ db2.close();
197
+ }
198
+ });
199
+
200
+ console.log(`\n${passed} passed, ${failed} failed`);
201
+ process.exit(failed ? 1 : 0);
202
+ })().catch((e) => { console.error('FATAL', e); process.exit(1); });