Files
Aut.ManagementFaculty/scripts/dump-database.mjs
T

199 lines
6.2 KiB
JavaScript

// Usage: node scripts/dump-database.mjs
// Reads DATABASE_URL from the environment or .env.local.
// Writes a restorable SQL snapshot under backups/ (gitignored).
import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
import path from "node:path";
import { fileURLToPath } from "node:url";
import pg from "pg";
const { Client } = pg;
const rootDir = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..");
if (!process.env.DATABASE_URL) {
const envPath = path.join(rootDir, ".env.local");
if (existsSync(envPath)) {
for (const line of readFileSync(envPath, "utf8").split(/\r?\n/)) {
const match = line.match(/^\s*([A-Z0-9_]+)\s*=\s*(.*)\s*$/);
if (match && !(match[1] in process.env)) {
process.env[match[1]] = match[2];
}
}
}
}
if (!process.env.DATABASE_URL) {
console.error("DATABASE_URL is not set. Copy .env.example → .env.local and fill it in.");
process.exit(1);
}
function quoteIdent(name) {
return `"${String(name).replaceAll('"', '""')}"`;
}
function topologicalTables(tables, edges) {
const remaining = new Set(tables);
const parentsByChild = new Map(tables.map((table) => [table, new Set()]));
for (const { child, parent } of edges) {
if (remaining.has(child) && remaining.has(parent) && child !== parent) {
parentsByChild.get(child).add(parent);
}
}
const ordered = [];
while (remaining.size > 0) {
const ready = [...remaining].filter((table) => {
const parents = parentsByChild.get(table);
return [...parents].every((parent) => !remaining.has(parent));
});
const batch = ready.length > 0 ? ready.toSorted() : [[...remaining].toSorted()[0]];
for (const table of batch) {
remaining.delete(table);
ordered.push(table);
}
}
return ordered;
}
async function main() {
const client = new Client({
connectionString: process.env.DATABASE_URL,
connectionTimeoutMillis: Number(process.env.DATABASE_CONNECTION_TIMEOUT_MS ?? 20_000),
});
await client.connect();
try {
const info = await client.query(`
SELECT current_database() AS database, current_user AS username, now() AS dumped_at
`);
const { database, username, dumped_at } = info.rows[0];
const tableRows = await client.query(`
SELECT table_name
FROM information_schema.tables
WHERE table_schema = 'public' AND table_type = 'BASE TABLE'
ORDER BY table_name
`);
const tables = tableRows.rows.map((row) => row.table_name);
const fkRows = await client.query(`
SELECT
tc.table_name AS child,
ccu.table_name AS parent
FROM information_schema.table_constraints AS tc
JOIN information_schema.constraint_column_usage AS ccu
ON tc.constraint_name = ccu.constraint_name
AND tc.table_schema = ccu.table_schema
WHERE tc.constraint_type = 'FOREIGN KEY'
AND tc.table_schema = 'public'
`);
const ordered = topologicalTables(tables, fkRows.rows);
const stamp = new Date(dumped_at).toISOString().replace(/[-:]/g, "").replace(/\.\d{3}Z$/, "Z");
const outDir = path.join(rootDir, "backups");
mkdirSync(outDir, { recursive: true });
const outFile = path.join(outDir, `${database}-${stamp}.sql`);
const lines = [
`-- Snapshot of ${database} (user ${username})`,
`-- Generated at ${new Date(dumped_at).toISOString()}`,
`-- Restore into an empty DB after migrations, or into a matching schema:`,
`-- psql -v ON_ERROR_STOP=1 -d TARGET_DB -f ${path.basename(outFile)}`,
"BEGIN;",
"SET client_encoding = 'UTF8';",
"SET statement_timeout = 0;",
"SET lock_timeout = 0;",
"",
];
if (ordered.length > 0) {
lines.push(
`TRUNCATE ${ordered.map(quoteIdent).join(", ")} RESTART IDENTITY CASCADE;`,
"",
);
}
const counts = [];
for (const table of ordered) {
const columns = await client.query(
`
SELECT column_name
FROM information_schema.columns
WHERE table_schema = 'public' AND table_name = $1
ORDER BY ordinal_position
`,
[table],
);
const colNames = columns.rows.map((row) => row.column_name);
if (colNames.length === 0) continue;
const colIdents = colNames.map(quoteIdent).join(", ");
const tupleSql = colNames
.map((name) => `quote_nullable(${quoteIdent(name)}::text)`)
.join(" || ',' || ");
const data = await client.query(
`SELECT ${tupleSql} AS tuple FROM ${quoteIdent(table)}`,
);
counts.push({ table, rows: data.rows.length });
lines.push(`-- ${table}: ${data.rows.length} row(s)`);
if (data.rows.length === 0) {
lines.push("");
continue;
}
const values = data.rows.map((row) => `(${row.tuple})`).join(",\n");
lines.push(
`INSERT INTO ${quoteIdent(table)} (${colIdents}) VALUES`,
`${values};`,
"",
);
}
const sequences = await client.query(`
SELECT sequencename, last_value
FROM pg_sequences
WHERE schemaname = 'public'
ORDER BY sequencename
`);
for (const seq of sequences.rows) {
if (seq.last_value == null) continue;
const seqName = String(seq.sequencename).replaceAll("'", "''");
lines.push(`SELECT setval('${seqName}', ${Number(seq.last_value)}, true);`);
}
lines.push("", "COMMIT;", "");
writeFileSync(outFile, lines.join("\n"), "utf8");
const statsFile = outFile.replace(/\.sql$/, ".tables.json");
writeFileSync(
statsFile,
JSON.stringify(
{
database,
dumpedAt: new Date(dumped_at).toISOString(),
tables: counts,
file: path.basename(outFile),
},
null,
2,
) + "\n",
"utf8",
);
const bytes = Buffer.byteLength(lines.join("\n"), "utf8");
console.log("DUMP_OK");
console.log(outFile);
console.log(`bytes=${bytes} tables=${counts.length} rows=${counts.reduce((sum, item) => sum + item.rows, 0)}`);
for (const item of counts) {
console.log(`${item.table}\t${item.rows}`);
}
} finally {
await client.end().catch(() => {});
}
}
main().catch((error) => {
console.error("DUMP_FAIL");
console.error(error instanceof Error ? error.message : error);
process.exit(1);
});