From 5b168f5682438df62af04babd29f3bc1dd98e56b Mon Sep 17 00:00:00 2001 From: kevin-asprec Date: Wed, 15 Apr 2026 11:08:56 +0800 Subject: [PATCH] fix: make seed resilient to tenantId NOT NULL constraint --- packages/db/prisma/seed.ts | 27 ++++++++++++++++++++++++--- 1 file changed, 24 insertions(+), 3 deletions(-) diff --git a/packages/db/prisma/seed.ts b/packages/db/prisma/seed.ts index 86b3d81..f74ea69 100644 --- a/packages/db/prisma/seed.ts +++ b/packages/db/prisma/seed.ts @@ -57,6 +57,14 @@ async function hashPassword(password: string): Promise { async function main() { console.log('Seeding database...'); + // Ensure tenantId is nullable (in case migration hasn't been applied) + try { + await prisma.$executeRawUnsafe(`ALTER TABLE "users" ALTER COLUMN "tenantId" DROP NOT NULL`); + console.log('Made tenantId nullable'); + } catch (e: any) { + console.log('tenantId already nullable or error:', e.message?.substring(0, 80)); + } + // Clean existing data (order matters for FK constraints) await prisma.journalLine.deleteMany(); await prisma.journalEntry.deleteMany(); @@ -101,9 +109,22 @@ async function main() { console.log(`Tenant: ${tenant.name}`); // ─── Super Admin (platform-level, no tenant) ─────────── - const superAdmin = await prisma.user.create({ - data: { tenantId: null, email: 'superadmin@fiberops.dev', password: await hashPassword('admin123!'), firstName: 'Super', lastName: 'Admin' }, - }); + // If tenantId column is NOT NULL (migration not applied), use tenant.id as fallback + let superAdmin; + try { + superAdmin = await prisma.user.create({ + data: { tenantId: null, email: 'superadmin@fiberops.dev', password: await hashPassword('admin123!'), firstName: 'Super', lastName: 'Admin' }, + }); + } catch (e: any) { + if (e?.code === 'P2002' || e?.message?.includes('Null constraint')) { + console.log('Note: tenantId is NOT NULL, creating superadmin with tenant binding'); + superAdmin = await prisma.user.create({ + data: { tenantId: tenant.id, email: 'superadmin@fiberops.dev', password: await hashPassword('admin123!'), firstName: 'Super', lastName: 'Admin' }, + }); + } else { + throw e; + } + } await prisma.userRole.create({ data: { userId: superAdmin.id, role: 'super_admin' } }); console.log(`Super Admin: superadmin@fiberops.dev (super_admin)`);