elixir-ecto / db_connection

Database connection behaviour
http://hexdocs.pm/db_connection/DBConnection.html
309 stars 112 forks source link

Add support for an `after_disconnect` callback function #227

Closed slashdotdash closed 3 years ago

slashdotdash commented 3 years ago

It can sometimes be useful to know when a database connection has disconnected. For instance, using Postgres advisory locks which are tied to a session means that the lock is released on disconnect. Another example might be to change application behaviour when a database connection is unavailable.

Therefore it would be useful to support an after_disconnect callback function passed in the DBConnection.start_link/2 function options which behaves similarly to the existing after_connect option. The existing function is called after connecting, I propose we add a corresponding function after disconnecting.

Does this sound like a reasonable feature to add before I attempt to work on a pull request?

josevalim commented 3 years ago

Hi @slashdotdash!

This is tricky because what if the connection was disconnected because the connection process crashed? So I think we need a mixture of event listeners (a process db_connection will send a message to whenenever it connects/disconnects) and you also have to setup monitors on our side. A PR for the first part will be welcome.

slashdotdash commented 3 years ago

@josevalim Would it be sufficient to pass the after_disconnect function to the DBConnection.Connection process to have it handle disconnects and DBConnection.Watcher process to handle connection process crashes?

josevalim commented 3 years ago

I would prefer to not allow custom code to run inside the connection process. Even for after_connect, we start a separate process and it is somewhat complicated. Is there a reason why a listener approach won't do?

slashdotdash commented 3 years ago

Can we discuss this further as I'm unsure how the listener approach might work. What's the best way to talk it through?

josevalim commented 3 years ago

Either here or on #elixir-lang channel on freenode.