'use strict'; const { create } = require("error-chain"); const pgErrorCodes = require("pg-error-codes"); const DatabaseError = require("../database-error.js"); let ForeignKeyConstraintViolationError = create("ForeignKeyConstraintViolationError", { inheritsFrom: DatabaseError }); let detailsRegex = /^Key \(([^\)]+)\)=\(([^\)]+)\) is not present in table "([^"]+)"\.$/; module.exports = { error: ForeignKeyConstraintViolationError, errorName: "ForeignKeyConstraintViolationError", check: function checkType(error) { return ( // PostgreSQL (via `pg`): (error.length != null && error.file != null && error.line != null && error.routine != null && error.code === "23503") ); }, convert: function convertError(error) { let [_, column, value, foreignTable] = detailsRegex.exec(error.detail); return new ForeignKeyConstraintViolationError(`Value for column '${column}' in table '${error.table}' refers to a non-existent key '${value}' in table '${foreignTable}'`, { originalError: error, pgCode: error.code, code: pgErrorCodes[error.code], schema: error.schema, table: error.table, foreignTable: foreignTable, column: column, value: value, constraint: error.constraint }); } };