-
Notifications
You must be signed in to change notification settings - Fork 1
/
db.go
48 lines (39 loc) · 1.11 KB
/
db.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
package db
import (
"context"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgconn"
"github.com/jackc/pgx/v5/pgxpool"
)
type DB struct {
pool *pgxpool.Pool
}
func New(pool *pgxpool.Pool) *DB {
return &DB{pool: pool}
}
func (db *DB) Query(ctx context.Context, query string, args ...any) (pgx.Rows, error) {
if tx, ok := txFromContext(ctx); ok {
return tx.Query(ctx, query, args...)
}
return db.pool.Query(ctx, query, args...)
}
func (db *DB) QueryRow(ctx context.Context, query string, args ...any) pgx.Row {
if tx, ok := txFromContext(ctx); ok {
return tx.QueryRow(ctx, query, args...)
}
return db.pool.QueryRow(ctx, query, args...)
}
func (db *DB) Exec(ctx context.Context, query string, args ...any) (pgconn.CommandTag, error) {
if tx, ok := txFromContext(ctx); ok {
return tx.Exec(ctx, query, args...)
}
return db.pool.Exec(ctx, query, args...)
}
func (db *DB) RunTx(ctx context.Context, fn func(ctx context.Context) error) (err error) {
if _, ok := txFromContext(ctx); ok {
return fn(ctx)
}
return executeTx(ctx, db.pool, func(tx pgx.Tx) error {
return fn(contextWithTx(ctx, tx))
})
}