Skip to content

Commit

Permalink
feat: allow passing options to a new transaction
Browse files Browse the repository at this point in the history
  • Loading branch information
zepatrik authored and stanislas-m committed Sep 24, 2020
1 parent b1085ba commit 5ce72a7
Show file tree
Hide file tree
Showing 3 changed files with 17 additions and 4 deletions.
9 changes: 7 additions & 2 deletions db.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package pop

import (
"context"
"database/sql"

"github.com/jmoiron/sqlx"
)
Expand All @@ -11,11 +12,15 @@ type dB struct {
}

func (db *dB) TransactionContext(ctx context.Context) (*Tx, error) {
return newTX(ctx, db)
return newTX(ctx, db, nil)
}

func (db *dB) Transaction() (*Tx, error) {
return newTX(context.Background(), db)
return newTX(context.Background(), db, nil)
}

func (db *dB) TransactionContextOptions(ctx context.Context, opts *sql.TxOptions) (*Tx, error) {
return newTX(ctx, db, opts)
}

func (db *dB) Rollback() error {
Expand Down
1 change: 1 addition & 0 deletions store.go
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ type store interface {
ExecContext(context.Context, string, ...interface{}) (sql.Result, error)
PrepareNamedContext(context.Context, string) (*sqlx.NamedStmt, error)
TransactionContext(context.Context) (*Tx, error)
TransactionContextOptions(context.Context, *sql.TxOptions) (*Tx, error)
}

// ContextStore wraps a store with a Context, so passes it with the functions that don't take it.
Expand Down
11 changes: 9 additions & 2 deletions tx.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package pop

import (
"context"
"database/sql"
"math/rand"
"time"

Expand All @@ -19,11 +20,11 @@ type Tx struct {
*sqlx.Tx
}

func newTX(ctx context.Context, db *dB) (*Tx, error) {
func newTX(ctx context.Context, db *dB, opts *sql.TxOptions) (*Tx, error) {
t := &Tx{
ID: rand.Int(),
}
tx, err := db.BeginTxx(ctx, nil)
tx, err := db.BeginTxx(ctx, opts)
t.Tx = tx
return t, errors.Wrap(err, "could not create new transaction")
}
Expand All @@ -34,6 +35,12 @@ func (tx *Tx) TransactionContext(ctx context.Context) (*Tx, error) {
return tx, nil
}

// TransactionContextOptions simply returns the current transaction,
// this is defined so it implements the `Store` interface.
func (tx *Tx) TransactionContextOptions(_ context.Context, _ *sql.TxOptions) (*Tx, error) {
return tx, nil
}

// Transaction simply returns the current transaction,
// this is defined so it implements the `Store` interface.
func (tx *Tx) Transaction() (*Tx, error) {
Expand Down

0 comments on commit 5ce72a7

Please sign in to comment.