All files mysqlClient.ts

94% Statements 188/200
94.44% Branches 17/18
100% Functions 7/7
94% Lines 188/200

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 2011x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 3x 3x 3x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 7x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 8x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 2x 2x 2x 7x 15x 15x 7x 7x 7x 7x 6x 6x 6x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x                         6x 6x 2x 2x 1x 1x 1x 1x 2x 2x 6x 6x 2x 2x 1x 1x 1x 1x 2x 2x 6x 6x 7x 1x 1x 1x 15x 15x 15x  
import { Pool, PoolConnection } from 'mysql2/promise'
import promiseRetry from 'promise-retry'
import { IDatabaseClient, ITransactionClient } from './IDatabaseClient'
import { RetryOptions } from '../core/types'
import { monitor, MonitorEvents } from '../monitor/monitor'
 
const transientErrorCodes = new Set([
  'ECONNRESET',
  'ETIMEDOUT',
  'PROTOCOL_CONNECTION_LOST',
  'ECONNREFUSED',
])
 
/**
 * Checks if the given error is a transient error that can be retried
 *
 * Transient errors are temporary network or connection issues that typically
 * resolve themselves and can be safely retried. This function checks if the
 * error code matches known transient error patterns for MySQL connections.
 *
 * @param error - The error object to check
 * @returns boolean - True if the error is transient and can be retried, false otherwise
 *
 * @example
 * try {
 *   const result = await pool.execute(sql, params);
 * } catch (error) {
 *   if (isTransientError(error)) {
 *     // Retry the operation
 *     console.log('Transient error detected, retrying...');
 *   } else {
 *     // Handle permanent error
 *     throw error;
 *   }
 * }
 */
function isTransientError(error: any): boolean {
  return error && error.code && transientErrorCodes.has(error.code)
}
 
/**
 * Creates a MySQL database client
 *
 * This function initializes a MySQL database client with the provided pool configuration
 * and optional retry options. It sets up monitoring for connection events and query operations.
 *
 * @param pool - The MySQL pool instance
 * @param retryOptions - Optional retry options for failed queries
 * @returns IDatabaseClient - The MySQL database client instance
 *
 * @example
 * const mysqlClient = createMysqlClient(pool, { retries: 3, factor: 2, minTimeout: 1000 });
 *
 * @example
 * const mysqlClient = createMysqlClient(pool, { retries: 3, factor: 2, minTimeout: 1000 });
 *
 * @example
 * const mysqlClient = createMysqlClient(pool, { retries: 3, factor: 2, minTimeout: 1000 });
 *
 * @example
 * const mysqlClient = createMysqlClient(pool, { retries: 3, factor: 2, minTimeout: 1000 });
 */
export const createMysqlClient = (
  pool: Pool,
  retryOptions?: RetryOptions
): IDatabaseClient => {
  monitor.emit(MonitorEvents.CONNECTION_CREATED, {
    clientType: 'mysql',
    poolOptions: pool.config,
  })
 
  return {
    clientType: 'mysql',
    query: async <T>(sql: string, params?: any[]): Promise<T> => {
      return promiseRetry(async (retry, attempt) => {
        const startTime = Date.now()
        try {
          monitor.emit(MonitorEvents.QUERY_START, {
            clientType: 'mysql',
            sql,
            params,
            attempt,
          })
 
          const [rows] = await pool.execute(sql, params)
 
          const elapsedTime = Date.now() - startTime
          monitor.emit(MonitorEvents.QUERY_END, {
            clientType: 'mysql',
            sql,
            params,
            attempt,
            elapsedTime,
          })
 
          return rows as unknown as T
        } catch (error: any) {
          const elapsedTime = Date.now() - startTime
          monitor.emit(MonitorEvents.QUERY_ERROR, {
            clientType: 'mysql',
            sql,
            params,
            attempt,
            elapsedTime,
            error,
          })
 
          if (isTransientError(error)) {
            console.warn(
              `MySQL query attempt ${attempt} failed, retrying...`,
              error
            )
            monitor.emit(MonitorEvents.RETRY_ATTEMPT, {
              clientType: 'mysql',
              sql,
              params,
              attempt,
              error,
            })
 
            return retry(error)
          }
 
          throw error
        }
      }, retryOptions)
    },
    beginTransaction: async (): Promise<ITransactionClient> => {
      const connection: PoolConnection = await pool.getConnection()
 
      try {
        await connection.beginTransaction()
 
        return {
          query: async <T>(sql: string, params?: any[]): Promise<T> => {
            const startTime = Date.now()
            try {
              monitor.emit(MonitorEvents.QUERY_START, {
                clientType: 'mysql',
                sql,
                params,
                attempt: 1,
                inTransaction: true,
              })
 
              const [rows] = await connection.execute(sql, params)
 
              const elapsedTime = Date.now() - startTime
              monitor.emit(MonitorEvents.QUERY_END, {
                clientType: 'mysql',
                sql,
                params,
                attempt: 1,
                elapsedTime,
                inTransaction: true,
              })
 
              return rows as unknown as T
            } catch (error) {
              const elapsedTime = Date.now() - startTime
              monitor.emit(MonitorEvents.QUERY_ERROR, {
                clientType: 'mysql',
                sql,
                params,
                attempt: 1,
                elapsedTime,
                error,
                inTransaction: true,
              })
              throw error
            }
          },
          commit: async (): Promise<void> => {
            try {
              await connection.commit()
              monitor.emit(MonitorEvents.TRANSACTION_COMMIT, {
                clientType: 'mysql',
              })
            } finally {
              connection.release()
            }
          },
          rollback: async (): Promise<void> => {
            try {
              await connection.rollback()
              monitor.emit(MonitorEvents.TRANSACTION_ROLLBACK, {
                clientType: 'mysql',
              })
            } finally {
              connection.release()
            }
          },
        }
      } catch (error) {
        connection.release()
        throw error
      }
    },
  }
}