From cbd021db15aa51db807b55d0527a34ce73e424c8 Mon Sep 17 00:00:00 2001 From: Krzysztof Kotlarek Date: Fri, 10 Feb 2023 11:14:22 +1100 Subject: [PATCH] FIX: add index to sidebar_section_link (#20234) Index on linkable_type and linkable_id should increase performance of this subquery https://github.com/discourse/discourse/blob/main/app/services/sidebar_site_settings_backfiller.rb#L86 Also, distinct is removing duplicates which are unnecessary. --- app/models/sidebar_section_link.rb | 3 ++- .../sidebar_site_settings_backfiller.rb | 2 +- ...linkable_index_to_sidebar_section_links.rb | 22 +++++++++++++++++++ 3 files changed, 25 insertions(+), 2 deletions(-) create mode 100644 db/migrate/20230209222225_add_linkable_index_to_sidebar_section_links.rb diff --git a/app/models/sidebar_section_link.rb b/app/models/sidebar_section_link.rb index ab89b950f9c..c9a799b89d0 100644 --- a/app/models/sidebar_section_link.rb +++ b/app/models/sidebar_section_link.rb @@ -40,5 +40,6 @@ end # # Indexes # -# idx_unique_sidebar_section_links (user_id,linkable_type,linkable_id) UNIQUE +# idx_unique_sidebar_section_links (user_id,linkable_type,linkable_id) UNIQUE +# index_sidebar_section_links_on_linkable_type_and_linkable_id (linkable_type,linkable_id) # diff --git a/app/services/sidebar_site_settings_backfiller.rb b/app/services/sidebar_site_settings_backfiller.rb index 7fe13f8162b..fae0f500512 100644 --- a/app/services/sidebar_site_settings_backfiller.rb +++ b/app/services/sidebar_site_settings_backfiller.rb @@ -81,7 +81,7 @@ class SidebarSiteSettingsBackfiller FROM users WHERE users.id NOT IN ( SELECT - sidebar_section_links.user_id + DISTINCT(sidebar_section_links.user_id) FROM sidebar_section_links WHERE sidebar_section_links.linkable_type = '#{@linkable_klass.to_s}' AND sidebar_section_links.linkable_id IN (#{@added_ids.join(",")}) diff --git a/db/migrate/20230209222225_add_linkable_index_to_sidebar_section_links.rb b/db/migrate/20230209222225_add_linkable_index_to_sidebar_section_links.rb new file mode 100644 index 00000000000..3cdcf23466d --- /dev/null +++ b/db/migrate/20230209222225_add_linkable_index_to_sidebar_section_links.rb @@ -0,0 +1,22 @@ +# frozen_string_literal: true + +class AddLinkableIndexToSidebarSectionLinks < ActiveRecord::Migration[7.0] + disable_ddl_transaction! + + def up + execute <<~SQL + DROP INDEX CONCURRENTLY IF EXISTS index_sidebar_section_links_on_linkable_type_and_linkable_id + SQL + + execute <<~SQL + CREATE INDEX CONCURRENTLY index_sidebar_section_links_on_linkable_type_and_linkable_id + ON sidebar_section_links (linkable_type,linkable_id) + SQL + end + + def down + execute <<~SQL + DROP INDEX CONCURRENTLY IF EXISTS index_sidebar_section_links_on_linkable_type_and_linkable_id + SQL + end +end