question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Document how to delete all records from all tables

See original GitHub issue

Sometimes it’s helpful to wipe all data records in the DB but keep the tables. This is currently not possible via the Prisma Client API so we should document a workaround.

One potential approach which currently doesn’t work because it relies on a private property of PrismaClient is this:

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

function lowerCase(name: string): string {
  return name.substring(0, 1).toLowerCase() + name.substring(1)
}

const promises = prisma.dmmf.datamodel.models.map(model => {
  return new Promise(async resolve => {
    const modelName = lowerCase(model.name)
    const modelMethods = prisma[modelName]

    if (modelMethods) {
      try {
        resolve(await modelMethods.findMany({}))
      } catch (e) {
        resolve(e)
      }
    }
  }

async function main() {                    
  await Promise.all(promises)
}

main()

Alternatively, the following approach (by @nnennajohn) which is based on knex.js can be used:

import camelCase from 'lodash/camelCase';
import { prisma } from '@cpath/universal/shared/db';
import knexClient from './knex';
// Contents of the knexClient import above
// import Knex from 'knex';
// const knexClient: Knex = Knex({
//   client: 'pg',
//   connection: {
//     user: process.env.POSTGRES_USER,
//     password: process.env.POSTGRES_PASSWORD,
//     host: process.env.POSTGRES_HOST,
//     port: Number(process.env.POSTGRES_PORT),
//     database: process.env.POSTGRES_DB,
//   },
// });
// Contents of the prisma import above
// export const prisma = new PrismaClient();
function deleteRecords(tablesList) {
  const validTables = tablesList.filter((tableName) => tableName[0] !== '_');
  console.log('These are the valid tables', validTables);
  const recordsDeletions = validTables.map((table) => {
    return prisma[camelCase(table)].deleteMany({});
  });
  return Promise.all(recordsDeletions);
}
function listTables() {
  const query =
    'SELECT table_name FROM information_schema.tables WHERE table_schema = current_schema() AND table_catalog = ?';
  const bindings = [knexClient.client.database()];
  return knexClient.raw(query, bindings).then((results) => {
    return results.rows.map((row) => row.table_name);
  });
}
async function main() {
  const tablesList = await listTables();
  console.log('This is the list of knex tables', tablesList);
  if (tablesList && tablesList.length) {
    deleteRecords(tablesList)
      .then((res) => {
        console.log('Successfully deleted table records', res);
      })
      .catch((err) => {
        console.log('Error deleting table records', err);
      });
  }
}
main()
  .catch((e) => console.error(e))
  .finally();

We should also document a workaround that allows to do this without an external dependency like knex.js.

Issue Analytics

  • State:closed
  • Created 4 years ago
  • Reactions:3
  • Comments:19 (4 by maintainers)

github_iconTop GitHub Comments

23reactions
sorenbscommented, Mar 16, 2020

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()
}
18reactions
kitzecommented, Mar 17, 2020

Maybe add a button in the data studio?

Read more comments on GitHub >

github_iconTop Results From Across the Web

How to delete all rows from all tables in a SQL Server database?
Step 2- Execute a Delete or truncate operation on each table of the database by using below sql command : EXEC sys.sp_msforeachtable 'DELETE...
Read more >
Delete all rows from all tables - SQLRelease
This post has various methods to delete all rows from all tables from a database. You can choose any of them to accomplish...
Read more >
Application programming and SQL - Deleting data from tables
You can delete data from a table by deleting one or more rows from the table, by deleting all rows from the table,...
Read more >
Delete all records from all tables in an application - ServiceNow
Solved: Hello Occasionally, I would like to delete all records in all tables of my application. My current approach: I am aware about...
Read more >
How to remove/delete all tables from a document in Word
How to remove/delete all tables from a document in Word · 1: Press Alt+F11 to open the Microsoft Visual Basic for Applications window;...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found