49 lines
918 B
Go
49 lines
918 B
Go
package repository
|
|
|
|
import (
|
|
"context"
|
|
|
|
"github.com/jackc/pgx/v5"
|
|
"github.com/jackc/pgx/v5/pgconn"
|
|
"github.com/jackc/pgx/v5/pgxpool"
|
|
)
|
|
|
|
type DBTX interface {
|
|
Exec(ctx context.Context, sql string, arguments ...any) (pgconn.CommandTag, error)
|
|
Query(ctx context.Context, sql string, args ...any) (pgx.Rows, error)
|
|
QueryRow(ctx context.Context, sql string, args ...any) pgx.Row
|
|
}
|
|
|
|
type TxManager struct {
|
|
pool *pgxpool.Pool
|
|
}
|
|
|
|
func NewTxManager(pool *pgxpool.Pool) *TxManager {
|
|
return &TxManager{pool: pool}
|
|
}
|
|
|
|
func (tm *TxManager) WithTx(ctx context.Context, fn func(tx pgx.Tx) error) error {
|
|
tx, err := tm.pool.Begin(ctx)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
defer func() {
|
|
if p := recover(); p != nil {
|
|
_ = tx.Rollback(ctx)
|
|
panic(p)
|
|
}
|
|
}()
|
|
|
|
if err := fn(tx); err != nil {
|
|
_ = tx.Rollback(ctx)
|
|
return err
|
|
}
|
|
|
|
return tx.Commit(ctx)
|
|
}
|
|
|
|
func (tm *TxManager) Pool() *pgxpool.Pool {
|
|
return tm.pool
|
|
}
|