Files
HamHam/scripts/migrate.ts

19 lines
805 B
TypeScript

import 'dotenv/config';
import { readdir, readFile } from 'node:fs/promises';
import postgres from 'postgres';
const sql = postgres(process.env.DATABASE_URL!, { max: 1 });
try {
await sql.begin(async (tx) => {
await tx`SELECT pg_advisory_xact_lock(7218194)`;
await tx`CREATE TABLE IF NOT EXISTS migrations (name text PRIMARY KEY, applied_at timestamptz NOT NULL DEFAULT now())`;
for (const name of (await readdir('migrations')).filter((f) => f.endsWith('.sql')).sort()) {
if ((await tx`SELECT name FROM migrations WHERE name = ${name}`).length) continue;
await tx.unsafe(await readFile(`migrations/${name}`, 'utf8'));
await tx`INSERT INTO migrations (name) VALUES (${name})`;
console.log(`Migration angewendet: ${name}`);
}
});
} finally {
await sql.end();
}