Skip to content

pgx-contrib/pgxquery

Repository files navigation

pgxquery

CI Release Go Reference License Go pgx

A pgx QueryRewriter adapter that substitutes sentinel comments in your SQL with dynamic WHERE and ORDER BY fragments at query time. Write your SQL with /* AND query.where */ and /* , query.order_by */ markers, set the Where / OrderBy strings on a QueryRewriter, and let it splice them in — preserving your chosen connective or separator verbatim.

Installation

go get github.com/pgx-contrib/pgxquery

Usage

Place sentinel comments in your SQL at the positions where dynamic fragments should appear. Each sentinel has the form /* <prefix> query.<name> <suffix> */. The prefix and suffix (whitespace, connectives like AND/OR, separators like ,) are preserved around the substituted value; when the value is empty the whole sentinel is dropped.

type User struct {
    ID   int    `db:"id"`
    Name string `db:"name"`
    Role string `db:"role"`
}

rows, err := pool.Query(ctx,
    `SELECT id, name, role
       FROM users
      WHERE tenant_id = $1
        /* AND query.where */
      ORDER BY id
        /* , query.order_by */`,
    &pgxquery.QueryRewriter{
        Where:   "role = 'admin'",
        OrderBy: "name asc",
        Args:    []any{42},
    },
)

Recognised sentinel names are where and order_by. Args are appended to the positional parameters passed to pool.Query — so the $1 above is filled from Args[0]. When Where or OrderBy is empty, its sentinel is stripped entirely, leaving the surrounding SQL valid.

$N placeholders inside Where and OrderBy use local numbering: $1 refers to Args[0], $2 to Args[1], and so on. The rewriter shifts them by the count of base args so they hit the right slots in the final flat parameter list. Placeholders inside string literals, quoted identifiers, dollar-quoted bodies and SQL comments are left untouched.

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/pgxquery?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/pgxquery?sslmode=disable"
go tool ginkgo run -r

License

MIT

About

pgx QueryRewriter that injects dynamic WHERE and ORDER BY clauses via SQL sentinel comments — safe, parameterised, zero-magic

Topics

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Contributors