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 1390e38
Showing 1 changed file with 8 additions and 4 deletions.
12 changes: 8 additions & 4 deletions lib/active_record_shards/connection_switcher.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand All @@ -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')

Expand Down

0 comments on commit 1390e38

Please sign in to comment.