Search code examples
rubysequel

What should happend when using a disconnected Sequel::Database object for querying?


The situation I'm facing is the following:

  1. Initialize a database connection:
DB = Sequel.connect('<my-connection-string>')
  1. Use it for raw queries as usual (SQL in this case):
DB['SELECT * FROM my-db'].each do |row|
    puts 'It works (as it should)'
end
  1. Disconnect all the connections from that DB's pool:
DB.disconnect
  1. Use again the disconnected DB object for querying (without explicitly connecting again):
DB['SELECT * FROM my-db'].each do |row|
    puts 'It STILL works (I did not expect it)'
end

As I'm observing in my connections inspector, even after disconnecting, re-using the object ends up in opening a new connection to the same DB the object was initially configured to connect, and everything works just fine.

I ended up here by configuring a simple connection at initialize time in a class but closing it after each iteration on a loop of queries, and to my surprise it worked fine without any complains.

My question is: is this how it is supposed to behave? Is this documented behavior or is just undefined behavior which, due to good design patterns (I guess?) from Sequel's side, ends up in consistent behavior? So far I haven't been able to find anything, neither in Sequel's documentation nor in SO.

I'd like to keep on using this format (since it saves quite a lot of code lines in my specific case), but only if it is something reliable.


Solution

  • That is expected behavior from the contributor Jeremy Evans

    It is expected behavior. Database#disconnect removes connections from the connection pool. When a new connection is needed, since the connection pool is empty, Sequel creates a new connection at that time. I think this would only seem like a bug to you if you are thinking that a Database object represents a single connection, when it does not.