pgxext

package module
v0.0.0-...-2021da7 Latest Latest
Warning

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

Go to latest
Published: Apr 1, 2026 License: MIT Imports: 11 Imported by: 0

README

 ███████████    █████████  █████ █████    ██████████ █████ █████ ███████████
░░███░░░░░███  ███░░░░░███░░███ ░░███    ░░███░░░░░█░░███ ░░███ ░█░░░███░░░█
 ░███    ░███ ███     ░░░  ░░███ ███      ░███  █ ░  ░░███ ███  ░   ░███  ░
 ░██████████ ░███           ░░█████       ░██████     ░░█████       ░███
 ░███░░░░░░  ░███    █████   ███░███      ░███░░█      ███░███      ░███
 ░███        ░░███  ░░███   ███ ░░███     ░███ ░   █  ███ ░░███     ░███
 █████        ░░█████████  █████ █████    ██████████ █████ █████    █████
░░░░░          ░░░░░░░░░  ░░░░░ ░░░░░    ░░░░░░░░░░ ░░░░░ ░░░░░    ░░░░░
    
Currently under active development — breaking changes are possible

A thin pgx/v5 connection-pool wrapper with migrations and a generic query builder.


Overview

pgxext wraps pgxpool to provide:

  • Config — fluent builder for connection settings, TLS, pool parameters, and runtime params.
  • DataSource — a *pgxpool.Pool wrapper exposing Query, Exec, QueryRow, transactions, and batch operations.
  • Migration — transactional SQL migration runner backed by a migrations table.
  • Repository — generic, type-safe query builder (SELECT / INSERT / UPDATE / DELETE) with JOIN and COUNT support.

Quick start

Config & DataSource

ds, err := pgxext.NewDataSource(ctx,
    pgxext.NewConfig().
        WithHost("localhost").
        WithPort(5432).
        WithDatabase("mydb").
        WithUser("alice").
        WithPassword("secret").
        WithMaxConns(10),
)

Or from a URL:

cfg, err := pgxext.NewConfig().WithURL("postgres://alice:secret@localhost/mydb?pool_max_conns=10")
ds, err := pgxext.NewDataSource(ctx, cfg)

Migrations

var schema = migration.MigrationSet{
    {
        Name:      "001_create_users",
        UpQuery:   `CREATE TABLE users (id SERIAL PRIMARY KEY, name TEXT NOT NULL)`,
        DownQuery: `DROP TABLE users`,
    },
}

m := migration.NewMigrator(ctx, ds)
m.Up(schema)   // apply
m.Down(schema) // revert

Repository

Define a model with db struct tags (pgx RowToAddrOfStructByName convention):

type User struct {
    ID    int    `db:"id"`
    Name  string `db:"name"`
    Email string `db:"email"`
}

Create a repository once and reuse it:

repo := repository.NewRepository[User](ds, "users")

Select

users, err := repo.Select().
    Where("name", repository.Like, "%alice%").
    OrderBy("name", repository.ASC).
    Limit(20).
    Execute(ctx)

Count

n, err := repo.Select().
    Where("email", repository.Like, "%@example.com").
    Count(ctx)

Insert

n, err := repo.Insert().
    Set("name", "Alice").
    Set("email", "alice@example.com").
    Execute(ctx)

Update

n, err := repo.Update().
    Set("email", "new@example.com").
    Where("id", repository.Equals, 42).
    Execute(ctx)

Delete

n, err := repo.Delete().
    Where("id", repository.Equals, 42).
    Execute(ctx)

Join

type UserOrder struct {
    UserID  int    `db:"id"`
    Name    string `db:"name"`
    OrderID int    `db:"order_id"`
}

repo := repository.NewRepository[UserOrder](ds, "users")
rows, err := repo.Select().
    Join("orders", "users.id", repository.Equals, "orders.user_id").
    Where("orders.status", repository.Equals, "paid").
    Execute(ctx)

Utilities

// Scan one row into *T (nil on no rows)
user, err := pgxext.CollectOneRow[User](rows)

// Scan all rows into []*T
users, err := pgxext.CollectRows[User](rows)

// Inspect a Postgres error code / constraint
if pgErr, ok := pgxext.IsPostgresError(err); ok {
    fmt.Println(pgErr.Code, pgErr.ConstraintName)
}

Documentation

Overview

Package pgxext provides a thin PostgreSQL connection-pool wrapper built on pgx/v5, with helpers for configuration, migrations, and a generic repository query builder.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func CollectOneRow

func CollectOneRow[T any](rows pgx.Rows) (*T, error)

CollectOneRow scans the first row of rows into *T using db-tag field mapping. Returns nil without an error if no rows are found.

func CollectRows

func CollectRows[T any](rows pgx.Rows) ([]*T, error)

CollectRows scans all rows into []*T using db-tag field mapping. Returns nil without an error if no rows are found.

func IsPostgresError

func IsPostgresError(err error) (*pgconn.PgError, bool)

IsPostgresError reports whether err is a PostgreSQL server error and returns the underlying *pgconn.PgError for inspection (e.g. Code, Constraint).

Types

type Config

type Config struct {
	*pgxpool.Config
}

Config extends pgxpool.Config with session parameters not directly representable as fields in the underlying pgxpool/pgconn structs.

func NewConfig

func NewConfig() *Config

NewConfig returns a Config initialised from an empty DSN via pgxpool.ParseConfig.

func (*Config) WithAfterConnect

func (config *Config) WithAfterConnect(fn func(context.Context, *pgx.Conn) error) *Config

WithAfterConnect sets a hook called after a connection is established, before it is added to the pool.

func (*Config) WithAfterRelease

func (config *Config) WithAfterRelease(fn func(*pgx.Conn) bool) *Config

WithAfterRelease sets a hook called after a connection is released but before it is returned to the pool. Return false to destroy the connection.

func (*Config) WithApplicationName

func (config *Config) WithApplicationName(name string) *Config

WithApplicationName sets the application_name runtime parameter.

func (*Config) WithBeforeAcquire

func (config *Config) WithBeforeAcquire(fn func(context.Context, *pgx.Conn) bool) *Config

WithBeforeAcquire sets a hook called before a connection is acquired from the pool. Deprecated: prefer WithPrepareConn.

func (*Config) WithBeforeClose

func (config *Config) WithBeforeClose(fn func(*pgx.Conn)) *Config

WithBeforeClose sets a hook called just before a connection is closed and removed from the pool.

func (*Config) WithBeforeConnect

func (config *Config) WithBeforeConnect(fn func(context.Context, *pgx.ConnConfig) error) *Config

WithBeforeConnect sets a hook called before each new connection is dialed. The pgx.ConnConfig copy passed to fn is not shared with any open connection.

func (*Config) WithConnectTimeout

func (config *Config) WithConnectTimeout(timeout time.Duration) *Config

WithConnectTimeout sets the maximum wait for a connection to be established.

func (*Config) WithDatabase

func (config *Config) WithDatabase(database string) *Config

WithDatabase sets the database name.

func (*Config) WithDialFunc

func (config *Config) WithDialFunc(fn pgconn.DialFunc) *Config

WithDialFunc overrides the function used to establish the underlying network connection (e.g. to use a custom dialer or proxy).

func (*Config) WithHealthCheckPeriod

func (config *Config) WithHealthCheckPeriod(d time.Duration) *Config

WithHealthCheckPeriod sets the interval between health checks on idle connections. Maps to pgxpool.Config.HealthCheckPeriod.

func (*Config) WithHost

func (config *Config) WithHost(host string) *Config

WithHost sets the database server host.

func (*Config) WithLookupFunc

func (config *Config) WithLookupFunc(fn pgconn.LookupFunc) *Config

WithLookupFunc overrides the DNS resolver used during connection.

func (*Config) WithMaxConnIdleTime

func (config *Config) WithMaxConnIdleTime(d time.Duration) *Config

WithMaxConnIdleTime sets the maximum idle time before a connection is closed. Maps to pgxpool.Config.MaxConnIdleTime.

func (*Config) WithMaxConnLifetime

func (config *Config) WithMaxConnLifetime(d time.Duration) *Config

WithMaxConnLifetime sets the maximum lifetime of a pooled connection. Maps to pgxpool.Config.MaxConnLifetime.

func (*Config) WithMaxConns

func (config *Config) WithMaxConns(n int32) *Config

WithMaxConns sets the maximum number of connections in the pool. Maps to pgxpool.Config.MaxConns.

func (*Config) WithMinConns

func (config *Config) WithMinConns(n int32) *Config

WithMinConns sets the minimum number of connections in the pool. Maps to pgxpool.Config.MinConns.

func (*Config) WithOnNotice

func (config *Config) WithOnNotice(fn pgconn.NoticeHandler) *Config

WithOnNotice sets a callback invoked whenever the server sends a notice.

func (*Config) WithOnNotification

func (config *Config) WithOnNotification(fn pgconn.NotificationHandler) *Config

WithOnNotification sets a callback invoked on LISTEN/NOTIFY notifications.

func (*Config) WithOnPgError

func (config *Config) WithOnPgError(fn pgconn.PgErrorHandler) *Config

WithOnPgError sets a callback invoked when the server returns a Postgres error. Return false to close the connection; return true to keep it open.

func (*Config) WithPassword

func (config *Config) WithPassword(password string) *Config

WithPassword sets the database password.

func (*Config) WithPort

func (config *Config) WithPort(port uint16) *Config

WithPort sets the database server port.

func (*Config) WithPrepareConn

func (config *Config) WithPrepareConn(fn func(context.Context, *pgx.Conn) (bool, error)) *Config

WithPrepareConn sets a hook called before a connection is acquired from the pool. Return (true, nil) to allow, (false, nil) to destroy and retry on a new connection, or (_, err) to surface an error to the caller.

func (*Config) WithSSLClientCert

func (config *Config) WithSSLClientCert(certFile, keyFile, password string) (*Config, error)

WithSSLClientCert loads the client certificate and private key from certFile and keyFile, building a ready-to-use tls.Certificate inside ConnConfig.TLSConfig. Pass a non-empty password if the private key is PEM-encrypted; otherwise pass "".

func (*Config) WithSSLMode

func (config *Config) WithSSLMode(mode string) *Config

WithSSLMode configures ConnConfig.TLSConfig according to the PostgreSQL sslmode:

  • "disable" — TLS is disabled entirely.
  • "require" — TLS is required; server certificate is not verified.
  • "verify-ca" — TLS is required; certificate chain is verified against RootCAs but the server hostname is not checked.
  • "verify-full" — TLS is required; both certificate chain and hostname are verified.

func (*Config) WithSSLRootCert

func (config *Config) WithSSLRootCert(rootCertFile string) (*Config, error)

WithSSLRootCert loads the PEM-encoded CA certificate from rootCertFile and registers it as the trusted root for TLS verification.

func (*Config) WithSearchPath

func (config *Config) WithSearchPath(path string) *Config

WithSearchPath sets the search_path runtime parameter.

func (*Config) WithShouldPing

func (config *Config) WithShouldPing(fn func(context.Context, pgxpool.ShouldPingParams) bool) *Config

WithShouldPing sets a hook that decides whether an acquired connection should be pinged to check liveness before use.

func (*Config) WithTimezone

func (config *Config) WithTimezone(tz string) *Config

WithTimezone sets the TimeZone runtime parameter.

func (*Config) WithURL

func (config *Config) WithURL(rawURL string) (*Config, error)

WithURL parses a PostgreSQL connection URL and fills all Config fields. Delegates entirely to pgxpool.ParseConfig, which handles all standard params, SSL (builds ConnConfig.TLSConfig directly), pool_* params, and runtime params.

Example:

postgres://alice:secret@localhost:5432/mydb?sslmode=verify-full&pool_max_conns=10

func (*Config) WithUser

func (config *Config) WithUser(user string) *Config

WithUser sets the database user.

func (*Config) WithValidateConnect

func (config *Config) WithValidateConnect(fn pgconn.ValidateConnectFunc) *Config

WithValidateConnect sets a hook called after authentication succeeds. Return an error to reject the connection and try the next fallback.

type DataSource

type DataSource struct {
	*pgxpool.Pool
}

DataSource wraps a pgxpool.Pool and exposes the query surface used by the rest of the library. A nil context is treated as context.Background().

func NewDataSource

func NewDataSource(ctx context.Context, config *Config) (ds *DataSource, err error)

NewDataSource opens a connection pool using the provided Config.

func (*DataSource) Exec

func (ds *DataSource) Exec(ctx context.Context, sql string, args ...interface{}) (pgconn.CommandTag, error)

Exec runs a SQL statement that does not return rows.

func (*DataSource) NewBatch

func (ds *DataSource) NewBatch() *pgx.Batch

NewBatch returns an empty pgx.Batch ready to queue statements.

func (*DataSource) NewCustomTransaction

func (ds *DataSource) NewCustomTransaction(ctx context.Context, options pgx.TxOptions) (pgx.Tx, error)

NewCustomTransaction begins a transaction with the specified isolation level and access mode.

func (*DataSource) NewTransaction

func (ds *DataSource) NewTransaction(ctx context.Context) (pgx.Tx, error)

NewTransaction begins a new database transaction with default options.

func (*DataSource) Query

func (ds *DataSource) Query(ctx context.Context, sql string, args ...any) (pgx.Rows, error)

Query executes a SQL query and returns the resulting rows.

func (*DataSource) QueryRow

func (ds *DataSource) QueryRow(ctx context.Context, sql string, args ...any) (pgx.Row, error)

QueryRow executes a SQL query expected to return at most one row.

func (*DataSource) SendBatch

func (ds *DataSource) SendBatch(ctx context.Context, batch *pgx.Batch) (pgx.BatchResults, error)

SendBatch dispatches all queued statements in batch as a single round-trip.

Directories

Path Synopsis
Package migration provides a simple transactional SQL migration runner backed by a pgxext.DataSource.
Package migration provides a simple transactional SQL migration runner backed by a pgxext.DataSource.
Package repository provides a generic, type-safe query builder for PostgreSQL backed by pgxext.DataSource.
Package repository provides a generic, type-safe query builder for PostgreSQL backed by pgxext.DataSource.

Jump to

Keyboard shortcuts

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