Files
weiguang-jewelry-ledger/新账系统/e2e/lib/db-dump.js
T
黄健铭andClaude Opus 5.5 28c64814f0 格式化:Prettier统一代码风格(仅格式,无逻辑变化)
仅为 npm run format 的输出;黄金对照、旧库兼容、浏览器流程与单元测试全部通过且零差异。

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-04 08:58:53 -08:00

42 lines
1.6 KiB
JavaScript

'use strict';
// 完整数据库转储:每张表的建表语句、列、索引,以及按 rowid 排序的全部行和全部列。
const { DatabaseSync } = require('node:sqlite');
function cell(value) {
if (value instanceof Uint8Array) return { blob: Buffer.from(value).toString('hex') };
if (typeof value === 'bigint') return { bigint: value.toString() };
return value;
}
function dumpDatabase(filename, { mask = {} } = {}) {
const db = new DatabaseSync(filename, { readOnly: true });
try {
const master = db
.prepare(
"SELECT type,name,tbl_name,sql FROM sqlite_master WHERE name NOT LIKE 'sqlite_autoindex_%' ORDER BY type,name",
)
.all();
const tables = {};
for (const { name, sql } of master.filter(row => row.type === 'table')) {
const columns = db
.prepare(`PRAGMA table_info("${name.replace(/"/g, '""')}")`)
.all()
.map(c => c.name);
const withoutRowid = /WITHOUT\s+ROWID/i.test(sql || '');
const order = withoutRowid ? columns.map((_, i) => i + 1).join(',') : 'rowid';
const rows = db
.prepare(`SELECT * FROM "${name.replace(/"/g, '""')}" ORDER BY ${order}`)
.all()
.map(row =>
columns.map(c => {
const masker = mask[name]?.[c];
return masker ? masker(row[c], row) : cell(row[c]);
}),
);
tables[name] = { columns, rows };
}
return { schema: master.map(({ type, name, tbl_name, sql }) => ({ type, name, table: tbl_name, sql })), tables };
} finally {
db.close();
}
}
module.exports = { dumpDatabase };