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.
This commit is contained in:
ayham291 2025-06-02 15:02:43 +02:00
parent b3b009761a
commit 3e05be4513
No known key found for this signature in database
GPG Key ID: 764F467A43553816

View File

@ -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");
-- 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;