- Rewrite scripts/run-migrations.js for PostgreSQL (was better-sqlite3) - Rewrite scripts/load-initial-data.js for PostgreSQL (was better-sqlite3) - Make db connection lazy in src/lib/db/index.ts to avoid build-time errors when DATABASE_URL is not available in Docker build stage
51 lines
1.5 KiB
TypeScript
51 lines
1.5 KiB
TypeScript
import { Pool } from 'pg';
|
||
import { drizzle, type NodePgDatabase } from 'drizzle-orm/node-postgres';
|
||
import { migrate } from 'drizzle-orm/node-postgres/migrator';
|
||
import * as schema from './schema';
|
||
import path from 'path';
|
||
|
||
let _pool: Pool | null = null;
|
||
let _db: NodePgDatabase<typeof schema> | null = null;
|
||
let _migrated = false;
|
||
|
||
function getPool(): Pool {
|
||
if (!_pool) {
|
||
const DATABASE_URL = process.env.DATABASE_URL;
|
||
if (!DATABASE_URL) {
|
||
throw new Error('DATABASE_URL environment variable is not set');
|
||
}
|
||
_pool = new Pool({ connectionString: DATABASE_URL, max: 10 });
|
||
}
|
||
return _pool;
|
||
}
|
||
|
||
function getDb(): NodePgDatabase<typeof schema> {
|
||
if (!_db) {
|
||
_db = drizzle(getPool(), { schema });
|
||
}
|
||
return _db;
|
||
}
|
||
|
||
export async function runMigrations() {
|
||
if (_migrated) return;
|
||
const isBuildTime = process.env.NEXT_PHASE === 'phase-production-build' || process.env.NEXT_PHASE === 'phase-development-build';
|
||
if (isBuildTime) {
|
||
console.log('ℹ️ Skipping migrations during build phase');
|
||
return;
|
||
}
|
||
try {
|
||
await migrate(getDb(), { migrationsFolder: path.join(process.cwd(), 'drizzle') });
|
||
console.log('✅ Database migrations completed');
|
||
_migrated = true;
|
||
} catch (error) {
|
||
console.error('❌ Migration failed:', error);
|
||
throw error;
|
||
}
|
||
}
|
||
|
||
// Lazy proxy: db is accessed as a module export but only connects on first use
|
||
export const db = new Proxy({} as NodePgDatabase<typeof schema>, {
|
||
get(_target, prop, receiver) {
|
||
return Reflect.get(getDb(), prop, receiver);
|
||
},
|
||
});
|