import { DatabaseSync, backup } from 'node:sqlite'; import { chmod, link, mkdir, stat, unlink } from 'node:fs/promises'; import { dirname, resolve } from 'node:path'; import { randomUUID } from 'node:crypto'; process.umask(0o077); const dataDir = resolve(process.env.DATA_DIR || './data'); const sourcePath = resolve(dataDir, 'demand-center.sqlite'); const stamp = new Date().toISOString().replace(/[:.]/g, '-'); const destination = resolve(process.argv[2] || `${dataDir}/backups/demand-${stamp}.sqlite`); const temporary = `${destination}.${randomUUID()}.tmp`; let source; try { if (sourcePath === destination) throw new Error('备份文件不能覆盖正在使用的数据库。'); if (!(await stat(sourcePath)).isFile()) throw new Error('数据库文件不存在。'); const existing = await stat(destination).catch(error => { if (error.code === 'ENOENT') return null; throw error; }); if (existing) throw new Error('目标文件已经存在,请选择新的备份文件名。'); await mkdir(dirname(destination), { recursive: true, mode: 0o700 }); source = new DatabaseSync(sourcePath, { readOnly: true }); source.exec('PRAGMA busy_timeout = 5000'); await backup(source, temporary); source.close(); source = undefined; const check = new DatabaseSync(temporary, { readOnly: true }); try { const rows = check.prepare('PRAGMA integrity_check').all(); if (rows.length !== 1 || rows[0].integrity_check !== 'ok') { throw new Error('备份完整性检查失败。'); } } finally { check.close(); } await chmod(temporary, 0o600); await link(temporary, destination); await unlink(temporary); process.stdout.write(`${destination}\n`); } catch (error) { if (source) source.close(); await unlink(temporary).catch(() => {}); process.stderr.write(`备份失败:${error.message}\n`); process.exitCode = 1; }