From 8405a49d4561e84e82c918e92e7953f457f31951 Mon Sep 17 00:00:00 2001 From: Sean O'Connor Date: Thu, 5 Dec 2024 13:23:47 -0500 Subject: [PATCH] refactor(db): Improve table dropping and seeding logic - Updated the dropAllTables function to drop tables in a specific order, considering foreign key dependencies, ensuring data integrity during the drop process. - Refactored the seed function to utilize role and permission data objects for cleaner insertion logic, enhancing readability and maintainability of the code. --- src/db/drop.ts | 14 +++++++++++--- src/db/seed.ts | 22 +++++++++++++--------- 2 files changed, 24 insertions(+), 12 deletions(-) diff --git a/src/db/drop.ts b/src/db/drop.ts index 4caa0e4..6eb0990 100644 --- a/src/db/drop.ts +++ b/src/db/drop.ts @@ -1,5 +1,4 @@ import { sql } from '@vercel/postgres'; -import { db } from './index'; import { config } from 'dotenv'; // load .env.local @@ -7,9 +6,18 @@ config({ path: '.env.local' }); async function dropAllTables() { try { - // drop all tables, regardless of name + // Drop tables in order considering foreign key dependencies await sql` - DROP TABLE IF EXISTS ${sql.raw(Object.values(tables).map(table => table.name).join(', '))} + DROP TABLE IF EXISTS + invitations, + user_roles, + role_permissions, + permissions, + roles, + participant, + study, + users + CASCADE; `; console.log('All tables dropped successfully'); } catch (error) { diff --git a/src/db/seed.ts b/src/db/seed.ts index 7376092..6b352a0 100644 --- a/src/db/seed.ts +++ b/src/db/seed.ts @@ -21,25 +21,29 @@ async function seed() { // Insert roles console.log("Inserting roles..."); for (const [roleKey, roleName] of Object.entries(ROLES)) { + const roleData = { + name: roleName, + description: getRoleDescription(roleKey), + } as const; + await db .insert(rolesTable) - .values({ - name: roleName, - description: getRoleDescription(roleKey), - }) + .values(roleData) .onConflictDoNothing(); } // Insert permissions console.log("Inserting permissions..."); for (const [permKey, permCode] of Object.entries(PERMISSIONS)) { + const permData = { + name: formatPermissionName(permKey), + code: permCode, + description: getPermissionDescription(permKey), + } as const; + await db .insert(permissionsTable) - .values({ - name: formatPermissionName(permKey), - code: permCode, - description: getPermissionDescription(permKey), - }) + .values(permData) .onConflictDoNothing(); }