File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change @@ -2,6 +2,7 @@ import sqlite3 from "sqlite3";
22import path from "node:path" ;
33import { open , Database } from "sqlite" ;
44import { CONFIG } from "@/utils/config" ;
5+ import { migrate } from "@/utils/migrateDb.mjs" ;
56
67let 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}
Original file line number Diff line number Diff line change 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+ }
You can’t perform that action at this time.
0 commit comments