pgx README

The project's README from github.com/jackc/pgx. As one markdown file: README.md.

Go Reference Build Status

pgx - PostgreSQL Driver and Toolkit

pgx is a pure Go driver and toolkit for PostgreSQL.

The pgx driver is a low-level, high performance interface that exposes PostgreSQL-specific features such as LISTEN / NOTIFY and COPY. It also includes an adapter for the standard database/sql interface.

The toolkit component is a related set of packages that implement PostgreSQL functionality such as parsing the wire protocol and type mapping between PostgreSQL and Go. These underlying packages can be used to implement alternative drivers, proxies, load balancers, logical replication clients, etc.

Quick Start

Installation

go get github.com/jackc/pgx/v5

Example Usage

package main

import (
	"context"
	"fmt"
	"os"

	"github.com/jackc/pgx/v5"
)

func main() {
	// urlExample := "postgres://username:password@localhost:5432/database_name"
	conn, err := pgx.Connect(context.Background(), os.Getenv("DATABASE_URL"))
	if err != nil {
		fmt.Fprintf(os.Stderr, "Unable to connect to database: %v\n", err)
		os.Exit(1)
	}
	defer conn.Close(context.Background())

	var name string
	var weight int64
	err = conn.QueryRow(context.Background(), "select name, weight from widgets where id=$1", 42).Scan(&name, &weight)
	if err != nil {
		fmt.Fprintf(os.Stderr, "QueryRow failed: %v\n", err)
		os.Exit(1)
	}

	fmt.Println(name, weight)
}

Connection Configuration

pgx.Connect and pgxpool.New accept PostgreSQL connection URLs (such as postgres://user:pass@host:5432/db?sslmode=verify-full) as well as key=value strings. See pgconn.ParseConfig and the PostgreSQL connection string documentation for supported options and environment variables.

For a step-by-step walkthrough, see the getting started guide.

Documentation

Package documentation and API reference are available on pkg.go.dev:

Features

Choosing Between the pgx and database/sql Interfaces

The pgx interface is faster. Many PostgreSQL specific features such as LISTEN / NOTIFY and COPY are not available through the database/sql interface.

The pgx interface is recommended when:

  1. The application only targets PostgreSQL.
  2. No other libraries that require database/sql are in use.

It is also possible to use the database/sql interface and convert a connection to the lower-level pgx interface as needed.

Development and Testing

Each checkout has its own PostgreSQL 14-18 clusters and CockroachDB node, so the whole test matrix is available locally on macOS, on Linux, or in the included devcontainer. Only PostgreSQL 18 stays running by default; other targets start and stop around their tests:

scripts/setup-host # native macOS (Homebrew required) or Ubuntu: host packages and mise
export PATH="$HOME/.local/bin:$PATH" # if mise was just installed
mise trust
mise install        # project tools
mise run dev:init   # checkout ports and certificates
mise run dev        # start PostgreSQL 18 and the on-demand database supervisor
./test.sh           # the suite against PostgreSQL 18
./test.sh all       # every target, starting and stopping each server as needed

Host setup installs PostgreSQL 14-18 and Ruby build dependencies. It does not install project tools or initialize the checkout; those remain separate steps above. The devcontainer already provides the host prerequisites.

See DEVELOPMENT.md for the full setup, and CONTRIBUTING.md for how to contribute — including how to run the tests against a PostgreSQL server you already have, without any of the above.

Architecture

See the presentation at Golang Estonia, PGX Top to Bottom for a description of pgx architecture.

Supported Go and PostgreSQL Versions

pgx supports the same versions of Go and PostgreSQL that are supported by their respective teams. For Go that is the two most recent major releases and for PostgreSQL the major releases in the last 5 years. This means pgx supports Go 1.25 and higher and PostgreSQL 14 and higher. pgx also is tested against the latest version of CockroachDB.

Version Policy

pgx follows semantic versioning for the documented public API on stable releases. v5 is the latest stable major version.

PGX Family Libraries

github.com/jackc/pglogrepl

pglogrepl provides functionality to act as a client for PostgreSQL logical replication.

github.com/jackc/pgmock

pgmock offers the ability to create a server that mocks the PostgreSQL wire protocol. This is used internally to test pgx by purposely inducing unusual errors. pgproto3 and pgmock together provide most of the foundational tooling required to implement a PostgreSQL proxy or MitM (such as for a custom connection pooler).

github.com/jackc/tern

tern is a stand-alone SQL migration system.

github.com/jackc/pgerrcode

pgerrcode contains constants for the PostgreSQL error codes.

Adapters for 3rd Party Types

Adapters for 3rd Party Tracers

Adapters for 3rd Party Loggers

These adapters can be used with the tracelog package.

3rd Party Libraries with PGX Support

github.com/pashagolub/pgxmock

pgxmock is a mock library implementing pgx interfaces. pgxmock has one and only purpose - to simulate pgx behavior in tests, without needing a real database connection.

github.com/georgysavva/scany

Library for scanning data from a database into Go structs and more.

github.com/vingarcia/ksql

A carefully designed SQL client for making using SQL easier, more productive, and less error-prone on Golang.

github.com/otan/gopgkrb5

Adds GSSAPI / Kerberos authentication support.

github.com/wcamarao/pmx

Explicit data mapping and scanning library for Go structs and slices.

github.com/stephenafamo/scan

Type safe and flexible package for scanning database data into Go types. Supports, structs, maps, slices and custom mapping functions.

github.com/z0ne-dev/mgx

Code first migration library for native pgx (no database/sql abstraction).

github.com/amirsalarsafaei/sqlc-pgx-monitoring

A database monitoring/metrics library for pgx and sqlc. Trace, log and monitor your sqlc query performance using OpenTelemetry.

https://github.com/nikolayk812/pgx-outbox

Simple Golang implementation for transactional outbox pattern for PostgreSQL using jackc/pgx driver.

https://github.com/Arlandaren/pgxWrappy

Simplifies working with the pgx library, providing convenient scanning of nested structures.

https://github.com/KoNekoD/pgx-colon-query-rewriter

Implementation of the pgx query rewriter to use ':' instead of '@' in named query parameters.

pgx (jackc/pgx)

Searching Database…

14.3K ·GitHub
这是什么?pgx 是一个用于 PostgreSQL 的纯 Go 驱动和工具包,提供底层、高性能的接口,支持 LISTEN/NOTIFY、COPY 等 PostgreSQL 专有功能,同时还提供适配标准 database/sql 接口的适配器。
它是 database/sql 驱动,还是别的什么?两者都是:它既是一个原生的 pgx 驱动,拥有更快的自有接口,也是一套底层包的工具集(包括线路协议解析、类型映射),这些包还可用于构建其他驱动、代理或负载均衡器。另外,stdlib 适配器也允许你通过 database/sql 使用它。
怎样把它加到项目里?在你的 Go 模块中导入 pgx 包,然后使用 PostgreSQL 连接 URL(例如 postgres://user:pass@host:5432/db?sslmode=verify-full)或 key=value 格式的字符串,通过 pgx.Connect 或 pgxpool.New 进行连接。
它需要哪些 Go 和 PostgreSQL 版本?pgx 支持最近两个主要 Go 版本,以及过去 5 年内发布的 PostgreSQL 版本,目前为 Go 1.25+ 和 PostgreSQL 14 及以上。它也已在最新版 CockroachDB 上进行测试。
我应该用 pgx 接口,还是继续用 database/sql?如果你的应用只面向 PostgreSQL,并且不需要依赖 database/sql 的其他库,就使用原生 pgx 接口,它更快,并且能使用 PostgreSQL 专有功能。你也可以使用 database/sql,需要时再切换到 pgx 接口。
开发和测试能在任何操作系统上运行吗?可以。完整的测试矩阵(包括 PostgreSQL 14-18 集群和一个 CockroachDB 节点)可以在 macOS 或 Linux 上本地运行,也可以在随附的 devcontainer 中运行。
pgx 开箱即用支持哪些 PostgreSQL 专有功能?约 70 种 PostgreSQL 类型、LISTEN/NOTIFY、用于批量加载的 COPY 协议、批量查询、二进制格式编码、hstore/json/jsonb 支持、大对象,以及通过保存点模拟的嵌套事务。
pgx 家族有哪些相关库?有的——pglogrepl 用于逻辑复制,pgmock 用于模拟 PostgreSQL 线路协议,tern 用于 SQL 迁移,pgerrcode 提供 PostgreSQL 错误码常量,此外还有许多第三方适配器,用于 UUID/decimal 类型、追踪器和日志记录器。
测试时能在没有真实数据库的情况下模拟 pgx 吗?可以,第三方库 pgxmock 专门实现了 pgx 接口,用于在测试中模拟 pgx 的行为,无需真实的数据库连接。
pgx 遵循语义化版本吗?遵循。对于稳定版本,pgx 对其已文档化的公共 API 遵循语义化版本,目前最新的稳定主版本是 v5。
Creator
jackc
Size
6.7 MB
Stars
14.3K
Age
13y
Commits · 90 Days