76 lines
3.8 KiB
TypeScript
76 lines
3.8 KiB
TypeScript
// One-time move of Peppa's data from Postgres to SQLite (PEP-36):
|
||
// peppa db migrate-to-sqlite <file> (source: DATABASE_URL)
|
||
// The Postgres session is read-only, so the source cannot change. The new file is built
|
||
// next to the target and renamed into place only after row counts and foreign keys check
|
||
// out; on any mismatch it is deleted and nothing else is touched.
|
||
import { createDb, migrateDb, tablesInFkOrder } from "@peppa/db";
|
||
import { existsSync, renameSync, rmSync } from "node:fs";
|
||
import postgres from "postgres";
|
||
|
||
const toSqlite = (v: unknown, c: { json: boolean; ms: boolean; bool: boolean }) => {
|
||
if (v === null || v === undefined) return null;
|
||
if (c.ms) return v instanceof Date ? v.getTime() : new Date(String(v)).getTime();
|
||
if (c.bool) return v ? 1 : 0;
|
||
if (c.json) return JSON.stringify(v);
|
||
if (typeof v === "bigint") return Number(v);
|
||
if (v instanceof Date) return v.getTime();
|
||
return v as string | number;
|
||
};
|
||
|
||
export interface MigrationReport {
|
||
file: string;
|
||
tables: { name: string; source: number; copied: number }[];
|
||
ms: number;
|
||
}
|
||
|
||
export async function migrateToSqlite(sourceUrl: string, file: string): Promise<MigrationReport> {
|
||
if (existsSync(file)) throw new Error(`${file} уже существует — переложите его`);
|
||
const tmp = `${file}.migrating`;
|
||
for (const s of ["", "-wal", "-shm"]) rmSync(tmp + s, { force: true });
|
||
const pg = postgres(sourceUrl, { max: 1, onnotice: () => {}, connection: { default_transaction_read_only: "on" } as never });
|
||
const t0 = Date.now();
|
||
const db = createDb(tmp);
|
||
try {
|
||
migrateDb(db);
|
||
// Copy first, then check: foreign_key_check names the table with a dangling reference.
|
||
db.$client.db.exec("PRAGMA foreign_keys = OFF");
|
||
const report: MigrationReport["tables"] = [];
|
||
// One read-only snapshot of Postgres for all tables.
|
||
await pg.begin("isolation level repeatable read read only", async (tx) => {
|
||
for (const t of tablesInFkOrder()) {
|
||
// Tables born after the move to SQLite (PEP-67 subscriptions…) don't exist in Postgres.
|
||
const [{ found }] = await tx.unsafe(`select to_regclass($1) is not null as found`, [`public."${t.name}"`]);
|
||
if (!found) {
|
||
report.push({ name: t.name, source: 0, copied: 0 });
|
||
continue;
|
||
}
|
||
const rows = await tx.unsafe(`select * from "${t.name}"`);
|
||
const cols = t.columns.filter((c) => rows.length === 0 || c.name in rows[0]!);
|
||
if (rows.length) {
|
||
const stmt = db.$client.db.prepare(`insert into "${t.name}" (${cols.map((c) => `"${c.name}"`).join(", ")}) values (${cols.map(() => "?").join(", ")})`);
|
||
db.$client.transaction(() => {
|
||
for (const r of rows) stmt.run(...cols.map((c) => toSqlite(r[c.name], c)));
|
||
}).immediate();
|
||
}
|
||
const [{ n }] = db.$client.db.prepare(`select count(*) n from "${t.name}"`).all() as { n: number }[];
|
||
report.push({ name: t.name, source: rows.length, copied: Number(n) });
|
||
}
|
||
});
|
||
const bad = report.filter((t) => t.source !== t.copied);
|
||
if (bad.length) throw new Error(`расходится число строк: ${bad.map((t) => `${t.name} ${t.source}→${t.copied}`).join(", ")}`);
|
||
const fk = db.$client.db.prepare("PRAGMA foreign_key_check").all() as { table: string }[];
|
||
if (fk.length) throw new Error(`${[...new Set(fk.map((r) => r.table))].join(", ")}: нарушение внешнего ключа`);
|
||
db.$client.db.exec("PRAGMA wal_checkpoint(TRUNCATE)");
|
||
db.$client.close();
|
||
renameSync(tmp, file);
|
||
for (const s of ["-wal", "-shm"]) rmSync(tmp + s, { force: true });
|
||
return { file, tables: report, ms: Date.now() - t0 };
|
||
} catch (e) {
|
||
db.$client.close();
|
||
for (const s of ["", "-wal", "-shm"]) rmSync(tmp + s, { force: true });
|
||
throw e;
|
||
} finally {
|
||
await pg.end({ timeout: 1 });
|
||
}
|
||
}
|