prismaで全てのテーブルをDropする(javascript)

JavaScript

Postgres

async function clearAllTables(modelNames?: Prisma.ModelName[]): Promise<void> {
  const tablenames = modelNames
    ? modelNames.map((modelName) => ({ tablename: modelName }))
    : await prisma.$queryRaw<
        Array<{ tablename: string }>
      >`SELECT tablename FROM pg_tables WHERE schemaname='public'`

  for (const { tablename } of tablenames) {
    try {
      await prisma.$executeRawUnsafe(
        `TRUNCATE TABLE "public"."${tablename}" RESTART IDENTITY CASCADE;`,
      )
    } catch (error) {
      console.log({ error })
    }
  }
}

MySQL

‘Tables_in_testdb’のtestdbの部分は設定しているDB名+dbです。

async function clearAllTables() {
  const result = await prisma.$queryRaw<
    Array<{ Tables_in_testdb: string }>
  >`SHOW TABLES`
  await prisma.$executeRawUnsafe(`SET FOREIGN_KEY_CHECKS = 0;`)
  for (const { Tables_in_testdb: tablename } of result) {
    await prisma.$executeRawUnsafe(`TRUNCATE TABLE ${tablename};`)
  }
  await prisma.$executeRawUnsafe(`SET FOREIGN_KEY_CHECKS = 1;`)
}

コメント