Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: Gracefully Handle Add Participants Unique Constraint Error in Postgres #495

Merged
merged 4 commits into from
Nov 22, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 21 additions & 2 deletions packages/adapter-postgres/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -729,15 +729,34 @@ export class PostgresDatabaseAdapter
async addParticipant(userId: UUID, roomId: UUID): Promise<boolean> {
const client = await this.pool.connect();
try {
// Check if the participant already exists
const existingParticipant = await client.query(
`SELECT * FROM participants WHERE "userId" = $1 AND "roomId" = $2`,
[userId, roomId]
);

if (existingParticipant.rows.length > 0) {
console.log(`Participant with userId ${userId} already exists in room ${roomId}.`);
return; // Exit early if the participant already exists
}

// Proceed to add the participant if they do not exist
await client.query(
`INSERT INTO participants (id, "userId", "roomId")
VALUES ($1, $2, $3)`,
[v4(), userId, roomId]
);
return true;
} catch (error) {
console.log("Error adding participant", error);
return false;
// This is to prevent duplicate participant error in case of a race condition
// Handle unique constraint violation error (code 23505)
if (error.code === '23505') {
console.warn(`Participant with userId ${userId} already exists in room ${roomId}.`); // Optionally, you can log this or handle it differently
} else {
// Handle other errors
console.error('Error adding participant:', error);
return false;
}
} finally {
client.release();
}
Expand Down