influitive / apartment

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

db:create fails #518

Closed mayeco closed 6 years ago

mayeco commented 6 years ago

Steps to reproduce

rake db:create (the database not create)

Expected behavior

create the database

Actual behavior

fails

System configuration

Mac (rails 5.2beta)

apartment (2.1.0)

ActiveRecord::NoDatabaseError: Unknown database 'xxx'
activerecord-5.2.0.beta2/lib/active_record/connection_adapters/mysql2_adapter.rb:26:in `rescue in mysql2_connection'
activerecord-5.2.0.beta2/lib/active_record/connection_adapters/mysql2_adapter.rb:12:in `mysql2_connection'
activerecord-5.2.0.beta2/lib/active_record/connection_adapters/abstract/connection_pool.rb:809:in `new_connection'
activerecord-5.2.0.beta2/lib/active_record/connection_adapters/abstract/connection_pool.rb:853:in `checkout_new_connection'
activerecord-5.2.0.beta2/lib/active_record/connection_adapters/abstract/connection_pool.rb:832:in `try_to_checkout_new_connection'
activerecord-5.2.0.beta2/lib/active_record/connection_adapters/abstract/connection_pool.rb:793:in `acquire_connection'
activerecord-5.2.0.beta2/lib/active_record/connection_adapters/abstract/connection_pool.rb:521:in `checkout'
activerecord-5.2.0.beta2/lib/active_record/connection_adapters/abstract/connection_pool.rb:380:in `connection'
activerecord-5.2.0.beta2/lib/active_record/connection_adapters/abstract/connection_pool.rb:411:in `with_connection'
apartment-2.1.0/lib/apartment/railtie.rb:31:in `block in <class:Railtie>'

Fix with this in apartment/lib/apartment/railtie.rb

    config.to_prepare do
      begin
        unless ARGV.any? { |arg| arg =~ /\Aassets:(?:precompile|clean)\z/ }
          Apartment.connection_class.connection_pool.with_connection do
            Apartment::Tenant.init
          end
        end
      rescue ::ActiveRecord::NoDatabaseError; end
    end
IngusSkaistkalns commented 6 years ago

+1

IngusSkaistkalns commented 6 years ago

currently there is guard check for assets related rake/rails tasks, i guess to continue same approach we need to add just db:create(?:all).

Is there any drawback on rescuing NoDatabaseError? Seems like a more universal fix

ahorek commented 6 years ago

I personally prefer a guard instead of rescue. https://github.com/influitive/apartment/pull/492

but it could be improved for more cases as @IngusSkaistkalns suggested

archonic commented 6 years ago

@mayeco It looks like you've endorsed https://github.com/influitive/apartment/pull/492. Should your related PR (https://github.com/influitive/apartment/pull/519) be closed?

mayeco commented 6 years ago

Yes, I think is better #492, and #519 should be closed.