import type { PoolConfig, QueryResultRow } from 'pg'; import { Pool } from 'pg'; import type { LoggerLike } from '@stock-bot/logger'; import { PostgreSQLTransactionManager } from './transactions'; import type { ConnectionEvents, PoolMetrics, PostgreSQLClientConfig, PostgreSQLConnectionOptions, QueryResult, TransactionCallback, } from './types'; export class PostgreSQLClient { private pool: Pool | null = null; private readonly config: PostgreSQLClientConfig; private readonly options: PostgreSQLConnectionOptions; private readonly logger: LoggerLike; private readonly transactionManager: PostgreSQLTransactionManager; private isConnected = false; private readonly metrics: PoolMetrics; private readonly events?: ConnectionEvents; constructor( config: PostgreSQLClientConfig, logger?: LoggerLike, options?: PostgreSQLConnectionOptions, events?: ConnectionEvents ) { this.config = config; this.options = { retryAttempts: 3, retryDelay: 1000, ...options, }; this.events = events; this.logger = logger || console; this.transactionManager = new PostgreSQLTransactionManager(this); this.metrics = { totalConnections: 0, activeConnections: 0, idleConnections: 0, waitingRequests: 0, errors: 0, created: new Date(), }; } async connect(): Promise { if (this.isConnected && this.pool) { return; } let lastError: Error | null = null; const attempts = this.options.retryAttempts ?? 3; for (let attempt = 1; attempt <= attempts; attempt++) { try { this.logger.info(`Connecting to PostgreSQL (attempt ${attempt}/${attempts})...`); this.pool = new Pool(this.buildPoolConfig()); const client = await this.pool.connect(); try { await client.query('SELECT 1'); } finally { client.release(); } this.isConnected = true; this.metrics.totalConnections = this.config.poolSettings?.max || 10; this.metrics.idleConnections = this.pool.idleCount; if (this.events?.onConnect) { await Promise.resolve(this.events.onConnect()); } if (this.events?.onPoolCreated) { await Promise.resolve(this.events.onPoolCreated()); } this.setupErrorHandlers(); this.logger.info('Successfully connected to PostgreSQL', { poolSize: this.metrics.totalConnections, }); return; } catch (error) { lastError = error as Error; this.metrics.errors++; this.metrics.lastError = lastError.message; if (this.events?.onError) { await Promise.resolve(this.events.onError(lastError)); } this.logger.error(`PostgreSQL connection attempt ${attempt} failed:`, error); if (this.pool) { await this.pool.end().catch(() => {}); this.pool = null; } if (attempt < attempts) { await new Promise(resolve => setTimeout(resolve, (this.options.retryDelay ?? 1000) * attempt)); } } } throw new Error( `Failed to connect to PostgreSQL after ${attempts} attempts: ${lastError?.message}` ); } async disconnect(): Promise { if (!this.pool) { return; } try { await this.pool.end(); this.isConnected = false; this.pool = null; if (this.events?.onDisconnect) { await Promise.resolve(this.events.onDisconnect()); } this.logger.info('Disconnected from PostgreSQL'); } catch (error) { this.logger.error('Error disconnecting from PostgreSQL:', error); throw error; } } async query( text: string, params?: unknown[] ): Promise> { if (!this.pool) { throw new Error('PostgreSQL client not connected'); } const startTime = Date.now(); try { const result = await this.pool.query(text, params); const executionTime = Date.now() - startTime; this.logger.debug(`Query executed in ${executionTime}ms`, { query: text.substring(0, 100), params: params?.length, }); return { ...result, executionTime, } as QueryResult; } catch (error) { const executionTime = Date.now() - startTime; this.logger.error(`Query failed after ${executionTime}ms:`, { error, query: text, params, }); throw error; } } async transaction(callback: TransactionCallback): Promise { return await this.transactionManager.execute(callback); } async getStats(): Promise { const result = await this.query(` SELECT (SELECT count(*) FROM pg_stat_activity WHERE state = 'active') as active_connections, (SELECT count(*) FROM pg_stat_activity WHERE state = 'idle') as idle_connections, (SELECT setting FROM pg_settings WHERE name = 'max_connections') as max_connections, pg_size_pretty(pg_database_size(current_database())) as database_size `); return result.rows[0] ?? {}; } get connected(): boolean { return this.isConnected && !!this.pool; } get connectionPool(): Pool | null { return this.pool; } buildPoolConfig(): PoolConfig { this.logger.debug('Building PostgreSQL pool config:', { host: this.config.host, port: this.config.port, database: this.config.database, user: this.config.username, hasPassword: Boolean(this.config.password), }); return { host: this.config.host, port: this.config.port, database: this.config.database, user: this.config.username, password: typeof this.config.password === 'string' ? this.config.password : String(this.config.password || ''), min: this.config.poolSettings?.min, max: this.config.poolSettings?.max, idleTimeoutMillis: this.config.poolSettings?.idleTimeoutMillis, connectionTimeoutMillis: this.config.timeouts?.connection, query_timeout: this.config.timeouts?.query, statement_timeout: this.config.timeouts?.statement, lock_timeout: this.config.timeouts?.lock, idle_in_transaction_session_timeout: this.config.timeouts?.idleInTransaction, ssl: this.config.ssl?.enabled ? { rejectUnauthorized: this.config.ssl.rejectUnauthorized, } : false, }; } getPoolMetrics(): PoolMetrics { this.metrics.lastUsed = new Date(); if (this.pool) { this.metrics.totalConnections = this.pool.totalCount; this.metrics.idleConnections = this.pool.idleCount; this.metrics.waitingRequests = this.pool.waitingCount; this.metrics.activeConnections = Math.max( 0, this.metrics.totalConnections - this.metrics.idleConnections ); } return { ...this.metrics }; } private setupErrorHandlers(): void { if (!this.pool) { return; } this.pool.on('error', error => { this.logger.error('PostgreSQL pool error:', error); }); } }