restore-sqlite-migration.ts 1012 B

123456789101112131415161718192021222324
  1. #!/usr/bin/env -S pnpm exec tsx
  2. // 工程恢复入口:先停止使用目标库的应用/CLI;恢复逻辑只有共享 migration 模块这一份。
  3. import { stat } from "node:fs/promises";
  4. import { resolve } from "node:path";
  5. import { DatabaseSync } from "node:sqlite";
  6. import { sqliteMigrations } from "../packages/shared/src/sqlite-migrations/index.js";
  7. const args = process.argv.slice(2);
  8. if (args.length !== 2 || args.some((arg) => arg.startsWith("-"))) {
  9. throw new Error(
  10. "Usage: pnpm exec tsx scripts/restore-sqlite-migration.ts <database.sqlite> <backup-directory>. Stop all database writers first.",
  11. );
  12. }
  13. const databasePath = resolve(args[0]!);
  14. const backupPath = resolve(args[1]!);
  15. if (!(await stat(databasePath)).isFile()) throw new Error("Database must already exist");
  16. const db = new DatabaseSync(databasePath);
  17. try {
  18. db.exec("PRAGMA busy_timeout=0");
  19. await sqliteMigrations.restore(db, backupPath);
  20. console.log(`Restored and verified: ${databasePath}`);
  21. } finally {
  22. db.close();
  23. }