From 1390e3870f80a3fd2ef6ac9b3b5907cdb7141677 Mon Sep 17 00:00:00 2001 From: Nony Dutton Date: Thu, 23 Mar 2023 10:40:25 +0100 Subject: [PATCH] Cache shard name integer check We only need to verify that all of the shard names are integers _once_, otherwise we will perform an expensive integer check on every shard name, every time we call `shard_names`. --- lib/active_record_shards/connection_switcher.rb | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) diff --git a/lib/active_record_shards/connection_switcher.rb b/lib/active_record_shards/connection_switcher.rb index 1424f265..995519fe 100644 --- a/lib/active_record_shards/connection_switcher.rb +++ b/lib/active_record_shards/connection_switcher.rb @@ -142,10 +142,6 @@ def current_shard_id end def shard_names - unless config_for_env.fetch(SHARD_NAMES_CONFIG_KEY, []).all? { |shard_name| shard_name.is_a?(Integer) } - raise "All shard names must be integers: #{config_for_env[SHARD_NAMES_CONFIG_KEY].inspect}." - end - config_for_env[SHARD_NAMES_CONFIG_KEY] || [] end @@ -166,11 +162,19 @@ def config_for_env raise "Did not find #{shard_env} in configurations, did you forget to add it to your database config? (configurations: #{configurations.to_h.keys.inspect})" end + ensure_all_shard_names_are_integers(config) + config end end alias_method :check_config_for_env, :config_for_env + def ensure_all_shard_names_are_integers(config) + unless config.fetch(SHARD_NAMES_CONFIG_KEY, []).all? { |shard_name| shard_name.is_a?(Integer) } + raise "All shard names must be integers: #{config.inspect}." + end + end + def switch_connection(options) ensure_legacy_connection_handling if ActiveRecord.version >= Gem::Version.new('6.1')