Go has very rich standard library which also contains
database/sql
module with generic interface over SQL databases. Further,
lib/pq
PostgreSQL
driver is fully compatible with database/sql
and provides all basic database operations. However, since this is generic implementation over all supported databases, using it is a trade-off not supporting some PostgreSQL specific features. Fans of PostgreSQL
(in further text pg
) may want more and here comes
pgx
in help. pgx
is a very rich pg
driver supporting LISTEN / NOTIFY
, COPY
, type mapping between pg
and Go
, all specific pg
types, wire protocol and much more.
In the latest version v5
, maintainer of pgx
starting using generics in the project and introduced many new features including:
- new tracing logger with hooks for tools like OpenTelemetry
CollectRows
function to collect results into a slice usingRowTo*
functionsCollectOneRow
function to collect one row also usingRowTo*
functionsRowToStructByName
andRowToStructByPos
functions to scan rows intoGo
struct typesForEachRow
function to iterate over resulting rows and perform an arbitrary functionQueryRewriter
interface andNamedArgs
implementation for named query parameters- improved
SendBatch
function
It this series we are going to cover all of these changes and try to disclose some of the pgx
secrets, specially the new ones. In order to make our code able to access the pg
database, we are goint to create the following docker-compose.yml
file in our project:
|
|
And also some initial database schema in .docker/schema.sql
:
|
|
As you can see in the last snippet, we are going to use some fancy pg
features like domain
and enum
types, constraint checks and
xid
as a primary key.
To initialize Go
project, just type go mod init
following by the name by your choice, e.g. go mod init pgx5
and create main.go
file with the following contents:
|
|
In this snippet we created the pgx
connection pool and now we are ready for the next part of the series where we will discuss on QueryRewriter
interface and NamedArgs
implementation. Stay tuned.