Skip to content

Instantly share code, notes, and snippets.

View KamilLelonek's full-sized avatar
🏋️‍♂️
Do you even lift?

Kamil Lelonek KamilLelonek

🏋️‍♂️
Do you even lift?
View GitHub Profile
defmodule PostgresPubSub.Repo.Migrations.CreateAccounts do
use Ecto.Migration
def change do
create_if_not_exists table(:accounts) do
add(:username, :string, null: true)
end
end
end
defmodule PostgresPubSub.Listener do
# ...
require Logger
@impl true
def handle_info({:notification, _pid, _ref, "accounts_changed", payload}, _state) do
with {:ok, data} <- Poison.decode(payload, keys: :atoms) do
data
|> inspect()
defmodule PostgresPubSub.Listener do
use GenServer
def child_spec(opts) do
%{
id: __MODULE__,
start: {__MODULE__, :start_link, [opts]}
}
end
@KamilLelonek
KamilLelonek / repo.ex
Last active September 17, 2018 23:27
defmodule PostgresPubSub.Repo do
# ...
def listen(event_name) do
with {:ok, pid} <- Postgrex.Notifications.start_link(__MODULE__.config()),
{:ok, ref} <- Postgrex.Notifications.listen(pid, event_name) do
{:ok, pid, ref}
end
end
end
defmodule PostgresPubSub.Application do
use Application
def start(_type, _args),
do: Supervisor.start_link(children(), opts())
defp children do
[
PostgresPubSub.Repo
]
defmodule PostgresPubSub.Repo do
use Ecto.Repo,
otp_app: :postgres_pubub
def child_spec(opts) do
%{
id: __MODULE__,
start: {__MODULE__, :start_link, [opts]},
type: :supervisor
}
CREATE TRIGGER accounts_changed
AFTER INSERT OR UPDATE
ON accounts
FOR EACH ROW
EXECUTE PROCEDURE notify_account_changes()
CREATE OR REPLACE FUNCTION notify_account_changes()
RETURNS trigger AS $$
BEGIN
PERFORM pg_notify(
'accounts_changed',
json_build_object(
'operation', TG_OP,
'record', row_to_json(NEW)
)::text
);
defmodule MinimalServer.Application do
# ...
defp children do
[
MinimalServer.Endpoint
]
end
end
defmodule MinimalServer.Endpoint do
# ...
def child_spec(opts) do
%{
id: __MODULE__,
start: {__MODULE__, :start_link, [opts]}
}
end