Skip to content

Commit

Permalink
Added pgx tx options
Browse files Browse the repository at this point in the history
  • Loading branch information
aneshas committed Mar 18, 2024
1 parent 50dc32e commit bad2cc6
Show file tree
Hide file tree
Showing 4 changed files with 38 additions and 9 deletions.
3 changes: 0 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -141,6 +141,3 @@ This way, your infrastructural concerns stay in the infrastructure layer where t
## Testing
You can use `testtx.New()` as a convenient test helper. It creates a test transactor which only calls f without
setting any sort of transaction in the `ctx` and preserves any errors raised by f in `.Err` field.

## Next up
- Add isolation level configuration for individual drivers eg. through `pgxtx.NewDBFromPool(pool, ...opts)`
13 changes: 13 additions & 0 deletions pgxtxv5/option.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
package pgxtxv5

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

// PgxTxOption represents pgx driver transaction option
type PgxTxOption func(pool *Pool)

// WithTxOptions allows us to set transaction options (eg. isolation level)
func WithTxOptions(txOptions pgx.TxOptions) PgxTxOption {
return func(pool *Pool) {
pool.txOpts = txOptions
}
}
17 changes: 12 additions & 5 deletions pgxtxv5/pgx.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,21 +10,28 @@ import (
var _ tx.DB = &Pool{}

// NewDBFromPool instantiates new tx.DB *pgxpool.Pool wrapper
func NewDBFromPool(pool *pgxpool.Pool) tx.DB {
// We can extend these to be able to receive isolation options
// which would then be passed to tx.Begin
func NewDBFromPool(pool *pgxpool.Pool, opts ...PgxTxOption) tx.DB {
p := Pool{
Pool: pool,
}

return &Pool{pool}
for _, opt := range opts {
opt(&p)
}

return &p
}

// Pool implements tx.DB
type Pool struct {
*pgxpool.Pool

txOpts pgx.TxOptions
}

// Begin begins pgx transaction
func (p *Pool) Begin(ctx context.Context) (tx.Transaction, error) {
return p.Pool.Begin(ctx)
return p.Pool.BeginTx(ctx, p.txOpts)
}

// From returns underlying pgx.Tx from the context.
Expand Down
14 changes: 13 additions & 1 deletion pgxtxv5/pgx_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import (
"github.com/aneshas/tx/v2"
"github.com/aneshas/tx/v2/pgxtxv5"
"github.com/aneshas/tx/v2/testutil"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgxpool"
"github.com/stretchr/testify/assert"
"testing"
Expand All @@ -27,7 +28,18 @@ func TestMain(m *testing.M) {
func TestShould_Commit_Pgx_Transaction(t *testing.T) {
name := "success_pgx"

doPgx(t, tx.New(pgxtxv5.NewDBFromPool(db)), name, false)
doPgx(
t,
tx.New(
pgxtxv5.NewDBFromPool(
db,
pgxtxv5.WithTxOptions(pgx.TxOptions{}),
),
),
name,
false,
)

testutil.AssertSuccess(t, db, name)
}

Expand Down

0 comments on commit bad2cc6

Please sign in to comment.