From 0205c7d01c192235447b3fe4ccf0a99eb34a5c26 Mon Sep 17 00:00:00 2001
From: Andreas Brandl <abrandl@gitlab.com>
Date: Wed, 16 Jun 2021 17:00:03 +0200
Subject: [PATCH] Replacement partial index for ci_builds.token

Relates to https://gitlab.com/gitlab-org/gitlab/-/issues/333812

Changelog: performance
---
 ...254_add_partial_index_for_ci_builds_token.rb | 17 +++++++++++++++++
 db/schema_migrations/20210616145254             |  1 +
 db/structure.sql                                |  2 ++
 3 files changed, 20 insertions(+)
 create mode 100644 db/post_migrate/20210616145254_add_partial_index_for_ci_builds_token.rb
 create mode 100644 db/schema_migrations/20210616145254

diff --git a/db/post_migrate/20210616145254_add_partial_index_for_ci_builds_token.rb b/db/post_migrate/20210616145254_add_partial_index_for_ci_builds_token.rb
new file mode 100644
index 00000000000..6e169a6f0e1
--- /dev/null
+++ b/db/post_migrate/20210616145254_add_partial_index_for_ci_builds_token.rb
@@ -0,0 +1,17 @@
+# frozen_string_literal: true
+
+class AddPartialIndexForCiBuildsToken < ActiveRecord::Migration[6.1]
+  include Gitlab::Database::MigrationHelpers
+
+  disable_ddl_transaction!
+
+  NAME = 'index_ci_builds_on_token_partial'
+
+  def up
+    add_concurrent_index :ci_builds, :token, unique: true, where: 'token IS NOT NULL', name: NAME
+  end
+
+  def down
+    remove_concurrent_index_by_name :ci_builds, NAME
+  end
+end
diff --git a/db/schema_migrations/20210616145254 b/db/schema_migrations/20210616145254
new file mode 100644
index 00000000000..e5d7553d883
--- /dev/null
+++ b/db/schema_migrations/20210616145254
@@ -0,0 +1 @@
+525fbdd66dcabbf1e6d0430468600f86fbc3c00dcfdab1c5a052294d7d73de37
\ No newline at end of file
diff --git a/db/structure.sql b/db/structure.sql
index 032f1230f36..efed4977864 100644
--- a/db/structure.sql
+++ b/db/structure.sql
@@ -22830,6 +22830,8 @@ CREATE UNIQUE INDEX index_ci_builds_on_token ON ci_builds USING btree (token);
 
 CREATE UNIQUE INDEX index_ci_builds_on_token_encrypted ON ci_builds USING btree (token_encrypted) WHERE (token_encrypted IS NOT NULL);
 
+CREATE UNIQUE INDEX index_ci_builds_on_token_partial ON ci_builds USING btree (token) WHERE (token IS NOT NULL);
+
 CREATE INDEX index_ci_builds_on_updated_at ON ci_builds USING btree (updated_at);
 
 CREATE INDEX index_ci_builds_on_upstream_pipeline_id ON ci_builds USING btree (upstream_pipeline_id) WHERE (upstream_pipeline_id IS NOT NULL);
-- 
2.30.9