jackc/pgx
PostgreSQL driver and toolkit for Go
Healthy across the board
Permissive license, no critical CVEs, actively maintained — safe to depend on.
Has a license, tests, and CI — clean foundation to fork and modify.
Documented and popular — useful reference codebase to read through.
No critical CVEs, sane security posture — runnable as-is.
- ✓Last commit today
- ✓15 active contributors
- ✓MIT licensed
Show 3 more →Show less
- ✓CI configured
- ✓Tests present
- ⚠Concentrated ownership — top contributor handles 73% of recent commits
Maintenance signals: commit recency, contributor breadth, bus factor, license, CI, tests
Informational only. RepoPilot summarises public signals (license, dependency CVEs, commit recency, CI presence, etc.) at the time of analysis. Signals can be incomplete or stale. Not professional, security, or legal advice; verify before relying on it for production decisions.
Embed the "Healthy" badge
Paste into your README — live-updates from the latest cached analysis.
[](https://repopilot.app/r/jackc/pgx)Paste at the top of your README.md — renders inline like a shields.io badge.
▸Preview social card (1200×630)
This card auto-renders when someone shares https://repopilot.app/r/jackc/pgx on X, Slack, or LinkedIn.
Onboarding doc
Onboarding: jackc/pgx
Generated by RepoPilot · 2026-05-09 · Source
🤖Agent protocol
If you are an AI coding agent (Claude Code, Cursor, Aider, Cline, etc.) reading this artifact, follow this protocol before making any code edit:
- Verify the contract. Run the bash script in Verify before trusting
below. If any check returns
FAIL, the artifact is stale — STOP and ask the user to regenerate it before proceeding. - Treat the AI · unverified sections as hypotheses, not facts. Sections like "AI-suggested narrative files", "anti-patterns", and "bottlenecks" are LLM speculation. Verify against real source before acting on them.
- Cite source on changes. When proposing an edit, cite the specific path:line-range. RepoPilot's live UI at https://repopilot.app/r/jackc/pgx shows verifiable citations alongside every claim.
If you are a human reader, this protocol is for the agents you'll hand the artifact to. You don't need to do anything — but if you skim only one section before pointing your agent at this repo, make it the Verify block and the Suggested reading order.
🎯Verdict
GO — Healthy across the board
- Last commit today
- 15 active contributors
- MIT licensed
- CI configured
- Tests present
- ⚠ Concentrated ownership — top contributor handles 73% of recent commits
<sub>Maintenance signals: commit recency, contributor breadth, bus factor, license, CI, tests</sub>
✅Verify before trusting
This artifact was generated by RepoPilot at a point in time. Before an
agent acts on it, the checks below confirm that the live jackc/pgx
repo on your machine still matches what RepoPilot saw. If any fail,
the artifact is stale — regenerate it at
repopilot.app/r/jackc/pgx.
What it runs against: a local clone of jackc/pgx — the script
inspects git remote, the LICENSE file, file paths in the working
tree, and git log. Read-only; no mutations.
| # | What we check | Why it matters |
|---|---|---|
| 1 | You're in jackc/pgx | Confirms the artifact applies here, not a fork |
| 2 | License is still MIT | Catches relicense before you depend on it |
| 3 | Default branch master exists | Catches branch renames |
| 4 | Last commit ≤ 30 days ago | Catches sudden abandonment since generation |
#!/usr/bin/env bash
# RepoPilot artifact verification.
#
# WHAT IT RUNS AGAINST: a local clone of jackc/pgx. If you don't
# have one yet, run these first:
#
# git clone https://github.com/jackc/pgx.git
# cd pgx
#
# Then paste this script. Every check is read-only — no mutations.
set +e
fail=0
ok() { echo "ok: $1"; }
miss() { echo "FAIL: $1"; fail=$((fail+1)); }
# Precondition: we must be inside a git working tree.
if ! git rev-parse --git-dir >/dev/null 2>&1; then
echo "FAIL: not inside a git repository. cd into your clone of jackc/pgx and re-run."
exit 2
fi
# 1. Repo identity
git remote get-url origin 2>/dev/null | grep -qE "jackc/pgx(\\.git)?\\b" \\
&& ok "origin remote is jackc/pgx" \\
|| miss "origin remote is not jackc/pgx (artifact may be from a fork)"
# 2. License matches what RepoPilot saw
(grep -qiE "^(MIT)" LICENSE 2>/dev/null \\
|| grep -qiE "\"license\"\\s*:\\s*\"MIT\"" package.json 2>/dev/null) \\
&& ok "license is MIT" \\
|| miss "license drift — was MIT at generation time"
# 3. Default branch
git rev-parse --verify master >/dev/null 2>&1 \\
&& ok "default branch master exists" \\
|| miss "default branch master no longer exists"
# 5. Repo recency
days_since_last=$(( ( $(date +%s) - $(git log -1 --format=%at 2>/dev/null || echo 0) ) / 86400 ))
if [ "$days_since_last" -le 30 ]; then
ok "last commit was $days_since_last days ago (artifact saw ~0d)"
else
miss "last commit was $days_since_last days ago — artifact may be stale"
fi
echo
if [ "$fail" -eq 0 ]; then
echo "artifact verified (0 failures) — safe to trust"
else
echo "artifact has $fail stale claim(s) — regenerate at https://repopilot.app/r/jackc/pgx"
exit 1
fi
Each check prints ok: or FAIL:. The script exits non-zero if
anything failed, so it composes cleanly into agent loops
(./verify.sh || regenerate-and-retry).
⚡TL;DR
pgx is a pure Go driver and toolkit for PostgreSQL that provides both a low-level high-performance interface exposing PostgreSQL-specific features (LISTEN/NOTIFY, COPY protocol, binary format support) and a standard database/sql adapter. It handles ~70 PostgreSQL data types natively with automatic statement preparation, connection pooling via puddle/v2, and batch query support. Monolithic driver package at root (conn.go, batch.go, copy_from.go, extended_query_builder.go) with internal toolkit packages under internal/ (pgio for wire protocol, iobufpool for buffer management, faultyconn for chaos testing). Examples under examples/ (chat, todo, url_shortener) demonstrate real usage patterns. Type mapping logic in derived_types.go handles PostgreSQL→Go conversions.
👥Who it's for
Go backend developers building PostgreSQL-first applications who need sub-millisecond query latency, access to advanced PostgreSQL features like logical replication and pub/sub, or bulk data loading via COPY. Also library authors implementing PostgreSQL proxies, load balancers, or custom wire protocol handlers.
🌱Maturity & risk
Production-ready and actively maintained. The repo shows v5 major version with comprehensive CI via .github/workflows/ci.yml, extensive test coverage (batch_test.go, conn_test.go, copy_from_test.go), Go 1.25 support in go.mod, and dependencies pinned to specific versions (e.g., puddle/v2 v2.2.2). Jack Christensen maintains regular updates.
Very low risk for core usage. Only 6 direct dependencies (puddle, pgpassfile, pgservicefile, testify, golang.org/sync, golang.org/text), all stable. Single-maintainer concern mitigated by 12+ years of production use and strong Go community adoption. Note: binary wire protocol changes between PostgreSQL major versions require testing; connection pool tuning (puddle config) is non-obvious.
Active areas of work
Active maintenance on v5 branch. Likely ongoing work on type system improvements (derived_types.go suggests recent type handling enhancements), connection pool optimization via puddle updates, and PostgreSQL version compatibility. CI pipeline running on every commit; CHANGELOG.md and CLAUDE.md suggest structured release notes.
🚀Get running
git clone https://github.com/jackc/pgx.git && cd pgx && go mod download && go test ./... (requires running PostgreSQL instance). See ci/setup_test.bash for test database configuration. Examples runnable via: cd examples/chat && go run main.go.
Daily commands: No dev server—this is a driver library. To test: DATABASE_URL='postgres://user:pass@localhost/testdb' go test ./... from repo root. Individual examples: cd examples/todo && go run main.go (requires PostgreSQL at localhost:5432). Use ci/setup_test.bash to initialize test database schema.
🗺️Map of the codebase
- conn.go: Core connection type implementing QueryRow, Exec, Query; handles prepared statements, transaction lifecycle, and context cancellation.
- batch.go: Batch query execution bundling multiple statements into single round-trip; critical for performance in bulk operations.
- copy_from.go: Implements PostgreSQL COPY protocol for streaming bulk inserts—2-10x faster than individual INSERTs.
- derived_types.go: Type codec registry mapping PostgreSQL OIDs to Go type handlers; handles custom arrays, JSON, hstore, inet/cidr netip conversion.
- internal/pgio/README.md: Documents wire protocol read/write primitives; essential for understanding how pgx marshals requests and unmarshals responses.
- extended_query_builder.go: Builds extended query protocol messages (Parse/Bind/Execute); foundation for prepared statement handling.
- go.mod: Explicitly declares v5 major version and Go 1.25 minimum; puddle/v2 is critical for connection pooling.
- .github/workflows/ci.yml: CI configuration testing against multiple PostgreSQL versions (10, 12, 14, 16) and Go versions; shows compatibility matrix.
🛠️How to make changes
For bug fixes in core driver: edit conn.go (connection lifecycle), batch.go (batch query logic), or copy_from.go (COPY protocol). For new type support: extend derived_types.go codec registry. For wire protocol changes: modify internal/pgio. For tests: add cases to *_test.go files matching the component. Verify with: go test ./... && go vet ./...
🪤Traps & gotchas
- DATABASE_URL environment variable required for tests; must include test user with createdb permissions. 2) PostgreSQL server must be running on localhost:5432 by default—ci/setup_test.bash initializes schema. 3) Type OID mapping is version-specific; custom types may have different OIDs across PostgreSQL major versions. 4) Connection pool tuning (MaxConns, MinConns in pgxpool.Config) is mandatory for production—defaults are conservative. 5) COPY protocol fails if transaction isolation level is SERIALIZABLE. 6) Binary format for custom types requires codec registration before use (RegisterDefaultTypesForFormat in derived_types.go). 7) Prepared statements are driver-scoped; each conn.Prepare() creates server-side prepared statement consuming server memory.
💡Concepts to learn
- PostgreSQL Extended Query Protocol — pgx uses Parse/Bind/Execute messages (not simple protocol) for prepared statements and security—understanding this wire protocol layer explains why prepared statements are cached per-connection and why binding happens at execution time.
- PostgreSQL COPY Protocol — copy_from.go implements COPY for bulk inserts—this binary streaming protocol is 2-10x faster than individual INSERTs but requires understanding message framing and error handling.
- Type OID (Object Identifier) Mapping — PostgreSQL identifies types by 32-bit OIDs; derived_types.go maps OIDs to Go codec handlers. Custom types have version-dependent OIDs, making type registration fragile across PostgreSQL versions.
- Connection Pooling with Puddle — pgx uses puddle/v2 for FIFO connection pools with configurable MinConns/MaxConns. Pool tuning (idle timeout, health checks, acquire timeouts) is critical for production stability and prevents resource exhaustion.
- Binary Format for PostgreSQL Types — pgx can encode/decode types in PostgreSQL's binary format (not just text)—dramatically faster for large payloads like arrays or JSON, but requires per-type codec implementation.
- Prepared Statement Server-Side Caching — conn.Prepare() creates persistent server-side prepared statements that consume server memory; pgx implements LRU-like eviction to prevent exhaustion, visible in batch.go and extended_query_builder.go.
- PostgreSQL Savepoints for Nested Transactions — pgx simulates nested transactions using SAVEPOINT commands (Go's context doesn't natively support nested transactions); important for error recovery in complex workflows without full ROLLBACK.
🔗Related repos
lib/pq— Older pure-Go PostgreSQL driver (database/sql only); pgx replaces it for most new projects but pq remains a lower-level alternative if you need minimal dependencies.jackc/puddle— Connection pool library that pgx depends on (puddle/v2 in go.mod); used for managing prepared statement and connection pooling logic.jackc/pgpassfile— Companion library pgx depends on for parsing ~/.pgpass password files; critical for production connection string authentication.jackc/pgservicefile— Companion library pgx depends on for parsing ~/.pg_service.conf configuration files; simplifies connection URL management in production environments.golang-migrate/migrate— Database migration tool commonly paired with pgx for schema versioning; complements pgx's raw SQL execution capabilities.
🪄PR ideas
To work on one of these in Claude Code or Cursor, paste:
Implement the "<title>" PR idea from CLAUDE.md, working through the checklist as the task list.
Add comprehensive benchmarks for extended_query_builder.go
The repo has bench_test.go but extended_query_builder.go lacks dedicated performance tests. Given that query building is a hot path in database drivers, adding benchmarks would help track performance regressions and guide optimization efforts. This is especially valuable since pgx emphasizes high performance.
- [ ] Create extended_query_builder_bench_test.go with benchmarks for common query patterns
- [ ] Benchmark parameter binding, placeholder substitution, and cache hit/miss scenarios
- [ ] Run benchmarks against the existing implementation to establish baseline metrics
- [ ] Document expected performance characteristics in internal/stmtcache/stmtcache.go comments
Add integration tests for derived_types.go functionality
derived_types.go and derived_types_test.go exist, but the test file appears minimal. Given that type mapping between PostgreSQL and Go is core to pgx's toolkit component (mentioned in README), comprehensive integration tests covering edge cases in custom type handling would be valuable. These tests should cover real PostgreSQL type scenarios.
- [ ] Expand derived_types_test.go with tests for composite types, arrays of derived types, and NULL handling
- [ ] Add integration tests that actually connect to test PostgreSQL database (use ci/setup_test.bash as reference)
- [ ] Test round-trip serialization/deserialization of complex derived types
- [ ] Document type mapping behavior in doc.go with examples
Add Windows-specific CI workflow and socket connection tests
.github/workflows/ci.yml likely runs on Linux/macOS only. pgx supports Unix domain sockets (conn.go references socket connections) but Windows uses named pipes. Adding Windows CI and socket connection tests would ensure cross-platform reliability and prevent Windows-specific regressions.
- [ ] Add windows-latest runner to .github/workflows/ci.yml alongside existing Linux runner
- [ ] Create conn_windows_test.go with named pipe connection tests (complement existing conn_test.go)
- [ ] Test connection string parsing for Windows-specific paths in conn.go
- [ ] Verify internal/pgio read/write operations work correctly on Windows I/O primitives
🌿Good first issues
- Add missing test coverage for helper_test.go functions—currently no dedicated *_test.go file for helper utilities like prepared statement caching logic. Start by examining what utilities exist in helper_test.go and writing isolated unit tests.
- Document the internal/pgio wire protocol package with concrete examples—internal/pgio/README.md exists but lacks code examples showing how to read/write specific PostgreSQL message types. Add Go snippets showing MessageType, ReadInt32, WriteString patterns.
- Implement connection diagnostic tooling: add methods to Conn to expose prepared statement cache stats and connection pool metrics. Currently no visibility into cache hit rates or pool saturation—write a helper function returning CacheStats{HitRate, StatementCount, EvictionCount}.
- Add more PostgreSQL type examples to examples/ directory—currently examples/chat, examples/todo, examples/url_shortener exist but lack examples for COPY bulk loading, LISTEN/NOTIFY pub/sub, or custom array/composite type handling. Create examples/bulk_copy_demo with COPY protocol showcase.
- Expand derived_types_test.go with round-trip tests for edge cases—test NULL handling, empty arrays, nested structures. Currently only basic type mapping tested; add parametric tests covering PostgreSQL 10, 12, 14, 16 type OID variations.
⭐Top contributors
Click to expand
Top contributors
- @jackc — 73 commits
- @abrightwell — 4 commits
- @dbussink — 3 commits
- @JelteF — 3 commits
- @makalaaneesh — 3 commits
📝Recent commits
Click to expand
Recent commits
82b212c— Merge pull request #2536 from Tubelight30/feat/struct-args-named-query (jackc)d2ed749— Fix data race when context cancelled during connect (jackc)cfd733d— Merge pull request #2543 from alexandear-org/enable-unconvert (jackc)3f10c33— update linters in CLAUDE.md (alexandear)23bdaad— Enable unconvert linter (alexandear)c00cd65— Example conn string uses dbname instead of database (jackc)0b4a1ad— Merge pull request #2539 from alliasgher/docs/1900-array-agg-slice (jackc)53941bc— Merge pull request #2532 from alliasgher/fix-kv-trailing-whitespace (jackc)7728d2d— docs: explain scanning array_agg (and other PG arrays) into Go slices (alliasgher)0aeabbc— Release v5.9.2 (jackc)
🔒Security observations
- Medium · Potential SQL Injection via Named Arguments —
named_args.go, internal/sanitize/. The file 'named_args.go' suggests dynamic SQL query construction with named arguments. If user input is not properly sanitized before being used in SQL queries, this could lead to SQL injection attacks. The presence of 'internal/sanitize' package indicates awareness of this risk, but improper usage could still occur. Fix: Ensure all SQL query construction uses parameterized queries exclusively. Audit named_args.go implementation to verify proper input validation and sanitization. Review all usages of the sanitize package to ensure comprehensive coverage. - Medium · SCRAM Authentication Implementation Review —
pgconn/auth_scram.go. The file 'pgconn/auth_scram.go' handles SCRAM authentication. Cryptographic implementations can be error-prone. Potential issues include improper handling of nonces, salts, or password hashing algorithms. Fix: Conduct a security audit of the SCRAM implementation against RFC 5802 specification. Verify proper use of cryptographic libraries (golang.org/x/crypto). Ensure nonce generation uses cryptographically secure random sources. - Medium · OAuth Authentication Handling —
pgconn/auth_oauth.go. The file 'pgconn/auth_oauth.go' implements OAuth authentication. Token handling and redirect URI validation are critical security concerns. Improper implementation could lead to token leakage or authorization bypass. Fix: Review OAuth token storage and transmission. Ensure tokens are not logged or exposed in error messages. Validate redirect URIs against a whitelist. Use secure, encrypted storage for sensitive credentials. - Low · Connection String Parsing —
pgconn/config.go. The file 'pgconn/config.go' handles connection string parsing. Complex parsing logic could be vulnerable to bypass attacks or information disclosure if error messages reveal connection details. Fix: Review error messages to ensure they don't expose sensitive connection information. Validate all connection string parameters. Document expected formats and validate against them strictly. - Low · Dependency Management —
go.mod. While dependencies appear current, golang.org/x/text v0.29.0 and golang.org/x/sync v0.17.0 should be regularly monitored. The go.mod specifies go 1.25.0 which may not be widely available yet. Fix: Regularly run 'go list -u -m all' to check for outdated dependencies. Subscribe to security advisories for all dependencies. Consider using tools like 'nancy' or 'snyk' for automated vulnerability scanning. - Low · Test Database Credentials in Examples —
examples/chat/main.go, examples/todo/main.go, examples/url_shortener/main.go. Example files in the 'examples/' directory may contain hardcoded database credentials or connection strings used for testing. Fix: Ensure examples use environment variables or configuration files for database credentials, not hardcoded values. Add clear documentation that credentials should never be hardcoded in production code. - Low · Large Objects Handling —
large_objects.go, large_objects_test.go. The 'large_objects.go' file handles file-like operations on database objects. Improper bounds checking or resource cleanup could lead to denial of service or resource leaks. Fix: Verify that large object operations have proper size limits and timeout handling. Ensure file descriptors/handles are properly cleaned up in all code paths, including error cases. - Low · Context Watching in pgconn —
pgconn/ctxwatch/context_watcher.go. The 'pgconn/ctxwatch/context_watcher.go' implements context deadline handling. Improper implementation could lead to resource leaks or race conditions. Fix: Review for proper goroutine cleanup. Use race detector during testing: 'go test -race ./...'. Verify no goroutine leaks with tools like 'goleak'. - Info · Security Testing Coverage —
undefined. No dedicated security test files found (e.g., security_test.go, fuzz_test.go for critical paths). The project has basic fuzzing Fix: undefined
LLM-derived; treat as a starting point, not a security audit.
👉Where to read next
- Open issues — current backlog
- Recent PRs — what's actively shipping
- Source on GitHub
Generated by RepoPilot. Verdict based on maintenance signals — see the live page for receipts. Re-run on a new commit to refresh.