Query result caching layer for pgx v5.
- Transparent caching of
Query,QueryRow,Exec, andSendBatchresults - Inline SQL annotation directives control caching per query
- Built-in
MemoryQueryCacherbacked by ristretto - Pluggable
QueryCacherinterface — bring your own backend (Redis, Memcached, etc.) - Works with any
pgx-compatible connection:*pgx.Conn,*pgxpool.Pool, orpgx.Tx
go get github.com/pgx-contrib/pgxcachepool, 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)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 = truerows, err := querier.Query(ctx, `
-- @cache-max-lifetime 5m
-- @cache-min-rows 1
SELECT id, name FROM users WHERE active = $1`, true)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
}| 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 |
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 develop # enter shell with Go
go tool ginkgo run -r# 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