Skip to content

Commit

Permalink
Merge pull request #144 from bcgov/bugfix/remove-dupe-users
Browse files Browse the repository at this point in the history
Remove duplicated users in database, prevent reoccurrence
  • Loading branch information
kyle1morel authored Sep 4, 2024
2 parents d724e78 + 591b698 commit 534aab6
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 0 deletions.
37 changes: 37 additions & 0 deletions app/src/db/migrations/20240828000000_008-user-id-constraint.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
/* eslint-disable max-len */
import type { Knex } from 'knex';

export async function up(knex: Knex): Promise<void> {
return (
Promise.resolve()
// Find all duplicated user entries in "user" table (by querying by "identity_id")
// Then delete the most recent duplicated entry
.then(() =>
knex.raw(`DELETE FROM "public"."user" AS u
WHERE u."user_id" IN (
SELECT DISTINCT ON ("public"."user"."identity_id") "public"."user"."user_id"
FROM "public"."user"
WHERE (
SELECT count(*)
FROM "public"."user" AS user2
WHERE user2."identity_id" = "public"."user"."identity_id") > 1
ORDER BY "public"."user"."identity_id", "public"."user"."created_at" DESC
)`)
)

// prevent further duplicate users - add unique index over columns identityId and idp in user table
.then(() =>
knex.schema.alterTable('user', (table) => {
table.unique(['identity_id', 'idp']);
})
)
);
}

export async function down(knex: Knex): Promise<void> {
return Promise.resolve().then(() =>
knex.schema.alterTable('user', (table) => {
table.dropUnique(['identity_id', 'idp']);
})
);
}
1 change: 1 addition & 0 deletions app/src/db/prisma/schema.prisma
Original file line number Diff line number Diff line change
Expand Up @@ -213,6 +213,7 @@ model user {
submission submission[]
identity_provider identity_provider? @relation(fields: [idp], references: [idp], onDelete: Cascade, map: "user_idp_foreign")
@@unique([identity_id, idp], map: "user_identity_id_idp_unique")
@@index([email], map: "user_email_index")
@@index([identity_id], map: "user_identity_id_index")
@@index([username], map: "user_username_index")
Expand Down

0 comments on commit 534aab6

Please sign in to comment.