39 lines
864 B
Go
39 lines
864 B
Go
package database
|
|
|
|
import (
|
|
"context"
|
|
|
|
"github.com/jackc/pgx/v4"
|
|
"github.com/jackc/pgx/v4/pgxpool"
|
|
"github.com/pkg/errors"
|
|
)
|
|
|
|
func WithTx(ctx context.Context, pool *pgxpool.Pool, fn func(context.Context, pgx.Tx) error) error {
|
|
tx, err := pool.BeginTx(ctx, pgx.TxOptions{})
|
|
if err != nil {
|
|
return errors.Wrap(err, "could not begin transaction")
|
|
}
|
|
|
|
defer func() {
|
|
if err := tx.Rollback(ctx); err != nil && !errors.Is(err, pgx.ErrTxClosed) {
|
|
panic(errors.Wrap(err, "could not rollback transaction"))
|
|
}
|
|
}()
|
|
|
|
if err := fn(ctx, tx); err != nil {
|
|
err := errors.Wrap(err, "could not apply down migration")
|
|
|
|
if rollbackErr := tx.Rollback(ctx); rollbackErr != nil {
|
|
return errors.Wrap(err, rollbackErr.Error())
|
|
}
|
|
|
|
return err
|
|
}
|
|
|
|
if err := tx.Commit(ctx); err != nil {
|
|
return errors.Wrap(err, "could not commit transaction")
|
|
}
|
|
|
|
return nil
|
|
}
|