Skip to content

Instantly share code, notes, and snippets.

@gmoigneu
Created August 4, 2024 16:44
Show Gist options
  • Select an option

  • Save gmoigneu/aa85fcb487235684ea7df7b44614854a to your computer and use it in GitHub Desktop.

Select an option

Save gmoigneu/aa85fcb487235684ea7df7b44614854a to your computer and use it in GitHub Desktop.
Prisma: truncate before seeding.
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