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.
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.
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.
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.