Skip to content

Bug: clerkUserId violates UNIQUE constraint when deleting multiple users #1

@kyundos

Description

@kyundos

Description
When deleting a user, the clerkUserId field is set to "deleted". However, since the database schema enforces a UNIQUE constraint on clerkUserId, this causes a conflict when deleting multiple users, resulting in a database error.

Code causing the issue:

export async function deleteUser({ clerkUserId }: { clerkUserId: string }) {
  const [deletedUser] = await db
    .update(UserTable)
    .set({
      deletedAt: new Date(),
      email: "redacted@deleted.com",
      name: "Deleted User",
      clerkUserId: "deleted", // ❌ Hardcoded value causes a UNIQUE constraint violation
      imageUrl: null,
    })
    .where(eq(UserTable.clerkUserId, clerkUserId))
    .returning();

  if (deletedUser == null) throw new Error("Failed to delete user");
  revalidateUserCache(deletedUser.id);

  return deletedUser;
}

Steps to Reproduce
Delete one user → ✅ Works fine.
Delete another user → ❌ Database error: duplicate key value violates unique constraint "user_clerkuserid_key", because of:

export const UserTable = pgTable("user", {
  id,
  clerkUserId: text().notNull().unique(), ❌ Violated constraint
  email: text().notNull(),
  name: text().notNull(),
  role: userRoleEnum().notNull().default("user"),
  imageUrl: text(),
  deletedAt: timestamp({ withTimezone: true }),
  createdAt,
  updatedAt,
})

Expected Behavior
The application should allow multiple users to be deleted without violating the UNIQUE constraint.

Suggested Fix
To avoid this issue, we can modify clerkUserId to be unique when a user is deleted.
Some possible solutions:

  • Append a unique identifier (fast and straightforward):
    "clerkUserId: deleted-${new Date()}"

  • Use a UUID (probably more robust solution):
    "clerkUserId: deleted-${crypto.randomUUID()}"

Would love to hear your thoughts on the best approach!

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