import pg from 'pg';
import { promises as fs } from 'fs';
import path from 'path';
import { fileURLToPath } from 'url';
import { CONFIG } from '../config.js';
import { sendLogMessage } from '../utils/logger.js';
const { Pool } = pg;
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
let pool;
let dbInitialized = false;
export function getPool() {
if (!pool) {
try {
pool = new Pool({
connectionString: CONFIG.db.connectionString,
max: CONFIG.db.maxPoolSize,
idleTimeoutMillis: CONFIG.db.idleTimeout
});
sendLogMessage('info', "PostgreSQL connection pool initialized");
} catch (error) {
sendLogMessage('error', `Failed to initialize PostgreSQL connection pool: ${error.message}`);
process.exit(1);
}
}
return pool;
}
export async function initializeDatabase() {
if (dbInitialized) return;
const currentPool = getPool();
try {
// Check if tables exist
const res = await currentPool.query(`
SELECT EXISTS (
SELECT FROM information_schema.tables
WHERE table_schema = 'public'
AND table_name = 'memories'
);
`);
if (!res.rows[0].exists) {
sendLogMessage('warn', 'Database tables not found. Please run "npm run db:init" to initialize the database schema.');
} else {
sendLogMessage('info', 'Database connected and schema verified');
}
dbInitialized = true;
} catch (error) {
sendLogMessage('error', `Error connecting to database: ${error.message}`, { stack: error.stack });
// Don't exit on database error - we might be able to handle some requests
}
}
export function isDbInitialized() {
return dbInitialized;
}
// Start database initialization in the background
initializeDatabase().catch(err => {
sendLogMessage('error', `Background database initialization failed: ${err.message}`);
});