From 0ecb0047d1b6208498e638410f8119143721eefc Mon Sep 17 00:00:00 2001 From: YetheSamartaka <55753928+YetheSamartaka@users.noreply.github.com> Date: Tue, 23 Jul 2024 18:25:53 +0200 Subject: [PATCH] Fix duplicate key value violates unique constraint "userGroups_pkey" This fixes the GraphQL error: insert into "userGroups" ("groupId", "userId") values ($1, $2) returning "groupId" - duplicate key value violates unique constraint "userGroups_pkey" when userGroups table was modified outside of web interface and there is already existing entry with ID that is the same of what is about to be added when assigning group to user. --- server/graph/resolvers/group.js | 16 ++++++++++++++-- 1 file changed, 14 insertions(+), 2 deletions(-) diff --git a/server/graph/resolvers/group.js b/server/graph/resolvers/group.js index 1e295979..fdcd93e3 100644 --- a/server/graph/resolvers/group.js +++ b/server/graph/resolvers/group.js @@ -71,8 +71,20 @@ module.exports = { throw new gql.GraphQLError('User is already assigned to group.') } - // Assign user to group - await grp.$relatedQuery('users').relate(usr.id) + // Check for unique ID conflict + const maxId = await WIKI.models.knex('userGroups').max('id as maxId').first() + const newId = maxId.maxId + 1 + const idConflict = await WIKI.models.knex('userGroups').where({ id: newId }).first() + if (idConflict) { + throw new gql.GraphQLError('ID conflict detected while assigning user to group.') + } + + // Assign user to group with unique ID + await WIKI.models.knex('userGroups').insert({ + id: newId, + userId: args.userId, + groupId: args.groupId + }) // Revoke tokens for this user WIKI.auth.revokeUserTokens({ id: usr.id, kind: 'u' })