86 lines
4.4 KiB
TypeScript
86 lines
4.4 KiB
TypeScript
import { PARTITION_SPECS } from "../db/partitions.js"
|
|
import { PARTITION_WRITER_ADVISORY_KEY } from "./partition-write-transaction.js"
|
|
import { assertDatabaseControlArchiveBoundary } from "./database-control-archive-boundary.js"
|
|
import { restoreManagedPartitionPrimaryKeysSql } from "./database-partition-restore-keys.js"
|
|
|
|
// --single-transaction begins on the actual psql backend BEFORE this first
|
|
// command. Admission precedes prelude/archive DDL and COPY on that same session.
|
|
export const partitionRestoreAdmissionSql = `SET LOCAL lock_timeout='10s'; SET LOCAL statement_timeout='600s'; SELECT pg_advisory_xact_lock_shared(${PARTITION_WRITER_ADVISORY_KEY}::bigint);`
|
|
const partitionRestoreExclusiveAdmissionSql = `SET LOCAL lock_timeout='10s'; SET LOCAL statement_timeout='600s'; SELECT pg_catalog.pg_advisory_xact_lock(${PARTITION_WRITER_ADVISORY_KEY}::bigint);`
|
|
|
|
function managedPartitionParents(toc: string) {
|
|
const tables = new Set<string>()
|
|
for (const line of toc.split(/\r?\n/)) {
|
|
const match = /^\d+;\s+\d+\s+\d+\s+TABLE public ([a-z_][a-z_0-9]*)\s/.exec(line)
|
|
if (match) tables.add(match[1])
|
|
}
|
|
if (!tables.has("servers") || !tables.has("schema_migrations")) {
|
|
throw new Error("Архив не содержит обязательные таблицы базы приложения")
|
|
}
|
|
return PARTITION_SPECS.map(s => s.parent).filter(name => tables.has(name))
|
|
}
|
|
|
|
/** Only application parents actually present in the archive may be prepared. */
|
|
export function partitionRestorePrelude(toc: string): string {
|
|
const parents = managedPartitionParents(toc)
|
|
if (!parents.length) return "SELECT 1;"
|
|
return `DO $mm_restore$
|
|
DECLARE r record;
|
|
BEGIN
|
|
FOR r IN
|
|
SELECT n.nspname, t.relname, c.conname
|
|
FROM pg_constraint c
|
|
JOIN pg_class t ON t.oid = c.conrelid
|
|
JOIN pg_namespace n ON n.oid = t.relnamespace
|
|
WHERE n.nspname = 'public' AND t.relkind = 'p'
|
|
AND c.conparentid = 0 AND c.contype IN ('p', 'u')
|
|
AND t.relname IN (${parents.map(name => `'${name}'`).join(", ")})
|
|
LOOP
|
|
EXECUTE format('ALTER TABLE %I.%I DROP CONSTRAINT %I CASCADE', r.nspname, r.relname, r.conname);
|
|
END LOOP;
|
|
END $mm_restore$;`
|
|
}
|
|
|
|
interface Dependencies {
|
|
command: (command: string, args: string[]) => Promise<Buffer>
|
|
prepareSql: (file: string) => Promise<void>
|
|
beforeTargetReplacement?: () => void | Promise<void>
|
|
targetCheckSql?: string
|
|
exclusivePartitionWriters?: boolean
|
|
writePublicSchemaPreservingList?: (file: string, list: string) => Promise<void>
|
|
}
|
|
|
|
export async function restorePartitionedDatabase(file: string, databaseUrl: string, deps: Dependencies): Promise<void> {
|
|
const toc = await deps.command("pg_restore", ["--list", file])
|
|
assertDatabaseControlArchiveBoundary(toc)
|
|
const parsedToc = toc.toString("utf8")
|
|
const prelude = partitionRestorePrelude(parsedToc)
|
|
const sqlFile = `${file}.sql`
|
|
await deps.prepareSql(sqlFile)
|
|
const selectEntries: string[] = []
|
|
if (deps.writePublicSchemaPreservingList) {
|
|
let schemaEntries = 0
|
|
const list = parsedToc.replace(/^\d+;\s+\d+\s+\d+\s+SCHEMA - public(?: [^\r\n]+)?$/gm, entry => {
|
|
schemaEntries++
|
|
return `;${entry}`
|
|
})
|
|
if (schemaEntries > 1) throw new Error("Архив содержит несколько определений схемы public")
|
|
if (schemaEntries === 1) {
|
|
const listFile = `${file}.list`
|
|
await deps.writePublicSchemaPreservingList(listFile, list)
|
|
selectEntries.push("--use-list", listFile)
|
|
}
|
|
}
|
|
// Keep the protected schema object itself and decode every other archive entry unchanged.
|
|
await deps.command("pg_restore", ["--clean", "--if-exists", ...selectEntries, "--file", sqlFile, file])
|
|
// psql wraps both -c and -f in ONE transaction and rolls back on a SQL error.
|
|
await deps.beforeTargetReplacement?.()
|
|
const targetCheck = deps.targetCheckSql ? ["-c", deps.targetCheckSql] : []
|
|
const admission = deps.exclusivePartitionWriters ? partitionRestoreExclusiveAdmissionSql : partitionRestoreAdmissionSql
|
|
// Recheck the owning session after a possibly blocking wait for writers.
|
|
const afterDrain = deps.exclusivePartitionWriters ? targetCheck : []
|
|
const postlude = deps.writePublicSchemaPreservingList ? ["-c", restoreManagedPartitionPrimaryKeysSql(managedPartitionParents(parsedToc))] : []
|
|
await deps.command("psql", ["-X", "--no-password", "--single-transaction", "--set", "ON_ERROR_STOP=on",
|
|
"-d", databaseUrl, ...targetCheck, "-c", admission, ...afterDrain, "-c", prelude, "-f", sqlFile, ...postlude, ...targetCheck])
|
|
}
|