Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Use the current adapter across all fibers within a thread #182

Open
wants to merge 1 commit into
base: development
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
41 changes: 21 additions & 20 deletions lib/apartment/tenant.rb
Original file line number Diff line number Diff line change
Expand Up @@ -19,36 +19,37 @@ module Tenant
# @return {subclass of Apartment::AbstractAdapter}
#
def adapter
Thread.current[:apartment_adapter] ||= begin
adapter_method = "#{config[:adapter]}_adapter"

if defined?(JRUBY_VERSION)
case config[:adapter]
when /mysql/
adapter_method = 'jdbc_mysql_adapter'
when /postgresql/
adapter_method = 'jdbc_postgresql_adapter'
end
end
current_adapter = Thread.current.thread_variable_get(:apartment_adapter)
return current_adapter if current_adapter

begin
require "apartment/adapters/#{adapter_method}"
rescue LoadError
raise "The adapter `#{adapter_method}` is not yet supported"
end
adapter_method = "#{config[:adapter]}_adapter"

unless respond_to?(adapter_method)
raise AdapterNotFound, "database configuration specifies nonexistent #{config[:adapter]} adapter"
if defined?(JRUBY_VERSION)
case config[:adapter]
when /mysql/
adapter_method = 'jdbc_mysql_adapter'
when /postgresql/
adapter_method = 'jdbc_postgresql_adapter'
end
end

send(adapter_method, config)
begin
require "apartment/adapters/#{adapter_method}"
rescue LoadError
raise "The adapter `#{adapter_method}` is not yet supported"
end

unless respond_to?(adapter_method)
raise AdapterNotFound, "database configuration specifies nonexistent #{config[:adapter]} adapter"
end

Thread.current.thread_variable_set(:apartment_adapter, send(adapter_method, config))
end

# Reset config and adapter so they are regenerated
#
def reload!(config = nil)
Thread.current[:apartment_adapter] = nil
Thread.current.thread_variable_set(:apartment_adapter, nil)
@config = config
end

Expand Down
8 changes: 8 additions & 0 deletions spec/tenant_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,14 @@
thread.join
expect(subject.current).to eq(db1)
end

it 'maintains the current tenant across fibers within a thread' do
subject.switch!(db1)
expect(subject.current).to eq(db1)
fiber = Fiber.new { expect(subject.current).to eq(db1) }
fiber.resume
expect(subject.current).to eq(db1)
end
end
end

Expand Down