From e1a1b53beff2d742c0a0691a3d85adf2d91da8ef Mon Sep 17 00:00:00 2001
From: Arturo Herrero <arturo.herrero@gmail.com>
Date: Thu, 25 Mar 2021 11:39:25 +0000
Subject: [PATCH] Validate foreign key on ServiceHooks

In 13.7 we prevented invalid records
https://gitlab.com/gitlab-org/gitlab/-/merge_requests/47821 and fixed
existing records
https://gitlab.com/gitlab-org/gitlab/-/merge_requests/48263.

We can now validate the foreign key.
---
 .../validate-foreign-key-service-hooks.yml      |  5 +++++
 ...129_validate_foreign_key_on_service_hooks.rb | 17 +++++++++++++++++
 db/schema_migrations/20210325113129             |  1 +
 db/structure.sql                                |  2 +-
 4 files changed, 24 insertions(+), 1 deletion(-)
 create mode 100644 changelogs/unreleased/validate-foreign-key-service-hooks.yml
 create mode 100644 db/migrate/20210325113129_validate_foreign_key_on_service_hooks.rb
 create mode 100644 db/schema_migrations/20210325113129

diff --git a/changelogs/unreleased/validate-foreign-key-service-hooks.yml b/changelogs/unreleased/validate-foreign-key-service-hooks.yml
new file mode 100644
index 00000000000..8891e4f8756
--- /dev/null
+++ b/changelogs/unreleased/validate-foreign-key-service-hooks.yml
@@ -0,0 +1,5 @@
+---
+title: Validate foreign key on ServiceHooks
+merge_request: 57483
+author:
+type: other
diff --git a/db/migrate/20210325113129_validate_foreign_key_on_service_hooks.rb b/db/migrate/20210325113129_validate_foreign_key_on_service_hooks.rb
new file mode 100644
index 00000000000..17dd4cad6ae
--- /dev/null
+++ b/db/migrate/20210325113129_validate_foreign_key_on_service_hooks.rb
@@ -0,0 +1,17 @@
+# frozen_string_literal: true
+
+class ValidateForeignKeyOnServiceHooks < ActiveRecord::Migration[6.0]
+  include Gitlab::Database::MigrationHelpers
+
+  DOWNTIME = false
+
+  CONSTRAINT_NAME = 'fk_d47999a98a'
+
+  def up
+    validate_foreign_key :web_hooks, :service_id, name: CONSTRAINT_NAME
+  end
+
+  def down
+    # no-op
+  end
+end
diff --git a/db/schema_migrations/20210325113129 b/db/schema_migrations/20210325113129
new file mode 100644
index 00000000000..86c212db71b
--- /dev/null
+++ b/db/schema_migrations/20210325113129
@@ -0,0 +1 @@
+27fcdd54a21d554e44df621e409b81fe248e00851c856d315f4f64b463c7a5b7
\ No newline at end of file
diff --git a/db/structure.sql b/db/structure.sql
index cfb660ea346..f9b2d53e56c 100644
--- a/db/structure.sql
+++ b/db/structure.sql
@@ -25133,7 +25133,7 @@ ALTER TABLE ONLY ci_builds
     ADD CONSTRAINT fk_d3130c9a7f FOREIGN KEY (commit_id) REFERENCES ci_pipelines(id) ON DELETE CASCADE;
 
 ALTER TABLE ONLY web_hooks
-    ADD CONSTRAINT fk_d47999a98a FOREIGN KEY (service_id) REFERENCES services(id) ON DELETE CASCADE NOT VALID;
+    ADD CONSTRAINT fk_d47999a98a FOREIGN KEY (service_id) REFERENCES services(id) ON DELETE CASCADE;
 
 ALTER TABLE ONLY ci_sources_pipelines
     ADD CONSTRAINT fk_d4e29af7d7 FOREIGN KEY (source_pipeline_id) REFERENCES ci_pipelines(id) ON DELETE CASCADE;
-- 
2.30.9