Skip to content

Commit

Permalink
Migration to remove duplicate users and add table constraints
Browse files Browse the repository at this point in the history
  • Loading branch information
wilwong89 committed Sep 4, 2024
1 parent d724e78 commit 8aac4e2
Showing 1 changed file with 36 additions and 0 deletions.
36 changes: 36 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,36 @@
/* eslint-disable max-len */
import type { Knex } from 'knex';

export async function up(knex: Knex): Promise<void> {
return (
Promise.resolve()
// Drop public schema functions
.then(() =>
knex.raw(`DELETE FROM "public"."user" AS u
WHERE u."userId" IN (
SELECT DISTINCT ON ("public"."user"."identityId") "public"."user"."userId"
FROM "public"."user"
WHERE (
SELECT count(*)
FROM "public"."user" AS user2
WHERE user2."identityId" = "public"."user"."identityId") > 1
ORDER BY "public"."user"."identityId", "public"."user"."createdAt" DESC
)`)
)

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

export async function down(knex: Knex): Promise<void> {
return Promise.resolve().then(() =>
knex.schema.alterTable('user', (table) => {
table.dropUnique(['identityId', 'idp']);
})
);
}

0 comments on commit 8aac4e2

Please sign in to comment.