All files / emp_audit_system/config db.js

46.57% Statements 34/73
31.25% Branches 10/32
58.33% Functions 7/12
46.47% Lines 33/71

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 1846x 6x 6x     6x                                                   6x         6x 6x 2x     2x 2x     2x 2x   2x                                                   2x         6x 6x 2x           6x 5x     6x 5x     6x       6x 5x       6x                       6x                   1x 1x     1x               1x                                                                           6x 6x 2x          
const mysql = require('mysql2/promise');
const logger = require('../utils/logger');
require('dotenv').config();
 
// Enhanced configuration with MySQL 8+ authentication support
const dbConfig = {
  host: process.env.DB_HOST || 'localhost',
  port: parseInt(process.env.DB_PORT) || 3306,
  user: process.env.DB_USER || 'emp_audit_user',
  password: process.env.DB_PASSWORD || 'SecurePass123!',
  database: process.env.DB_NAME || 'emp_audit_system',
  waitForConnections: true,
  connectionLimit: 10,
  queueLimit: 0,
  timezone: '+00:00',
  charset: 'utf8mb4_unicode_ci',
  debug: process.env.DB_DEBUG === 'true',
  ssl: process.env.DB_SSL === 'true' ? {
    rejectUnauthorized: true
  } : undefined,
  // MySQL 8+ authentication plugin support
  authPlugins: {
    mysql_clear_password: () => () => Buffer.from(process.env.DB_PASSWORD + '\0')
  },
  // Additional connection options
  connectTimeout: 10000, // 10 seconds
  // Removed invalid option acquireTimeout to prevent warning and timeout error
  enableKeepAlive: true,
  keepAliveInitialDelay: 10000 // 10 seconds
};
 
const pool = mysql.createPool(dbConfig);
 
// Enhanced connection test with validation query
async function testConnection() {
  let connection;
  try {
    connection = await pool.getConnection();
    logger.info('✅ Successfully connected to database');
    
    // Test with a simple query
    const [result] = await connection.query('SELECT 1 + 1 AS test_result');
    logger.debug('Database test query successful:', { testResult: result[0].test_result });
    
    // Verify database structure
    const [tables] = await connection.query('SHOW TABLES');
    logger.debug(`Database contains ${tables.length} tables`);
    
    return true;
  } catch (err) {
    logger.error('❌ Database connection failed:', {
      message: err.message,
      code: err.code,
      errno: err.errno,
      sqlState: err.sqlState,
      stack: process.env.NODE_ENV === 'development' ? err.stack : undefined
    });
    
    // Detailed error diagnostics
    if (err.code === 'ER_ACCESS_DENIED_ERROR') {
      logger.error('Authentication failed. Please verify:');
      logger.error(`- Username: ${dbConfig.user}`);
      logger.error('- Password: ' + (dbConfig.password ? '*****' : 'NOT SET'));
      logger.error('- Database: ' + dbConfig.database);
    } else if (err.code === 'ER_BAD_DB_ERROR') {
      logger.error(`Database '${dbConfig.database}' does not exist`);
    } else if (err.code === 'ECONNREFUSED') {
      logger.error('Connection refused. Verify MySQL is running and accessible at:');
      logger.error(`- Host: ${dbConfig.host}`);
      logger.error(`- Port: ${dbConfig.port}`);
    }
    
    return false;
  } finally {
    Eif (connection) connection.release();
  }
}
 
// Initialize database connection
(async () => {
  const connectionSuccessful = await testConnection();
  Iif (!connectionSuccessful) {
    process.exit(1);
  }
})();
 
// Connection pool event logging
pool.on('acquire', connection => {
  logger.debug(`Connection acquired (ID: ${connection.threadId})`);
});
 
pool.on('release', connection => {
  logger.debug(`Connection released (ID: ${connection.threadId})`);
});
 
pool.on('enqueue', () => {
  logger.debug('Waiting for available connection slot');
});
 
pool.on('connection', connection => {
  logger.debug(`New connection established (ID: ${connection.threadId})`);
});
 
// Graceful shutdown handler
process.on('SIGINT', async () => {
  try {
    logger.info('Closing database connections...');
    await pool.end();
    logger.info('Database connections closed gracefully');
    process.exit(0);
  } catch (err) {
    logger.error('Error closing database connections:', err);
    process.exit(1);
  }
});
 
module.exports = {
  pool,
  
  /**
   * Execute a SQL query
   * @param {string} sql - SQL query string
   * @param {Array} [params] - Query parameters
   * @returns {Promise<Array>} Query results
   */
  query: async (sql, params) => {
    try {
      const [rows] = await pool.query(sql, params);
      return rows;
    } catch (error) {
      logger.error('Database query error:', {
        message: error.message,
        sql: process.env.DB_DEBUG === 'true' ? sql : '[REDACTED]',
        params: process.env.DB_DEBUG === 'true' ? params : '[REDACTED]',
        code: error.code,
        errno: error.errno,
        sqlState: error.sqlState
      });
      throw error;
    }
  },
  
  /**
   * Execute operations in a transaction
   * @param {Function} callback - Transaction callback
   * @returns {Promise<any>} Transaction result
   */
  transaction: async callback => {
    const conn = await pool.getConnection();
    try {
      await conn.beginTransaction();
      logger.debug('Transaction started');
      
      const result = await callback(conn);
      await conn.commit();
      logger.debug('Transaction committed');
      
      return result;
    } catch (error) {
      await conn.rollback();
      logger.error('Transaction rolled back:', {
        message: error.message,
        stack: process.env.NODE_ENV === 'development' ? error.stack : undefined
      });
      throw error;
    } finally {
      conn.release();
      logger.debug('Transaction connection released');
    }
  },
  
  /**
   * Check if database connection is healthy
   * @returns {Promise<boolean>} Connection status
   */
  checkHealth: async () => {
    try {
      await pool.query('SELECT 1');
      return true;
    } catch (err) {
      return false;
    }
  }
};