Skip to content

Instantly share code, notes, and snippets.

@laudaikinhdi
Forked from rsaryev/prisma-utils.ts
Created February 23, 2024 04:43
Show Gist options
  • Save laudaikinhdi/c2d6fec7806ee5bc1a14559130168fb4 to your computer and use it in GitHub Desktop.
Save laudaikinhdi/c2d6fec7806ee5bc1a14559130168fb4 to your computer and use it in GitHub Desktop.

Revisions

  1. @rsaryev rsaryev revised this gist Jan 15, 2022. No changes.
  2. @rsaryev rsaryev created this gist Jan 15, 2022.
    41 changes: 41 additions & 0 deletions prisma-utils.ts
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,41 @@
    import { Prisma, PrismaClient } from '@prisma/client';
    import { exec } from 'child_process';
    import * as util from 'util';

    const execPromisify = util.promisify(exec);
    const prisma = new PrismaClient();

    const tables = Prisma.dmmf.datamodel.models
    .map((model) => model.dbName)
    .filter((table) => table);

    const clearMysql = async () => {
    await prisma.$transaction([
    prisma.$executeRaw`SET FOREIGN_KEY_CHECKS = 0;`,
    ...tables.map((table) =>
    prisma.$executeRawUnsafe(`TRUNCATE ${table};`),
    ),
    prisma.$executeRaw`SET FOREIGN_KEY_CHECKS = 1;`,
    ]);
    };

    const clearPostgres = async () => {
    await prisma.$transaction([
    ...tables.map((table) =>
    prisma.$executeRawUnsafe(`TRUNCATE ${table} CASCADE;`),
    ),
    ]);
    };

    const clearDefault = async () =>
    execPromisify('npx prisma migrate reset --force --skip-seed');

    export const clear = async (provider: string) => {
    const executeClear = {
    mysql: clearMysql,
    postgres: clearPostgres,
    };

    const execute = executeClear[provider] || clearDefault;
    return execute();
    };