Repository based on the pgx client
Help us grow this site 🚀. Disable your ad blocker to see non-intrusive ads
As we know, the pgx
package, in addition to the database/sql
compatible driver, also has its own DB client, which is faster and has more features, so it is even more recommended than the classic driver.
Let’s add a repository based on this client. Create a new file repository_postgresql_pgx.go
in the website
package. Then copy its contents, and let’s trace how such a repository differs from the one we previously created.
To use the
pgxpool
package, we need to add it to our project:go get github.com/jackc/pgx/v4/pgxpool
This repository is very similar to our classic database/sql
based repository. It differs actually only in two things:
- Instead of using the
sql.DB
to connect with the database, we use apgxpool.Pool
object here. Likesql.DB
, it represents a pool of connections to a database and is concurrency safe. - All the database methods we use are practically the same as in
database/sql
based repository, except that you always have to passcontext.Context
and there is no version without context. So we have theQuery()
method instead ofQueryContext()
,Exec()
instead ofExecContext()
, etc.
Using pgx
client is therefore not significantly different from using a database/sql
compatible driver. The authors of pgx
recommend this way of connecting to PostgreSQL but explain in more detail when to choose which version here.
website/repository_postgresql_pgx.go
|
|