diff --git a/README.md b/README.md index 7e78da7..50ca430 100644 --- a/README.md +++ b/README.md @@ -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)` \ No newline at end of file diff --git a/pgxtxv5/option.go b/pgxtxv5/option.go new file mode 100644 index 0000000..3200768 --- /dev/null +++ b/pgxtxv5/option.go @@ -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 + } +} diff --git a/pgxtxv5/pgx.go b/pgxtxv5/pgx.go index d8b12bb..963662d 100644 --- a/pgxtxv5/pgx.go +++ b/pgxtxv5/pgx.go @@ -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. diff --git a/pgxtxv5/pgx_test.go b/pgxtxv5/pgx_test.go index 5a2e27b..d35c7d4 100644 --- a/pgxtxv5/pgx_test.go +++ b/pgxtxv5/pgx_test.go @@ -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" @@ -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) }