59 lines
1.9 KiB
JavaScript
59 lines
1.9 KiB
JavaScript
import { createHash } from "node:crypto";
|
|
import { readdir, readFile } from "node:fs/promises";
|
|
import path from "node:path";
|
|
import pg from "pg";
|
|
|
|
function databaseUrl() {
|
|
if (process.env.DATABASE_URL) return process.env.DATABASE_URL;
|
|
const host = process.env.DB_HOST;
|
|
if (host) {
|
|
const user = encodeURIComponent(process.env.DB_USER ?? "");
|
|
const password = encodeURIComponent(process.env.DB_PASSWORD ?? "");
|
|
const name = process.env.DB_NAME ?? "courier";
|
|
const port = process.env.DB_PORT ?? "5432";
|
|
return `postgresql://${user}:${password}@${host}:${port}/${name}`;
|
|
}
|
|
return `postgresql://courier@127.0.0.1:${process.env.DB_PORT || "55432"}/courier`;
|
|
}
|
|
|
|
const url = databaseUrl();
|
|
|
|
const client = new pg.Client({ connectionString: url });
|
|
await client.connect();
|
|
|
|
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 dir = path.join(process.cwd(), "db", "migrations");
|
|
const files = (await readdir(dir)).filter((file) => file.endsWith(".sql")).sort();
|
|
|
|
for (const file of files) {
|
|
const sql = await readFile(path.join(dir, file), "utf8");
|
|
const checksum = createHash("sha256").update(sql).digest("hex");
|
|
const { rows } = await client.query(`select checksum from schema_migrations where name = $1`, [file]);
|
|
if (rows[0]) {
|
|
if (rows[0].checksum !== checksum) {
|
|
throw new Error(`${file} wurde nach dem Anwenden geändert`);
|
|
}
|
|
continue;
|
|
}
|
|
console.log(`migrate ${file}`);
|
|
await client.query("begin");
|
|
try {
|
|
await client.query(sql);
|
|
await client.query(`insert into schema_migrations (name, checksum) values ($1, $2)`, [file, checksum]);
|
|
await client.query("commit");
|
|
} catch (error) {
|
|
await client.query("rollback");
|
|
throw error;
|
|
}
|
|
}
|
|
|
|
await client.end();
|
|
console.log("Datenbank aktuell.");
|