https://github.com/nicolasparada/go-db
Wrapper over pgx with better transaction API
https://github.com/nicolasparada/go-db
go go-module go-package golang
Last synced: about 1 year ago
JSON representation
Wrapper over pgx with better transaction API
- Host: GitHub
- URL: https://github.com/nicolasparada/go-db
- Owner: nicolasparada
- License: isc
- Created: 2023-02-21T20:26:16.000Z (over 3 years ago)
- Default Branch: main
- Last Pushed: 2025-04-14T19:09:48.000Z (about 1 year ago)
- Last Synced: 2025-04-19T13:39:25.744Z (about 1 year ago)
- Topics: go, go-module, go-package, golang
- Language: Go
- Homepage:
- Size: 89.8 KB
- Stars: 5
- Watchers: 1
- Forks: 1
- Open Issues: 3
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
# Golang Database Wrapper
[](https://pkg.go.dev/github.com/nicolasparada/go-db)
```bash
go get github.com/nicolasparada/go-db
```
Simple Golang database wrapper over [github.com/jackc/pgx/v5](https://github.com/jackc/pgx) with better transactions API.
Specifically designed to work with [CockroachDB](https://cockroachlabs.com).
Instead of starting a transaction, commiting (or rolling back) each time,
you simply pass a callback function. This allows for defining methods
over a single database object and you can either run them standalone
or inside a transaction.
```go
type Repo struct {
db *db.DB
}
func (repo *Repo) Insert(ctx context.Context) error {
repo.db.Exec(ctx, "INSERT INTO ...")
}
func (repo *Repo) Update(ctx context.Context) error {
repo.db.Exec(ctx, "UPDATE ... SET ...")
}
func (repo *Repo) InsertAndUpdate(ctx context.Context) error {
return repo.db.RunTx(ctx, func(ctx context.Context) error {
repo.Insert(ctx)
repo.Update(ctx)
})
}
```
## How it works?
When you call `RunTx` it starts a new transaction and saves that object inside context. Calls to `Query`, `QueryRow` and `Exec` will check on the context and will either use the new transaction object or take a connection directly from the pool.