All files / src/errors map-pg-error.ts

100% Statements 33/33
90.24% Branches 37/41
100% Functions 12/12
100% Lines 31/31

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                                      133x   133x                                             29x 29x 2x   27x 29x 34x                     6056x 1x   6055x 6056x   15x   7x   5x   4x   6024x                         55x 1x   54x 55x     55x       15x 15x 15x           12x                 27x             14x   15x                       73x       6024x          
import {
  AccessDeniedError,
  BaseError,
  ConnectionError,
  ConnectionRefusedError,
  ConnectionTimedOutError,
  DatabaseError,
  ExclusionConstraintError,
  ForeignKeyConstraintError,
  HostNotFoundError,
  HostNotReachableError,
  InvalidConnectionError,
  TimeoutError,
  UniqueConstraintError,
  ValidationErrorItem,
  type DriverError,
  type QueryErrorContext,
} from './errors.ts';
 
const KEY_DETAIL = /Key \((.*?)\)=\((.*?)\)/;
 
const CONNECTION_CODES: ReadonlyMap<string, new (parent: Error) => ConnectionError> = new Map<
  string,
  new (parent: Error) => ConnectionError
>([
  ['ECONNREFUSED', ConnectionRefusedError],
  ['ENOTFOUND', HostNotFoundError],
  ['EAI_AGAIN', HostNotFoundError],
  ['EHOSTUNREACH', HostNotReachableError],
  ['EINVAL', InvalidConnectionError],
  ['ETIMEDOUT', ConnectionTimedOutError],
  ['28P01', AccessDeniedError],
  ['28000', AccessDeniedError],
]);
 
/** Maps `pg` driver errors to the matching Sequelize v6 error classes. */
export class PgErrorMapper {
  /**
   * Parses `Key (a, b)=(1, 2)` from a PostgreSQL error detail into `{ a: '1', b: '2' }`.
   *
   * @param detail - `detail` of the driver error.
   * @returns Key values by column, or `undefined` when the detail has no key.
   */
  parseKeyDetail(detail: string | undefined): Readonly<Record<string, string>> | undefined {
    const match = detail === undefined ? null : KEY_DETAIL.exec(detail);
    if (match === null) {
      return undefined;
    }
    const keys = PgErrorMapper.#splitList(match[1] ?? '');
    const values = PgErrorMapper.#splitList(match[2] ?? '');
    return Object.fromEntries(keys.map((key, index) => [key, values[index] ?? '']));
  }
 
  /**
   * Maps a `pg` error raised by a query to the matching Sequelize v6 error class.
   *
   * @param error - Error thrown by the driver.
   * @param context - SQL and parameters of the failed query.
   * @returns Sequelize error (the error itself when it already is one).
   */
  mapQueryError(error: unknown, context: QueryErrorContext = {}): BaseError {
    if (error instanceof BaseError) {
      return error;
    }
    const driverError: DriverError = error instanceof Error ? error : new Error(String(error));
    switch (driverError.code) {
      case '23505':
        return this.#uniqueViolation(driverError, context);
      case '23503':
        return new ForeignKeyConstraintError(this.#constraintOptions(driverError, context));
      case '23P01':
        return new ExclusionConstraintError(this.#constraintOptions(driverError, context));
      case '57014':
        return new TimeoutError(driverError, context);
      default:
        return PgErrorMapper.#isConnectionFailure(driverError)
          ? this.mapConnectionError(driverError)
          : new DatabaseError(driverError, context);
    }
  }
 
  /**
   * Maps an error raised while connecting to the matching Sequelize v6 connection error class.
   *
   * @param error - Error thrown by the driver.
   * @returns Connection error (the error itself when it already is one).
   */
  mapConnectionError(error: unknown): ConnectionError {
    if (error instanceof ConnectionError) {
      return error;
    }
    const driverError: DriverError = error instanceof Error ? error : new Error(String(error));
    const ErrorClass =
      (driverError.code === undefined ? undefined : CONNECTION_CODES.get(driverError.code)) ??
      ConnectionError;
    return new ErrorClass(driverError);
  }
 
  #uniqueViolation(error: DriverError, context: QueryErrorContext): UniqueConstraintError {
    const fields = this.parseKeyDetail(error.detail);
    const base = { parent: error, ...context, ...PgErrorMapper.#tableAndConstraint(error) };
    return fields === undefined
      ? new UniqueConstraintError({ ...base, message: error.message })
      : new UniqueConstraintError({ ...base, fields, errors: PgErrorMapper.#uniqueItems(fields) });
  }
 
  #constraintOptions(error: DriverError, context: QueryErrorContext) {
    return {
      parent: error,
      ...context,
      fields: Object.keys(this.parseKeyDetail(error.detail) ?? {}),
      ...PgErrorMapper.#tableAndConstraint(error),
    };
  }
 
  static #tableAndConstraint(error: DriverError): { table?: string; constraint?: string } {
    return {
      ...(error.table === undefined ? {} : { table: error.table }),
      ...(error.constraint === undefined ? {} : { constraint: error.constraint }),
    };
  }
 
  static #uniqueItems(fields: Readonly<Record<string, string>>): ValidationErrorItem[] {
    return Object.entries(fields).map(
      ([field, value]) =>
        new ValidationErrorItem(
          `${field} must be unique`,
          'unique violation',
          field,
          value,
          null,
          'not_unique',
        ),
    );
  }
 
  static #splitList(value: string): readonly string[] {
    return value.split(',').map((part) => part.trim().replace(/^"(.*)"$/, '$1'));
  }
 
  static #isConnectionFailure(error: DriverError): boolean {
    return (
      error.code !== undefined && (CONNECTION_CODES.has(error.code) || error.code.startsWith('08'))
    );
  }
}