All files pgClient.ts

91.05% Statements 224/246
90.47% Branches 19/21
100% Functions 8/8
91.05% Lines 224/246

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 2471x 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 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 16x 16x 16x 16x 16x 16x 1x 1x 16x 16x 16x 16x 16x 16x 16x 16x 16x 8x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 9x 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 1x 2x 2x 2x 8x 16x 16x 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 16x 16x 16x  
import { Pool, PoolConfig, PoolClient } from 'pg'
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', '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 PostgreSQL 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.query(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)
}
 
/**
 * Ensures that the unaccent extension is installed in the PostgreSQL database
 *
 * This function checks if the unaccent extension is installed in the database
 * and installs it if it is not. It also emits a connection created event to
 * the monitor.
 *
 * @param pool - The PostgreSQL pool instance
 * @returns Promise<void> - Resolves when the unaccent extension is installed or already exists
 *
 * @example
 * await ensureUnaccentExtension(pool);
 */
async function ensureUnaccentExtension(pool: Pool): Promise<void> {
  try {
    const checkResult = await pool.query(`
      SELECT 1 FROM pg_extension WHERE extname = 'unaccent'
    `)
 
    if (checkResult.rows.length === 0) {
      await pool.query('CREATE EXTENSION IF NOT EXISTS unaccent')
 
      monitor.emit(MonitorEvents.CONNECTION_CREATED, {
        clientType: 'pg',
        extension: 'unaccent',
        status: 'installed',
      })
 
      console.info(
        '@starbemtech/star-db-query-builder: Extensão unaccent instalada com sucesso.'
      )
    }
  } catch (error) {
    monitor.emit(MonitorEvents.QUERY_ERROR, {
      clientType: 'pg',
      action: 'install_unaccent',
      error,
    })
    throw new Error(
      `@starbemtech/star-db-query-builder: Não foi possível instalar a extensão unaccent:
      ${error}`
    )
  }
}
 
/**
 * Creates a PostgreSQL database client
 *
 * This function initializes a PostgreSQL database client with the provided pool configuration
 * and optional retry options. It sets up monitoring for connection events and query operations.
 *
 * @param pool - The PostgreSQL pool instance
 * @param retryOptions - Optional retry options for failed queries
 * @param poolConfig - Optional pool configuration
 * @param installUnaccentExtension - Optional flag to install unaccent extension
 * @returns IDatabaseClient - The PostgreSQL database client instance
 *
 * @example
 * const pgClient = await createPgClient(pool, { retries: 3, factor: 2, minTimeout: 1000 });
 *
 * @example
 * const pgClient = await createPgClient(pool, { retries: 3, factor: 2, minTimeout: 1000 });
 *
 * @example
 * const pgClient = await createPgClient(pool, { retries: 3, factor: 2, minTimeout: 1000 });
 */
export const createPgClient = async (
  pool: Pool,
  retryOptions?: RetryOptions,
  poolConfig?: PoolConfig,
  installUnaccentExtension?: boolean
): Promise<IDatabaseClient> => {
  if (installUnaccentExtension) {
    await ensureUnaccentExtension(pool)
  }
 
  monitor.emit(MonitorEvents.CONNECTION_CREATED, {
    clientType: 'pg',
    poolOptions: poolConfig,
  })
 
  return {
    clientType: 'pg',
    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: 'pg',
            sql,
            params,
            attempt,
          })
 
          const { rows } = await pool.query(sql, params)
 
          const elapsedTime = Date.now() - startTime
          monitor.emit(MonitorEvents.QUERY_END, {
            clientType: 'pg',
            sql,
            params,
            attempt,
            elapsedTime,
          })
 
          return rows as unknown as T
        } catch (error) {
          const elapsedTime = Date.now() - startTime
          monitor.emit(MonitorEvents.QUERY_ERROR, {
            clientType: 'pg',
            sql,
            params,
            attempt,
            elapsedTime,
            error,
          })
 
          if (isTransientError(error)) {
            console.warn(
              `Postgres query attempt ${attempt} failed, retrying...`,
              error
            )
 
            monitor.emit(MonitorEvents.RETRY_ATTEMPT, {
              clientType: 'pg',
              sql,
              params,
              attempt,
              error,
            })
 
            return retry(error)
          }
 
          throw error
        }
      }, retryOptions)
    },
    beginTransaction: async (): Promise<ITransactionClient> => {
      const client: PoolClient = await pool.connect()
 
      try {
        await client.query('BEGIN')
 
        return {
          query: async <T>(sql: string, params?: any[]): Promise<T> => {
            const startTime = Date.now()
            try {
              monitor.emit(MonitorEvents.QUERY_START, {
                clientType: 'pg',
                sql,
                params,
                attempt: 1,
                inTransaction: true,
              })
 
              const { rows } = await client.query(sql, params)
 
              const elapsedTime = Date.now() - startTime
              monitor.emit(MonitorEvents.QUERY_END, {
                clientType: 'pg',
                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: 'pg',
                sql,
                params,
                attempt: 1,
                elapsedTime,
                error,
                inTransaction: true,
              })
              throw error
            }
          },
          commit: async (): Promise<void> => {
            try {
              await client.query('COMMIT')
              monitor.emit(MonitorEvents.TRANSACTION_COMMIT, {
                clientType: 'pg',
              })
            } finally {
              client.release()
            }
          },
          rollback: async (): Promise<void> => {
            try {
              await client.query('ROLLBACK')
              monitor.emit(MonitorEvents.TRANSACTION_ROLLBACK, {
                clientType: 'pg',
              })
            } finally {
              client.release()
            }
          },
        }
      } catch (error) {
        client.release()
        throw error
      }
    },
  }
}