From 272783be20927148d86b05a7e22f88b291c6dd93 Mon Sep 17 00:00:00 2001 From: Stan Hu Date: Thu, 15 Mar 2018 13:12:00 -0700 Subject: [PATCH] Cache table_exists?('application_settings') to reduce repeated schema reloads Closes #43355 --- changelogs/unreleased/sh-cache-table-exists.yml | 5 +++++ lib/gitlab/current_settings.rb | 2 +- lib/gitlab/database.rb | 5 +++++ spec/lib/gitlab/database_spec.rb | 12 ++++++++++++ 4 files changed, 23 insertions(+), 1 deletion(-) create mode 100644 changelogs/unreleased/sh-cache-table-exists.yml diff --git a/changelogs/unreleased/sh-cache-table-exists.yml b/changelogs/unreleased/sh-cache-table-exists.yml new file mode 100644 index 00000000000..37407b2a005 --- /dev/null +++ b/changelogs/unreleased/sh-cache-table-exists.yml @@ -0,0 +1,5 @@ +--- +title: Cache table_exists?('application_settings') to reduce repeated schema reloads +merge_request: +author: +type: performance diff --git a/lib/gitlab/current_settings.rb b/lib/gitlab/current_settings.rb index b7c596a973d..e392a015b91 100644 --- a/lib/gitlab/current_settings.rb +++ b/lib/gitlab/current_settings.rb @@ -70,7 +70,7 @@ module Gitlab active_db_connection = ActiveRecord::Base.connection.active? rescue false active_db_connection && - ActiveRecord::Base.connection.table_exists?('application_settings') + Gitlab::Database.cached_table_exists?('application_settings') rescue ActiveRecord::NoDatabaseError false end diff --git a/lib/gitlab/database.rb b/lib/gitlab/database.rb index d4fc69cb173..76501dd50e8 100644 --- a/lib/gitlab/database.rb +++ b/lib/gitlab/database.rb @@ -187,6 +187,11 @@ module Gitlab connection.schema_cache.columns_hash(table_name).has_key?(column_name.to_s) end + def self.cached_table_exists?(table_name) + # Rails 5 uses data_source_exists? instead of table_exists? + connection.schema_cache.table_exists?(table_name) + end + private_class_method :connection def self.database_version diff --git a/spec/lib/gitlab/database_spec.rb b/spec/lib/gitlab/database_spec.rb index 689bbbfaa8d..1fe1d3926ad 100644 --- a/spec/lib/gitlab/database_spec.rb +++ b/spec/lib/gitlab/database_spec.rb @@ -298,6 +298,18 @@ describe Gitlab::Database do end end + describe '.cached_table_exists?' do + it 'only retrieves data once per table' do + expect(ActiveRecord::Base.connection).to receive(:table_exists?).with(:projects).once.and_call_original + expect(ActiveRecord::Base.connection).to receive(:table_exists?).with(:bogus_table_name).once.and_call_original + + 2.times do + expect(described_class.cached_table_exists?(:projects)).to be_truthy + expect(described_class.cached_table_exists?(:bogus_table_name)).to be_falsey + end + end + end + describe '#true_value' do it 'returns correct value for PostgreSQL' do expect(described_class).to receive(:postgresql?).and_return(true)