Skip to content

Commit ae5f305

Browse files
Fix cleanupDb when foreign key constraints exist (#795)
Co-authored-by: Kent C. Dodds <[email protected]>
1 parent 69bf0df commit ae5f305

File tree

1 file changed

+13
-8
lines changed

1 file changed

+13
-8
lines changed

tests/db-utils.ts

Lines changed: 13 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -120,13 +120,18 @@ export async function cleanupDb(prisma: PrismaClient) {
120120
{ name: string }[]
121121
>`SELECT name FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%' AND name NOT LIKE '_prisma_migrations';`
122122

123-
await prisma.$transaction([
123+
try {
124124
// Disable FK constraints to avoid relation conflicts during deletion
125-
prisma.$executeRawUnsafe(`PRAGMA foreign_keys = OFF`),
126-
// Delete all rows from each table, preserving table structures
127-
...tables.map(({ name }) =>
128-
prisma.$executeRawUnsafe(`DELETE from "${name}"`),
129-
),
130-
prisma.$executeRawUnsafe(`PRAGMA foreign_keys = ON`),
131-
])
125+
await prisma.$executeRawUnsafe(`PRAGMA foreign_keys = OFF`)
126+
await prisma.$transaction([
127+
// Delete all rows from each table, preserving table structures
128+
...tables.map(({ name }) =>
129+
prisma.$executeRawUnsafe(`DELETE from "${name}"`),
130+
),
131+
])
132+
} catch (error) {
133+
console.error('Error cleaning up database:', error)
134+
} finally {
135+
await prisma.$executeRawUnsafe(`PRAGMA foreign_keys = ON`)
136+
}
132137
}

0 commit comments

Comments
 (0)