CI Hex version HexDocs REUSE MIT

Replicant

Replicant is an Elixir library for PostgreSQL change data capture. Use it to stream committed transactions from a logical replication slot into a sink you write, starting with an optional snapshot of existing rows.

Install

Add {:replicant, "~> 3.0"} to your Mix dependencies.

Record committed changes

In a demo database with wal_level = logical, run this SQL as the table owner. For the pipeline, use a role with replication access, read access to the source table, and read and insert access to the ledger.

CREATE TABLE orders (id integer PRIMARY KEY, note text);
CREATE PUBLICATION orders_pub FOR TABLE orders;
CREATE TABLE cdc_ledger (commit_lsn numeric(20, 0) PRIMARY KEY, payload bytea NOT NULL);

Set PGHOST, PGPORT, PGDATABASE, PGUSER and PGPASSWORD for the connection. In your application's IEx session, use a ledger row to commit the change and its checkpoint in the same write. Use one ledger per source and slot.

defmodule OrdersLedger do
  @behaviour Replicant.Sink

  @impl true
  def checkpoint do
    case Postgrex.query!(__MODULE__, "SELECT max(commit_lsn) FROM cdc_ledger", []).rows do
      [[nil]] -> {:ok, nil}
      [[lsn]] -> {:ok, Decimal.to_integer(lsn)}
    end
  end

  @impl true
  def handle_transaction(%Replicant.Transaction{commit_lsn: lsn, changes: changes}) do
    Postgrex.query!(
      __MODULE__,
      """
      INSERT INTO cdc_ledger (commit_lsn, payload)
      SELECT $1, $2
      WHERE NOT EXISTS (SELECT 1 FROM cdc_ledger WHERE commit_lsn >= $1)
      ON CONFLICT (commit_lsn) DO NOTHING
      """,
      [Decimal.new(lsn), :erlang.term_to_binary(changes)]
    )

    {:ok, lsn}
  end
end

connection = [
  hostname: System.fetch_env!("PGHOST"),
  port: String.to_integer(System.get_env("PGPORT", "5432")),
  database: System.fetch_env!("PGDATABASE"),
  username: System.fetch_env!("PGUSER"),
  password: System.fetch_env!("PGPASSWORD")
]

{:ok, _} = Postgrex.start_link(connection ++ [name: OrdersLedger])

{:ok, _} =
  Replicant.start_link(
    connection: connection,
    slot_name: "replicant_orders",
    publication: "orders_pub",
    sink: OrdersLedger,
    go_forward_only: true
  )

Once the slot is active, insert an order and check the ledger.

INSERT INTO orders VALUES (1, 'ready');
SELECT commit_lsn FROM cdc_ledger;

Documentation

See Compatibility for supported versions and dependency floors.

License

MIT. NOTICE records the attribution for vendored code.