All files / database/src connection-manager.js

91.41% Statements 149/163
84.12% Branches 106/126
100% Functions 16/16
91.25% Lines 146/160

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 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543                                                                                                  89x   89x 89x 89x 89x 89x 89x 89x     89x 89x 89x 1x       84x                                     89x 1x       88x 42x           42x 8x 34x       42x       46x   46x 1x     45x 45x 1x     44x 1x       43x               43x                                                         85x 1x     84x   84x     84x 50x 34x 34x           77x   71x 71x     71x   67x     71x     13x   13x 13x     13x   13x 9x 9x 9x     4x                     13x 13x 13x 13x   13x 7x     6x 6x 3x 3x                                     84x 47x       37x         3x     37x 37x       37x 37x 37x                         81x   81x 81x 41x 40x   37x 3x         73x 73x 73x     8x 8x                                 235x 1x     234x   234x       234x 230x     4x 4x           225x 225x 225x         225x       225x   225x     9x 9x   9x                               3x 1x     2x 1x     1x                                                                   29x 1x     28x       28x 26x     2x   2x 2x   1x 1x   1x     1x 1x   1x                           67x       67x 2x 2x 1x   1x   1x         67x                 6x                             49x 1x       48x 48x 48x       48x 48x 15x 33x 33x       48x 48x 48x   48x   48x                                     26x    
/**
 * 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;
    this.retryDelay = 2000;
 
    // Health check interval (config.healthCheckInterval, in milliseconds)
    this.healthCheckInterval = null;
    this.healthCheckFrequency = this.config.healthCheckInterval ?? 30000;
    if (!Number.isFinite(this.healthCheckFrequency) || this.healthCheckFrequency <= 0) {
      throw new Error(`healthCheckInterval must be a positive number of milliseconds, got ${this.healthCheckFrequency}`);
    }
 
    // 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
      if (!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', 'memory'];
    if (!supportedTypes.includes(type)) {
      throw new Error(`Unsupported database type: ${type}. Supported types: ${supportedTypes.join(', ')}`);
    }
 
    if (!database && type !== 'memory') {
      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,
      memory: 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 if (typeof this.adapter.connect === 'function') {
        this.pool = await this.adapter.connect(this.config);
      } else E{
        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 the adapter can test its connection
      if (this.config.healthCheck !== false &&
          (typeof this.adapter.testConnection === 'function' || typeof this.adapter.ping === 'function')) {
        this.startHealthCheck();
      }
 
      return this;
    } catch (_error) {
      // Close whatever this attempt opened before retrying, or every retry leaks a pool
      await this.discardFailedConnection();
 
      this.connectionAttempts++;
      this.stats.failedConnections++;
      // The failure also surfaces through the rejected promise, so only emit
      // when someone listens: an unhandled 'error' event would throw here.
      if (this.listenerCount('error') > 0) this.emit('error', _error);
 
      if (this.connectionAttempts < this.maxRetries) {
        console.warn(`Connection attempt ${this.connectionAttempts} failed. Retrying in ${this.retryDelay}ms...`);
        await new Promise(resolve => setTimeout(resolve, this.retryDelay));
        return this.connect();
      }
 
      throw new Error(`Failed to connect to database after ${this.connectionAttempts} attempts: ${_error.message}`);
    }
  }
 
  /**
   * Close the pool of a connection attempt that failed.
   *
   * @private
   * @returns {Promise<void>}
   */
  async discardFailedConnection() {
    const { adapter, pool } = this;
    this.pool = null;
    this.adapter = null;
    this.isConnected = false;
 
    if (!adapter || !pool) {
      return;
    }
 
    try {
      if (typeof adapter.closePool === 'function') {
        await adapter.closePool(pool);
      } else Iif (typeof adapter.disconnect === 'function') {
        await adapter.disconnect();
      }
    } catch (closeError) {
      if (this.config.debug) {
        console.error('Failed to close pool after a failed connection attempt:', closeError.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)
    if (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];
    Iif (!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 if (typeof this.adapter.ping === 'function') {
        // Adapters whose ping() reports failure as `false` instead of throwing
        if (await this.adapter.ping() === false) {
          throw new Error('ping failed');
        }
      }
      // 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) {
      if (this.listenerCount('error') > 0) 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}`);
    }
  }
 
  /**
   * Get a document-store collection (MongoDB)
   *
   * @param {string} name - Collection name
   * @returns {Object} Raw driver collection (insertOne, findOne, updateOne, …)
   * @throws {Error} If not connected, or the adapter is not a document store
   *
   * @example
   * const users = db.collection('users');
   * await users.insertOne({ email: 'ada@example.com' });
   */
  collection(name) {
    if (!this.isConnected) {
      throw new Error('Database not connected. Call connect() first.');
    }
 
    if (this.pool && typeof this.pool.collection === 'function') {
      return this.pool.collection(name);
    }
 
    throw new Error(`collection() is not supported by the '${this.config.type}' adapter — it is only available for document databases (mongodb)`);
  }
 
  /**
   * Start a database transaction, or run a callback in one
   *
   * With options (or nothing), resolves to a transaction object with `query`, `commit`
   * and `rollback`. With a callback, runs it with the transaction, commits when it
   * resolves, rolls back when it throws, and resolves to the callback's result.
   *
   * @param {Function|Object} [callbackOrOptions] - Callback, or transaction options
   * @param {Object} [options={}] - Transaction options when a callback is given
   * @param {string} [options.isolationLevel] - READ UNCOMMITTED, READ COMMITTED, REPEATABLE READ or SERIALIZABLE
   * @param {boolean} [options.readOnly] - Start a read-only transaction
   * @returns {Promise<Object|*>} Transaction object, or the callback's result
   *
   * @example
   * const tx = await db.transaction({ isolationLevel: 'SERIALIZABLE' });
   * 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;
   * }
   *
   * @example
   * const user = await db.transaction(async (tx) => {
   *   await tx.query('INSERT INTO users (name) VALUES (?)', ['John']);
   *   return (await tx.query('SELECT * FROM users WHERE name = ?', ['John'])).rows[0];
   * });
   */
  async transaction(callbackOrOptions, options) {
    if (!this.isConnected) {
      throw new Error('Database not connected. Call connect() first.');
    }
 
    Iif (typeof this.adapter.transaction !== 'function') {
      throw new Error(`The ${this.config.type || 'configured'} adapter does not support transactions`);
    }
 
    if (typeof callbackOrOptions !== 'function') {
      return await this.adapter.transaction(this.pool, callbackOrOptions || {});
    }
 
    const tx = await this.adapter.transaction(this.pool, options || {});
    let result;
    try {
      result = await callbackOrOptions(tx);
    } catch (_error) {
      Eif (!tx.isCommitted && !tx.isRolledBack) {
        await tx.rollback();
      }
      throw _error;
    }
 
    Eif (!tx.isCommitted && !tx.isRolledBack) {
      await tx.commit();
    }
    return result;
  }
 
  /**
   * Start health check monitoring
   *
   * Runs the connection test every `config.healthCheckInterval` ms (default 30s) and
   * emits `healthCheck` with `{ status: 'healthy' | 'unhealthy', ... }`. Started by
   * connect() unless `config.healthCheck` is false; stopped by close(). The timer does
   * not keep the process alive.
   *
   * @private
   */
  startHealthCheck() {
    Iif (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() });
 
        Iif (this.config.debug) {
          console.error('Database health check failed:', _error.message);
        }
      }
    }, this.healthCheckFrequency);
    this.healthCheckInterval.unref?.();
  }
 
  /**
   * Get connection statistics
   *
   * @returns {Object} Connection statistics
   */
  getStats() {
    return {
      ...this.stats,
      isConnected: this.isConnected,
      poolStats: this.pool && typeof this.adapter?.getPoolStats === 'function'
        ? this.adapter.getPoolStats(this.pool)
        : null
    };
  }
 
  /**
   * Close database connection
   *
   * @returns {Promise<void>}
   */
  async close() {
    if (!this.isConnected) {
      return;
    }
 
    // Stop health checks
    Eif (this.healthCheckInterval) {
      clearInterval(this.healthCheckInterval);
      this.healthCheckInterval = null;
    }
 
    // Close connection pool (connect-style adapters expose disconnect instead)
    Eif (this.pool && this.adapter) {
      if (typeof this.adapter.closePool === 'function') {
        await this.adapter.closePool(this.pool);
      } else Eif (typeof this.adapter.disconnect === 'function') {
        await this.adapter.disconnect();
      }
    }
 
    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);
}