pgxrepl

package module
v0.0.0-...-76c9cb8 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 23, 2026 License: MIT Imports: 9 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

pgxrepl

CI Release Go Reference License Go Version pgx Version

Logical replication consumer for pgx v5.

Features

  • Typed Insert, Update, Delete, and Truncate events with BEGIN / COMMIT framing
  • Replicated rows expose pgx.CollectableRow — decode with pgx.RowTo / pgx.RowToStructByName
  • Slot and publication helpers (CreateSlot, DropSlot, CreatePublication, DropPublication)
  • At-least-once delivery — the slot advances only after HandleCommit returns nil, so failed transactions replay on restart

Installation

go get github.com/pgx-contrib/pgxrepl

Your Postgres server must be configured with wal_level=logical.

Usage

package main

import (
    "context"
    "os"

    "github.com/jackc/pgx/v5"
    "github.com/jackc/pgx/v5/pgconn"
    "github.com/pgx-contrib/pgxrepl"
)

type Logger struct{}

func (Logger) HandleBegin(op *pgxrepl.BeginOperation) error    { return nil }
func (Logger) HandleCommit(op *pgxrepl.CommitOperation) error  { return nil }
func (Logger) HandleInsert(op *pgxrepl.InsertOperation) error {
    var id int
    var name string
    if err := op.NewRow.Scan(&id, &name); err != nil {
        return err
    }
    // ... forward to your sink
    return nil
}
func (Logger) HandleUpdate(op *pgxrepl.UpdateOperation) error     { return nil }
func (Logger) HandleDelete(op *pgxrepl.DeleteOperation) error     { return nil }
func (Logger) HandleTruncate(op *pgxrepl.TruncateOperation) error { return nil }

func main() {
    ctx := context.Background()
    dsn := os.Getenv("PGX_DATABASE_URL")

    // 1. Create a publication on a normal connection.
    normal, err := pgconn.Connect(ctx, dsn)
    must(err)
    must(pgxrepl.CreatePublication(ctx, normal, "users_pub", []pgx.Identifier{{"public", "users"}}))
    must(normal.Close(ctx))

    // 2. Create a slot on a replication connection.
    cfg, err := pgconn.ParseConfig(dsn)
    must(err)
    cfg.RuntimeParams["replication"] = "database"
    repl, err := pgconn.ConnectConfig(ctx, cfg)
    must(err)
    must(pgxrepl.CreateSlot(ctx, repl, "users_slot"))

    // 3. Run the broker.
    broker := &pgxrepl.Broker{
        Conn:        repl,
        Handler:     Logger{},
        Slot:        "users_slot",
        Publication: "users_pub",
    }
    must(broker.Run(ctx))
}

func must(err error) { if err != nil { panic(err) } }

Non-goals

pgxrepl deliberately stays narrow. The following pgoutput features are not handled, and there are no plans to add them:

  • Streaming in-progress transactions (StreamStart / StreamStop / StreamCommit / StreamAbort)
  • Origin, Type, and LogicalDecodingMessage events
  • Physical replication

If you need any of these, drive pglogrepl directly.

Development

DevContainer

Open in VS Code with the Dev Containers extension. The environment provides Go, Nix, and a PostgreSQL 18 instance started with wal_level=logical.

PGX_DATABASE_URL=postgres://vscode@postgres:5432/pgxrepl?sslmode=disable
Nix
nix develop          # enter shell with Go
go tool ginkgo run -r
Run tests
# Unit tests only (no database required — integration specs skip)
go tool ginkgo run -r

# With integration tests
export PGX_DATABASE_URL="postgres://localhost/pgxrepl?sslmode=disable"
go tool ginkgo run -r

License

MIT

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func CreatePublication

func CreatePublication(ctx context.Context, conn *pgconn.PgConn, name string, tables []pgx.Identifier) error

CreatePublication creates a PUBLICATION for the given tables. If tables is empty, the publication is created FOR ALL TABLES. Use a regular (not replication-mode) connection.

func CreateSlot

func CreateSlot(ctx context.Context, conn *pgconn.PgConn, name string) error

CreateSlot creates a logical replication slot with the pgoutput plugin. It is safe to call only against a connection opened in replication mode.

func DropPublication

func DropPublication(ctx context.Context, conn *pgconn.PgConn, name string) error

DropPublication drops a publication if it exists.

func DropSlot

func DropSlot(ctx context.Context, conn *pgconn.PgConn, name string) error

DropSlot drops a replication slot.

Types

type BeginOperation

type BeginOperation struct {
	XID        uint32
	FinalLSN   pglogrepl.LSN
	CommitTime time.Time
}

BeginOperation marks the start of a transaction.

type Broker

type Broker struct {
	// Conn is an open replication connection (opened with
	// "?replication=database" in the connection string).
	Conn *pgconn.PgConn
	// Handler receives decoded operations.
	Handler Handler
	// Slot is the logical replication slot name (see CreateSlot).
	Slot string
	// Publication is the publication name (see CreatePublication).
	Publication string
}

Broker runs the replication loop. It starts streaming from Slot using Publication, decodes WAL payloads, and dispatches them to Handler.

The slot's confirmed flush LSN advances only after Handler.HandleCommit returns nil, so a failed transaction replays on restart.

func (*Broker) Run

func (x *Broker) Run(ctx context.Context) error

Run blocks until ctx is canceled or a handler/connection error occurs.

type Collector

type Collector struct {
	// contains filtered or unexported fields
}

Collector decodes pgoutput WAL payloads into handler calls.

func (*Collector) Collect

func (x *Collector) Collect(data []byte) error

Collect parses a WAL payload and dispatches to the handler.

type CommitOperation

type CommitOperation struct {
	CommitLSN         pglogrepl.LSN
	TransactionEndLSN pglogrepl.LSN
	CommitTime        time.Time
}

CommitOperation marks the end of a transaction. The broker advances the replication slot to TransactionEndLSN after the handler returns nil.

type Connector

type Connector struct {
	// contains filtered or unexported fields
}

Connector wraps a replication connection: starts replication for a slot, sends periodic standby status updates, and receives backend messages.

func (*Connector) Ack

func (x *Connector) Ack(lsn pglogrepl.LSN)

Ack advances the position reported back to the primary. The next Status call will send it as the confirmed flush LSN.

func (*Connector) Receive

Receive reads the next backend message, respecting the keepalive deadline.

func (*Connector) Start

func (x *Connector) Start(ctx context.Context, slot, publication string) error

Start begins streaming from the current server XLog position for the given slot, with pgoutput proto v1 and the given publication.

func (*Connector) Status

func (x *Connector) Status(ctx context.Context) error

Status sends a StandbyStatusUpdate when the keepalive deadline passes.

type DeleteOperation

type DeleteOperation struct {
	TableName pgx.Identifier
	OldRow    pgx.CollectableRow
}

DeleteOperation represents a single row delete. OldRow contains the key columns (or all columns under REPLICA IDENTITY FULL).

type Handler

type Handler interface {
	HandleBegin(*BeginOperation) error
	HandleCommit(*CommitOperation) error
	HandleInsert(*InsertOperation) error
	HandleUpdate(*UpdateOperation) error
	HandleDelete(*DeleteOperation) error
	HandleTruncate(*TruncateOperation) error
}

Handler receives decoded replication events. Every method is called in WAL order on a single goroutine. Returning a non-nil error aborts the broker loop; the slot's confirmed LSN is only advanced after HandleCommit returns nil, so a failed event replays on restart.

type InsertOperation

type InsertOperation struct {
	TableName pgx.Identifier
	NewRow    pgx.CollectableRow
}

InsertOperation represents a single row insert.

type Row

type Row struct {
	// contains filtered or unexported fields
}

Row adapts a pgoutput TupleData to pgx.CollectableRow, so handlers can decode replicated values with pgx.RowTo / pgx.RowToStructByName.

func (*Row) FieldDescriptions

func (r *Row) FieldDescriptions() []pgconn.FieldDescription

FieldDescriptions implements pgx.CollectableRow.

func (*Row) RawValues

func (r *Row) RawValues() [][]byte

RawValues implements pgx.CollectableRow.

func (*Row) Scan

func (r *Row) Scan(values ...any) error

Scan implements pgx.CollectableRow.

func (*Row) Values

func (r *Row) Values() ([]any, error)

Values implements pgx.CollectableRow.

type TruncateOperation

type TruncateOperation struct {
	TableNames      []pgx.Identifier
	Cascade         bool
	RestartIdentity bool
}

TruncateOperation represents a TRUNCATE affecting one or more tables.

type UpdateOperation

type UpdateOperation struct {
	TableName pgx.Identifier
	NewRow    pgx.CollectableRow
	OldRow    pgx.CollectableRow
}

UpdateOperation represents a single row update. OldRow is nil unless the table has REPLICA IDENTITY FULL or an explicit replica identity index.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL
⌂ 换网址