forked from admin/runners-calendar
50 lines
1.3 KiB
TypeScript
50 lines
1.3 KiB
TypeScript
import fs from "fs";
|
|
import path from "path";
|
|
import { pool } from "./db";
|
|
|
|
export async function migrate() {
|
|
console.log("[migrate] Running migrations…");
|
|
|
|
const migrationsDir = path.resolve(__dirname, "../migrations");
|
|
const files = fs.readdirSync(migrationsDir).filter((f) => f.endsWith(".sql")).sort();
|
|
|
|
const client = await pool.connect();
|
|
try {
|
|
await client.query(`
|
|
CREATE TABLE IF NOT EXISTS _migrations (
|
|
filename TEXT PRIMARY KEY,
|
|
applied_at TIMESTAMPTZ DEFAULT NOW()
|
|
)
|
|
`);
|
|
|
|
for (const file of files) {
|
|
const { rowCount } = await client.query(
|
|
"SELECT 1 FROM _migrations WHERE filename = $1",
|
|
[file],
|
|
);
|
|
if (rowCount && rowCount > 0) {
|
|
console.log(`[migrate] Already applied: ${file}`);
|
|
continue;
|
|
}
|
|
|
|
const sql = fs.readFileSync(path.join(migrationsDir, file), "utf-8");
|
|
await client.query(sql);
|
|
await client.query("INSERT INTO _migrations (filename) VALUES ($1)", [file]);
|
|
console.log(`[migrate] Applied: ${file}`);
|
|
}
|
|
|
|
console.log("[migrate] Done.");
|
|
} finally {
|
|
client.release();
|
|
}
|
|
}
|
|
|
|
if (require.main === module) {
|
|
migrate()
|
|
.catch((err) => {
|
|
console.error("[migrate] FAILED:", err.message);
|
|
process.exitCode = 1;
|
|
})
|
|
.finally(() => pool.end());
|
|
}
|