From 51c32f4d02e67a18f7cc7b92fc3e08e1657c376f Mon Sep 17 00:00:00 2001
From: Alex Pooley <apooley@gitlab.com>
Date: Tue, 6 Apr 2021 15:22:21 +0800
Subject: [PATCH] Partial index optimization for namespaces id

---
 ...26637-index-namespaces-id-and-parent_id.yml |  5 +++++
 ...te_namespaces_id_parent_id_partial_index.rb | 18 ++++++++++++++++++
 db/schema_migrations/20210406063442            |  1 +
 db/structure.sql                               |  2 ++
 4 files changed, 26 insertions(+)
 create mode 100644 changelogs/unreleased/326637-index-namespaces-id-and-parent_id.yml
 create mode 100644 db/migrate/20210406063442_create_namespaces_id_parent_id_partial_index.rb
 create mode 100644 db/schema_migrations/20210406063442

diff --git a/changelogs/unreleased/326637-index-namespaces-id-and-parent_id.yml b/changelogs/unreleased/326637-index-namespaces-id-and-parent_id.yml
new file mode 100644
index 000000000000..3f10c6a81f03
--- /dev/null
+++ b/changelogs/unreleased/326637-index-namespaces-id-and-parent_id.yml
@@ -0,0 +1,5 @@
+---
+title: Partial index optimization for namespaces id
+merge_request: 58220
+author:
+type: performance
diff --git a/db/migrate/20210406063442_create_namespaces_id_parent_id_partial_index.rb b/db/migrate/20210406063442_create_namespaces_id_parent_id_partial_index.rb
new file mode 100644
index 000000000000..073d1ee2bc5d
--- /dev/null
+++ b/db/migrate/20210406063442_create_namespaces_id_parent_id_partial_index.rb
@@ -0,0 +1,18 @@
+# frozen_string_literal: true
+
+class CreateNamespacesIdParentIdPartialIndex < ActiveRecord::Migration[6.0]
+  include Gitlab::Database::MigrationHelpers
+
+  DOWNTIME = false
+  NAME = 'index_namespaces_id_parent_id_is_null'
+
+  disable_ddl_transaction!
+
+  def up
+    add_concurrent_index :namespaces, :id, where: 'parent_id IS NULL', name: NAME
+  end
+
+  def down
+    remove_concurrent_index :namespaces, :id, name: NAME
+  end
+end
diff --git a/db/schema_migrations/20210406063442 b/db/schema_migrations/20210406063442
new file mode 100644
index 000000000000..75b07b541584
--- /dev/null
+++ b/db/schema_migrations/20210406063442
@@ -0,0 +1 @@
+d29f002f88440a10674b251791fa027cb0ae1c1b0c4fd776a2078e3c94160f17
\ No newline at end of file
diff --git a/db/structure.sql b/db/structure.sql
index 16b69a4370ea..85ffb1b3e91f 100644
--- a/db/structure.sql
+++ b/db/structure.sql
@@ -23160,6 +23160,8 @@ CREATE UNIQUE INDEX index_namespace_root_storage_statistics_on_namespace_id ON n
 
 CREATE UNIQUE INDEX index_namespace_statistics_on_namespace_id ON namespace_statistics USING btree (namespace_id);
 
+CREATE INDEX index_namespaces_id_parent_id_is_null ON namespaces USING btree (id) WHERE (parent_id IS NULL);
+
 CREATE INDEX index_namespaces_on_created_at ON namespaces USING btree (created_at);
 
 CREATE INDEX index_namespaces_on_custom_project_templates_group_id_and_type ON namespaces USING btree (custom_project_templates_group_id, type) WHERE (custom_project_templates_group_id IS NOT NULL);
-- 
GitLab