candle-annotator/src/lib/db/index.ts
Marko Djordjevic d5fc4662e9 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
2026-02-17 23:48:47 +01:00

51 lines
1.5 KiB
TypeScript
Raw Blame History

This file contains invisible Unicode characters

This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

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);
},
});