Call a function every time that a specific row in your database changes
If available in Hex, the package can be installed
by adding phoenix_postgres_pub_sub
to your list of dependencies in mix.exs
:
def deps do
[
{:phoenix_postgres_pub_sub, "~> 0.1.0"}
]
end
In your config.exs add the following:
config :phoenix_postgres_pub_sub, :config,
adapter: MainModuleOfYourApp, # this should be the main module of your phoenix application
repo: MainModuleOfYourApp.Repo # and this should be the main repo of your phoenix application
In your Application Module change the configuration in the following way:
defmodule MainModuleOfYourApp do
@moduledoc """
Application Module
"""
use Application
# See http://elixir-lang.org/docs/stable/elixir/Application.html
# for more information on OTP Applications
def start(_type, _args) do
import Supervisor.Spec, warn: false
children = [
# Start the endpoint when the application starts
supervisor(MainModuleOfYourApp.Endpoint, []),
# Start the Ecto repository
worker(MainModuleOfYourApp.Repo, []),
worker(
PhoenixPostgresPubSub,
[
[
"skills_changes" # this should be always in the format NAME_OF_TABLE_changes,
"users_changes" # this should be always in the format NAME_OF_TABLE_changes,
"companies_changes" # this should be always in the format NAME_OF_TABLE_changes,
...
]
],
restart: :permanent
),
# Here you could define other workers and supervisors as children
# worker(MainModuleOfYourApp.Worker, [arg1, arg2, arg3]),
]
At this point you have to generate a migration to add the trigger to Postgres. You can do this by running the following command:
mix phoenix_postgres_pub_sub.gen.channel CHOOSE_A_MIGRATION_NAME --table=users
# check the migration file just generated and make your changes if necessary
And run the migration with mix ecto.migration
--table
is the table upon which your want to listen to changes
Create a module called something like MainModuleOfYourApp.PhoenixPostgresPubSub
.
This module should have a function called handle_postgres_notification
that accepts two arguments: notification, state
The notification is the one generated by Postgres and sent to this function, while the state is the state of GenServer of PhoenixPostgresPubSub
Example:
defmodule MainModuleOfYourApp.PhoenixPostgresPubSub do
def handle_postgres_notification(notification, _state) do
IO.inspect(notification, label: "Some table has changed")
end
end
You you have followed all the steps correctly you should be able to make changes to the table on which your are listening to and you should see that the function MainModuleOfYourApp.PhoenixPostgresPubSub.handle_postgres_notification/2
is called every time this happens.
The docs can be found at https://hexdocs.pm/phoenix_postgres_pub_sub.