pgx是一款纯go的PostgreSQL工具集。pgx是一个低级、高性能的PostgreSQL驱动,支持PostgreSQL特定的功能,比如LISTEN、NOTIFY、COPY,也支持标准的database/sql接口。
工具集组件包含一组实现PostgreSQL相关功能的包,比如PostgreSQL协议、PostgreSQL与GO之间的类型映射。这些底层包可用于实现替代驱动程序、代理、负载均衡、逻辑复制客户端等。
主要功能有:
- 支持大约70种PostgreSQL类型
- Automatic statement preparation and caching
- Batch queries
- Single-round trip query mode
- Full TLS connection control
- Binary format support for custom types (allows for much quicker encoding/decoding)
- COPY protocol support for faster bulk data loads
- Tracing and logging support
- Connection pool with after-connect hook for arbitrary connection setup
- LISTEN / NOTIFY
- Conversion of PostgreSQL arrays to Go slice mappings for integers, floats, and strings
- hstore support
- json and jsonb support
- Maps inet and cidr PostgreSQL types to netip.Addr and netip.Prefix
- Large object support
- NULL mapping to pointer to pointer
- Supports database/sql.Scanner and database/sql/driver.Valuer interfaces for custom types
- Notice response handling
- Simulated nested transactions with savepoints
使用也很简单:
packagemainimport ( "context""fmt""os""github.com/jackc/pgx/v5") funcmain() { // urlExample := "postgres://username:password@localhost:5432/database_name"conn, err :=pgx.Connect(context.Background(), os.Getenv("DATABASE_URL")) iferr!=nil { fmt.Fprintf(os.Stderr, "Unable to connect to database: %v\n", err) os.Exit(1) } deferconn.Close(context.Background()) varnamestringvarweightint64err=conn.QueryRow(context.Background(), "select name, weight from widgets where id=$1", 42).Scan(&name, &weight) iferr!=nil { fmt.Fprintf(os.Stderr, "QueryRow failed: %v\n", err) os.Exit(1) } fmt.Println(name, weight) }
下面是使用连接池的例子(需要github.com/jackc/pgx/v4/pgxpool):
urlExample :="postgres://username:password@localhost:5432/database_name"config, err :=pgxpool.ParseConfig(urlExample) iferr!=nil { log.Panic("parse database config failed", zap.Error(err)) } ctx :=context.Background() pool, err :=pgxpool.ConnectConfig(ctx, config) iferr!=nil { log.Panic("Connect database failed", zap.Error(err)) } pool.Query(ctx, sql, arg1, arg2,...)
使用pgx还是database/sql接口?
pgx接口速度更快,许多PostgreSQL特有的功能,如LISTEN/NOTIFY、COPY,不能通过database/sql接口使用。
建议在以下情况下使用pgx接口:
1.该应用程序仅针对PostgreSQL。
2.没有使用其他需要database/sql的库。
也可以使用database/sql接口做一些日常操作,并根据需要将连接转换到较低级别的pgx接口去执行一些特殊的操作。