Files
lunch/scripts/migrate.mjs
T
Kai BöhmandClaude Opus 5.5 fa83e560b2
ci / olares chart · sanity (pull_request) Successful in 5s
ci / app · types + tests + build (pull_request) Successful in 3m54s
release / which version (pull_request) Successful in 1s
release / olares chart · sanity (pull_request) Successful in 3s
release / app (pull_request) Successful in 1m25s
release / tag and release (pull_request) Skipped
Scaffold the app, chart, CI and release (26.11.1)
Next.js 15 with next-intl (de, en, fr, es; locale per person, no URL
prefix), Tailwind v4 tokens for the warm palette with dark mode, a
shadcn/ui button, Serwist service worker and PWA manifest with icons.
One Postgres pool with withHousehold() setting app.household_id per
transaction; the first migration creates households with FORCE ROW
LEVEL SECURITY, and a two-household test checks the isolation as the
table owner. scripts/migrate.mjs applies db/migrations once each with a
checksum and retries until the database is reachable.

Olares chart with one deployment (init: chown, migrate from the same
image), ClusterIP service, entrance internal until the own sign-in
exists, image path fixed in the template and tag from appVersion.
scripts/check-chart.sh carries the rules from Rocket; CI runs it, type
check, tests against Postgres and the build; release builds
lunch-app, tags and attaches the chart.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01HUc2nv7rJVU2gp3Bgtha3q
2026-11-06 19:08:21 +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);
});