Files
lunch/scripts/migrate.mjs
T
kai a62e48116a
release / which version (push) Successful in 3s
release / olares chart · sanity (push) Successful in 3s
release / app (push) Successful in 55s
release / tag and release (push) Successful in 3s
Scaffold app, chart, CI and release (26.11.1) (#2)
2026-11-06 19:14:55 +00:00

84 lines
3.2 KiB
JavaScript

// Spielt db/migrations/*.sql in Namensreihenfolge ein — als Vorlauf-Container
// auf der Box (olares/templates/deployment.yaml) und lokal mit `npm run migrate`.
//
// Jede Datei läuft einmal, in einer eigenen Transaktion, und wird mit
// Prüfsumme in schema_migrations vermerkt. Eine schon angewandte Datei, deren
// Inhalt sich geändert hat, ist ein Fehler: Migrationen werden nie
// nachträglich bearbeitet, sondern durch eine neue ergänzt.
//
// Die Wiederholschleife beim Verbinden deckt das Fenster ab, in dem Olares
// das ns-owner-Label noch nicht gesetzt hat und die NetworkPolicy den Weg zur
// Datenbank sperrt (bei Insilo und Rocket gelernt; kein Helm-Hook).
import { createHash } from "node:crypto";
import { readdir, readFile } from "node:fs/promises";
import path from "node:path";
import { fileURLToPath } from "node:url";
import pg from "pg";
const DIR = process.env.MIGRATIONS_DIR ?? path.join(path.dirname(fileURLToPath(import.meta.url)), "..", "db", "migrations");
function config() {
if (process.env.DATABASE_URL) return { connectionString: process.env.DATABASE_URL };
return {
host: process.env.DB_HOST,
port: Number(process.env.DB_PORT ?? 5432),
user: process.env.DB_USER,
password: process.env.DB_PASSWORD,
database: process.env.DB_NAME,
};
}
async function connect(attempts = Number(process.env.MIGRATE_ATTEMPTS ?? 60), pause = 5000) {
let last;
for (let i = 1; i <= attempts; i++) {
const client = new pg.Client({ ...config(), connectionTimeoutMillis: 4000 });
try {
await client.connect();
return client;
} catch (error) {
last = error;
console.log(` attempt ${i}/${attempts}: ${error.message}`);
await client.end().catch(() => {});
if (i < attempts) await new Promise((r) => setTimeout(r, pause));
}
}
throw last;
}
async function main() {
console.log("waiting for postgres …");
const client = await connect();
try {
await client.query(`create table if not exists schema_migrations (
name text primary key, checksum text not null, applied_at timestamptz not null default now())`);
const done = new Map((await client.query("select name, checksum from schema_migrations")).rows.map((r) => [r.name, r.checksum]));
const files = (await readdir(DIR)).filter((f) => f.endsWith(".sql")).sort();
for (const file of files) {
const sql = await readFile(path.join(DIR, file), "utf8");
const sum = createHash("sha256").update(sql).digest("hex");
if (done.has(file)) {
if (done.get(file) !== sum) throw new Error(`${file} was changed after it was applied — add a new migration instead`);
continue;
}
console.log(`applying ${file}`);
await client.query("begin");
try {
await client.query(sql);
await client.query("insert into schema_migrations (name, checksum) values ($1, $2)", [file, sum]);
await client.query("commit");
} catch (error) {
await client.query("rollback");
throw new Error(`${file}: ${error.message}`);
}
}
console.log(`migrations up to date (${files.length} files)`);
} finally {
await client.end();
}
}
main().catch((error) => {
console.error(error.message);
process.exit(1);
});