github.com/nshntarora/pop@v0.1.2/tx.go (about)

     1  package pop
     2  
     3  import (
     4  	"context"
     5  	"database/sql"
     6  	"fmt"
     7  	"math/rand"
     8  	"time"
     9  
    10  	"github.com/jmoiron/sqlx"
    11  )
    12  
    13  func init() {
    14  	rand.Seed(time.Now().UnixNano())
    15  }
    16  
    17  // Tx stores a transaction with an ID to keep track.
    18  type Tx struct {
    19  	ID int
    20  	*sqlx.Tx
    21  }
    22  
    23  func newTX(ctx context.Context, db *dB, opts *sql.TxOptions) (*Tx, error) {
    24  	t := &Tx{
    25  		ID: rand.Int(),
    26  	}
    27  	tx, err := db.BeginTxx(ctx, opts)
    28  	t.Tx = tx
    29  	if err != nil {
    30  		return nil, fmt.Errorf("could not create new transaction: %w", err)
    31  	}
    32  	return t, nil
    33  }
    34  
    35  // TransactionContext simply returns the current transaction,
    36  // this is defined so it implements the `Store` interface.
    37  func (tx *Tx) TransactionContext(ctx context.Context) (*Tx, error) {
    38  	return tx, nil
    39  }
    40  
    41  // TransactionContextOptions simply returns the current transaction,
    42  // this is defined so it implements the `Store` interface.
    43  func (tx *Tx) TransactionContextOptions(_ context.Context, _ *sql.TxOptions) (*Tx, error) {
    44  	return tx, nil
    45  }
    46  
    47  // Transaction simply returns the current transaction,
    48  // this is defined so it implements the `Store` interface.
    49  func (tx *Tx) Transaction() (*Tx, error) {
    50  	return tx, nil
    51  }
    52  
    53  // Close does nothing. This is defined so it implements the `Store` interface.
    54  func (tx *Tx) Close() error {
    55  	return nil
    56  }
    57  
    58  // Workaround for https://github.com/jmoiron/sqlx/issues/447
    59  func (tx *Tx) NamedQueryContext(ctx context.Context, query string, arg interface{}) (*sqlx.Rows, error) {
    60  	return sqlx.NamedQueryContext(ctx, tx, query, arg)
    61  }