'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 };