Skip to content

P2002 error doesn't include meaningful meta with SQL Server #17433

Open

Description

@pete-otaqui

Bug description

I have a unique constraint on a name field in a table. When I try and update one record with the same name as another one, I correctly get a PrismaKnownClientError, but I don't get any other useful information in meta.

So, when I do this:

prismaClient.thing.update({
  where: { id: 1 },
  data: { name: 'Thing 2' }
});

I get an error thrown like this:

{
  code: 'P2002',
  clientVersion: '4.9.0',
  meta: { target: 'dbo.Thing' },
}

As you can see, the "target" is the name of the table rather than the name of the field.

If I manually a similar query against the database using Azure Data Studio like this (which tries to set the name of one Thing to the same as that of another):

UPDATE [dbo].[Thing]
SET [name] = 'Thing 2'
WHERE [dbo].[Thing].[id] = 1

I can see that SQL Server itself gives back the following message:

Violation of UNIQUE KEY constraint 'Thing_name_key'.
Cannot insert duplicate key in object 'dbo.Thing'. The
duplicate key value is (Test Thing 2).

I understand that this does not include the column name directly, but I would assume that prisma ought to be able to get the relevant column name(s) from the constraint name that is provided.

How to reproduce

Trigger a unique constraint error on update (or in fact, on create), and inspect the error object.

Expected behavior

I expect the error object meta to include something like fields, target, or constraint so that I can provide meaningful error messages myself.

See #10829 for a similar request.

Prisma information

generator client {
  provider = "prisma-client-js"
}
datasource db {
  provider          = "sqlserver"
  url               = env("SQL_SERVER_DB_URL")
  shadowDatabaseUrl = env("SQL_SERVER_SHADOW_DB_URL")
}
model Thing {
  id              Int          @id @default(autoincrement())
  name            String       @unique
}
// Add your code using Prisma Client
const prismaClient = new PrismaClient();
await prismaClient.thing.create({ name: 'Thing' });
await prismaClient.thing.create({ name: 'Thing 2'});

// this is where the error is thrown
await prismaClient.thing.update({
  where: { id: 1 },
  data: { name: 'Thing 2' },
});

Environment & setup

  • OS: macOS (M1 chip), Azure SQL Edge in Docker
  • Database: SQL Server
  • Node.js version: 16.6

Prisma Version

4.9.0

Activity

  1. pete-otaqui commented on Jan 22, 2023

    @pete-otaqui
    Author

    Thanks for looking @dev-xo, let me know if there's any more information I can provide, or other testing you'd like me to do (in other environments / with a specific branch of prisma, etc)

  2. added
    bug/0-unknown
    topic: sql server
    on Jan 24, 2023
  3. BryanDGuy commented on Jan 31, 2023

    @BryanDGuy

    I've made a similar feature request here #15046. Would love to see this come to fruition. Even just allowing us to access the raw error thrown by the DB would be great help.

  4. AlimovSV commented on May 23, 2023

    @AlimovSV
  5. EricDotSmith commented on May 27, 2023

    @EricDotSmith

    Just ran into this issue too. If the error was more meaningful I would've saved lots of time debugging.

  6. andriiwp3 commented on Jul 9, 2023

    @andriiwp3

    I just ran into this issue as well. I'm trying to debug it, but I feel like some kind of error message could save me a lot of time

  7. daiho-nfq commented on Jul 12, 2023

    @daiho-nfq

    same here

    image
  8. janpio commented on Jul 12, 2023

    @janpio
    Contributor

    @daiho-nfq Isn't that the name of the constraint that is failing in your database? To me this looks as good as it can get on a database level.

  9. added
    tech/engines
    on Jul 13, 2023
  10. added
    bug/1-unconfirmed
    and removed
    bug/0-unknown
    on Jul 13, 2023
  11. 6 remaining items

  12. added
    bug/2-confirmed
    and removed
    bug/1-unconfirmed
    on May 24, 2024
  13. janpio commented on May 24, 2024

    @janpio
    Contributor

    Back to the original report for SQL Server:

    Running the script:

      await prisma.thing.create({ data: { name: 'Thing' }});
      await prisma.thing.create({ data: { name: 'Thing 2'}});
    
      // this is where the error is thrown
      await prisma.thing.update({
        where: { id: 1 },
        data: { name: 'Thing 2' },
      });

    Indeed throws this error:

    PrismaClientKnownRequestError: 
    Invalid `prisma.thing.update()` invocation in
    C:\Users\Jan\Documents\throwaway\19963\script.js:10:22
    
       7 await prisma.thing.create({ data: { name: 'Thing 2'}});
       8
       9 // this is where the error is thrown
    → 10 await prisma.thing.update(
    Unique constraint failed on the constraint: `dbo.Thing`
        at In.handleRequestError (C:\Users\Jan\Documents\throwaway\19963\node_modules\@prisma\client\runtime\library.js:122:6877)
        at In.handleAndLogRequestError (C:\Users\Jan\Documents\throwaway\19963\node_modules\@prisma\client\runtime\library.js:122:6211)
        at In.request (C:\Users\Jan\Documents\throwaway\19963\node_modules\@prisma\client\runtime\library.js:122:5919)
        at async l (C:\Users\Jan\Documents\throwaway\19963\node_modules\@prisma\client\runtime\library.js:127:11167)
        at async main (C:\Users\Jan\Documents\throwaway\19963\script.js:10:3) {
      code: 'P2002',
      clientVersion: '5.14.0',
      meta: { modelName: 'Thing', target: 'dbo.Thing' }
    }
    

    And then the manual equivalent SQL via another database client directly:

    UPDATE [dbo].[Thing] SET [name] = 'Thing 2' WHERE ([dbo].[Thing].[id] = 1

    returns this error message:

    SQL Error [2627] [23000]: Violation of UNIQUE KEY constraint 'Thing_name_key'. Cannot insert duplicate key in object 'dbo.Thing'. The duplicate key value is (Thing 2).
    

    As @pete-otaqui identified, Prisma currently only parses the object name dbo.Thing for its error message and target, but the error message also includes the constraint name Thing_name_key and value Thing 2. It might be possible to go from the constraint name to the affected column in many cases.

  14. self-assigned this
    on May 24, 2024
  15. janpio commented on May 24, 2024

    @janpio
    Contributor

    Aside: @daiho-nfq's screenshot indicates that for some other Non SQL Server database Prisma might return the constraint name as the target, instead of the object name. This might indicate some inconsistency in how Prisma utilized the target property.

    @daeteck Would you prefer the MongoDB or the PostgreSQL behavior in these cases?

  16. shaununderwood commented on Jun 13, 2024

    @shaununderwood

    Guys, this bug is > 18 months old, can we get some closure?

  17. janpio commented on Jun 13, 2024

    @janpio
    Contributor

    Happy to take a look at any pull request you opened @shaununderwood and see if it fixes the problem. If you didn't open one, then we will get to it when we have the capacity to figure this out ourselves. That can take some time, as you can see we have many open feature requests and also bug reports and are doing our best to work on them in a prioritized manner that will affect most of our users. Thanks for understanding.

  18. removed their assignment
    on Nov 1, 2024
  19. iagomissias commented on Dec 28, 2024

    @iagomissias

    tive esse retorno no terminal após realizar o teste de descrição de dados via POST,

    PrismaClientKnownRequestError:
    Invalid prisma.user.create() invocation:

    Unique constraint failed on the constraint: User_email_key
    at qn.handleRequestError (/home/iago/Sistema-de-Login/node_modules/@prisma/client/runtime/library.js:121:7315)
    at qn.handleAndLogRequestError (/home/iago/Sistema-de-Login/node_modules/@prisma/client/runtime/library.js:121:6640)
    at qn.request (/home/iago/Sistema-de-Login/node_modules/@prisma/client/runtime/library.js:121:6347)
    at async l (/home/iago/Sistema-de-Login/node_modules/@prisma/client/runtime/library.js:130:9616)
    at async file:///home/iago/Sistema-de-Login/server.js:12:6 {
    code: 'P2002',
    clientVersion: '6.1.0',
    meta: { modelName: 'User', target: 'User_email_key' }
    }

    mesmo rodando
    $:npx prisma migrate dev --name add_age_field

    ele não corrige o erro

    porem ao realizar o inserimento manual no banco de dados o mesmo aceita como isso é possivel

  20. Shahor commented on Mar 24, 2025

    @Shahor

    Also I'm seeing that in Postgres the meta.target of a compound index comes as an array and not the name of the unique index.

    For example if I have: @@unique([name, code], map: "name_code_idx")

    The error P2002 meta.target in Postgres is an array: ["name", "code"]

    but in MongoDB meta.target is an string "name_code_idx"

    Having the same exact issue right now and it seems there is no way to obtain the actual database error as Prisma seems to insist on providing its own rewrite of it.

    I've tried running a raw query as well, but my understanding is that this rewrite might be happening on the intermediate rust part instead so I suppose there's no way for me to know about the actual real error that happened and that means I can't differentiate the types of error happening in my application.

    What is the rationale behind Prisma rewriting the error? We're losing actual information from the database, and it makes handling issues more difficult than it needs to be.

    At the very least, can we maybe have the original information somewhere in the meta array?

  21. jason-jos commented on Apr 25, 2025

    @jason-jos

    It's probably because the data you are creating, already exists in your db

  22. capaj commented on Sep 18, 2025

    @capaj

    I just updated to rust-free client and there is nothing on error.meta.target

    I hackfixed it with authier-pm/authier@769195d

    but this suxx.
    bring meta.target back pls

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

    bug/2-confirmedkind/bugtech/enginestopic: P2002topic: constrainttopic: error handlingtopic: sql server

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions