From 591b698fc1c89effc3872297caa92b7c59c070a2 Mon Sep 17 00:00:00 2001 From: Wilson Wong Date: Fri, 30 Aug 2024 18:08:09 -0700 Subject: [PATCH] Fix column names, add comments to migration --- .../20240828000000_008-user-id-constraint.ts | 15 ++++++++------- app/src/db/prisma/schema.prisma | 1 + 2 files changed, 9 insertions(+), 7 deletions(-) diff --git a/app/src/db/migrations/20240828000000_008-user-id-constraint.ts b/app/src/db/migrations/20240828000000_008-user-id-constraint.ts index f49ab2b8..93df9da4 100644 --- a/app/src/db/migrations/20240828000000_008-user-id-constraint.ts +++ b/app/src/db/migrations/20240828000000_008-user-id-constraint.ts @@ -4,24 +4,25 @@ import type { Knex } from 'knex'; export async function up(knex: Knex): Promise { return ( Promise.resolve() - // Drop public schema functions + // 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."userId" IN ( - SELECT DISTINCT ON ("public"."user"."identityId") "public"."user"."userId" + 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."identityId" = "public"."user"."identityId") > 1 - ORDER BY "public"."user"."identityId", "public"."user"."createdAt" DESC + 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(['identityId', 'idp']); + table.unique(['identity_id', 'idp']); }) ) ); @@ -30,7 +31,7 @@ export async function up(knex: Knex): Promise { export async function down(knex: Knex): Promise { return Promise.resolve().then(() => knex.schema.alterTable('user', (table) => { - table.dropUnique(['identityId', 'idp']); + table.dropUnique(['identity_id', 'idp']); }) ); } diff --git a/app/src/db/prisma/schema.prisma b/app/src/db/prisma/schema.prisma index 93fa188c..5fc7d444 100644 --- a/app/src/db/prisma/schema.prisma +++ b/app/src/db/prisma/schema.prisma @@ -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")