forked from gobuffalo/pop
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtx.go
73 lines (61 loc) · 1.75 KB
/
tx.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
package pop
import (
"context"
"database/sql"
"fmt"
"github.com/jackc/pgx/v5/pgxpool"
"github.com/gobuffalo/pop/v6/internal/randx"
"github.com/jmoiron/sqlx"
)
// Tx stores a transaction with an ID to keep track.
type Tx struct {
ID int
*sqlx.Tx
db *sql.DB
pool *pgxpool.Pool
}
func newTX(ctx context.Context, db *dB, pool *pgxpool.Pool, opts *sql.TxOptions) (*Tx, error) {
t := &Tx{
ID: randx.NonNegativeInt(),
db: db.SQLDB(),
pool: pool,
}
tx, err := db.BeginTxx(ctx, opts)
t.Tx = tx
if err != nil {
return nil, fmt.Errorf("could not create new transaction: %w", err)
}
return t, nil
}
func (tx *Tx) SQLDB() *sql.DB {
return tx.db
}
func (tx *Tx) PGXPool() *pgxpool.Pool {
return tx.pool
}
func (tx *Tx) PingContext(ctx context.Context) error {
return tx.db.PingContext(ctx)
}
// TransactionContext simply returns the current transaction,
// this is defined so it implements the `Store` interface.
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) {
return tx, nil
}
// Close does nothing. This is defined so it implements the `Store` interface.
func (tx *Tx) Close() error {
return nil
}
// Workaround for https://github.com/jmoiron/sqlx/issues/447
func (tx *Tx) NamedQueryContext(ctx context.Context, query string, arg interface{}) (*sqlx.Rows, error) {
return sqlx.NamedQueryContext(ctx, tx, query, arg)
}