fix(db): read unique violations and missing tables the same way on both engines

guardIdentity matched only SQLite's message text, so on Postgres a lost
race for an email or a username escaped as a 500 instead of a 409. The new
dialect module driver-errors.ts reads a unique violation by Postgres's
SQLSTATE 23505 and constraint name, or by SQLite's message, and the users
repository maps the key names of both engines. isMissingTableError moves
there too and also knows Postgres's 42P01 for an unconverted error.
This commit is contained in:
Maurice
2026-11-17 11:42:36 +01:00
parent 98529bc84c
commit e5fb6d9107
5 changed files with 117 additions and 17 deletions
+49
View File
@@ -0,0 +1,49 @@
import { TableNotFoundException } from '@mikro-orm/core';
/**
* What a database error says, read the same way on both engines. The engines
* report the same failure differently: SQLite (better-sqlite3) in the message
* text, Postgres (`pg`) in a SQLSTATE `code` and, for a constraint, the
* constraint's name. MikroORM's exception classes carry both: they copy every
* property of the driver's error. Code outside the dialect layer asks these
* functions instead of matching either engine's text.
*/
/** Postgres's SQLSTATE for a unique violation. */
const PG_UNIQUE_VIOLATION = '23505';
/** Postgres's SQLSTATE for an unknown table. */
const PG_UNDEFINED_TABLE = '42P01';
/** SQLite's unique violation: `UNIQUE constraint failed: users.email` or `... index 'idx_users_email_lower'`. */
const SQLITE_UNIQUE = /UNIQUE constraint failed: ([^\n]+)/;
/** The error's own properties a driver sets, read without trusting their types. */
function driverFields(err: unknown): { message: string; code: unknown; constraint: unknown } | null {
if (!(err instanceof Error)) return null;
const fields = err as Error & { code?: unknown; constraint?: unknown };
return { message: err.message, code: fields.code, constraint: fields.constraint };
}
/**
* The key a unique violation names, or null when `err` is not one. On
* Postgres it is the constraint or index name (`users_email_unique`,
* `idx_users_email_lower`); on SQLite the columns (`users.email`) or the
* index (`index 'idx_users_email_lower'`). A caller matches the names of
* both engines, which the baselines fix.
*/
export function uniqueViolationKey(err: unknown): string | null {
const fields = driverFields(err);
if (!fields) return null;
if (fields.code === PG_UNIQUE_VIOLATION) return typeof fields.constraint === 'string' ? fields.constraint : '';
return SQLITE_UNIQUE.exec(fields.message)?.[1].trim() ?? null;
}
/**
* Whether a statement failed because its table does not exist: MikroORM's
* `TableNotFoundException` (both engines), or the driver's own error where it
* reached the caller unconverted (SQLite's message, Postgres's 42P01).
*/
export function isMissingTableError(err: unknown): boolean {
if (err instanceof TableNotFoundException) return true;
const fields = driverFields(err);
return fields !== null && (fields.code === PG_UNDEFINED_TABLE || fields.message.includes('no such table'));
}
+1 -11
View File
@@ -1,6 +1,6 @@
import { columnNamesSql, tableExistsSql } from './dialect/catalog';
import { forEngine, type EngineColumn, type EngineDdl } from './dialect/ddl';
import { TableNotFoundException } from '@mikro-orm/core';
import { isMissingTableError } from './dialect/driver-errors';
import type { Migration } from '@mikro-orm/migrations';
/**
@@ -106,16 +106,6 @@ export async function execUnlessTableMissing(migration: Migration, sql: string,
}
}
/**
* True when a statement failed because its table does not exist. The ORM maps
* SQLite's "no such table" and Postgres's SQLSTATE 42P01 to
* `TableNotFoundException`; the raw SQLite message is checked too, for an error
* that reached the caller unconverted.
*/
export function isMissingTableError(err: unknown): boolean {
return err instanceof TableNotFoundException || (err instanceof Error && err.message.includes('no such table'));
}
/**
* Runs a group of statements the legacy step wrapped in a single swallowing
* try/catch. A failure part-way through leaves the earlier statements applied,
@@ -1,4 +1,4 @@
import { isMissingTableError } from '../migration-utils';
import { isMissingTableError } from '../dialect/driver-errors';
import type { EntityManager } from '@mikro-orm/core';
/**
+13 -5
View File
@@ -2,7 +2,7 @@ import { Users } from '../entities/Users.entity';
import { toRow, type AssertRowKeys } from './_shared/rows';
import { coalesce, columnIncrementedBy, currentTimestamp, lower, lowerParam } from '../dialect/sql-functions';
import { TrekRepository } from './_shared/trek-repository';
import { UniqueConstraintViolationException } from '@mikro-orm/core';
import { uniqueViolationKey } from '../dialect/driver-errors';
/**
* The three third-party keys that belong to the instance rather than to a
@@ -264,15 +264,23 @@ export class UserIdentityTakenError extends Error {
}
}
/**
* The keys that name the email and the username in a unique violation: SQLite
* names the column (`users.email`) or the index, Postgres the constraint
* (`users_email_unique`, `users_username_unique`) or the index
* (`idx_users_email_lower`).
*/
const EMAIL_KEY = /users\.email|users_email_unique|idx_users_email/;
const USERNAME_KEY = /users\.username|users_username_unique/;
/** Runs a users write, turning a unique violation on email or username into {@link UserIdentityTakenError}. */
async function guardIdentity<T>(write: () => Promise<T>): Promise<T> {
try {
return await write();
} catch (err) {
if (err instanceof UniqueConstraintViolationException) {
if (/users\.email|idx_users_email/.test(err.message)) throw new UserIdentityTakenError('email');
if (/users\.username/.test(err.message)) throw new UserIdentityTakenError('username');
}
const key = uniqueViolationKey(err);
if (key !== null && EMAIL_KEY.test(key)) throw new UserIdentityTakenError('email');
if (key !== null && USERNAME_KEY.test(key)) throw new UserIdentityTakenError('username');
throw err;
}
}
@@ -0,0 +1,53 @@
/**
* The engine-neutral reading of database errors (src/db/dialect/driver-errors.ts):
* a unique violation and a missing table, as better-sqlite3 and `pg` report
* them, raw and wrapped in MikroORM's exception classes (which copy every
* property of the driver's error). The Postgres errors are built with the
* fields `pg` sets; the Postgres lane meets the real ones.
*/
import { isMissingTableError, uniqueViolationKey } from '../../../../src/db/dialect/driver-errors';
import { TableNotFoundException, UniqueConstraintViolationException } from '@mikro-orm/core';
import { describe, expect, it } from 'vitest';
/** An error with the fields `pg` puts on a failed statement. */
function pgError(message: string, fields: { code: string; constraint?: string }): Error {
return Object.assign(new Error(message), fields);
}
describe('driver errors', () => {
it('DRVERR-001: a SQLite unique violation names its columns or its index', () => {
expect(uniqueViolationKey(new Error('UNIQUE constraint failed: users.email'))).toBe('users.email');
expect(uniqueViolationKey(new Error("UNIQUE constraint failed: index 'idx_users_email_lower'"))).toBe(
"index 'idx_users_email_lower'",
);
const wrapped = new UniqueConstraintViolationException(new Error('UNIQUE constraint failed: users.username'));
expect(uniqueViolationKey(wrapped)).toBe('users.username');
});
it('DRVERR-002: a Postgres unique violation is read by its SQLSTATE and named by its constraint', () => {
const raw = pgError('duplicate key value violates unique constraint "users_username_unique"', {
code: '23505',
constraint: 'users_username_unique',
});
expect(uniqueViolationKey(raw)).toBe('users_username_unique');
expect(uniqueViolationKey(new UniqueConstraintViolationException(raw))).toBe('users_username_unique');
expect(uniqueViolationKey(pgError('duplicate key', { code: '23505' }))).toBe('');
});
it('DRVERR-003: anything else is not a unique violation', () => {
expect(uniqueViolationKey(new Error('FOREIGN KEY constraint failed'))).toBeNull();
expect(uniqueViolationKey(pgError('null value in column', { code: '23502', constraint: 'x' }))).toBeNull();
expect(uniqueViolationKey('UNIQUE constraint failed: users.email')).toBeNull();
expect(uniqueViolationKey(null)).toBeNull();
});
it('DRVERR-004: a missing table is recognised on both engines, converted or not', () => {
expect(isMissingTableError(new TableNotFoundException(new Error('no such table: x')))).toBe(true);
expect(isMissingTableError(new Error('no such table: plugin_user_config'))).toBe(true);
expect(isMissingTableError(pgError('relation "x" does not exist', { code: '42P01' }))).toBe(true);
expect(isMissingTableError(pgError('syntax error', { code: '42601' }))).toBe(false);
expect(isMissingTableError(new Error('database is locked'))).toBe(false);
expect(isMissingTableError(undefined)).toBe(false);
});
});