influitive / apartment

Database multi-tenancy for Rack (and Rails) applications
2.66k stars 464 forks source link

Establishes connection during application boot #607

Open fsateler opened 5 years ago

fsateler commented 5 years ago

Steps to reproduce

Boot an application with bin/rails r "puts ActiveRecord::Base.connected?"

Expected behavior

The above command to print false

Actual behavior

It prints true

System configuration

config.excluded_models = %w[Tenant Delayed::Job]
config.tenant_names = lambda { Tenant.pluck :name }
config.use_schemas = true
config.persistent_schemas = %w[shared_extensions]
config.prepend_environment = !Rails.env.production?
Rails.application.config.middleware.insert_before Warden::Manager, Apartment::Elevators::Subdomain

Apartment::Railtie calls Apartment::Tenant.init during to_prepare, which is executed during application boot. This means that a connection is established before user code gets to run.

This is problematic as it disallows booting the rails application if the database server is down or unavailable:

% DATABASE_URL=postgresql://asdf:asdf@localhost:1234/buk_development bin/rails runner 'puts 1'
<snip>
`initialize': could not connect to server: Connection refused (PG::ConnectionBad)
    Is the server running on host "localhost" (::1) and accepting
    TCP/IP connections on port 1234?
could not connect to server: Connection refused
    Is the server running on host "localhost" (127.0.0.1) and accepting
    TCP/IP connections on port 1234?

This means that certain tasks, which shouldn't require a database, now do.

mikecmpbll commented 5 years ago

this is one of my bugbears too.