P
Prisma•2w ago
wvn

Error saving in database

I have this code but it save to the db
Unique constraint failed on the constraint: `UkladanieRole_username_key`
at Vn.handleRequestError (C:\Users\wvn_0\Desktop\GalaxyBOT\bot\node_modules\@prisma\client\runtime\library.js:121:7339)
at Vn.handleAndLogRequestError (C:\Users\wvn_0\Desktop\GalaxyBOT\bot\node_modules\@prisma\client\runtime\library.js:121:6663)
at Vn.request (C:\Users\wvn_0\Desktop\GalaxyBOT\bot\node_modules\@prisma\client\runtime\library.js:121:6370)
at async l (C:\Users\wvn_0\Desktop\GalaxyBOT\bot\node_modules\@prisma\client\runtime\library.js:130:9617)
at async execute (file:///C:/Users/wvn_0/Desktop/GalaxyBOT/bot/dist/events/discord/leave.js:41:9) {
code: 'P2002',
clientVersion: '6.2.1',
meta: { modelName: 'UkladanieRole', target: 'UkladanieRole_username_key' }
}
Unique constraint failed. It seems that the username already exists in the database.
Unique constraint failed on the constraint: `UkladanieRole_username_key`
at Vn.handleRequestError (C:\Users\wvn_0\Desktop\GalaxyBOT\bot\node_modules\@prisma\client\runtime\library.js:121:7339)
at Vn.handleAndLogRequestError (C:\Users\wvn_0\Desktop\GalaxyBOT\bot\node_modules\@prisma\client\runtime\library.js:121:6663)
at Vn.request (C:\Users\wvn_0\Desktop\GalaxyBOT\bot\node_modules\@prisma\client\runtime\library.js:121:6370)
at async l (C:\Users\wvn_0\Desktop\GalaxyBOT\bot\node_modules\@prisma\client\runtime\library.js:130:9617)
at async execute (file:///C:/Users/wvn_0/Desktop/GalaxyBOT/bot/dist/events/discord/leave.js:41:9) {
code: 'P2002',
clientVersion: '6.2.1',
meta: { modelName: 'UkladanieRole', target: 'UkladanieRole_username_key' }
}
Unique constraint failed. It seems that the username already exists in the database.
const existingUser = await prisma.ukladanieRole.findUnique({
where: { username: c.user.username },
});

try {
if (existingUser) {
console.log("Existing User! Updating the record...");

// Update the existing user's roles
await prisma.ukladanieRole.update({
where: { username: c.user.username },
data: { rolesID: roleIds },
});

console.log(`Updated roles for user: ${c.user.username}`);
} else {
console.log("New User! Creating a new record...");

// Create a new record for the user
await prisma.ukladanieRole.create({
data: {
username: c.user.username,
userID: c.id,
rolesID: roleIds,
},
});

console.log(`Created new record for user: ${c.user.username}`);
}
const existingUser = await prisma.ukladanieRole.findUnique({
where: { username: c.user.username },
});

try {
if (existingUser) {
console.log("Existing User! Updating the record...");

// Update the existing user's roles
await prisma.ukladanieRole.update({
where: { username: c.user.username },
data: { rolesID: roleIds },
});

console.log(`Updated roles for user: ${c.user.username}`);
} else {
console.log("New User! Creating a new record...");

// Create a new record for the user
await prisma.ukladanieRole.create({
data: {
username: c.user.username,
userID: c.id,
rolesID: roleIds,
},
});

console.log(`Created new record for user: ${c.user.username}`);
}
7 Replies
Prisma AI Help
Prisma AI Help•2w ago
You've gone full bot mode! Let me fetch that AI answer for you ASAP. The error you're encountering is a unique constraint violation, specifically on the username field of your UkladanieRole model. This error occurs when you're trying to insert a record with a username that already exists in the database. Let's analyze the issue and provide a solution based on the information from the knowledge sources. The error code P2002 indicates a unique constraint failure, as described in the Error message reference. Your code is attempting to handle both new and existing users, but there's a potential race condition that can cause this error. Here's what might be happening: 1. The findUnique operation doesn't find an existing user. 2. Before the create operation is executed, another process inserts a user with the same username. 3. When your create operation runs, it encounters the unique constraint violation. To handle this situation, you can use Prisma's upsert operation, which combines the create and update operations into a single atomic transaction. This approach is recommended in the Prisma documentation for handling potential race conditions. Here's how you can modify your code to use upsert:
try {
await prisma.ukladanieRole.upsert({
where: { username: c.user.username },
update: { rolesID: roleIds },
create: {
username: c.user.username,
userID: c.id,
rolesID: roleIds,
},
});

console.log(`Upserted record for user: ${c.user.username}`);
} catch (error) {
if (error.code === 'P2002') {
console.error("Unique constraint failed. The username already exists in the database.");
} else {
console.error("An error occurred:", error);
}
}
try {
await prisma.ukladanieRole.upsert({
where: { username: c.user.username },
update: { rolesID: roleIds },
create: {
username: c.user.username,
userID: c.id,
rolesID: roleIds,
},
});

console.log(`Upserted record for user: ${c.user.username}`);
} catch (error) {
if (error.code === 'P2002') {
console.error("Unique constraint failed. The username already exists in the database.");
} else {
console.error("An error occurred:", error);
}
}
This code will attempt to update the record if it exists, or create it if it doesn't, all in a single operation. This reduc es the chance of a race condition causing the unique constraint violation. However, it's important to note that even with this approach, there's still a small possibility of encountering a P2002 error in concurrent scenarios, as mentioned in the Prisma documentation. If this occurs, you may need to implement a retry mechanism or handle the error appropriately in your application logic. Remember to adjust your error handling to fit your application's needs, and consider logging or reporting errors for debugging purposes. 🤔 Alright, thanks for letting us know that there's still some help needed. A team member will reply to you shortly. In the meantime, please let us know any additional info, questions, or which parts of the answer may need clarification.
wvn
wvnOP•2w ago
Invalid `prisma.ukladanieRole.create()` invocation:


Unique constraint failed on the constraint: `UkladanieRole_username_key`
at Vn.handleRequestError (C:\Users\wvn_0\Desktop\GalaxyBOT\bot\node_modules\@prisma\client\runtime\library.js:121:7339)
at Vn.handleAndLogRequestError (C:\Users\wvn_0\Desktop\GalaxyBOT\bot\node_modules\@prisma\client\runtime\library.js:121:6663)
at Vn.request (C:\Users\wvn_0\Desktop\GalaxyBOT\bot\node_modules\@prisma\client\runtime\library.js:121:6370)
at async l (C:\Users\wvn_0\Desktop\GalaxyBOT\bot\node_modules\@prisma\client\runtime\library.js:130:9617)
at async execute (file:///C:/Users/wvn_0/Desktop/GalaxyBOT/bot/dist/events/discord/index.js:30:7) {
code: 'P2002',
clientVersion: '6.2.1',
meta: { modelName: 'UkladanieRole', target: 'UkladanieRole_username_key' }
}
Saved role IDs for alphaboosts to the database.
Invalid `prisma.ukladanieRole.create()` invocation:


Unique constraint failed on the constraint: `UkladanieRole_username_key`
at Vn.handleRequestError (C:\Users\wvn_0\Desktop\GalaxyBOT\bot\node_modules\@prisma\client\runtime\library.js:121:7339)
at Vn.handleAndLogRequestError (C:\Users\wvn_0\Desktop\GalaxyBOT\bot\node_modules\@prisma\client\runtime\library.js:121:6663)
at Vn.request (C:\Users\wvn_0\Desktop\GalaxyBOT\bot\node_modules\@prisma\client\runtime\library.js:121:6370)
at async l (C:\Users\wvn_0\Desktop\GalaxyBOT\bot\node_modules\@prisma\client\runtime\library.js:130:9617)
at async execute (file:///C:/Users/wvn_0/Desktop/GalaxyBOT/bot/dist/events/discord/index.js:30:7) {
code: 'P2002',
clientVersion: '6.2.1',
meta: { modelName: 'UkladanieRole', target: 'UkladanieRole_username_key' }
}
Saved role IDs for alphaboosts to the database.
if (!c || !c.user) {
console.log("Invalid member or user data.");
return;
}

console.log(`Event triggered: ${c.user.tag} left the server!`);
console.log(`User ID: ${c.id}`);

const roleIds = c.roles.cache
.filter(
(role) => !ignoredRoleIds.includes(role.id) && role.name !== "@everyone"
)
.map((role) => role.id);

if (roleIds.length === 0) {
console.log("No roles found for this user.");
} else {
console.log("Role IDs:", roleIds);
}

await prisma.ukladanieRole.upsert({
where: { username: c.user.username },
update: { rolesID: roleIds },
create: {
username: c.user.username,
userID: c.id,
rolesID: roleIds,
},
});

console.log(`Saved role IDs for ${c.user.tag} to the database.`);
if (!c || !c.user) {
console.log("Invalid member or user data.");
return;
}

console.log(`Event triggered: ${c.user.tag} left the server!`);
console.log(`User ID: ${c.id}`);

const roleIds = c.roles.cache
.filter(
(role) => !ignoredRoleIds.includes(role.id) && role.name !== "@everyone"
)
.map((role) => role.id);

if (roleIds.length === 0) {
console.log("No roles found for this user.");
} else {
console.log("Role IDs:", roleIds);
}

await prisma.ukladanieRole.upsert({
where: { username: c.user.username },
update: { rolesID: roleIds },
create: {
username: c.user.username,
userID: c.id,
rolesID: roleIds,
},
});

console.log(`Saved role IDs for ${c.user.tag} to the database.`);
Only happens when updating user
model UkladanieRole {
id Int @id @default(autoincrement())
username String @unique
userID String @unique
rolesID Json
}
model UkladanieRole {
id Int @id @default(autoincrement())
username String @unique
userID String @unique
rolesID Json
}
Nurul
Nurul•2w ago
Hey 👋 The error suggests that there is an existing record with the same username. If I understand correctly, do you mean you are getting the unique constraint error even though there isn't record with same value?
wvn
wvnOP•2w ago
Yes
wvn
wvnOP•2w ago
And with the create it create but crash the bot
Nurul
Nurul•2w ago
I think the core issue is that you have two unique fields You have @unique on both username and userID. If either value duplicates what’s already in the database, Prisma raises a P2002 error. A user might have changed their username, but their userID is still the same. If you upsert by username, Prisma may see a conflicting record because the userID is already taken by that same person (but with the old username). Can you try upserting using userID instead of username, and update the username field in the update block.
await prisma.ukladanieRole.upsert({
where: { userID: c.id }, // Use userID as the lookup
update: {
rolesID: roleIds,
username: c.user.username,
},
create: {
username: c.user.username,
userID: c.id,
rolesID: roleIds,
},
});
await prisma.ukladanieRole.upsert({
where: { userID: c.id }, // Use userID as the lookup
update: {
rolesID: roleIds,
username: c.user.username,
},
create: {
username: c.user.username,
userID: c.id,
rolesID: roleIds,
},
});
wvn
wvnOP•2w ago
I im not on pc anymore So u are telling to select delete and update and create by userid not username? Its not like that its my alt and it didnt changed my name Unique constraint failed on the constraint: UkladanieRole_username_key at Vn.handleRequestError (C:\Users\wvn_0\Desktop\GalaxyBOT\bot\node_modules@prisma\client\runtime\library.js:121:7339) at Vn.handleAndLogRequestError (C:\Users\wvn_0\Desktop\GalaxyBOT\bot\node_modules@prisma\client\runtime\library.js:121:6663) at Vn.request (C:\Users\wvn_0\Desktop\GalaxyBOT\bot\node_modules@prisma\client\runtime\library.js:121:6370) at async l (C:\Users\wvn_0\Desktop\GalaxyBOT\bot\node_modules@prisma\client\runtime\library.js:130:9617) at async execute (file:///C:/Users/wvn_0/Desktop/GalaxyBOT/bot/dist/events/discord/leave.js:23:5) Emitted 'error' event at: at C:\Users\wvn_0\Desktop\GalaxyBOT\bot\node_modules@sern\handler\dist\handlers\event-utils.js:45:22 at C:\Users\wvn_0\Desktop\GalaxyBOT\bot\node_modules\rxjs\dist\cjs\internal\operators\catchError.js:13:51 at OperatorSubscriber._this._error (C:\Users\wvn_0\Desktop\GalaxyBOT\bot\node_modules\rxjs\dist\cjs\internal\operators\OperatorSubscriber.js:43:21) at Subscriber.error (C:\Users\wvn_0\Desktop\GalaxyBOT\bot\node_modules\rxjs\dist\cjs\internal\Subscriber.js:60:18) at Subscriber._error (C:\Users\wvn_0\Desktop\GalaxyBOT\bot\node_modules\rxjs\dist\cjs\internal\Subscriber.js:84:30) at Subscriber.error (C:\Users\wvn_0\Desktop\GalaxyBOT\bot\node_modules\rxjs\dist\cjs\internal\Subscriber.js:60:18) at Subscriber._error (C:\Users\wvn_0\Desktop\GalaxyBOT\bot\node_modules\rxjs\dist\cjs\internal\Subscriber.js:84:30) at Subscriber.error (C:\Users\wvn_0\Desktop\GalaxyBOT\bot\node_modules\rxjs\dist\cjs\internal\Subscriber.js:60:18) at C:\Users\wvn_0\Desktop\GalaxyBOT\bot\node_modules\rxjs\dist\cjs\internal\observable\innerFrom.js:123:47 { code: 'P2002', clientVersion: '6.2.1', meta: { modelName: 'UkladanieRole', target: 'UkladanieRole_username_key' } } Node.js v22.12.0 await prisma.ukladanieRole.upsert({ where: { username: c.id }, update: { rolesID: roleIds, username: c.user.username }, create: { username: c.user.username, userID: c.id, rolesID: roleIds, }, }); Yep founded the issue. The command handler was usining old version of the my code. So like the code didnt changed at all. Now its all working Thanks!

Did you find this page helpful?