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.

prisma.$executeRaw(`DELETE FROM "${table}";`) does not work

See original GitHub issue

Bug description

Hey folks, I’m currently writing my jest integration tests and getting:

Invalid prisma.user.create() invocation: Unique constraint failed on the fields: (id)

This is because a call to empty the database after each tests isn’t working properly.

This is the code which should execute, but doesn’t, the data doesn’t get deleted and therefore the unique constraint error is fired when adding the new (but becuase not deleted equal) seed data for the next test.

// Inspired by prisma/docs#451
async function emptyDatabase() {
  const tables = Prisma.dmmf.datamodel.models.map(
    (model) => model.dbName || model.name
  );

 await Promise.all(
    tables.map((table) => prisma.$executeRaw(`DELETE FROM "${table}";`))
  );
}

This is the error.

yarn run v1.22.4
$ jest
 FAIL  src/server/graphql/Team/test.ts
  ● createTeam › should create team
    Invalid `prisma.user.create()` invocation:
      Unique constraint failed on the fields: (`id`)

      37 | async function seedDatabase({ users = [], projects = [], teams = [] }: SeedData) {
      38 |   // Insert users
    > 39 |   await Promise.all(
         |   ^
      40 |     users.map((user) =>
      41 |       prisma.user.create({
      42 |         data: user

      at cb (node_modules/@prisma/client/runtime/index.js:79160:17)
          at async Promise.all (index 0)
      at seedDatabase (src/test/seed/index.ts:39:3)
      at reseedDatabase (src/test/seed/index.ts:81:3)
      at Object.<anonymous> (src/test/jest-setup.ts:6:3)

 PASS  src/server/graphql/User/test.ts

Test Suites: 1 failed, 1 passed, 2 total
Tests:       1 failed, 3 passed, 4 total
Snapshots:   6 passed, 6 total
Time:        3.023 s
Ran all test suites.

How to reproduce

// Inspired by prisma/docs#451
async function emptyDatabase() {
  const tables = Prisma.dmmf.datamodel.models.map(
    (model) => model.dbName || model.name
  );

 await Promise.all(
    tables.map((table) => prisma.$executeRaw(`DELETE FROM "${table}";`))
  );
}

Expected behavior

No response

Prisma information

This is the seeding code which fails because the database isn’t empty.

async function seedDatabase({ users = [], projects = [], teams = [] }: SeedData) {
  // Insert users
  await Promise.all(
    users.map((user) =>
      prisma.user.create({
        data: user
      })
    )
  );

  // Insert projects & connect them to their users
  await Promise.all(
    projects.map((project) =>
      prisma.project.create({
        data: {
          ...project,
          users: {
            connect: project.users?.map((id) => ({ id })),
          },
        },
      })
    )
  );

  // Insert Teams
  await Promise.all(
    teams.map((team) =>
      prisma.team.create({
        data: {
          ...team,
          users: {
            connect: team.users?.map((id) => ({ id })),
          },
          projects: {
            connect: team.projects?.map((id) => ({ id })),
          }
        },
      })
    )
  );
}

Environment & setup

macOS 10.15.7

Prisma Version

I’m running on "jest": "^26.6.3", and "@prisma/client": "~2.18.0",

Issue Analytics

  • State:closed
  • Created 2 years ago
  • Comments:6 (4 by maintainers)

github_iconTop GitHub Comments

3reactions
Weakkycommented, Apr 25, 2022

Hey folks,

@jtlindsey Your error happens because you’re missing the quotes surrounding your table name 👇

await prisma.$executeRaw`DROP TABLE "user"`;

@felixhaeberle I’m unable to reproduce your issue mostly because your DELETE query is invalid in the first place. Identifiers (table or column names) can not be passed as parameters of prepared statements.

You should be using $executeRawUnsafe for what you’re trying to achieve. Below is a working example of what I think you’re trying to do 👇:

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

const prisma = new PrismaClient();

async function emptyDatabase() {
  const tables = Prisma.dmmf.datamodel.models.map(
    (model) => model.dbName || model.name
  );

  return Promise.all(
    tables.map((table) => prisma.$executeRawUnsafe(`DELETE FROM "${table}";`))
  );
}

afterEach(async () => {
  await emptyDatabase();
});

test("create user 1", async () => {
  let { id } = await prisma.user.create({
    data: { id: 1 },
  });
  expect(id).toBe(1);
});

test("create user 2", async () => {
  let { id } = await prisma.user.create({
    data: { id: 1 },
  });
  expect(id).toBe(1);
});

test("create user 3", async () => {
  let { id } = await prisma.user.create({
    data: { id: 1 },
  });
  expect(id).toBe(1);
});

test("create user 4", async () => {
  let { id } = await prisma.user.create({
    data: { id: 1 },
  });
  expect(id).toBe(1);
});

test("create user 5", async () => {
  let { id } = await prisma.user.create({
    data: { id: 1 },
  });
  expect(id).toBe(1);
});

The table is properly cleared after each test so we’re not running into constraint violations.

With that, I’m suggesting to close the issue. Feel free to re-open it if you’re still having a problem.

Thanks 🙏

2reactions
jtlindseycommented, Sep 17, 2021

I was able to reproduce the problem with just the following code and postgresql:

create.test.ts

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

const prisma = new PrismaClient();

beforeAll(async () => {
  await prisma.$executeRaw`DROP TABLE user`;
  // await prisma.$executeRaw('TRUNCATE TABLE user RESTART IDENTITY CASCADE;');
});

test('should random test ', async () => {
  expect(3).toBe(3);
});

and run npm run test and get:

    Invalid `prisma.executeRaw()` invocation:


      Raw query failed. Code: `42601`. Message: `db error: ERROR: syntax error at or near "user"`

      at cb (node_modules/@prisma/client/runtime/index.js:35943:17)
Read more comments on GitHub >

github_iconTop Results From Across the Web

Raw database access (Reference) - Prisma
Like $executeRaw , it does not return database records, but returns the number of rows affected. Note: $executeRawUnsafe can only run one query...
Read more >
Remove all items in table with Prisma2 and Jest - Stack Overflow
This way you can iterate over all the tables and order doesn't matter. prisma.$executeRaw(`TRUNCATE TABLE ${table} RESTART IDENTITY CASCADE ...
Read more >
It's Prisma Time - Execute your own queries
In prisma we can run two kind of custom queries: "Actionable" queries (INSERT, UPDATE or DELETE) and "Retrievable" queries (SELECT). The first ...
Read more >
Prisma 3.14.0 Release - GitClear
The following SQL will be generated in your migration when you run prisma migrate dev : CREATE TABLE "Post" ( "id" INTEGER NOT...
Read more >
error [exceptionshandler] | The AI Search Engine You Control
Invalid prisma.executeRaw() invocation: Raw query failed. Code: 42703 . Message: column "transaction_idout" does not exist. Open side panel.
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