Skip to content

Commit

Permalink
Cache shard name integer check
Browse files Browse the repository at this point in the history
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`.
  • Loading branch information
HeyNonster committed Mar 23, 2023
1 parent ee5b2c7 commit 83aa878
Showing 1 changed file with 11 additions and 3 deletions.
14 changes: 11 additions & 3 deletions lib/active_record_shards/connection_switcher.rb
Original file line number Diff line number Diff line change
Expand Up @@ -142,9 +142,7 @@ 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
all_shard_names_are_integers?

config_for_env[SHARD_NAMES_CONFIG_KEY] || []
end
Expand All @@ -171,6 +169,16 @@ def config_for_env
end
alias_method :check_config_for_env, :config_for_env

def all_shard_names_are_integers?
@all_shard_names_are_integers ||= begin
if config_for_env.fetch(SHARD_NAMES_CONFIG_KEY, []).all? { |shard_name| shard_name.is_a?(Integer) }
true
else
raise "All shard names must be integers: #{config_for_env[SHARD_NAMES_CONFIG_KEY].inspect}."
end
end
end

def switch_connection(options)
ensure_legacy_connection_handling if ActiveRecord.version >= Gem::Version.new('6.1')

Expand Down

0 comments on commit 83aa878

Please sign in to comment.