Skip to content

pgx-contrib/pgxcache

Repository files navigation

pgxcache

CI Release Go Reference License Go Version pgx Version

Query result caching layer for pgx v5.

Features

  • Transparent caching of Query, QueryRow, Exec, and SendBatch results
  • Inline SQL annotation directives control caching per query
  • Built-in MemoryQueryCacher backed by ristretto
  • Pluggable QueryCacher interface — bring your own backend (Redis, Memcached, etc.)
  • Works with any pgx-compatible connection: *pgx.Conn, *pgxpool.Pool, or pgx.Tx

Installation

go get github.com/pgx-contrib/pgxcache

Usage

Basic pool setup

pool, err := pgxpool.New(ctx, os.Getenv("PGX_DATABASE_URL"))
if err != nil {
    panic(err)
}

querier := &pgxcache.Querier{
    // Default options applied when a query has no inline annotations.
    Options: &pgxcache.QueryOptions{
        MinRows:     1,
        MaxRows:     1000,
        MaxLifetime: 30 * time.Second,
    },
    Cacher:  pgxcache.NewMemoryQueryCacher(),
    Querier: pool,
}

rows, err := querier.Query(ctx, "SELECT id, name FROM users WHERE active = $1", true)

Per-query annotations

Embed cache directives in SQL comments. Annotations override the default Options for that query:

-- @cache-max-lifetime 5m
-- @cache-min-rows 1
-- @cache-max-rows 500
SELECT id, name FROM users WHERE active = true
rows, err := querier.Query(ctx, `
    -- @cache-max-lifetime 5m
    -- @cache-min-rows 1
    SELECT id, name FROM users WHERE active = $1`, true)

Custom cacher

Implement the QueryCacher interface to use any cache backend:

type QueryCacher interface {
    Get(context.Context, *QueryKey) (*QueryItem, error)
    Set(context.Context, *QueryKey, *QueryItem, time.Duration) error
    Reset(context.Context) error
}

Annotation directives

Directive Value Description
@cache-max-lifetime <n>s, <n>m, <n>h How long to cache the result
@cache-min-rows <n> Skip caching if the result has fewer than n rows
@cache-max-rows <n> Skip caching if the result has more than n rows

Development

DevContainer

Open in VS Code with the Dev Containers extension. The environment provides Go, PostgreSQL 18, and Nix automatically.

PGX_DATABASE_URL=postgres://vscode@postgres:5432/pgxcache?sslmode=disable

Nix

nix develop          # enter shell with Go
go tool ginkgo run -r

Run tests

# Unit tests only (no database required)
go tool ginkgo run -r

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

License

MIT

About

Query result caching for pgx v5 — drop-in wrapper with inline SQL annotations, ristretto backend, and pluggable QueryCacher interface

Topics

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Contributors