diff --git a/src/lib/database.ts b/src/lib/database.ts index d4c0848..a2ce8b2 100644 --- a/src/lib/database.ts +++ b/src/lib/database.ts @@ -38,15 +38,35 @@ async function connectWithRetry(maxRetries: number = 10, baseDelay: number = 100 throw new Error('Max retries exceeded'); } +function wrapPoolWithWriteLogging(pool: pg.Pool): pg.Pool { + const originalQuery = pool.query.bind(pool); + + pool.query = ((text: any, values?: any, callback?: any) => { + const sqlText = typeof text === 'string' ? text : text?.text; + const isWriteQuery = typeof sqlText === 'string' && /^(INSERT|UPDATE|DELETE)\b/i.test(sqlText.trim()); + + if (isWriteQuery) { + console.info('[DB WRITE]', { + sql: sqlText, + params: values ?? null, + }); + } + + return originalQuery(text as any, values as any, callback as any); + }) as typeof pool.query; + + return pool; +} + // Initialize database schema export async function initializeDatabase(options: DatabaseOptions = {}) { // Initialize pool - db = new Pool({ + db = wrapPoolWithWriteLogging(new Pool({ connectionString: options.url || process.env.DATABASE_URL || 'postgresql://postgres:password@localhost:5432/linkforty', ssl: process.env.NODE_ENV === 'production' ? { rejectUnauthorized: false } : false, min: options.pool?.min || 2, max: options.pool?.max || 10, - }); + })); const client = await connectWithRetry();