All files / src/errors database-errors.ts

100% Statements 25/25
100% Branches 10/10
100% Functions 5/5
100% Lines 25/25

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                                                                                      6042x 6042x 6042x 6042x 6042x 6042x 6042x                                                                               1x 1x 1x 1x 1x 1x                                                   4x 4x                                                                                                                               11x 11x 11x 11x 11x                                                                   8x 8x 8x 8x 8x      
import { BaseError, type DriverError } from './base-error.ts';
 
/** Context attached to errors raised while executing SQL. */
export type QueryErrorContext = Readonly<{
  /** Executed SQL text. */
  sql?: string;
  /** Bound parameter values. */
  parameters?: readonly unknown[];
}>;
 
/**
 * Error returned by PostgreSQL while executing a query (Sequelize v6 `DatabaseError`).
 *
 * Any driver error without a more specific mapping becomes a `DatabaseError`; `sql` and `parameters` describe the failed statement and `parent.code` holds the SQLSTATE.
 *
 * @example
 * ```ts
 * try {
 *   await sequelize.query('SELECT * FROM missing_table');
 * } catch (e) {
 *   if (e instanceof DatabaseError) {
 *     console.error(e.parent.code, e.sql, e.parameters);
 *   }
 * }
 * ```
 */
export class DatabaseError extends BaseError {
  /** Original driver error. */
  readonly parent: DriverError;
  /** Original driver error (alias of `parent`). */
  readonly original: DriverError;
  /** Executed SQL text. */
  readonly sql: string;
  /** Bound parameter values. */
  readonly parameters: readonly unknown[];
 
  /**
   * Wraps a driver error together with the statement that failed.
   *
   * @param parent - Original driver error; an empty one is substituted when omitted.
   * @param context - Executed SQL and parameters; `sql` defaults to `''` and `parameters` to `[]`.
   */
  constructor(parent: DriverError | undefined, context: QueryErrorContext = {}) {
    const driverError = parent ?? Object.assign(new Error(''), { sql: '' });
    super(driverError.message, { cause: driverError });
    this.name = 'SequelizeDatabaseError';
    this.parent = driverError;
    this.original = driverError;
    this.sql = context.sql ?? '';
    this.parameters = context.parameters ?? [];
  }
}
 
/**
 * A constraint that does not exist was referenced (Sequelize v6 `UnknownConstraintError`).
 *
 * @example
 * ```ts
 * try {
 *   await queryInterface.removeConstraint('users', 'missing');
 * } catch (e) {
 *   if (e instanceof UnknownConstraintError) {
 *     console.error(e.constraint, e.table);
 *   }
 * }
 * ```
 */
export class UnknownConstraintError extends DatabaseError {
  /** Constraint name. */
  readonly constraint: string | undefined;
  /** Constraint columns. */
  readonly fields: Readonly<Record<string, unknown>> | undefined;
  /** Table name. */
  readonly table: string | undefined;
 
  /**
   * Builds the error; `message` defaults to v6's "The specified constraint does not exist".
   *
   * @param options - Constraint details and an optional driver error.
   */
  constructor(
    options: Readonly<{
      message?: string;
      constraint?: string;
      fields?: Readonly<Record<string, unknown>>;
      table?: string;
      parent?: DriverError;
    }> = {},
  ) {
    super(options.parent);
    this.name = 'SequelizeUnknownConstraintError';
    this.message = options.message ?? 'The specified constraint does not exist';
    this.constraint = options.constraint;
    this.fields = options.fields;
    this.table = options.table;
  }
}
 
/**
 * Query cancelled by PostgreSQL, e.g. because `statement_timeout` elapsed (SQLSTATE `57014`).
 *
 * @example
 * ```ts
 * try {
 *   await sequelize.query('SELECT pg_sleep(10)');
 * } catch (e) {
 *   if (e instanceof TimeoutError) {
 *     console.error('query was cancelled:', e.sql);
 *   }
 * }
 * ```
 */
export class TimeoutError extends DatabaseError {
  /**
   * Wraps a driver error together with the statement that failed.
   *
   * @param parent - Original driver error.
   * @param context - Executed SQL and parameters.
   */
  constructor(parent: DriverError, context?: QueryErrorContext) {
    super(parent, context);
    this.name = 'SequelizeTimeoutError';
  }
}
 
/**
 * Input of the constraint error constructors: the driver error plus what PostgreSQL reported about the constraint.
 *
 * @example
 * ```ts
 * const options: ConstraintErrorOptions = {
 *   parent: Object.assign(new Error('violates foreign key constraint'), { code: '23503' }),
 *   fields: ['userId'],
 *   table: 'posts',
 *   constraint: 'posts_userId_fkey',
 *   sql: 'INSERT INTO "posts" ("userId") VALUES ($1)',
 *   parameters: [42],
 * };
 * const error = new ForeignKeyConstraintError(options);
 * ```
 */
export type ConstraintErrorOptions = QueryErrorContext &
  Readonly<{
    /** Original driver error; an empty one is substituted when omitted. */
    parent?: DriverError;
    /** Constraint columns mapped to offending values. */
    fields?: Readonly<Record<string, string>> | readonly string[];
    /** Table name. */
    table?: string;
    /** Constraint name. */
    constraint?: string;
    /** Error message, defaults to the driver message. */
    message?: string;
  }>;
 
/**
 * Thrown when a write references a missing row or removes a row that is still referenced (SQLSTATE `23503`).
 *
 * `fields` lists the referencing columns (parsed from the PostgreSQL detail), `table` the table and `index` the constraint name.
 *
 * @example
 * ```ts
 * try {
 *   await Post.create({ title: 'Hello', userId: 999999 });
 * } catch (e) {
 *   if (e instanceof ForeignKeyConstraintError) {
 *     console.error(e.table, e.fields, e.index);
 *   }
 * }
 * ```
 */
export class ForeignKeyConstraintError extends DatabaseError {
  /** Referencing columns, exactly as passed (an object or an array, like v6). */
  readonly fields: Readonly<Record<string, string>> | readonly string[] | undefined;
  /** Table name. */
  readonly table: string | undefined;
  /** Constraint name. */
  readonly index: string | undefined;
 
  /**
   * Builds the error from the constraint details.
   *
   * @param options - Driver error, fields and context.
   */
  constructor(options: ConstraintErrorOptions) {
    super(options.parent, options);
    this.name = 'SequelizeForeignKeyConstraintError';
    this.fields = options.fields;
    this.table = options.table;
    this.index = options.constraint;
  }
}
 
/**
 * Thrown when a row conflicts with an exclusion constraint, e.g. overlapping ranges (SQLSTATE `23P01`). PostgreSQL-specific; v6 has no such class.
 *
 * `constraint` is the constraint name, `fields` the columns parsed from the PostgreSQL detail and `table` the table.
 *
 * @example
 * ```ts
 * try {
 *   await Task.create({ room: 'A', during: [new Date('2026-01-01'), new Date('2026-01-02')] });
 * } catch (e) {
 *   if (e instanceof ExclusionConstraintError) {
 *     console.error(e.constraint, e.fields);
 *   }
 * }
 * ```
 */
export class ExclusionConstraintError extends DatabaseError {
  /** Constraint name. */
  readonly constraint: string | undefined;
  /** Constraint columns, exactly as passed (an object or an array, like v6). */
  readonly fields: Readonly<Record<string, string>> | readonly string[] | undefined;
  /** Table name. */
  readonly table: string | undefined;
 
  /**
   * Builds the error from the constraint details.
   *
   * @param options - Driver error, fields and context.
   */
  constructor(options: ConstraintErrorOptions) {
    super(options.parent, options);
    this.name = 'SequelizeExclusionConstraintError';
    this.constraint = options.constraint;
    this.fields = options.fields;
    this.table = options.table;
  }
}