Skip to content

Easy workflow to reset all data #742

Closed

Description

@schickling

Problem

There currently doesn't seem to be a way to easily reset a database.

Suggested solution

Provide a way to reset the database (via CLI, SDK, Studio). This should delete the database, re-create it from the schema and finally seed it (if there is a seed).

Alternatives

Additional context

Popular frameworks like Ruby on Rails have integrated tools to manage the lifecycle of a database:

  • db:create creates the database for the current env
  • db:create:all creates the databases for all envs
  • db:drop drops the database for the current env
  • db:drop:all drops the databases for all envs
  • db:migrate runs migrations for the current env that have not run yet
  • db:migrate:up runs one specific migration
  • db:migrate:down rolls back one specific migration
  • db:migrate:status shows current migration status
  • db:rollback rolls back the last migration
  • db:forward advances the current schema version to the next one
  • db:seed (only) runs the db/seed.rb file
  • db:schema:load loads the schema into the current env's database
  • db:schema:dump dumps the current env's schema (and seems to create the db as well)

Original issue

There currently doesn't seem to be a way to easily reset all data. This should be possible via Studio, CLI and/or SDK.

Activity

  1. added
    kind/feature
    on Oct 14, 2019
  2. janpio commented on Oct 16, 2019

    @janpio
    Contributor

    Clarification: First step here would be to create a spec that defines how this might work and what it might be called.

  3. janpio commented on Oct 28, 2019

    @janpio
    Contributor

    Internal Note: Move to specs

  4. added this to the Preview 16 milestone on Oct 28, 2019
  5. schickling commented on Nov 7, 2019

    @schickling
    MemberAuthor

    First step: Implement this functionality in Studio (See issue prisma/studio#237).

    After that we'll investigate further whether/how to expose this functionality via other tools (e.g. CLI, SDK, ...)

  6. timsuchanek commented on Nov 7, 2019

    @timsuchanek
    Contributor

    Internal Note: Dropping, because this is a Studio only thing.

  7. pantharshit00 commented on Mar 26, 2020

    @pantharshit00
    Contributor

    Internal note: Candidating this because of another duplicate issue that refered to same feature was candidated by @schickling

  8. frandiox commented on Apr 9, 2020

    @frandiox

    We use Prisma v1 CLI to prepare the database for e2e and for integration tests. It's really handy to do prisma reset && prisma seed -e .env.[e2e|int].
    What would be the equivalent in Prisma 2?

  9. 16 remaining items

  10. albertoperdomo commented on Mar 3, 2021

    @albertoperdomo
    Contributor

    We have prisma migrate reset now, which:

    1. drops the database
    2. creates the database
    3. applies migrations
    4. seeds the database.

    We are closing this issue.

    For those who are interested in truncating tables over dropping and re-creating the database, which is tracked here: #5596

  11. beeman commented on Mar 3, 2021

    @beeman

    We have prisma migrate reset now, which:

    1. drops the database
    
    2. creates the database
    
    3. applies migrations
    
    4. seeds the database.
    

    We are closing this issue.

    For those who are interested in truncating tables over dropping and re-creating the database, which is tracked here: #5596

    You folks are amazing!! 🙏

  12. chinanderm commented on Mar 9, 2021

    @chinanderm

    We have prisma migrate reset now, which:

    1. drops the database
    2. creates the database
    3. applies migrations
    4. seeds the database.

    We are closing this issue.

    For those who are interested in truncating tables over dropping and re-creating the database, which is tracked here: #5596

    Thanks for sharing! However, after dropping and creating the database, it doesn't recreate the tables. Is there a way to have it allow run a prism db push?

  13. Jolg42 commented on Mar 9, 2021

    @Jolg42
    Contributor

    @chinanderm We actually added the --force-reset flag to prisma db push in 2.17 that will force a reset of the database before doing the push.
    You can use it like prisma db push --force-reset --preview-feature, I think it's exactly what you needed?

  14. chinanderm commented on Mar 9, 2021

    @chinanderm

    @Jolg42 Yep, that works great. Thank you!

  15. Jolg42 commented on Mar 9, 2021

    @Jolg42
    Contributor

    @chinanderm Note that if you're already using migrations files I would recommend to use

    prisma migrate reset --force --preview-feature && prisma migrate deploy --preview-feature
    

    Why? Because db push creates the SQL on the fly while you could have extra SQL that it could not guess (like if you edited the migration.sql files).
    So using reset + deploy makes sure you have the same end-state as in production (minus the data).

  16. phoenixeliot commented on Apr 2, 2024

    @phoenixeliot

    For doing this inside Jest for speed, I found doing the truncate all in one query to be about 1 second faster (+.2sec vs +1.2sec)

        // 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`,
        );
    
  17. Athar-ali-siddiqui commented on May 1, 2024

    @Athar-ali-siddiqui

    I have used this strategy to ensure the database is cleaned up before executing each test.

    await this.$queryRaw(
                Prisma.sql`
                do $$DECLARE
                begin 
                    EXECUTE 
                    (SELECT 'TRUNCATE TABLE '
                        || string_agg(format('%I.%I', schemaname, tablename), ', ')
                        || ' CASCADE'
                    FROM   pg_tables
                    WHERE  tableowner = 'postgres'
                    AND    schemaname = 'public'
                    AND    hastriggers = true
                    );
                END$$;`
            );
    
  18. removed their assignment
    on May 3, 2024
  19. campellcl commented on Dec 11, 2024

    @campellcl

    If you are trying to get this working from inside a .ts file (for instance seed.ts) you can:

    import { exec, execSync } from "child_process";
    import { promisify } from "util";
    
    export default async function clearDatabase() {
      const execAsync = promisify(exec)
      try {
        const {stdout, stderr} = await execAsync('pnpm prisma db push --force-reset')
        console.log(`stdout: ${stdout}`)
        console.error(`stderr: ${stderr}`)
      } catch (error) {
        console.error(`error: ${error}`)
      }
    }
    

    In the invoker (i.e. jest testing script):

      beforeAll(async () => {
        // Reseed the database before running the tests
        await clearDatabase()
        await seed()
      })
    
  20. s14051sa-png commented on Jan 30, 2026

    @s14051sa-png

    All the evidence must be clear.

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: cli

    Type

    No type

    Projects

    No projects

      Milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions