inspect for AR model classes does not initiate a new connection.#11014
Conversation
|
@rafaelfranca @neerajdotname can you take a look? |
activerecord/CHANGELOG.md
Outdated
|
Looks good to me, thanks! |
…hout_connection `inspect` for AR model classes does not initiate a new connection.
|
I try to get the ActiveRecord::Base.establish_connection :development # `adapter: mysql2`
User.inspect #=> User(no database connection)There was no connection made actually User.connected? #=> false
ActiveRecord::Base.connected? #=> falseAfter triggering the connection initialization manually ActiveRecord::Base.connection
ActiveRecord::Base.connected? #=> true
User.connected? #=> trueor User.first
User.connected? #=> truethen succeeded to get the User scheme User.inspect #=> User(id: integer)It's just a little bit inconvenient to call I think it's got nothing to do with def establish_connection(spec = ENV["DATABASE_URL"])
resolver = ConnectionAdapters::ConnectionSpecification::Resolver.new spec, configurations
spec = resolver.spec
unless respond_to?(spec.adapter_method)
raise AdapterNotFound, "database configuration specifies nonexistent #{spec.config[:adapter]} adapter"
end
remove_connection
connection_handler.establish_connection(self, spec).tap { retrieve_connection } # origin: connection_handler.establish_connection self, spec
endBut I don't think it's a good thing. Any suggestion here? Thanks, |
|
I can confirm this behavior with the following gist. I don't know ActiveRecord so much but as far as I can see, ActiveRecord is not establishing the connection to the database until you really need it. This leads to an unexpected behavior so I think the fix should be at the |
|
Before patching After patching, it passed. |
|
I agree but what your patch is doing is that it retrieve the connection in any case. It means that when you call |
|
I agree with you. Not only am I not a ActiveRecord guy, I don't think it's a good approach either. It was just a bad example. :) |
Closes #10936
The behavior of
Model.inspectwith a missing database connection was different for each adapter:sqlite3
postgresql
mysql2
This patch changes the implementation of
inspectto not initiate a connection and simply return "not connected" if no connection is established. This prevents the exceptions on inspect and should still be expressive enough.