forked from mtusi2026/mtusi2026lab6
36 lines
746 B
Go
36 lines
746 B
Go
package postgres
|
|
|
|
import (
|
|
"context"
|
|
|
|
"github.com/jackc/pgx/v5"
|
|
|
|
"high-loud-apps-labs/internal/domain"
|
|
)
|
|
|
|
type pgxTx struct {
|
|
tx pgx.Tx
|
|
}
|
|
|
|
func (t *pgxTx) Exec(ctx context.Context, sql string, args ...any) error {
|
|
_, err := t.tx.Exec(ctx, sql, args...)
|
|
return mapError(err)
|
|
}
|
|
|
|
// WithTx выполняет fn в одной транзакции:
|
|
// - commit, если fn вернул nil;
|
|
// - rollback, если fn вернул ошибку.
|
|
|
|
func (s *Storage) WithTx(ctx context.Context, fn func(tx domain.Tx) error) error {
|
|
tx, err := s.pool.Begin(ctx)
|
|
if err != nil {
|
|
return mapError(err)
|
|
}
|
|
defer func() { _ = tx.Rollback(ctx) }()
|
|
|
|
if err := fn(&pgxTx{tx: tx}); err != nil {
|
|
return err
|
|
}
|
|
return mapError(tx.Commit(ctx))
|
|
}
|