Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: allow passing options to a new transaction #594

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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