public
anord
read
Ledger
Why work hard when you can work easier?
Languages
Repository composition by tracked source files.
TypeScript
86%
CSS
10%
SQL
3%
Shell
1%
HTML
0%
Trace
apps/api/src/db/migrate.ts
Trace helps you understand code history line by line. See who changed each line, when it changed, and which commit introduced it.
Author
Date
Commit
Line
Code
1
import { readdir, readFile } from "node:fs/promises";
2
import path from "node:path";
3
import { fileURLToPath } from "node:url";
4
import { pool } from "./pool.js";
6
const __dirname = path.dirname(fileURLToPath(import.meta.url));
8
async function main() {
9
await pool.query(`
10
CREATE TABLE IF NOT EXISTS schema_migrations (
11
id SERIAL PRIMARY KEY,
12
filename TEXT NOT NULL UNIQUE,
13
applied_at TIMESTAMPTZ NOT NULL DEFAULT now()
14
)
15
`);
17
const files = (await readdir(path.join(__dirname, "migrations")))
18
.filter((file) => file.endsWith(".sql"))
19
.sort();
21
for (const filename of files) {
22
const existing = await pool.query(
23
"SELECT 1 FROM schema_migrations WHERE filename = $1",
24
[filename]
25
);
27
if (existing.rowCount) {
28
continue;
29
}
31
const sql = await readFile(path.join(__dirname, "migrations", filename), "utf8");
33
await pool.query("BEGIN");
34
try {
35
await pool.query(sql);
36
await pool.query("INSERT INTO schema_migrations (filename) VALUES ($1)", [filename]);
37
await pool.query("COMMIT");
38
console.log(`applied migration ${filename}`);
39
} catch (error) {
40
await pool.query("ROLLBACK");
41
throw error;
42
}
43
}
44
}
46
main()
47
.catch((error) => {
48
console.error(error);
49
process.exitCode = 1;
50
})
51
.finally(async () => {
52
await pool.end();
53
});