diff --git a/server/src/db/dialect/driver-errors.ts b/server/src/db/dialect/driver-errors.ts new file mode 100644 index 000000000..17c4f1adb --- /dev/null +++ b/server/src/db/dialect/driver-errors.ts @@ -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')); +} diff --git a/server/src/db/migration-utils.ts b/server/src/db/migration-utils.ts index 2b06a9c94..44984f3a7 100644 --- a/server/src/db/migration-utils.ts +++ b/server/src/db/migration-utils.ts @@ -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, diff --git a/server/src/db/repositories/MaintenanceRepository.ts b/server/src/db/repositories/MaintenanceRepository.ts index 1e988649f..f492cfb88 100644 --- a/server/src/db/repositories/MaintenanceRepository.ts +++ b/server/src/db/repositories/MaintenanceRepository.ts @@ -1,4 +1,4 @@ -import { isMissingTableError } from '../migration-utils'; +import { isMissingTableError } from '../dialect/driver-errors'; import type { EntityManager } from '@mikro-orm/core'; /** diff --git a/server/src/db/repositories/Users.repository.ts b/server/src/db/repositories/Users.repository.ts index ae4384855..79a415767 100644 --- a/server/src/db/repositories/Users.repository.ts +++ b/server/src/db/repositories/Users.repository.ts @@ -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(write: () => Promise): Promise { 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; } } diff --git a/server/tests/unit/db/dialect/driver-errors.test.ts b/server/tests/unit/db/dialect/driver-errors.test.ts new file mode 100644 index 000000000..1b57b69f7 --- /dev/null +++ b/server/tests/unit/db/dialect/driver-errors.test.ts @@ -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); + }); +});