Skip to content

Commit b21d7ee

Browse files
authored
Merge pull request #225 from janezd/db-migrations
Implement database migrations
2 parents d41a71c + 8e1dbd2 commit b21d7ee

2 files changed

Lines changed: 33 additions & 0 deletions

File tree

utils/db.ts

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ import sqlite3 from "sqlite3";
22
import path from "node:path";
33
import { open, Database } from "sqlite";
44
import { CONFIG } from "@/utils/config";
5+
import { migrate } from "@/utils/migrateDb.mjs";
56

67
let db: Database;
78

@@ -36,6 +37,7 @@ if (!(process.env.NEXT_PHASE === 'phase-production-build' || process.env.CI)) {
3637
}
3738

3839
await db.exec("PRAGMA foreign_keys = ON");
40+
await migrate(db);
3941
} else {
4042
db = {} as unknown as Database;
4143
}

utils/migrateDb.mjs

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
/* This is not TypeScript because it has await at top-level => must be imported with dynamic import by ingest */
2+
3+
import path from "node:path";
4+
import fs from "fs";
5+
import { fileURLToPath } from "node:url";
6+
7+
export const migrate = async (db) => {
8+
const filename = fileURLToPath(import.meta.url);
9+
const dirname = path.dirname(filename);
10+
const migrationsDir = path.resolve(dirname, "db-migrations");
11+
12+
if (!fs.existsSync(migrationsDir)) {
13+
console.warn(`Migrations directory not found at ${migrationsDir}`);
14+
return;
15+
}
16+
const migrationFiles = fs.readdirSync(migrationsDir)
17+
.filter((file) => file.endsWith(".sql"))
18+
.sort();
19+
const { user_version } = await db.get(`PRAGMA user_version`);
20+
for (const file of migrationFiles) {
21+
const version = parseInt(file.split("-")[0]);
22+
if (version > user_version) {
23+
const sql = fs.readFileSync(path.join(migrationsDir, file), "utf-8");
24+
await db.exec("BEGIN TRANSACTION");
25+
await db.exec(sql);
26+
await db.exec(`PRAGMA user_version = ${version}`);
27+
await db.exec("COMMIT");
28+
console.log("Applied migration:", file);
29+
}
30+
}
31+
}

0 commit comments

Comments
 (0)