Skip to content

Incorrect constraint name in duplicate key error — violates UNIQUE(email) but reports "user_pkey" #462

@AndrewSmithDev

Description

@AndrewSmithDev

Describe the bug

When violating a UNIQUE constraint (e.g., on the email column), pg-mem throws an error referencing the primary key constraint (user_pkey) instead of the actual violated constraint (user_email_key).

This leads to misleading error messages and breaks error handling logic that inspects constraint names.

ERROR: insert into "user" (email, password, id) values ($1, $2, $3) returning "email" - duplicate key value violates unique constraint "user_pkey"
DETAIL: Key (email)=(user@example.com) already exists.

🐜 This seems to be an execution error, which means that your request syntax seems okay,
    but the resulting statement cannot be executed → Probably not a pg-mem error.

*⃣ Failed SQL statement:
      INSERT INTO "user" (email, password) VALUES ('user@example.com', 'anotherpass');
    ;

👉 You can file an issue at https://github.com/oguimbal/pg-mem along with a way to reproduce this error (if you can), and  the stacktrace:

To Reproduce

-- Schema
CREATE TABLE "user" (
  id SERIAL PRIMARY KEY,
  email TEXT NOT NULL,
  password TEXT NOT NULL,
  CONSTRAINT user_email_key UNIQUE (email)
);

-- Data
INSERT INTO "user" (email, password) VALUES ('user@example.com', 'password123');
-- This should fail due to UNIQUE(email), but error message incorrectly says "user_pkey"
INSERT INTO "user" (email, password) VALUES ('user@example.com', 'anotherpass');

Node alternative

const { newDb } = require("pg-mem");

(async () => {
  const db = newDb();

  // Create schema with primary key and named UNIQUE constraint
  await db.public.none(`
    CREATE TABLE "user" (
      id SERIAL PRIMARY KEY,
      email TEXT NOT NULL,
      password TEXT NOT NULL,
      CONSTRAINT user_email_key UNIQUE (email)
    );
  `);

  // Insert a user (valid)
  await db.public.none(`
    INSERT INTO "user" (email, password) VALUES ('user@example.com', 'password123');
  `);

  // Insert duplicate (violates email constraint, but error says user_pkey)
  try {
    await db.public.none(`
      INSERT INTO "user" (email, password) VALUES ('user@example.com', 'anotherpass');
    `);
  } catch (err) {
    console.error(err.message);
  }
})();

pg-mem version

3.0.5

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions