-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #144 from bcgov/bugfix/remove-dupe-users
Remove duplicated users in database, prevent reoccurrence
- Loading branch information
Showing
2 changed files
with
38 additions
and
0 deletions.
There are no files selected for viewing
37 changes: 37 additions & 0 deletions
37
app/src/db/migrations/20240828000000_008-user-id-constraint.ts
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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']); | ||
}) | ||
); | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters