forked from mtusi2026/mtusi2026lab6
Реализация на 5
This commit is contained in:
@@ -0,0 +1,59 @@
|
||||
package txmanager
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
)
|
||||
|
||||
type TransactionManager struct {
|
||||
pool *pgxpool.Pool
|
||||
}
|
||||
|
||||
func New(pool *pgxpool.Pool) *TransactionManager {
|
||||
return &TransactionManager{
|
||||
pool: pool,
|
||||
}
|
||||
}
|
||||
|
||||
func (tm *TransactionManager) RunInTransaction(ctx context.Context, opts *pgx.TxOptions, fn func(tx pgx.Tx) error) (err error) {
|
||||
var tx pgx.Tx
|
||||
|
||||
if opts != nil {
|
||||
tx, err = tm.pool.BeginTx(ctx, *opts)
|
||||
} else {
|
||||
tx, err = tm.pool.Begin(ctx)
|
||||
}
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to begin transaction: %w", err)
|
||||
}
|
||||
|
||||
var committed bool
|
||||
|
||||
defer func() {
|
||||
if p := recover(); p != nil {
|
||||
err = fmt.Errorf("panic in transaction: %v", p)
|
||||
}
|
||||
if !committed {
|
||||
rollbackErr := tx.Rollback(ctx)
|
||||
if rollbackErr != nil && !errors.Is(rollbackErr, pgx.ErrTxClosed) {
|
||||
slog.Error("failed to rollback transaction", "error", rollbackErr)
|
||||
}
|
||||
}
|
||||
}()
|
||||
|
||||
if err = fn(tx); err != nil {
|
||||
return fmt.Errorf("failed to execute transaction: %w", err)
|
||||
}
|
||||
|
||||
if err = tx.Commit(ctx); err != nil {
|
||||
return fmt.Errorf("failed to commit transaction: %w", err)
|
||||
}
|
||||
|
||||
committed = true
|
||||
return nil
|
||||
}
|
||||
Reference in New Issue
Block a user