0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

prismaでテーブルのレコードを削除したい

Posted at

テスト時にテーブル名でループさせてdeleteManyしていたが、prismaの更新で利用できなくなったため以下のように変更

コード

  • Prisma.ModelNameにはテーブルのみが含まれるのではなく、viewも含まれているため、filterで除外した
  • 一応、pg_tablesをWHERE schemaname='public'でselectするとハードコードせずにテーブル名の取得が可能だが、今回はクエリ回数を抑えるため不採用にした
import { Prisma, type PrismaClient } from "@prisma/client";

export const truncateTables = async (client: PrismaClient) => {
  const tableNames = Object.values(Prisma.ModelName)
    .filter((name) => name !== "ExampleView")
    .map((name) => `"public"."${name}"`)
    .join(", ");

  await client.$executeRawUnsafe(
    `TRUNCATE TABLE ${tableNames} RESTART IDENTITY CASCADE;`,
  );
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?