Stufe 0: Grundgerüst mit Rechenkern, Datenbank, Oberfläche und Docker-Betrieb
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01AmyPfuNc4sCRfaF3oURXZz
This commit is contained in:
40
src/server/migrate.ts
Normal file
40
src/server/migrate.ts
Normal file
@@ -0,0 +1,40 @@
|
||||
import { readdir, readFile } from "node:fs/promises";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import path from "node:path";
|
||||
import type { Pool } from "./db.js";
|
||||
|
||||
const ORDNER = path.join(path.dirname(fileURLToPath(import.meta.url)), "migrations");
|
||||
|
||||
/**
|
||||
* Spielt alle noch fehlenden Migrationen in Namensreihenfolge ein, jede in eigener Transaktion.
|
||||
* Eine Sperre verhindert, dass zwei Container gleichzeitig migrieren.
|
||||
*/
|
||||
export async function migriere(pool: Pool, log: (text: string) => void = () => {}): Promise<string[]> {
|
||||
const c = await pool.connect();
|
||||
const neu: string[] = [];
|
||||
try {
|
||||
await c.query("select pg_advisory_lock(4711)");
|
||||
await c.query("create table if not exists schema_version (name text primary key, eingespielt_am timestamptz not null default now())");
|
||||
const vorhanden = new Set((await c.query<{ name: string }>("select name from schema_version")).rows.map((r) => r.name));
|
||||
const dateien = (await readdir(ORDNER)).filter((d) => d.endsWith(".sql")).sort();
|
||||
for (const datei of dateien) {
|
||||
if (vorhanden.has(datei)) continue;
|
||||
const sql = await readFile(path.join(ORDNER, datei), "utf8");
|
||||
await c.query("begin");
|
||||
try {
|
||||
await c.query(sql);
|
||||
await c.query("insert into schema_version (name) values ($1)", [datei]);
|
||||
await c.query("commit");
|
||||
} catch (e) {
|
||||
await c.query("rollback");
|
||||
throw new Error(`Migration ${datei} fehlgeschlagen: ${(e as Error).message}`);
|
||||
}
|
||||
log(`Migration ${datei} eingespielt`);
|
||||
neu.push(datei);
|
||||
}
|
||||
} finally {
|
||||
await c.query("select pg_advisory_unlock(4711)").catch(() => {});
|
||||
c.release();
|
||||
}
|
||||
return neu;
|
||||
}
|
||||
Reference in New Issue
Block a user