[Feature Request] Add after_connect hook to Active Record

Hey!

Problem: I’m using PostgreSQL pg_trgm module which I need to configure by executing SELECT set_limit(0.5). I need to do this for every connection. I cannot do this in an initializer because connections can be reestablished during the app’s lifetime.

In general, the problem is setting per-connection database options.

Solution: add an after_connect hook that would run after a connection is established and would receive the connection as the parameter.

If you think this is a good idea I can cook up a PR next week.

Best regards

I'm not sure about other web servers, but I believe you can do this in your Unicorn or Puma configuration in an "after_fork" hook (in Puma it is on_worker_boot)

You can establish AR connection here, pass it any configuration you want, as well as run your special command.

Since this is correctly part of the configuration of Ruby web server level (Webbrick, Unicorn, Puma, etc), I would say if it can be done there it should stay out of Rails core itself.

see Deploying Rails Applications with the Puma Web Server | Heroku Dev Center

-Jason

Jason, thanks for your reply. I think your approach has the same problem as initializers - the code won't be executed for connections reestablished during the app's lifetime. Please correct me if I'm wrong here.

Ah yes I see what you mean. I think you're right, the after_fork only runs when the Unicorn/Puma process is forked, not AR connection re-established.

In that case, a hook inside of ActiveRecord::Base does indeed seem more appropriate.

It may also be more appropriate to use Postgres’s built-in ability to set per-user connection defaults rather than relying on Rails to set them up after connecting.

Thanks for the idea, James. Do you know how to change the per-user connection defaults in a managed environment like Heroku?

I would expect that you would just need to execute the proper SQL:

http://stackoverflow.com/questions/2951875/postgresql-how-do-i-set-the-search-path-at-the-user-level