Skip to content

Feature request: prisma db truncate #5596

Open

Description

@Jolg42

Problem

prisma migrate reset or a reset in general (drop and recreate) is slow and not something you want for testing for example.

Suggested solution

prisma db truncate would be nice to have and really useful when testing.

Alternatives

Additional context

#742
#5063
#5161 (comment)

Activity

  1. ydennisy commented on Feb 23, 2022

    @ydennisy

    @Jolg42 anything to mention here is that reset drops all internal postgres tables when using something like supabase, this causes issues and essentially breaks the database.

    We really need a nice way to reset the state of the DB to just the tables managed by prisma.

  2. janpio commented on Feb 23, 2022

    @janpio
    Contributor

    @Jolg42 anything to mention here is that reset drops all internal postgres tables when using something like supabase, this causes issues and essentially breaks the database.

    Can you please create a new bug report issue about this? We want to look into that separately and figure out if there is a more direct way to fix this. reset should never destroy things. Thanks.

  3. tsongas commented on Jul 18, 2022

    @tsongas

    Yes please!

  4. rubenhelsloot commented on Feb 24, 2023

    @rubenhelsloot

    Any progress on this? I would really like to be able to reset my Postgres database between e2e test suites, but right now this means that my NextJS server errors with cache lookup failed for type 27622 (or some other number). When I restart the server, this error goes away - the first test suite always succeeds.

    I believe the reason is that db push --force-reset also drops all tables and enums, and generates a new enum with the same name, but a different type number. But the server is of course not notified of this, so it's still using some internal cache with the old enum definitions.

    In an ideal situation, I would like to

    1. On the start of the test suite, run the migrations (I believe prisma migrate dev --force is suitable for this);
    2. Before each test suite, empty the database and apply seed data, but do keep all tables, enums and sequences.
  5. foloinfo commented on Oct 6, 2023

    @foloinfo

    I was trying to figure out how to smoothly run tests while resetting the data between each spec.

    I found this CRUD (Reference) | Prisma Docs and Easy workflow to reset all data · Issue #742 · prisma/prisma helpful, but needed to change slightly since the API has changed.
    This is my current setup. I want a function like await prisma.truncate(), prisma db drop. Such utilities greatly enhance the developer experience.

    setupAfterEnv.ts

    import prisma, { Prisma } from '@/lib/prisma'
    
    type TableNames = Array<{ tablename: string }>
    const tableNamesSQL = Prisma.sql`
      SELECT tablename FROM pg_tables WHERE schemaname='public'
    `
    type Sequences = Array<{ relname: string }>
    const sequencesSQL = Prisma.sql`
      SELECT c.relname FROM pg_class AS c
        JOIN pg_namespace AS n ON c.relnamespace = n.oid
      WHERE
        c.relkind='S'
      AND
        n.nspname='public';
    `
    
    // waiting for [Feature request: `prisma db truncate` · Issue #5596 · prisma/prisma](https://github.com/prisma/prisma/issues/5596)
    const truncate = async () => {
      // truncate all the tables
      const tablenames = await prisma.$queryRaw<TableNames>(tableNamesSQL)
      const tables = tablenames
        .map(({ tablename }) => tablename)
        .filter((name) => name !== '_prisma_migrations')
        .map((name) => `"public"."${name}"`)
        .join(', ')
      await prisma.$executeRawUnsafe(`TRUNCATE TABLE ${tables} CASCADE;`)
    
      // reset all the sequences (ids)
      const sequences = await prisma.$queryRaw<Sequences>(sequencesSQL)
      for (const { relname } of sequences) {
        await prisma.$executeRawUnsafe(`ALTER SEQUENCE "public"."${relname}" RESTART WITH 1;`)
      }
    }
    
    afterEach(async () => {
      await truncate()
    })

    jest.config.js (nextjs)

    const config = {
      ...
      setupFilesAfterEnv: ['<rootDir>/spec/setupAfterEnv.ts'],
    }

    package.json

      "scripts": {
        ...
        "docker:up": "docker-compose up -d",
        "docker:down": "docker-compose down",
        "db:migrate:test": "yarn docker:up && dotenv -e .env.test -- yarn prisma migrate deploy",
        "test": "yarn docker:up && jest -i --watchAll",
    

    When running the test for the first time, I need to create the db with yarn db:migrate:test just like rails db:migrate RAILS_ENV=test

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    kind/featuretopic: clitopic: migrate

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions