Skip to content

Commit

Permalink
Decorating the ActiveRecord @config object in a thread-safe manner
Browse files Browse the repository at this point in the history
Not sure if this is needed as @config[:database] doesn't seem to affect any tests.
  • Loading branch information
zdennis committed Jun 10, 2020
1 parent ce8cea7 commit 1aaaf27
Showing 1 changed file with 27 additions and 1 deletion.
28 changes: 27 additions & 1 deletion lib/active_record_host_pool/connection_adapter_mixin.rb
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,31 @@
require "active_record/connection_adapters/mysql2_adapter"

module ActiveRecordHostPool
module ThreadSafeDbConfig
def self.module_for(connection_id)
Module.new do
define_method(:[]=) do |key, value|
storage_key = _arhp_thread_safe_config_key(key)
DatabaseSwitch.thread_local_storage[connection_id][storage_key] = value
end

define_method(:[]) do |key|
storage_key = _arhp_thread_safe_config_key(key)
if DatabaseSwitch.thread_local_storage[connection_id].key?(storage_key)
DatabaseSwitch.thread_local_storage[connection_id][storage_key]
else
DatabaseSwitch.thread_local_storage[connection_id][storage_key] = super(key)
end
end

define_method(:_arhp_thread_safe_config_key) do |key|
"database_config_#{key}"
end
private :_arhp_thread_safe_config_key
end
end
end

module DatabaseSwitch
def self.included(base)
base.class_eval do
Expand All @@ -13,7 +38,7 @@ def _host_pool_current_database

def _host_pool_current_database=(database)
_ahrp_per_thread_per_connection_storage[:_host_pool_current_database] = database
# @config[:database] = _host_pool_current_database if ActiveRecord::VERSION::MAJOR >= 5
@config[:database] = _host_pool_current_database if ActiveRecord::VERSION::MAJOR >= 5
end

alias_method :execute_without_switching, :execute
Expand All @@ -37,6 +62,7 @@ def self.thread_local_storage
def initialize(*)
self._cached_current_database = nil
super
@config.singleton_class.prepend ThreadSafeDbConfig.module_for(@connection.object_id)
end

def execute_with_switching(*args)
Expand Down

0 comments on commit 1aaaf27

Please sign in to comment.