From 3e05be45135aa60ebe71f9f35724a89170e223a8 Mon Sep 17 00:00:00 2001 From: ayham291 Date: Mon, 2 Jun 2025 15:02:43 +0200 Subject: [PATCH] fix(migration): handle existing git providers by assigning to org owner Previously the migration would fail in production when trying to add a NOT NULL userId column to git_provider table with existing data. Now existing providers are automatically assigned to their organization owner. --- apps/dokploy/drizzle/0093_elite_warlock.sql | 24 ++++++++++++++++++--- 1 file changed, 21 insertions(+), 3 deletions(-) diff --git a/apps/dokploy/drizzle/0093_elite_warlock.sql b/apps/dokploy/drizzle/0093_elite_warlock.sql index 7b165485..c8169711 100644 --- a/apps/dokploy/drizzle/0093_elite_warlock.sql +++ b/apps/dokploy/drizzle/0093_elite_warlock.sql @@ -1,3 +1,21 @@ -ALTER TABLE "git_provider" ADD COLUMN "userId" text NOT NULL;--> statement-breakpoint -ALTER TABLE "git_provider" ADD CONSTRAINT "git_provider_userId_account_user_id_fk" FOREIGN KEY ("userId") REFERENCES "public"."account"("user_id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint -ALTER TABLE "account" ADD CONSTRAINT "account_user_id_unique" UNIQUE("user_id"); \ No newline at end of file +-- Add the userId column as nullable first +ALTER TABLE "git_provider" ADD COLUMN "userId" text;--> statement-breakpoint + +-- Add the unique constraint on account.user_id first (needed for foreign key) +ALTER TABLE "account" ADD CONSTRAINT "account_user_id_unique" UNIQUE("user_id");--> statement-breakpoint + +-- Update existing git providers to be owned by the organization owner +-- We need to get the account.user_id for the organization owner +UPDATE "git_provider" +SET "userId" = ( + SELECT a.user_id + FROM "organization" o + JOIN "account" a ON o."owner_id" = a.user_id + WHERE o.id = "git_provider"."organizationId" +);--> statement-breakpoint + +-- Now make the column NOT NULL since all rows should have values +ALTER TABLE "git_provider" ALTER COLUMN "userId" SET NOT NULL;--> statement-breakpoint + +-- Add the foreign key constraint (after unique constraint exists) +ALTER TABLE "git_provider" ADD CONSTRAINT "git_provider_userId_account_user_id_fk" FOREIGN KEY ("userId") REFERENCES "public"."account"("user_id") ON DELETE cascade ON UPDATE no action; \ No newline at end of file