上线单个审计覆盖索引并严格核验旧库的结构增量
This commit is contained in:
1 parent
cf0b0be83f
commit
240452d8a1
5 files changed
+230
-6
No files matched your search
@@ -317,6 +317,7 @@ class Ledger {
|
|||||||
CREATE INDEX IF NOT EXISTS ix_payment_order ON payments(order_id);
|
CREATE INDEX IF NOT EXISTS ix_payment_order ON payments(order_id);
|
||||||
CREATE INDEX IF NOT EXISTS ix_journal_date ON journal(date);
|
CREATE INDEX IF NOT EXISTS ix_journal_date ON journal(date);
|
||||||
CREATE INDEX IF NOT EXISTS ix_after_sales_date ON after_sales(date);
|
CREATE INDEX IF NOT EXISTS ix_after_sales_date ON after_sales(date);
|
||||||
|
CREATE INDEX IF NOT EXISTS ix_audit_entity_action_id ON audit(entity,action,id);
|
||||||
`);
|
`);
|
||||||
// 增量升级旧库,不改写历史订单金额、单号和成本。
|
// 增量升级旧库,不改写历史订单金额、单号和成本。
|
||||||
const columns = this.rows('PRAGMA table_info(orders)').map(r => r.name);
|
const columns = this.rows('PRAGMA table_info(orders)').map(r => r.name);
|
||||||
|
|||||||
+11
-5
@@ -13,6 +13,7 @@ const { Session } = require('./lib/client');
|
|||||||
const { Normalizer } = require('./lib/normalize');
|
const { Normalizer } = require('./lib/normalize');
|
||||||
const { dumpDatabase } = require('./lib/db-dump');
|
const { dumpDatabase } = require('./lib/db-dump');
|
||||||
const { compare, report } = require('./lib/diff');
|
const { compare, report } = require('./lib/diff');
|
||||||
|
const ApprovedAuditIndex = require('./lib/approved-audit-index');
|
||||||
const scenario = require('./golden-scenario');
|
const scenario = require('./golden-scenario');
|
||||||
const args = process.argv.slice(2),
|
const args = process.argv.slice(2),
|
||||||
check = args.includes('--check'),
|
check = args.includes('--check'),
|
||||||
@@ -46,9 +47,11 @@ async function run() {
|
|||||||
} finally {
|
} finally {
|
||||||
await server.stop();
|
await server.stop();
|
||||||
}
|
}
|
||||||
const dump = dumpDatabase(path.join(dataDir, 'ledger.sqlite'), {
|
const filename = path.join(dataDir, 'ledger.sqlite');
|
||||||
|
const dump = dumpDatabase(filename, {
|
||||||
mask: { users: { salt: () => MASKED, hash: () => MASKED }, sessions: { hash: () => MASKED } },
|
mask: { users: { salt: () => MASKED, hash: () => MASKED }, sessions: { hash: () => MASKED } },
|
||||||
});
|
});
|
||||||
|
const auditIndex = check ? ApprovedAuditIndex.inspect(filename) : null;
|
||||||
fs.rmSync(dataDir, { recursive: true, force: true });
|
fs.rmSync(dataDir, { recursive: true, force: true });
|
||||||
const n = new Normalizer();
|
const n = new Normalizer();
|
||||||
n.literal(session.base, 'http://<host>');
|
n.literal(session.base, 'http://<host>');
|
||||||
@@ -58,7 +61,7 @@ async function run() {
|
|||||||
// JSON 往返,去掉 undefined 字段,使内存结果与落盘基线同形。
|
// JSON 往返,去掉 undefined 字段,使内存结果与落盘基线同形。
|
||||||
const transcript = JSON.parse(JSON.stringify(session.entries.map(e => n.value(e))));
|
const transcript = JSON.parse(JSON.stringify(session.entries.map(e => n.value(e))));
|
||||||
const db = JSON.parse(JSON.stringify(n.value(dump)));
|
const db = JSON.parse(JSON.stringify(n.value(dump)));
|
||||||
return { transcript, db, problems: session.problems };
|
return { transcript, db, auditIndex, problems: session.problems };
|
||||||
}
|
}
|
||||||
function write(dir, result) {
|
function write(dir, result) {
|
||||||
fs.mkdirSync(dir, { recursive: true });
|
fs.mkdirSync(dir, { recursive: true });
|
||||||
@@ -85,12 +88,14 @@ function describeTranscript(transcript) {
|
|||||||
}
|
}
|
||||||
if (check) {
|
if (check) {
|
||||||
write(OUT, result);
|
write(OUT, result);
|
||||||
|
const frozenDb = JSON.parse(fs.readFileSync(path.join(BASELINE, 'db.json'), 'utf8'));
|
||||||
const expected = {
|
const expected = {
|
||||||
transcript: JSON.parse(fs.readFileSync(path.join(BASELINE, 'transcript.json'), 'utf8')),
|
transcript: JSON.parse(fs.readFileSync(path.join(BASELINE, 'transcript.json'), 'utf8')),
|
||||||
db: JSON.parse(fs.readFileSync(path.join(BASELINE, 'db.json'), 'utf8')),
|
db: { ...frozenDb, schema: ApprovedAuditIndex.expectedMaster(frozenDb.schema) },
|
||||||
};
|
};
|
||||||
const t = compare(expected.transcript, result.transcript),
|
const t = compare(expected.transcript, result.transcript),
|
||||||
d = compare(expected.db, result.db);
|
d = compare(expected.db, result.db),
|
||||||
|
i = compare(ApprovedAuditIndex.definition, result.auditIndex);
|
||||||
const describeDb = p => {
|
const describeDb = p => {
|
||||||
const m = p.match(/^\$\.tables\.([^.]+)\.rows\[(\d+)\]\[(\d+)\](.*)$/);
|
const m = p.match(/^\$\.tables\.([^.]+)\.rows\[(\d+)\]\[(\d+)\](.*)$/);
|
||||||
if (!m) return p;
|
if (!m) return p;
|
||||||
@@ -100,11 +105,12 @@ function describeTranscript(transcript) {
|
|||||||
const text = [
|
const text = [
|
||||||
report('请求记录', t, limit, describeTranscript(expected.transcript)),
|
report('请求记录', t, limit, describeTranscript(expected.transcript)),
|
||||||
report('数据库', d, limit, describeDb),
|
report('数据库', d, limit, describeDb),
|
||||||
|
report('批准的审计索引', i, limit),
|
||||||
]
|
]
|
||||||
.filter(Boolean)
|
.filter(Boolean)
|
||||||
.join('\n');
|
.join('\n');
|
||||||
if (text) console.log(text);
|
if (text) console.log(text);
|
||||||
const failed = t.diffs.length + d.diffs.length > 0;
|
const failed = t.diffs.length + d.diffs.length + i.diffs.length > 0;
|
||||||
console.log(
|
console.log(
|
||||||
`golden ${failed ? 'FAIL' : 'PASS'}:${result.transcript.length} 条记录,${Object.keys(result.db.tables).length} 张表,用时 ${seconds}s(实际结果在 e2e/out/golden/)`,
|
`golden ${failed ? 'FAIL' : 'PASS'}:${result.transcript.length} 条记录,${Object.keys(result.db.tables).length} 张表,用时 ${seconds}s(实际结果在 e2e/out/golden/)`,
|
||||||
);
|
);
|
||||||
|
|||||||
+12
-1
@@ -14,6 +14,7 @@ const { startServer } = require('./lib/server');
|
|||||||
const { Session } = require('./lib/client');
|
const { Session } = require('./lib/client');
|
||||||
const { Normalizer } = require('./lib/normalize');
|
const { Normalizer } = require('./lib/normalize');
|
||||||
const { compare, report } = require('./lib/diff');
|
const { compare, report } = require('./lib/diff');
|
||||||
|
const ApprovedAuditIndex = require('./lib/approved-audit-index');
|
||||||
const args = process.argv.slice(2),
|
const args = process.argv.slice(2),
|
||||||
check = args.includes('--check');
|
check = args.includes('--check');
|
||||||
const FIXTURE = args.includes('--fixture')
|
const FIXTURE = args.includes('--fixture')
|
||||||
@@ -178,6 +179,7 @@ async function run() {
|
|||||||
unchangedOriginalTables: Object.keys(before.hashes).filter(t => before.hashes[t] === after.hashes[t]).length,
|
unchangedOriginalTables: Object.keys(before.hashes).filter(t => before.hashes[t] === after.hashes[t]).length,
|
||||||
changedOriginalTables: Object.keys(before.hashes).filter(t => before.hashes[t] !== after.hashes[t]),
|
changedOriginalTables: Object.keys(before.hashes).filter(t => before.hashes[t] !== after.hashes[t]),
|
||||||
responses,
|
responses,
|
||||||
|
...(check ? { auditIndex: ApprovedAuditIndex.inspect(file) } : {}),
|
||||||
};
|
};
|
||||||
} finally {
|
} finally {
|
||||||
fs.rmSync(dataDir, { recursive: true, force: true });
|
fs.rmSync(dataDir, { recursive: true, force: true });
|
||||||
@@ -189,7 +191,16 @@ async function run() {
|
|||||||
const seconds = ((Date.now() - started) / 1000).toFixed(1);
|
const seconds = ((Date.now() - started) / 1000).toFixed(1);
|
||||||
const integrityOk = result.before.integrity.join() === 'ok' && result.after.integrity.join() === 'ok';
|
const integrityOk = result.before.integrity.join() === 'ok' && result.after.integrity.join() === 'ok';
|
||||||
if (check) {
|
if (check) {
|
||||||
const expected = JSON.parse(fs.readFileSync(BASELINE, 'utf8'));
|
const frozen = JSON.parse(fs.readFileSync(BASELINE, 'utf8'));
|
||||||
|
const expected = {
|
||||||
|
...frozen,
|
||||||
|
before: { ...frozen.before, schema: ApprovedAuditIndex.expectedLegacySchema(frozen.before.schema) },
|
||||||
|
after: {
|
||||||
|
...frozen.after,
|
||||||
|
schema: ApprovedAuditIndex.expectedLegacySchema(frozen.after.schema, { afterStartup: true }),
|
||||||
|
},
|
||||||
|
auditIndex: ApprovedAuditIndex.definition,
|
||||||
|
};
|
||||||
const d = compare(expected, JSON.parse(JSON.stringify(result)));
|
const d = compare(expected, JSON.parse(JSON.stringify(result)));
|
||||||
const text = report('旧库兼容', d);
|
const text = report('旧库兼容', d);
|
||||||
if (text) console.log(text);
|
if (text) console.log(text);
|
||||||
|
|||||||
@@ -0,0 +1,75 @@
|
|||||||
|
'use strict';
|
||||||
|
|
||||||
|
const assert = require('node:assert/strict');
|
||||||
|
const { DatabaseSync } = require('node:sqlite');
|
||||||
|
|
||||||
|
const name = 'ix_audit_entity_action_id';
|
||||||
|
const masterEntry = {
|
||||||
|
type: 'index',
|
||||||
|
name,
|
||||||
|
table: 'audit',
|
||||||
|
sql: 'CREATE INDEX ix_audit_entity_action_id ON audit(entity,action,id)',
|
||||||
|
};
|
||||||
|
const listEntry = { name, unique: 0, columns: ['entity', 'action', 'id'] };
|
||||||
|
const definition = {
|
||||||
|
...masterEntry,
|
||||||
|
unique: 0,
|
||||||
|
origin: 'c',
|
||||||
|
partial: 0,
|
||||||
|
columns: [
|
||||||
|
{ seqno: 0, cid: 1, name: 'entity', desc: 0, coll: 'BINARY', key: 1 },
|
||||||
|
{ seqno: 1, cid: 2, name: 'action', desc: 0, coll: 'BINARY', key: 1 },
|
||||||
|
{ seqno: 2, cid: 0, name: 'id', desc: 0, coll: 'BINARY', key: 1 },
|
||||||
|
{ seqno: 3, cid: -1, name: null, desc: 0, coll: 'BINARY', key: 0 },
|
||||||
|
],
|
||||||
|
};
|
||||||
|
|
||||||
|
function insertExpected(entries, entry, follows) {
|
||||||
|
const i = entries.findIndex(follows);
|
||||||
|
return entries.toSpliced(i === -1 ? entries.length : i, 0, entry);
|
||||||
|
}
|
||||||
|
|
||||||
|
function expectedMaster(entries) {
|
||||||
|
const recorded = entries.filter(entry => entry.name === name);
|
||||||
|
if (recorded.length) {
|
||||||
|
assert.deepEqual(recorded, [masterEntry], '基线中的批准审计索引定义不符');
|
||||||
|
return entries;
|
||||||
|
}
|
||||||
|
return insertExpected(entries, masterEntry, row => row.type > 'index' || (row.type === 'index' && row.name > name));
|
||||||
|
}
|
||||||
|
|
||||||
|
function expectedLegacySchema(schema, { afterStartup = false } = {}) {
|
||||||
|
const recorded = Object.entries(schema).flatMap(([table, { indexes }]) =>
|
||||||
|
indexes.filter(index => index.name === name).map(index => ({ table, ...index })),
|
||||||
|
);
|
||||||
|
if (recorded.length) {
|
||||||
|
assert.deepEqual(recorded, [{ table: masterEntry.table, ...listEntry }], '基线中的批准审计索引定义不符');
|
||||||
|
return schema;
|
||||||
|
}
|
||||||
|
if (!afterStartup) return schema;
|
||||||
|
const { audit } = schema;
|
||||||
|
const indexes = insertExpected(audit.indexes, listEntry, row => row.name > name);
|
||||||
|
return { ...schema, audit: { ...audit, indexes } };
|
||||||
|
}
|
||||||
|
|
||||||
|
function inspect(filename) {
|
||||||
|
const db = new DatabaseSync(filename, { readOnly: true });
|
||||||
|
try {
|
||||||
|
const master = db
|
||||||
|
.prepare("SELECT type,name,tbl_name AS 'table',sql FROM sqlite_master WHERE type='index' AND name=?")
|
||||||
|
.get(name);
|
||||||
|
if (!master) return null;
|
||||||
|
const flags = db
|
||||||
|
.prepare('SELECT "unique",origin,partial FROM pragma_index_list(?) WHERE name=?')
|
||||||
|
.get(master.table, name);
|
||||||
|
const columns = db
|
||||||
|
.prepare('SELECT seqno,cid,name,"desc",coll,"key" FROM pragma_index_xinfo(?) ORDER BY seqno')
|
||||||
|
.all(name)
|
||||||
|
.map(row => ({ ...row }));
|
||||||
|
return { ...master, ...flags, columns };
|
||||||
|
} finally {
|
||||||
|
db.close();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
module.exports = { definition, expectedMaster, expectedLegacySchema, inspect };
|
||||||
@@ -0,0 +1,131 @@
|
|||||||
|
'use strict';
|
||||||
|
|
||||||
|
const assert = require('node:assert/strict');
|
||||||
|
const { spawnSync } = require('node:child_process');
|
||||||
|
const { mkdtempSync, rmSync } = require('node:fs');
|
||||||
|
const { tmpdir } = require('node:os');
|
||||||
|
const { join } = require('node:path');
|
||||||
|
const { DatabaseSync } = require('node:sqlite');
|
||||||
|
const test = require('node:test');
|
||||||
|
const { Ledger } = require('../core/ledger');
|
||||||
|
|
||||||
|
const name = 'ix_audit_entity_action_id';
|
||||||
|
|
||||||
|
function filename(t) {
|
||||||
|
const dir = mkdtempSync(join(tmpdir(), 'weiguang-audit-index-'));
|
||||||
|
t.after(() => rmSync(dir, { recursive: true, force: true }));
|
||||||
|
return join(dir, 'ledger.sqlite');
|
||||||
|
}
|
||||||
|
|
||||||
|
function assertIndex(db) {
|
||||||
|
const found = db.prepare("SELECT * FROM pragma_index_list('audit') WHERE name=?").get(name);
|
||||||
|
assert(found);
|
||||||
|
assert.equal(found.unique, 0);
|
||||||
|
assert.equal(found.origin, 'c');
|
||||||
|
assert.equal(found.partial, 0);
|
||||||
|
const columns = db.prepare('SELECT * FROM pragma_index_xinfo(?) ORDER BY seqno').all(name);
|
||||||
|
assert.deepEqual(
|
||||||
|
columns.filter(row => row.key).map(row => [row.name, row.desc, row.coll]),
|
||||||
|
[
|
||||||
|
['entity', 0, 'BINARY'],
|
||||||
|
['action', 0, 'BINARY'],
|
||||||
|
['id', 0, 'BINARY'],
|
||||||
|
],
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function seedOldAudit(file) {
|
||||||
|
const db = new DatabaseSync(file);
|
||||||
|
try {
|
||||||
|
db.exec(`CREATE TABLE audit(id INTEGER PRIMARY KEY AUTOINCREMENT,entity TEXT NOT NULL,
|
||||||
|
action TEXT NOT NULL,actor TEXT NOT NULL,detail TEXT NOT NULL,created TEXT NOT NULL)`);
|
||||||
|
const insert = db.prepare('INSERT INTO audit(entity,action,actor,detail,created) VALUES (?,?,?,?,?)');
|
||||||
|
const created = '2026-11-30T01:00:00.000Z';
|
||||||
|
for (const [entity, action] of [
|
||||||
|
['one', '保存草稿'],
|
||||||
|
['two', '保存草稿'],
|
||||||
|
['one', '复核'],
|
||||||
|
['one', '保存草稿'],
|
||||||
|
])
|
||||||
|
insert.run(entity, action, '合成员工', '{}', created);
|
||||||
|
return db.prepare('SELECT * FROM audit ORDER BY id').all();
|
||||||
|
} finally {
|
||||||
|
db.close();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
test('新库启动创建一个普通审计索引,旧表升级和重复启动保留原行、唯一性与排序', t => {
|
||||||
|
const fresh = new Ledger(':memory:');
|
||||||
|
try {
|
||||||
|
assertIndex(fresh.db);
|
||||||
|
} finally {
|
||||||
|
fresh.close();
|
||||||
|
}
|
||||||
|
const file = filename(t);
|
||||||
|
const rows = seedOldAudit(file);
|
||||||
|
for (let boot = 0; boot < 2; boot++) {
|
||||||
|
const ledger = new Ledger(file);
|
||||||
|
try {
|
||||||
|
assertIndex(ledger.db);
|
||||||
|
assert.deepEqual(ledger.rows('SELECT * FROM audit ORDER BY id'), rows);
|
||||||
|
assert.deepEqual(
|
||||||
|
ledger.rows('SELECT id FROM audit WHERE entity=? ORDER BY id DESC LIMIT 100', 'one').map(row => row.id),
|
||||||
|
[4, 3, 1],
|
||||||
|
);
|
||||||
|
assert.equal(ledger.one('SELECT MIN(id) AS id FROM audit WHERE entity=? AND action=?', 'one', '保存草稿').id, 1);
|
||||||
|
} finally {
|
||||||
|
ledger.close();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
test('打开索引事务后进程中断,未提交索引回滚,重启补齐且保留审计数据', t => {
|
||||||
|
const file = filename(t);
|
||||||
|
const rows = seedOldAudit(file);
|
||||||
|
// 在独立进程包住实际启动 DDL,中断发生在 SQLite 已建好索引且尚未提交时。
|
||||||
|
const stopped = spawnSync(
|
||||||
|
process.execPath,
|
||||||
|
[
|
||||||
|
'-e',
|
||||||
|
`
|
||||||
|
const assert = require('node:assert/strict');
|
||||||
|
const { DatabaseSync } = require('node:sqlite');
|
||||||
|
const { writeSync } = require('node:fs');
|
||||||
|
const { Ledger } = require(process.argv[1]);
|
||||||
|
const original = DatabaseSync.prototype.exec;
|
||||||
|
DatabaseSync.prototype.exec = function(sql) {
|
||||||
|
if (!sql.includes('CREATE INDEX IF NOT EXISTS ix_audit_entity_action_id ON audit(entity,action,id)'))
|
||||||
|
return original.call(this, sql);
|
||||||
|
original.call(this, 'BEGIN IMMEDIATE');
|
||||||
|
original.call(this, sql);
|
||||||
|
assert(this.isTransaction);
|
||||||
|
assert(this.prepare("SELECT name FROM sqlite_master WHERE name='ix_audit_entity_action_id'").get());
|
||||||
|
writeSync(1, 'index created in open transaction');
|
||||||
|
process.kill(process.pid, 'SIGKILL');
|
||||||
|
};
|
||||||
|
new Ledger(process.argv[2]);
|
||||||
|
`,
|
||||||
|
require.resolve('../core/ledger'),
|
||||||
|
file,
|
||||||
|
],
|
||||||
|
{ encoding: 'utf8', timeout: 10000 },
|
||||||
|
);
|
||||||
|
assert.equal(stopped.stdout, 'index created in open transaction', stopped.stderr);
|
||||||
|
assert.equal(stopped.signal, 'SIGKILL', stopped.stderr);
|
||||||
|
|
||||||
|
const recovering = new DatabaseSync(file);
|
||||||
|
try {
|
||||||
|
assert.equal(recovering.prepare('SELECT name FROM sqlite_master WHERE name=?').get(name), undefined);
|
||||||
|
assert.deepEqual(recovering.prepare('SELECT * FROM audit ORDER BY id').all(), rows);
|
||||||
|
assert.equal(recovering.prepare('PRAGMA quick_check').get().quick_check, 'ok');
|
||||||
|
} finally {
|
||||||
|
recovering.close();
|
||||||
|
}
|
||||||
|
const ledger = new Ledger(file);
|
||||||
|
try {
|
||||||
|
assertIndex(ledger.db);
|
||||||
|
assert.deepEqual(ledger.rows('SELECT * FROM audit ORDER BY id'), rows);
|
||||||
|
} finally {
|
||||||
|
ledger.close();
|
||||||
|
}
|
||||||
|
});
|
||||||
Reference in new issue
Block a user