All files / database/src connection-manager.js

72.95% Statements 89/122
68.11% Branches 47/69
71.42% Functions 10/14
72.72% Lines 88/121

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430                                                                                                  54x   54x 54x 54x 54x 54x 54x     54x 54x     54x                                     54x 1x       53x 37x           37x   37x       37x       16x   16x 1x     15x 15x 1x     14x 1x       13x             13x                                                         41x 1x     40x   40x     40x 40x               33x   33x 33x     33x       33x   7x 7x 7x   7x 5x 5x 5x     2x                         40x 40x                                                               38x   38x 38x 38x             37x 37x 37x     1x 1x                                 68x 1x     67x   67x       67x 51x     16x 16x           65x 65x 65x         65x       65x   65x     2x 2x   2x                                         8x 2x     6x                                                                 4x                         26x 2x       24x           24x 24x     24x 24x 24x   24x   24x                                          
/**
 * Database Connection Manager for Coherent.js
 *
 * @fileoverview Manages database connections, connection pooling, and adapter selection
 * with support for multiple database engines and automatic failover.
 */
 
import { EventEmitter } from 'events';
 
// Import adapters statically to work with bundled builds
import { createPostgreSQLAdapter } from './adapters/postgresql.js';
import { createMySQLAdapter } from './adapters/mysql.js';
import { createSQLiteAdapter } from './adapters/sqlite.js';
import { createMongoDBAdapter } from './adapters/mongodb.js';
import { MemoryAdapter } from './adapters/memory.js';
 
/**
 * Database Connection Manager
 *
 * @class DatabaseManager
 * @extends EventEmitter
 * @description Manages database connections with pooling, health checks, and adapter abstraction.
 * Provides a unified interface for different database engines.
 *
 * @param {Object} config - Database configuration
 * @param {string} config.type - Database type ('postgresql', 'mysql', 'sqlite', 'mongodb')
 * @param {string} [config.host='localhost'] - Database host
 * @param {number} [config.port] - Database port (auto-detected by type)
 * @param {string} config.database - Database name
 * @param {string} [config.username] - Database username
 * @param {string} [config.password] - Database password
 * @param {Object} [config.pool] - Connection pool configuration
 * @param {boolean} [config.debug=false] - Enable debug logging
 *
 * @example
 * const db = new DatabaseManager({
 *   type: 'postgresql',
 *   host: 'localhost',
 *   database: 'myapp',
 *   username: 'user',
 *   password: 'pass',
 *   pool: { min: 2, max: 10 }
 * });
 *
 * await db.connect();
 * const users = await db.query('SELECT * FROM users WHERE active = ?', [true]);
 */
export class DatabaseManager extends EventEmitter {
  constructor(config) {
    super();
 
    this.config = this.validateConfig(config);
    this.adapter = null;
    this.pool = null;
    this.isConnected = false;
    this.connectionAttempts = 0;
    this.maxRetries = 3;
 
    // Health check interval
    this.healthCheckInterval = null;
    this.healthCheckFrequency = 30000; // 30 seconds
 
    // Connection statistics
    this.stats = {
      totalConnections: 0,
      activeConnections: 0,
      failedConnections: 0,
      queriesExecuted: 0,
      averageQueryTime: 0,
      lastHealthCheck: null
    };
  }
 
  /**
   * Validate database configuration
   *
   * @private
   * @param {Object} config - Configuration to validate
   * @returns {Object} Validated configuration
   * @throws {Error} If configuration is invalid
   */
  validateConfig(config) {
    if (!config || typeof config !== 'object') {
      throw new Error('Database configuration is required');
    }
 
    // New adapter-based configuration
    if (config.adapter) {
      Iif (typeof config.adapter !== 'object' ||
          typeof config.adapter.createPool !== 'function') {
        throw new Error('Invalid adapter provided. Adapter must be an object with a createPool method');
      }
 
      // Set default store config if not provided
      Iif (!config.store) {
        config.store = { name: 'default' };
      } else Iif (typeof config.store === 'string') {
        config.store = { name: config.store };
      }
 
      return config;
    }
 
    // Legacy type-based configuration
    const { type, database } = config;
 
    if (!type) {
      throw new Error('Either database type or adapter is required');
    }
 
    const supportedTypes = ['postgresql', 'mysql', 'sqlite', 'mongodb'];
    if (!supportedTypes.includes(type)) {
      throw new Error(`Unsupported database type: ${type}. Supported types: ${supportedTypes.join(', ')}`);
    }
 
    if (!database) {
      throw new Error('Database name is required for type-based configuration');
    }
 
    // Set default ports based on database type
    const defaultPorts = {
      postgresql: 5432,
      mysql: 3306,
      mongodb: 27017,
      sqlite: null
    };
 
    return {
      host: config.host || 'localhost',
      port: config.port || defaultPorts[type],
      ...config,
      pool: {
        min: 2,
        max: 10,
        acquireTimeoutMillis: 30000,
        createTimeoutMillis: 30000,
        destroyTimeoutMillis: 5000,
        idleTimeoutMillis: 30000,
        reapIntervalMillis: 1000,
        createRetryIntervalMillis: 200,
        ...config.pool
      }
    };
  }
 
  /**
   * Connect to the database
   *
   * @returns {Promise<void>}
   * @throws {Error} If connection fails after retries
   *
   * @example
   * await db.connect();
   * console.log('Database connected successfully');
   */
  async connect() {
    if (this.isConnected) {
      return;
    }
 
    try {
      // Load appropriate adapter
      this.adapter = await this.loadAdapter(this.config.type);
 
      // Create connection pool or connect (adapters may have different methods)
      if (typeof this.adapter.createPool === 'function') {
        this.pool = await this.adapter.createPool(this.config);
      } else Eif (typeof this.adapter.connect === 'function') {
        this.pool = await this.adapter.connect(this.config);
      } else {
        throw new Error('Adapter must have either createPool or connect method');
      }
 
      // Test connection
      await this.testConnection();
 
      this.isConnected = true;
      this.connectionAttempts = 0;
 
      // Start health checks if supported by the adapter
      Iif (this.adapter.startHealthChecks) {
        this.startHealthChecks();
      }
 
      return this;
    } catch (_error) {
      this.connectionAttempts++;
      this.stats.failedConnections++;
      this.emit('_error', _error);
 
      if (this.connectionAttempts < this.maxRetries) {
        console.warn(`Connection attempt ${this.connectionAttempts} failed. Retrying in 2 seconds...`);
        await new Promise(resolve => setTimeout(resolve, 2000));
        return this.connect();
      }
 
      throw new Error(`Failed to connect to database after ${this.connectionAttempts} attempts: ${_error.message}`);
    }
  }
 
  /**
   * Load database adapter
   *
   * @private
   * @param {string} type - Database type
   * @returns {Object} Database adapter
   */
  loadAdapter(type) {
    // If using direct adapter instance (for custom adapters like MemoryAdapter)
    Eif (this.config.adapter) {
      return Promise.resolve(this.config.adapter);
    }
 
    // For built-in adapters - use statically imported factory functions
    const adapterFactories = {
      postgresql: createPostgreSQLAdapter,
      mysql: createMySQLAdapter,
      sqlite: createSQLiteAdapter,
      mongodb: createMongoDBAdapter,
      memory: () => new MemoryAdapter()
    };
 
    const adapterFactory = adapterFactories[type];
    if (!adapterFactory) {
      return Promise.reject(new Error(`No adapter found for database type: ${type}`));
    }
 
    try {
      const adapter = adapterFactory();
      return Promise.resolve(adapter);
    } catch (_error) {
      return Promise.reject(new Error(`Failed to load ${type} adapter: ${_error.message}`));
    }
  }
 
  /**
   * Test database connection
   *
   * @private
   * @returns {Promise<void>}
   */
  async testConnection() {
    const startTime = Date.now();
 
    try {
      if (typeof this.adapter.testConnection === 'function') {
        await this.adapter.testConnection(this.pool);
      } else Eif (this.adapter.ping) {
        // Try ping if available
        await this.adapter.ping();
      }
      // If no test method is available, we'll assume the connection is good
 
      const duration = Date.now() - startTime;
      this.stats.lastHealthCheck = new Date();
      this.emit('connect:test', { duration });
 
    } catch (_error) {
      this.emit('_error', _error);
      throw new Error(`Database connection test failed: ${_error.message}`);
    }
  }
 
  /**
   * Execute a database query
   *
   * @param {string} sql - SQL query string
   * @param {Array} [params=[]] - Query parameters
   * @param {Object} [options={}] - Query options
   * @returns {Promise<Object>} Query result
   *
   * @example
   * const users = await db.query('SELECT * FROM users WHERE age > ?', [18]);
   * const user = await db.query('SELECT * FROM users WHERE id = ?', [123], { single: true });
   */
  async query(operation, params = {}) {
    if (!this.isConnected) {
      throw new Error('Database not connected. Call connect() first.');
    }
 
    const startTime = Date.now();
 
    try {
      let result;
 
      // Handle MemoryAdapter's query method
      if (typeof this.pool.query === 'function') {
        result = await this.pool.query(operation, params);
      }
      // Handle SQL adapters
      else if (typeof this.adapter.query === 'function') {
        result = await this.adapter.query(this.pool, operation, params);
      } else E{
        throw new Error('No valid query method found on adapter or pool');
      }
 
      // Update statistics
      const duration = Date.now() - startTime;
      this.stats.queriesExecuted++;
      this.stats.averageQueryTime = (
        (this.stats.averageQueryTime * (this.stats.queriesExecuted - 1) + duration) /
        this.stats.queriesExecuted
      );
 
      Iif (this.config.debug) {
        console.log(`Query executed in ${duration}ms: ${operation}`, params);
      }
 
      this.emit('query', { operation, params, duration });
 
      return result;
 
    } catch (_error) {
      const duration = Date.now() - startTime;
      this.emit('queryError', { operation, params, duration, _error: _error.message });
 
      throw new Error(`Query failed: ${_error.message}`);
    }
  }
 
  /**
   * Start a database transaction
   *
   * @returns {Promise<Object>} Transaction object
   *
   * @example
   * const tx = await db.transaction();
   * try {
   *   await tx.query('INSERT INTO users (name) VALUES (?)', ['John']);
   *   await tx.query('INSERT INTO profiles (user_id) VALUES (?)', [userId]);
   *   await tx.commit();
   * } catch (_error) {
   *   await tx.rollback();
   *   throw _error;
   * }
   */
  async transaction() {
    if (!this.isConnected) {
      throw new Error('Database not connected. Call connect() first.');
    }
 
    return await this.adapter.transaction(this.pool);
  }
 
  /**
   * Start health check monitoring
   *
   * @private
   */
  startHealthCheck() {
    if (this.healthCheckInterval) {
      return;
    }
 
    this.healthCheckInterval = setInterval(async () => {
      try {
        await this.testConnection();
        this.emit('healthCheck', { status: 'healthy', timestamp: new Date() });
      } catch (_error) {
        this.emit('healthCheck', { status: 'unhealthy', _error: _error.message, timestamp: new Date() });
 
        if (this.config.debug) {
          console.error('Database health check failed:', _error.message);
        }
      }
    }, this.healthCheckFrequency);
  }
 
  /**
   * Get connection statistics
   *
   * @returns {Object} Connection statistics
   */
  getStats() {
    return {
      ...this.stats,
      isConnected: this.isConnected,
      poolStats: this.pool ? this.adapter.getPoolStats(this.pool) : null
    };
  }
 
  /**
   * Close database connection
   *
   * @returns {Promise<void>}
   */
  async close() {
    if (!this.isConnected) {
      return;
    }
 
    // Stop health checks
    Iif (this.healthCheckInterval) {
      clearInterval(this.healthCheckInterval);
      this.healthCheckInterval = null;
    }
 
    // Close connection pool
    Eif (this.pool && this.adapter) {
      await this.adapter.closePool(this.pool);
    }
 
    this.isConnected = false;
    this.pool = null;
    this.adapter = null;
 
    this.emit('disconnected');
 
    Iif (this.config.debug) {
      console.log('Database connection closed');
    }
  }
}
 
/**
 * Factory function to create a DatabaseManager instance
 *
 * @param {Object} config - Database configuration
 * @returns {DatabaseManager} Database manager instance
 *
 * @example
 * const db = createDatabaseManager({
 *   type: 'sqlite',
 *   database: './app.db'
 * });
 */
export function createDatabaseManager(config) {
  return new DatabaseManager(config);
}