From 8aac4e22f17d0fbb84e6c4261952bb3a8d53408c Mon Sep 17 00:00:00 2001 From: Wilson Wong Date: Wed, 28 Aug 2024 17:14:56 -0700 Subject: [PATCH] Migration to remove duplicate users and add table constraints --- .../20240828000000_008-user-id-constraint.ts | 36 +++++++++++++++++++ 1 file changed, 36 insertions(+) create mode 100644 app/src/db/migrations/20240828000000_008-user-id-constraint.ts diff --git a/app/src/db/migrations/20240828000000_008-user-id-constraint.ts b/app/src/db/migrations/20240828000000_008-user-id-constraint.ts new file mode 100644 index 00000000..f49ab2b8 --- /dev/null +++ b/app/src/db/migrations/20240828000000_008-user-id-constraint.ts @@ -0,0 +1,36 @@ +/* eslint-disable max-len */ +import type { Knex } from 'knex'; + +export async function up(knex: Knex): Promise { + 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 { + return Promise.resolve().then(() => + knex.schema.alterTable('user', (table) => { + table.dropUnique(['identityId', 'idp']); + }) + ); +}