Skip to content

🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

🐛 fix(database): detect unique violations through drizzle's error wrapper (#21886)

Arvin Xu34cfcb0ac76c
diff --git a/packages/database/src/models/__tests__/task.helpers.test.ts b/packages/database/src/models/__tests__/task.helpers.test.ts
index 2694e1f452b..87c0b63f231 100644
--- a/packages/database/src/models/__tests__/task.helpers.test.ts
+++ b/packages/database/src/models/__tests__/task.helpers.test.ts
@@ -2,6 +2,7 @@
import type { TaskItem } from '@lobechat/types';
import { describe, expect, it } from 'vitest';
+import { isUniqueViolation } from '../../utils/uniqueViolation';
import { checkpointTaskMatcher, checkpointTaskPairsMatch } from '../task/checkpoint';
import { getVerifyConfig } from '../task/config';
import { isTaskIdentifierUniqueViolation, withStaleReposCleared } from '../task/utils';
@@ -43,14 +44,7 @@ describe('task withStaleReposCleared', () => {
});
describe('task isTaskIdentifierUniqueViolation', () => {
- it('reads a thrown non-Error value by its string form', () => {
- expect(isTaskIdentifierUniqueViolation('duplicate key value')).toBe(true);
- expect(isTaskIdentifierUniqueViolation('connection reset')).toBe(false);
- expect(isTaskIdentifierUniqueViolation(null)).toBe(false);
- });
-
- it('reads a code from a plain object', () => {
- expect(isTaskIdentifierUniqueViolation({ code: '23505' })).toBe(true);
- expect(isTaskIdentifierUniqueViolation({ code: '23503' })).toBe(false);
+ it('is the shared unique-violation check', () => {
+ expect(isTaskIdentifierUniqueViolation).toBe(isUniqueViolation);
});
});
diff --git a/packages/database/src/models/agentEval/__tests__/experiment.coverage.test.ts b/packages/database/src/models/agentEval/__tests__/experiment.coverage.test.ts
index 6df5fdfdf11..964d601e1f8 100644
--- a/packages/database/src/models/agentEval/__tests__/experiment.coverage.test.ts
+++ b/packages/database/src/models/agentEval/__tests__/experiment.coverage.test.ts
@@ -25,34 +25,54 @@ afterEach(async () => {
describe('AgentEvalExperimentModel coverage', () => {
describe('create race', () => {
/**
- * The concurrent create commits first and ours fails on the primary key. The stand-in throws
- * the driver's error shape (`code` on the error itself) — see the PR "Findings" for why the
- * drizzle-wrapped shape never reaches this branch today.
+ * The concurrent create commits after our idempotency pre-check and before our insert, so our
+ * insert hits a real primary-key violation. drizzle wraps the driver error, putting the code on
+ * `cause` rather than on the error itself.
*/
+ const commitBeforeInsert = (winner: typeof agentEvalExperiments.$inferInsert) => {
+ const transaction = serverDB.transaction.bind(serverDB);
+ return vi
+ .spyOn(serverDB, 'transaction')
+ .mockImplementationOnce(async (run: Parameters<typeof transaction>[0]) => {
+ await serverDB.insert(agentEvalExperiments).values(winner);
+ return transaction(run);
+ });
+ };
+
it('returns the winner of a create race that surfaces as a unique violation', async () => {
const id = 'experiment-cov-race-winner';
- vi.spyOn(serverDB, 'transaction').mockImplementationOnce(async () => {
- await serverDB.insert(agentEvalExperiments).values({ id, name: 'winner', userId });
- throw Object.assign(new Error('duplicate key value'), { code: '23505' });
- });
+ commitBeforeInsert({ id, name: 'winner', userId });
const created = await model.create({ benchmarkIds: [], id, name: 'loser' });
expect(created.id).toBe(id);
expect(created.name).toBe('winner');
+ const rows = await serverDB
+ .select()
+ .from(agentEvalExperiments)
+ .where(inArray(agentEvalExperiments.id, [id]));
+ expect(rows).toHaveLength(1);
});
it('rethrows a unique violation whose winner is not visible to the caller', async () => {
const id = 'experiment-cov-race-hidden';
- const violation = Object.assign(new Error('duplicate key value'), { code: '23505' });
- vi.spyOn(serverDB, 'transaction').mockImplementationOnce(async () => {
- await serverDB
- .insert(agentEvalExperiments)
- .values({ id, name: 'hidden', userId: otherOwnerId });
- throw violation;
- });
-
- await expect(model.create({ benchmarkIds: [], id, name: 'mine' })).rejects.toBe(violation);
+ commitBeforeInsert({ id, name: 'hidden', userId: otherOwnerId });
+
+ const error = await model.create({ benchmarkIds: [], id, name: 'mine' }).catch((e) => e);
+
+ expect(error).toBeInstanceOf(Error);
+ expect((error as { cause?: { code?: string } }).cause?.code).toBe('23505');
+ });
+
+ it('rethrows an insert failure that is not a unique violation', async () => {
+ // No users row for this owner, so the insert fails its foreign key (23503), not a race.
+ const orphan = new AgentEvalExperimentModel(serverDB, 'experiment-coverage-missing-user');
+
+ const error = await orphan
+ .create({ benchmarkIds: [], id: 'experiment-cov-orphan', name: 'orphan' })
+ .catch((e) => e);
+
+ expect((error as { cause?: { code?: string } }).cause?.code).toBe('23503');
});
});
diff --git a/packages/database/src/models/agentEval/experiment.ts b/packages/database/src/models/agentEval/experiment.ts
index 802b0616344..18f33f8969b 100644
--- a/packages/database/src/models/agentEval/experiment.ts
+++ b/packages/database/src/models/agentEval/experiment.ts
@@ -15,6 +15,7 @@ import {
type NewAgentEvalExperiment,
} from '../../schemas';
import { type LobeChatDatabase } from '../../type';
+import { isUniqueViolation } from '../../utils/uniqueViolation';
import { buildWorkspaceWhere } from '../../utils/workspace';
import { AgentEvalDatasetModel } from './dataset';
import { AgentEvalRunModel } from './run';
@@ -130,7 +131,7 @@ export class AgentEvalExperimentModel {
} catch (error) {
// Race-safe idempotency: a concurrent insert with the same id lost the
// race — return the winner's row.
- if (experiment.id && (error as { code?: string })?.code === '23505') {
+ if (experiment.id && isUniqueViolation(error)) {
const [existing] = await this.db
.select()
.from(agentEvalExperiments)
diff --git a/packages/database/src/models/agentIntervention/__tests__/utils.test.ts b/packages/database/src/models/agentIntervention/__tests__/utils.test.ts
index 7db212bc456..3ef186ff976 100644
--- a/packages/database/src/models/agentIntervention/__tests__/utils.test.ts
+++ b/packages/database/src/models/agentIntervention/__tests__/utils.test.ts
@@ -18,7 +18,6 @@ import {
isCanonicalJsonSafe,
isCustomExecutionResult,
isPlainRecord,
- isUniqueViolation,
normalizeDtoJson,
providerOptionIds,
sameDtoJson,
@@ -124,13 +123,6 @@ describe('small helpers', () => {
expect(asRecord(null)).toEqual({});
});
- it('detects a pg unique violation including the wrapped cause', () => {
- expect(isUniqueViolation({ code: '23505' })).toBe(true);
- expect(isUniqueViolation({ cause: { code: '23505' } })).toBe(true);
- expect(isUniqueViolation({ code: '23503' })).toBe(false);
- expect(isUniqueViolation(null)).toBe(false);
- });
-
it('accepts only the custom execution result shape', () => {
expect(isCustomExecutionResult({ content: 'c', pluginState: {} })).toBe(true);
expect(isCustomExecutionResult({ content: 'c', extra: 1, pluginState: {} })).toBe(false);
diff --git a/packages/database/src/models/agentIntervention/constants.ts b/packages/database/src/models/agentIntervention/constants.ts
index c772540676c..384d35c5606 100644
--- a/packages/database/src/models/agentIntervention/constants.ts
+++ b/packages/database/src/models/agentIntervention/constants.ts
@@ -20,8 +20,6 @@ export const HASH_PATTERN = /^[a-f0-9]{64}$/;
export const UUID_PATTERN = /^[\da-f]{8}-(?:[\da-f]{4}-){3}[\da-f]{12}$/i;
-export const PG_UNIQUE_VIOLATION = '23505';
-
export const AGENT_INTERVENTION_CUSTOM_EXECUTION_MIN_LEASE_MS = 1000;
export const AGENT_INTERVENTION_CUSTOM_EXECUTION_MAX_LEASE_MS = 15 * 60_000;
diff --git a/packages/database/src/models/agentIntervention/creation.ts b/packages/database/src/models/agentIntervention/creation.ts
index 04638f796cd..c93ffd7de2f 100644
--- a/packages/database/src/models/agentIntervention/creation.ts
+++ b/packages/database/src/models/agentIntervention/creation.ts
@@ -3,6 +3,7 @@ import { and, asc, eq, isNull } from 'drizzle-orm';
import { type AgentInterventionItem, agentInterventions, agentOperations } from '../../schemas';
import type { Transaction } from '../../type';
+import { isUniqueViolation } from '../../utils/uniqueViolation';
import {
AGENT_INTERVENTION_IDENTITY_CONFLICT,
AGENT_INTERVENTION_INVALID_ACTION,
@@ -19,7 +20,6 @@ import type {
import {
hasValidCustomDetail,
isCanonicalDtoJsonSafe,
- isUniqueViolation,
normalizeDtoJson,
sameDtoJson,
sameJson,
diff --git a/packages/database/src/models/agentIntervention/utils.ts b/packages/database/src/models/agentIntervention/utils.ts
index da9c32d7662..c712c6e9710 100644
--- a/packages/database/src/models/agentIntervention/utils.ts
+++ b/packages/database/src/models/agentIntervention/utils.ts
@@ -7,14 +7,6 @@ import type {
AgentInterventionSanitizedRequest,
} from '@lobechat/types';
-import { PG_UNIQUE_VIOLATION } from './constants';
-
-export const isUniqueViolation = (error: unknown): boolean =>
- !!error &&
- typeof error === 'object' &&
- (('code' in error && (error as { code?: string }).code === PG_UNIQUE_VIOLATION) ||
- ('cause' in error && isUniqueViolation((error as { cause?: unknown }).cause)));
-
export const asRecord = (value: unknown): Record<string, unknown> =>
value !== null && typeof value === 'object' && !Array.isArray(value)
? (value as Record<string, unknown>)
diff --git a/packages/database/src/models/messengerAccountLink.ts b/packages/database/src/models/messengerAccountLink.ts
index e57c84fbf2d..aa20d9b26f6 100644
--- a/packages/database/src/models/messengerAccountLink.ts
+++ b/packages/database/src/models/messengerAccountLink.ts
@@ -3,6 +3,7 @@ import { and, eq, getTableColumns, inArray, isNull, type SQL } from 'drizzle-orm
import type { MessengerAccountLinkItem, NewMessengerAccountLink } from '../schemas';
import { messengerAccountLinks } from '../schemas';
import type { LobeChatDatabase } from '../type';
+import { uniqueViolationConstraint } from '../utils/uniqueViolation';
interface GateKeeper {
decrypt: (ciphertext: string) => Promise<{ plaintext: string }>;
@@ -48,21 +49,6 @@ const GLOBAL_TENANT_ID = '';
const APPLICATION_UNIQUE_CONSTRAINT = 'messenger_account_links_platform_tenant_application_unique';
-/**
- * Returns the violated constraint name when `error` is a Postgres unique
- * violation. Diagnostics land on `cause` (drizzle/pg wrappers) or on the error
- * itself (node-postgres driver), so read both levels.
- */
-const uniqueViolationConstraint = (error: unknown): string | undefined => {
- const pgError = error as {
- cause?: { code?: string; constraint?: string };
- code?: string;
- constraint?: string;
- };
- const code = pgError.cause?.code ?? pgError.code;
- return code === '23505' ? (pgError.cause?.constraint ?? pgError.constraint) : undefined;
-};
-
/**
* Thrown by `upsertForPlatform` when the IM identity is already bound to a
* different LobeHub user. Callers (e.g. the messenger router) should surface
diff --git a/packages/database/src/models/resourceTransferRequest.ts b/packages/database/src/models/resourceTransferRequest.ts
index 5fd3c87a5d7..960a3a9a3e1 100644
--- a/packages/database/src/models/resourceTransferRequest.ts
+++ b/packages/database/src/models/resourceTransferRequest.ts
@@ -4,6 +4,7 @@ import { and, desc, eq, gt, inArray, isNotNull, lte, or, sql } from 'drizzle-orm
import type { ResourceTransferRequestItem } from '../schemas';
import { notifications, resourceTransferRequests } from '../schemas';
import type { LobeChatDatabase, Transaction } from '../type';
+import { isUniqueViolation } from '../utils/uniqueViolation';
/** Create rejected: the resource already carries a live transfer request. */
export const TRANSFER_REQUEST_ALREADY_PENDING = 'TRANSFER_REQUEST_ALREADY_PENDING';
@@ -19,14 +20,6 @@ export const PENDING_TRANSFER_LIST_LIMIT = 50;
type Executor = Transaction | LobeChatDatabase;
-const PG_UNIQUE_VIOLATION = '23505';
-
-const isUniqueViolation = (error: unknown): boolean =>
- !!error &&
- typeof error === 'object' &&
- (('code' in error && (error as { code?: string }).code === PG_UNIQUE_VIOLATION) ||
- ('cause' in error && isUniqueViolation((error as { cause?: unknown }).cause)));
-
/**
* Lifecycle of member-to-member ownership handover requests, scoped to one
* workspace. Pure request-state machine: the actual ownership rewrite on
diff --git a/packages/database/src/models/task/rows.ts b/packages/database/src/models/task/rows.ts
index 8899863ba5a..8040926381e 100644
--- a/packages/database/src/models/task/rows.ts
+++ b/packages/database/src/models/task/rows.ts
@@ -3,9 +3,10 @@ import { and, eq, inArray, ne, or, sql } from 'drizzle-orm';
import { tasks } from '../../schemas/task';
import type { LobeChatDatabase } from '../../type';
+import { isUniqueViolation } from '../../utils/uniqueViolation';
import { countOf } from '../utils/rows';
import { seqOwnership, type TaskModelContext, taskOwnership } from './context';
-import { isTaskIdentifierUniqueViolation, normalizeTaskRefs } from './utils';
+import { normalizeTaskRefs } from './utils';
/**
* Insert a task under the next free `seq` in scope, retrying when a concurrent
@@ -52,8 +53,7 @@ export const insertWithNextSeq = async (
return task;
} catch (error: any) {
// Retry on unique constraint violation (concurrent seq conflict)
- // Check error itself, cause, and stringified message for PG error code 23505
- if (isTaskIdentifierUniqueViolation(error) && attempt < maxRetries - 1) {
+ if (isUniqueViolation(error) && attempt < maxRetries - 1) {
continue;
}
throw error;
diff --git a/packages/database/src/models/task/utils.ts b/packages/database/src/models/task/utils.ts
index 98713a3afb3..978c079b1a2 100644
--- a/packages/database/src/models/task/utils.ts
+++ b/packages/database/src/models/task/utils.ts
@@ -5,6 +5,8 @@ import {
toTaskExecutionConfigPatch,
} from '@lobechat/types';
+import { isUniqueViolation } from '../../utils/uniqueViolation';
+
export const DEFAULT_TASK_IDENTIFIER_PREFIX = 'T';
/** Columns whose change is worth a line in the task activity feed. */
@@ -127,19 +129,5 @@ export const withStaleReposCleared = (
};
};
-export const isTaskIdentifierUniqueViolation = (error: unknown): boolean => {
- const message = error instanceof Error ? error.message : String(error);
- const code =
- typeof error === 'object' && error && 'code' in error
- ? String((error as { code?: unknown }).code)
- : '';
- const cause = error instanceof Error ? error.cause : undefined;
-
- return (
- code === '23505' ||
- message.includes('23505') ||
- message.includes('duplicate') ||
- message.includes('unique') ||
- (!!cause && isTaskIdentifierUniqueViolation(cause))
- );
-};
+/** Kept under its historical name for callers outside this package. */
+export const isTaskIdentifierUniqueViolation = isUniqueViolation;
diff --git a/packages/database/src/models/work/__tests__/linear.test.ts b/packages/database/src/models/work/__tests__/linear.test.ts
index de2f6c3574d..dc736a796de 100644
--- a/packages/database/src/models/work/__tests__/linear.test.ts
+++ b/packages/database/src/models/work/__tests__/linear.test.ts
@@ -51,9 +51,9 @@ describe('WorkModel · linear', () => {
});
expect(first).toBeDefined();
- // Simulate losing the version-number race: the first insert attempt fails
- // with a unique violation while a concurrent registration commits a
- // version that renames the issue.
+ // Simulate losing the version-number race: a concurrent registration
+ // commits a version that renames the issue, then the first attempt fails
+ // with a real unique violation on (work_id, version).
const originalTransaction = serverDB.transaction.bind(serverDB);
let raced = false;
// Drizzle's transaction signature gained an optional config param upstream;
@@ -73,9 +73,10 @@ describe('WorkModel · linear', () => {
title: 'Winner title',
});
- throw new Error(
- 'duplicate key value violates unique constraint "work_versions_work_id_version_unique"',
- );
+ // Re-insert the winner's version number to raise the real violation our
+ // insert would hit; drizzle wraps it with the code on `cause`.
+ const { id: _id, ...winnerVersion } = await currentVersionRow(first!.id);
+ await serverDB.insert(workVersions).values(winnerVersion);
}) as never);
try {
diff --git a/packages/database/src/models/work/writes.ts b/packages/database/src/models/work/writes.ts
index bd58d172401..4a03754c637 100644
--- a/packages/database/src/models/work/writes.ts
+++ b/packages/database/src/models/work/writes.ts
@@ -15,6 +15,7 @@ import { documents } from '../../schemas/file';
import { tasks } from '../../schemas/task';
import { works, workVersions } from '../../schemas/work';
import type { LobeChatDatabase } from '../../type';
+import { isUniqueViolation } from '../../utils/uniqueViolation';
import { buildWorkspaceWhere } from '../../utils/workspace';
import {
documentOwnership,
@@ -61,27 +62,6 @@ const versionSnapshotSelection = {
url: workVersions.url,
};
-const isUniqueViolation = (error: unknown) => {
- const message = error instanceof Error ? error.message : String(error);
- const code =
- typeof error === 'object' && error && 'code' in error
- ? String((error as { code?: unknown }).code)
- : '';
- const cause = error instanceof Error ? error.cause : undefined;
- const causeCode =
- typeof cause === 'object' && cause && 'code' in cause
- ? String((cause as { code?: unknown }).code)
- : '';
-
- return (
- code === '23505' ||
- causeCode === '23505' ||
- message.includes('23505') ||
- message.includes('duplicate') ||
- message.includes('unique')
- );
-};
-
const findVersionByToolCall = async (
ctx: WorkContext,
workId: string,
diff --git a/packages/database/src/repositories/agentIntervention/claim.ts b/packages/database/src/repositories/agentIntervention/claim.ts
index 45b4f381426..3d28ef8fb20 100644
--- a/packages/database/src/repositories/agentIntervention/claim.ts
+++ b/packages/database/src/repositories/agentIntervention/claim.ts
@@ -20,7 +20,6 @@ import type {
import {
hasExactKeys,
isCanonicalJsonSafe,
- isUniqueViolation,
sameJson,
uniqueSorted,
} from '../../models/agentIntervention/utils';
@@ -34,6 +33,7 @@ import {
agentInterventionResolutions,
agentInterventions,
} from '../../schemas';
+import { isUniqueViolation } from '../../utils/uniqueViolation';
import { applyArgumentEffect, applyRememberEffect } from './effects';
/**
diff --git a/packages/database/src/repositories/channel/claim.ts b/packages/database/src/repositories/channel/claim.ts
index 7ec350e72d7..fb2d5425694 100644
--- a/packages/database/src/repositories/channel/claim.ts
+++ b/packages/database/src/repositories/channel/claim.ts
@@ -15,6 +15,7 @@ import {
import type { Transaction } from '../../type';
import { createNanoId } from '../../utils/idGenerator';
import { notTrashed } from '../../utils/softDelete';
+import { uniqueViolationConstraint } from '../../utils/uniqueViolation';
import { resolveExecutionConfig } from './agent';
import { findThread } from './delivery';
import { buildManifest } from './manifest';
@@ -42,16 +43,6 @@ export interface ChannelClaim {
const DIRECTORY_LOCK = 'channel_jobs_active_directory_unique';
-const uniqueViolation = (error: unknown): string | undefined => {
- const pgError = error as {
- cause?: { code?: string; constraint?: string };
- code?: string;
- constraint?: string;
- };
- const code = pgError.cause?.code ?? pgError.code;
- return code === '23505' ? (pgError.cause?.constraint ?? pgError.constraint ?? '') : undefined;
-};
-
/** Records why a queued job cannot start; clients read the code, never the text. */
const block = async (
tx: Transaction,
@@ -354,7 +345,7 @@ export const claimJob = async (
return { job: updated, topic };
});
} catch (error) {
- const constraint = uniqueViolation(error);
+ const constraint = uniqueViolationConstraint(error);
if (constraint === undefined) throw error;
if (constraint === DIRECTORY_LOCK)
await block(tx, job, 'directory_locked', 'Another run is using this directory');
diff --git a/packages/database/src/repositories/dataImporter/__tests__/index.test.ts b/packages/database/src/repositories/dataImporter/__tests__/index.test.ts
index 4af67914b58..5d7bfa7a036 100644
--- a/packages/database/src/repositories/dataImporter/__tests__/index.test.ts
+++ b/packages/database/src/repositories/dataImporter/__tests__/index.test.ts
@@ -556,6 +556,22 @@ describe('DataImporter', () => {
});
});
+ it('should parse a real unique violation that escapes the import transaction', async () => {
+ // A real conflict raised through drizzle: the driver error (code + detail) sits on `cause`.
+ vi.spyOn(clientDB, 'transaction').mockImplementationOnce(async () => {
+ await clientDB.insert(Schema.users).values({ id: userId });
+ });
+
+ const result = await importer.importPgData(agentsData as ImportPgDataStructure);
+
+ expect(result.success).toBe(false);
+ expect((result as ImportErrorResult).error?.details).toEqual({
+ constraintType: 'unique',
+ field: 'id',
+ value: userId,
+ });
+ });
+
it('should fall back to raw detail when error is not a 23505 unique violation', async () => {
const genericError: any = new Error('some db failure');
genericError.detail = 'raw detail message';
@@ -616,6 +632,11 @@ describe('DataImporter', () => {
// The transaction itself still succeeds; the batch error is swallowed and counted.
expect(result.success).toBe(true);
expect(result.results.userInstalledPlugins?.errors).toBe(2);
+ // The real driver error reaches the catch wrapped by drizzle (code on `cause`), and is
+ // still recognised as a unique conflict.
+ expect((importer as any).conflictRecords.userInstalledPlugins).toEqual([
+ { field: 'user_id, identifier', value: `${userId}, dup-plugin` },
+ ]);
});
});
diff --git a/packages/database/src/repositories/dataImporter/index.ts b/packages/database/src/repositories/dataImporter/index.ts
index 70f9b1b37b8..3205ce7faf6 100644
--- a/packages/database/src/repositories/dataImporter/index.ts
+++ b/packages/database/src/repositories/dataImporter/index.ts
@@ -6,6 +6,7 @@ import { uuid } from '@/utils/uuid';
import * as EXPORT_TABLES from '../../schemas';
import type { LobeChatDatabase } from '../../type';
+import { getUniqueViolation } from '../../utils/uniqueViolation';
import { buildWorkspaceWhere } from '../../utils/workspace';
import { DeprecatedDataImporterRepos } from './deprecated';
@@ -340,9 +341,9 @@ export class DataImporterRepos {
* Extract detailed information from error
*/
private extractErrorDetails(error: any) {
- if (error.code === '23505') {
- // PostgreSQL unique constraint error code
- const match = error.detail?.match(/Key \((.+?)\)=\((.+?)\) already exists/);
+ const violation = getUniqueViolation(error);
+ if (violation) {
+ const match = violation.detail?.match(/Key \((.+?)\)=\((.+?)\) already exists/);
if (match) {
return {
constraintType: 'unique',
@@ -731,8 +732,9 @@ export class DataImporterRepos {
console.error(`Error batch inserting ${tableName}:`, error);
// Handle error and record
- if ((error as any).code === '23505') {
- const match = (error as any).detail?.match(/Key \((.+?)\)=\((.+?)\) already exists/);
+ const violation = getUniqueViolation(error);
+ if (violation) {
+ const match = violation.detail?.match(/Key \((.+?)\)=\((.+?)\) already exists/);
if (match) {
const conflictField = match[1];
diff --git a/packages/database/src/utils/uniqueViolation.test.ts b/packages/database/src/utils/uniqueViolation.test.ts
new file mode 100644
index 00000000000..312f86985e5
--- /dev/null
+++ b/packages/database/src/utils/uniqueViolation.test.ts
@@ -0,0 +1,137 @@
+import { PGlite } from '@electric-sql/pglite';
+import { sql } from 'drizzle-orm';
+import { drizzle as nodeDrizzle } from 'drizzle-orm/node-postgres';
+import { integer, pgTable, text } from 'drizzle-orm/pg-core';
+import { drizzle as pgliteDrizzle } from 'drizzle-orm/pglite';
+import { Client } from 'pg';
+import { afterAll, beforeAll, describe, expect, it } from 'vitest';
+
+import {
+ getUniqueViolation,
+ isUniqueViolation,
+ PG_UNIQUE_VIOLATION,
+ uniqueViolationConstraint,
+} from './uniqueViolation';
+
+const probe = pgTable('unique_violation_probe', {
+ id: integer('id').primaryKey(),
+ name: text('name').notNull(),
+});
+
+const CREATE_PROBE =
+ 'CREATE TEMP TABLE unique_violation_probe (id integer CONSTRAINT unique_violation_probe_pkey PRIMARY KEY, name text NOT NULL)';
+
+const catchError = async (run: () => Promise<unknown>) => {
+ try {
+ await run();
+ } catch (error) {
+ return error;
+ }
+ throw new Error('expected the statement to fail');
+};
+
+interface DriverHarness {
+ db: ReturnType<typeof pgliteDrizzle> | ReturnType<typeof nodeDrizzle>;
+ /** Runs SQL straight on the driver, so its error is not wrapped. */
+ raw: (statement: string) => Promise<unknown>;
+}
+
+/**
+ * Both drivers raise their own error (`code` on the error itself); drizzle
+ * wraps it in a `DrizzleQueryError` whose `cause` is that driver error.
+ */
+const describeDriver = (
+ name: string,
+ setup: () => Promise<DriverHarness & { close: () => Promise<void> }>,
+ skip = false,
+) =>
+ describe.skipIf(skip)(`${name} errors`, () => {
+ let harness: DriverHarness & { close: () => Promise<void> };
+
+ // PGlite boots a whole Postgres in WASM; give it room on a loaded host.
+ beforeAll(async () => {
+ harness = await setup();
+ await harness.raw(CREATE_PROBE);
+ await harness.raw("INSERT INTO unique_violation_probe VALUES (1, 'first')");
+ }, 60_000);
+
+ afterAll(async () => {
+ await harness?.close();
+ });
+
+ it('reads a unique violation raised by the driver itself', async () => {
+ const error = await catchError(() =>
+ harness.raw("INSERT INTO unique_violation_probe VALUES (1, 'again')"),
+ );
+
+ expect((error as { code?: string }).code).toBe(PG_UNIQUE_VIOLATION);
+ expect(isUniqueViolation(error)).toBe(true);
+ expect(uniqueViolationConstraint(error)).toBe('unique_violation_probe_pkey');
+ expect(getUniqueViolation(error)?.detail).toBe('Key (id)=(1) already exists.');
+ });
+
+ it('reads a unique violation wrapped by drizzle', async () => {
+ const error = await catchError(() =>
+ harness.db.insert(probe).values({ id: 1, name: 'again' }),
+ );
+
+ // The wrapper carries no code; the driver error sits on `cause`.
+ expect((error as { code?: string }).code).toBeUndefined();
+ expect((error as { cause?: { code?: string } }).cause?.code).toBe(PG_UNIQUE_VIOLATION);
+ expect(isUniqueViolation(error)).toBe(true);
+ expect(uniqueViolationConstraint(error)).toBe('unique_violation_probe_pkey');
+ expect(getUniqueViolation(error)?.detail).toBe('Key (id)=(1) already exists.');
+ });
+
+ it('rejects other constraint violations at either level', async () => {
+ const raw = await catchError(() =>
+ harness.raw('INSERT INTO unique_violation_probe VALUES (2, NULL)'),
+ );
+ const wrapped = await catchError(() =>
+ harness.db.execute(sql`INSERT INTO unique_violation_probe VALUES (3, NULL)`),
+ );
+
+ for (const error of [raw, wrapped]) {
+ expect(isUniqueViolation(error)).toBe(false);
+ expect(uniqueViolationConstraint(error)).toBeUndefined();
+ }
+ });
+ });
+
+describeDriver('PGlite', async () => {
+ const client = new PGlite();
+ return {
+ close: () => client.close(),
+ db: pgliteDrizzle({ client }),
+ raw: (statement) => client.query(statement),
+ };
+});
+
+describeDriver(
+ 'node-postgres',
+ async () => {
+ // A single client (not a pool) so the temp table stays on one session.
+ const client = new Client({ connectionString: process.env.DATABASE_TEST_URL });
+ await client.connect();
+ return {
+ close: () => client.end(),
+ db: nodeDrizzle({ client }),
+ raw: (statement) => client.query(statement),
+ };
+ },
+ !process.env.DATABASE_TEST_URL,
+);
+
+describe('non-error values', () => {
+ it('treats anything without a unique-violation code as no violation', () => {
+ for (const value of [null, undefined, 'duplicate key value', 23_505, {}, { cause: null }]) {
+ expect(isUniqueViolation(value)).toBe(false);
+ }
+ expect(isUniqueViolation({ cause: 'duplicate key value' })).toBe(false);
+ });
+
+ it('reports an empty constraint name when the driver omits it', () => {
+ expect(uniqueViolationConstraint({ code: PG_UNIQUE_VIOLATION })).toBe('');
+ expect(uniqueViolationConstraint({ cause: { code: PG_UNIQUE_VIOLATION } })).toBe('');
+ });
+});
diff --git a/packages/database/src/utils/uniqueViolation.ts b/packages/database/src/utils/uniqueViolation.ts
new file mode 100644
index 00000000000..66adf69f5da
--- /dev/null
+++ b/packages/database/src/utils/uniqueViolation.ts
@@ -0,0 +1,41 @@
+/** Postgres SQLSTATE for `unique_violation`. */
+export const PG_UNIQUE_VIOLATION = '23505';
+
+interface PgErrorFields {
+ cause?: unknown;
+ code?: unknown;
+ constraint?: string;
+ detail?: string;
+}
+
+/**
+ * Returns the driver error that carries a Postgres unique violation, or
+ * `undefined` for any other error.
+ *
+ * drizzle (0.45+) wraps every driver error in a `DrizzleQueryError`, so the
+ * SQLSTATE and its diagnostics live on `error.cause`. A driver error that
+ * reaches us unwrapped (raw client calls, node-postgres or PGlite alike)
+ * carries them on the error itself, so read both levels.
+ */
+export const getUniqueViolation = (error: unknown): PgErrorFields | undefined => {
+ if (!error || typeof error !== 'object') return undefined;
+
+ const pgError = error as PgErrorFields;
+ if (pgError.code === PG_UNIQUE_VIOLATION) return pgError;
+
+ const cause = pgError.cause as PgErrorFields | undefined;
+ if (cause && typeof cause === 'object' && cause.code === PG_UNIQUE_VIOLATION) return cause;
+
+ return undefined;
+};
+
+export const isUniqueViolation = (error: unknown): boolean => !!getUniqueViolation(error);
+
+/**
+ * The violated constraint name when `error` is a unique violation, `''` when
+ * the driver did not report one, and `undefined` for any other error.
+ */
+export const uniqueViolationConstraint = (error: unknown): string | undefined => {
+ const violation = getUniqueViolation(error);
+ return violation ? (violation.constraint ?? '') : undefined;
+};