DBConnectionListener example
by Paulo Gonzalez
2023-01-01 | elixir db-connection open-source
db-connection-example
DBConnectionListener example
DBConnectionListener example:
Update, this got merged to the library:
# Source
# https://github.com/elixir-ecto/db_connection/commit/eae538ec06b4603f69b28bf00f3603a3e4ecd1a5.patch
From eae538ec06b4603f69b28bf00f3603a3e4ecd1a5 Mon Sep 17 00:00:00 2001
From: Paulo Daniel Gonzalez
Date: Fri, 2 Sep 2022 14:14:11 -0500
Subject: [PATCH] Add example implementation for a connection_listener
---
lib/db_connection.ex | 32 ++++++++++++++++++++++++++++++++
1 file changed, 32 insertions(+)
diff --git a/lib/db_connection.ex b/lib/db_connection.ex
index 2356017..a2c79d5 100644
--- a/lib/db_connection.ex
+++ b/lib/db_connection.ex
@@ -433,6 +433,38 @@ defmodule DBConnection do
`pid` for connection crashes. So it is recommended to monitor the connected
`pid` if you want to track all disconnections.
+ Here is an example of a `connection_listener` implementation:
+
+ defmodule DBConnectionListener do
+ use GenServer
+
+ def start_link() do
+ GenServer.start_link(__MODULE__, [], name: {:global, "db_connection_listener"})
+ end
+
+ @impl true
+ def init(stack) when is_list(stack) do
+ {:ok, stack}
+ end
+
+ @impl true
+ def handle_call(:read_state, _from, state) do
+ {:reply, state, state}
+ end
+
+ @impl true
+ def handle_info(msg, state) do
+ {:noreply, [msg | state]}
+ end
+ end
+
+ You can then start it, pass it into a `DBConnection.start_link/1` and when needed
+ can query the notifications:
+
+ {:ok, connection_listener} = DBConnectionListener.start_link([])
+ {:ok, _conn} = DBConnection.start_link(SomeModule, [connection_listeners: [connection_listener]])
+ notifications = GenServer.call({:global, "db_connection_listener"}, :read_state)
+
Thanks for reading!