Created
August 4, 2024 16:44
-
-
Save gmoigneu/aa85fcb487235684ea7df7b44614854a to your computer and use it in GitHub Desktop.
Prisma: truncate before seeding.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import { PrismaClient } from '@prisma/client' | |
| const prisma = new PrismaClient() | |
| async function main() { | |
| // Get all table names from the information_schema | |
| const result: { table_name: string }[] = await prisma.$queryRaw` | |
| SELECT table_name | |
| FROM information_schema.tables | |
| WHERE table_schema = 'public' AND table_type = 'BASE TABLE'; | |
| `; | |
| // Truncate them all in one combined query | |
| await prisma.$queryRawUnsafe( | |
| `TRUNCATE TABLE ${result.map(({ table_name }) => `"${table_name}"`).join(", ")} RESTART IDENTITY CASCADE`, | |
| ); | |
| } | |
| main() | |
| .then(async () => { | |
| await prisma.$disconnect() | |
| }) | |
| .catch(async (e) => { | |
| console.error(e) | |
| await prisma.$disconnect() | |
| process.exit(1) | |
| }) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment