From 214d2295825675a79262f5c7e6aa42daa31d54ae Mon Sep 17 00:00:00 2001
From: Marius Bobin <mbobin@gitlab.com>
Date: Wed, 5 Mar 2025 13:28:49 +0200
Subject: [PATCH] Remove broken FK between builds and pipelines

Changelog: other
---
 ...broken_fk_on_ci_builds_and_ci_pipelines.rb | 40 +++++++++++++++++++
 db/schema_migrations/20250303122513           |  1 +
 db/structure.sql                              |  3 --
 3 files changed, 41 insertions(+), 3 deletions(-)
 create mode 100644 db/post_migrate/20250303122513_remove_broken_fk_on_ci_builds_and_ci_pipelines.rb
 create mode 100644 db/schema_migrations/20250303122513

diff --git a/db/post_migrate/20250303122513_remove_broken_fk_on_ci_builds_and_ci_pipelines.rb b/db/post_migrate/20250303122513_remove_broken_fk_on_ci_builds_and_ci_pipelines.rb
new file mode 100644
index 0000000000000..95e09af7edd1d
--- /dev/null
+++ b/db/post_migrate/20250303122513_remove_broken_fk_on_ci_builds_and_ci_pipelines.rb
@@ -0,0 +1,40 @@
+# frozen_string_literal: true
+
+class RemoveBrokenFkOnCiBuildsAndCiPipelines < Gitlab::Database::Migration[2.2]
+  include Gitlab::Database::PartitioningMigrationHelpers::ForeignKeyHelpers
+
+  milestone '17.10'
+  disable_ddl_transaction!
+
+  SOURCE_TABLE_NAME = :p_ci_builds
+  TARGET_TABLE_NAME = :p_ci_pipelines
+  COLUMN = :commit_id
+  TARGET_COLUMN = :id
+  PARTITION_COLUMN = :partition_id
+  FK_NAME = :fk_d3130c9a7f_p
+
+  def up
+    with_lock_retries do
+      remove_foreign_key_if_exists(
+        SOURCE_TABLE_NAME,
+        TARGET_TABLE_NAME,
+        name: FK_NAME,
+        reverse_lock_order: true
+      )
+    end
+  end
+
+  def down
+    add_concurrent_partitioned_foreign_key(
+      SOURCE_TABLE_NAME,
+      TARGET_TABLE_NAME,
+      column: [PARTITION_COLUMN, COLUMN],
+      target_column: [PARTITION_COLUMN, TARGET_COLUMN],
+      validate: true,
+      reverse_lock_order: true,
+      on_update: :cascade,
+      on_delete: :cascade,
+      name: FK_NAME
+    )
+  end
+end
diff --git a/db/schema_migrations/20250303122513 b/db/schema_migrations/20250303122513
new file mode 100644
index 0000000000000..f11c8c199d175
--- /dev/null
+++ b/db/schema_migrations/20250303122513
@@ -0,0 +1 @@
+69ff9869b90cc16ad930ad0ad78ffaa00b52e03995bbed87c0ed38f8b4a77fb9
\ No newline at end of file
diff --git a/db/structure.sql b/db/structure.sql
index 9336cd884cbf1..71aeaa0c2bbba 100644
--- a/db/structure.sql
+++ b/db/structure.sql
@@ -40437,9 +40437,6 @@ ALTER TABLE ONLY environments
 ALTER TABLE ONLY issue_user_mentions
     ADD CONSTRAINT fk_d1f967521a FOREIGN KEY (namespace_id) REFERENCES namespaces(id) ON DELETE CASCADE;
 
-ALTER TABLE p_ci_builds
-    ADD CONSTRAINT fk_d3130c9a7f_p FOREIGN KEY (partition_id, commit_id) REFERENCES p_ci_pipelines(partition_id, id) ON UPDATE CASCADE ON DELETE CASCADE;
-
 ALTER TABLE ONLY boards_epic_user_preferences
     ADD CONSTRAINT fk_d32c3d693c FOREIGN KEY (group_id) REFERENCES namespaces(id) ON DELETE CASCADE;
 
-- 
GitLab