Reputation: 1323
First off, I am using Rails 3.2 on Puma (but with MRI), and am not doing any explicit threading by hand.
I am in places using the execute
method, like MyModel.connection.execute
or I know ActiveRecord::Base.connection.execute
can do the same thing since all connections are to the same DB for me right now.
I recently started seeing
DEPRECATION WARNING: Database connections will not be closed automatically, please close your database connection at the end of the thread by calling `close` on your connection. For example ActiveRecord::Base.connection.close
This seems self-explanatory, but I can find very little information on it online, mostly about using ActiveRecord with Sinatra (ex ActiveRecord connection warning. (Database connections will not be closed automatically)).
I read this:
http://blog.daniel-azuma.com/archives/216
which suggests that Rack middleware does it for me as long as the DB execute transaction is done in a controller (if I understand correctly). Does this mean transactions done elsewhere (such as a model, or decorator - they're useful in many places, so I don't want to put them right in a single controller) must be explicitly closed? Even if it's a model method that does it which was called from a controller, ex:
class MyController
def show
MyModel.do_execute_sql_stuff
end
end
class MyModel
def self.do_execute_sql_stuff
connection.execute("WHATEVER;")
end
end
Do I need to explicitly close here? If so, should I use MyModel.connection.close
or MyModel.clear_active_connections!
as the article suggests? Maybe because English is not my first language, but that method sounds dangerous! And how do I go do it?
conn = MyModel.connection
result = conn.execute("STUFF")
do_stuff_with(result)
conn.close |or| MyModel.clear_active_connections!
Like that?
What about when using find_by_sql
? Will it return the connection to the pool, or do I have to explicitly do that?
EDIT: Strangely, I only see this in my production logs. Not on development, nor staging (which should be identical to production).
Upvotes: 6
Views: 14152
Reputation: 57
In This case You need to close your connection manually.
After running your script, you can close it Manually like this.
after do
ActiveRecord::Base.connection.close
end
Upvotes: 4