aboutsummaryrefslogtreecommitdiff
path: root/src/lib/server/db/errors.test.ts
diff options
context:
space:
mode:
authorMartin Kagamino Lehoux <martin@lehoux.net>2026-10-18 21:47:21 +0200
committerMartin Kagamino Lehoux <martin@lehoux.net>2026-10-18 21:47:21 +0200
commitc3c61894d2b119ae424bac605d4b3099e0b674e5 (patch)
treec525ebf4d33cbdfac22fc8702367f20d8f7ba344 /src/lib/server/db/errors.test.ts
parentc2722b62832afe2d028f1bcb6954116f7eec9cde (diff)
fix: report a duplicate name instead of failing the page
Adding a category or project whose name exists, or renaming an item onto an existing name, hit the unique constraint and rendered SvelteKit's 500 page. Translate SQLITE_CONSTRAINT_UNIQUE into a form error on the three forms.
Diffstat (limited to 'src/lib/server/db/errors.test.ts')
-rw-r--r--src/lib/server/db/errors.test.ts45
1 files changed, 45 insertions, 0 deletions
diff --git a/src/lib/server/db/errors.test.ts b/src/lib/server/db/errors.test.ts
new file mode 100644
index 0000000..d19aec2
--- /dev/null
+++ b/src/lib/server/db/errors.test.ts
@@ -0,0 +1,45 @@
+import { describe, it, expect, beforeEach } from 'vitest';
+import { groceries, categories } from '$lib/server/db/schema';
+import { eq } from 'drizzle-orm';
+import { createTestDb, type TestDb } from '$lib/server/db/test-helper';
+import { isUniqueViolation } from './errors';
+
+describe('isUniqueViolation', () => {
+ let db: TestDb['db'];
+
+ beforeEach(async () => {
+ db = (await createTestDb()).db;
+ await db.insert(categories).values({ name: 'Épices' });
+ await db
+ .insert(groceries)
+ .values({ name: 'olives', createdAt: '2026-01-01T00:00:00.000Z' });
+ });
+
+ it('detects a duplicate insert on a unique column', async () => {
+ const error = await db
+ .insert(categories)
+ .values({ name: 'Épices' })
+ .catch((e: unknown) => e);
+
+ expect(isUniqueViolation(error)).toBe(true);
+ });
+
+ it('detects a duplicate name on update', async () => {
+ await db
+ .insert(groceries)
+ .values({ name: 'pain', createdAt: '2026-01-02T00:00:00.000Z' });
+
+ const error = await db
+ .update(groceries)
+ .set({ name: 'olives' })
+ .where(eq(groceries.name, 'pain'))
+ .catch((e: unknown) => e);
+
+ expect(isUniqueViolation(error)).toBe(true);
+ });
+
+ it('leaves other failures alone', () => {
+ expect(isUniqueViolation(new Error('network is unreachable'))).toBe(false);
+ expect(isUniqueViolation(undefined)).toBe(false);
+ });
+});