fix: replace all SQLite references with PostgreSQL in scripts and lazy-init db connection

- 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
This commit is contained in:
Marko Djordjevic 2026-02-17 23:48:47 +01:00
parent 2481fda68c
commit d5fc4662e9
3 changed files with 139 additions and 149 deletions

View file

@ -1,35 +1,51 @@
import { Pool } from 'pg';
import { drizzle } from 'drizzle-orm/node-postgres';
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';
// Read DATABASE_URL from environment
const DATABASE_URL = process.env.DATABASE_URL;
let _pool: Pool | null = null;
let _db: NodePgDatabase<typeof schema> | null = null;
let _migrated = false;
if (!DATABASE_URL) {
throw new Error('DATABASE_URL environment variable is not set');
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;
}
// Create PostgreSQL connection pool
const pool = new Pool({
connectionString: DATABASE_URL,
max: 10,
});
function getDb(): NodePgDatabase<typeof schema> {
if (!_db) {
_db = drizzle(getPool(), { schema });
}
return _db;
}
export const db = drizzle(pool, { schema });
// Run migrations at startup (skip during build phase)
const isBuildTime = process.env.NEXT_PHASE === 'phase-production-build' || process.env.NEXT_PHASE === 'phase-development-build';
if (!isBuildTime) {
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(db, { migrationsFolder: path.join(process.cwd(), 'drizzle') });
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;
}
} else {
console.log(' Skipping migrations during build phase');
}
// 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);
},
});