Giter VIP home page Giter VIP logo

Comments (22)

kitze avatar kitze commented on August 16, 2024 31

Maybe add a button in the data studio?

from docs.

sorenbs avatar sorenbs commented on August 16, 2024 28

I guess you could also do something like this:

const { PrismaClient } = require('@prisma/client')
const prisma = new PrismaClient()

const allProperties = Reflect.ownKeys(Object.getPrototypeOf(prisma))
const modelNames = allProperties.filter(x => x != "constructor" && x != "on" && x != "connect" && x != "runDisconnect" && x != "disconnect")

for (modelName of modelNames) {

    // handle async stuff
    prisma[modelName].deleteMany()
}

from docs.

seanwash avatar seanwash commented on August 16, 2024 19

I found this approach in the docs, works well enough for me: https://www.prisma.io/docs/concepts/components/prisma-client/crud#deleting-all-data-with-raw-sql--truncate

from docs.

5t111111 avatar 5t111111 commented on August 16, 2024 14

With the latest versions of prisma and prisma cilent , unfortunately any solutions proposed in this issue fails.

prisma               : 2.20.0
@prisma/client       : 2.20.0

Although I don't know if I am doing correct ways, I have got them work with the following fixes:

import { PrismaClient, Prisma } from '@prisma/client';

export const cleanupDatabase = () => {
  const prisma = new PrismaClient();
  const modelNames = Prisma.dmmf.datamodel.models.map((model) => model.name);

  return Promise.all(
    modelNames.map((modelName) => prisma[modelName.toLowerCase()].deleteMany())
  );
};

or

import { PrismaClient } from '@prisma/client';

export const cleanupDatabase = () => {
  const prisma = new PrismaClient();
  const propertyNames = Object.getOwnPropertyNames(prisma);
  const modelNames = propertyNames.filter(
    (propertyName) => !propertyName.startsWith('_')
  );

  return Promise.all(modelNames.map((model) => prisma[model].deleteMany()));
};

from docs.

munirmuratovic avatar munirmuratovic commented on August 16, 2024 12

npx prisma db push --force-reset

from docs.

yoshitamagoshi avatar yoshitamagoshi commented on August 16, 2024 7

The recommendation on this thread on using
prisma migrate reset --force && prisma migrate deploy
is likely the most Prisma native approach for dropping and resetting the database tables as you'd have happen on production, without the production data.

from docs.

kieronjmckenna avatar kieronjmckenna commented on August 16, 2024 6

I couldn't seem to get any of the above solutions to work as Prisma was unhappy removing the data due to relations.

An easy solution for me was to run a yarn script that dropped the schema with Postgres, then ran Prisma migrate immediately after.

Package.json

 "scripts": {
    "nuke": "psql -Atx postgresql://<username>:<password>@<host:<port>/<db> -f nuke.sql",
    "reset": "yarn nuke && prisma migrate dev -n reset"
  }

-n to stop being promoted

nuke.sql

DROP SCHEMA public CASCADE;
CREATE SCHEMA public;

Run

yarn reset

and you've got an empty DB

I thought I'd share; even though it's not strictly done with Prisma, I hope it helps someone out.

from docs.

sneko avatar sneko commented on August 16, 2024 5

I found this approach in the docs, works well enough for me: https://www.prisma.io/docs/concepts/components/prisma-client/crud#deleting-all-data-with-raw-sql--truncate

I really recommend this suggestion as a reference. You will avoid wasting time on adjusting things due to foreign key constraints... (much harder when you manage soft delete too).

Thank you @seanwash !

from docs.

harryhorton avatar harryhorton commented on August 16, 2024 4

Another approach:

import { Injectable, OnModuleDestroy, OnModuleInit } from '@nestjs/common';
import { PrismaClient, dmmf } from '@prisma/client';

@Injectable()
export class PrismaService extends PrismaClient
  implements OnModuleInit, OnModuleDestroy {
  constructor() {
    super();
  }

  onModuleInit() {
    return this.$connect();
  }

  onModuleDestroy() {
    return this.$disconnect();
  }

  clearDatabase() {
    const modelKeys = dmmf.datamodel.models.map(model=>model.name);

    return Promise.all(
      modelKeys.map((table) => this.executeRaw(`DELETE FROM ${table};`)),
    );
  }
}

or

import { Injectable, OnModuleDestroy, OnModuleInit } from '@nestjs/common';
import { PrismaClient } from '@prisma/client';


@Injectable()
export class PrismaService extends PrismaClient
  implements OnModuleInit, OnModuleDestroy {
  constructor() {
    super();
  }

  async onModuleInit() {
    return await this.$connect();
  }

  async onModuleDestroy() {
    return await this.$disconnect();
  }

  clearDatabase() {
    const models = Reflect.ownKeys(this).filter(key=> key[0] !== '_');

    return Promise.all(
      models.map(modelKey => this[modelKey].deleteMany()),
    );
  }
}

from docs.

lord007tn avatar lord007tn commented on August 16, 2024 3

@vuki656 I updated your version. I found an error where the key "_middleware" was not deleted.

import prisma from "../client";

(async function flush() {
    const models = Object.keys(prisma).filter((key) => key[0] !== "_");

    const promises = models.map((name) => {
        // @ts-expect-error
        return prisma[name].deleteMany();
    });

    await Promise.all(promises);
})();

from docs.

nemanjam avatar nemanjam commented on August 16, 2024 1

TypeError: prisma[modelName].deleteMany is not a function

from docs.

vuki656 avatar vuki656 commented on August 16, 2024 1

This works nicely for me:

export const wipeDatabase = async () => {
    // @ts-expect-error -- Extract all model names
    const models = Object.keys(orm._dmmf.mappingsMap)

    const promises = models.map((model) => {
        // Names formatted like `AccessRight`, we need `accessRight` for the orm call
        const name = model.charAt(0).toLowerCase() + model.slice(1)

        // @ts-expect-error
        return orm[name].deleteMany()
    })

    await Promise.all(promises)
}

from docs.

joshbedo avatar joshbedo commented on August 16, 2024 1

how is this not a button in the prisma studio

from docs.

schickling avatar schickling commented on August 16, 2024

Maybe add a button in the data studio?

I've already created an issue for this back in October last year prisma/studio#237. I'll raise it to the Studio team to fast track this 🙏

from docs.

adam-arold avatar adam-arold commented on August 16, 2024

I guess you could also do something like this:

const { PrismaClient } = require('@prisma/client')
const prisma = new PrismaClient()

const allProperties = Reflect.ownKeys(Object.getPrototypeOf(prisma))
const modelNames = allProperties.filter(x => x != "constructor" && x != "on" && x != "connect" && x != "runDisconnect" && x != "disconnect")

for (modelName of modelNames) {

    // handle async stuff
    prisma[modelName].deleteMany()
}

Note that this is not the same as TRUNCATE TABLE as this will not reset the ids!

from docs.

nemanjam avatar nemanjam commented on August 16, 2024

these two don't work, data is still in db

from docs.

ydennisy avatar ydennisy commented on August 16, 2024

@yoshitamagoshi I do not suggest using that as it wipes settings that your DB may have which you want to keep, such as various users, permissions etc.

If used with a hosted platform like supabase it will destroy your project.

from docs.

yoshitamagoshi avatar yoshitamagoshi commented on August 16, 2024

@ydennisy yes agreed, but the thread here is about "how to delete all records from all tables"?

from docs.

tsongas avatar tsongas commented on August 16, 2024

@yoshitamagoshi it's also painfully slow (like ten seconds) compared to a raw query with a script to truncate tables, not ideal for CI/CD.

from docs.

Chetan11-dev avatar Chetan11-dev commented on August 16, 2024

async function deleteAll() {
const models = [db.user]
await Promise.all(models.map(model=>model.deleteMany()))
}

from docs.

Lagyu avatar Lagyu commented on August 16, 2024
const prismaClient = new PrismaClient();
const modelNames = Object.keys(prismaClient).filter(
  (key) => !["_", "$"].includes(key[0])
);

for (let i = 0; i < modelNames.length; i += 1) {
  const name = modelNames[i];
  try {
    // @ts-expect-error https://github.com/prisma/docs/issues/451
    await prismaClient[name].deleteMany();
  } catch (e) {
    console.error(`Error while deleting ${name}`);
    throw e;
  }
}

In my case, $extends key prevented from working.
Also, running in parallel sometimes causes deadlock, so you might better await each delete.

from docs.

fredanup avatar fredanup commented on August 16, 2024

I think the most easiest solution is create another table at the beginning of the schema and then cut your old schema for a while, then run "npx prisma migrate dev --name init", these will erase all your data and create and schema with your only new table, and then do the same but now erase your single table and paste your old database schema

from docs.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.