// Rôle : crée, vérifie et restaure des sauvegardes cohérentes de la base Sokko TCG. import { copyFileSync, mkdirSync, renameSync, rmSync } from "node:fs"; import { dirname } from "node:path"; import { backup, DatabaseSync } from "node:sqlite"; export async function backupCardsDatabase(sourcePath, destinationPath) { mkdirSync(dirname(destinationPath), { recursive: true }); const temporaryPath = `${destinationPath}.tmp`; rmSync(temporaryPath, { force: true }); const source = new DatabaseSync(sourcePath, { readOnly: true }); try { await backup(source, temporaryPath); } finally { source.close(); } verifyCardsDatabase(temporaryPath); renameSync(temporaryPath, destinationPath); return destinationPath; } export function verifyCardsDatabase(path) { const database = new DatabaseSync(path, { readOnly: true }); try { const result = database.prepare("PRAGMA integrity_check").get(); if (result.integrity_check !== "ok") throw new Error(`SQLite integrity check failed: ${result.integrity_check}`); database.prepare("SELECT version FROM schema_migrations ORDER BY version DESC LIMIT 1").get(); return true; } finally { database.close(); } } export function restoreCardsDatabase(backupPath, destinationPath) { verifyCardsDatabase(backupPath); mkdirSync(dirname(destinationPath), { recursive: true }); const temporaryPath = `${destinationPath}.restore`; rmSync(temporaryPath, { force: true }); copyFileSync(backupPath, temporaryPath); verifyCardsDatabase(temporaryPath); renameSync(temporaryPath, destinationPath); return destinationPath; }