A clean, Markdown-based publishing platform made for writers. Write together, and build a community. https://writefreely.org
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 

27 lines
626 B

  1. package db
  2. import (
  3. "context"
  4. "database/sql"
  5. )
  6. // TransactionScopedWork describes code executed within a database transaction.
  7. type TransactionScopedWork func(ctx context.Context, db *sql.Tx) error
  8. // RunTransactionWithOptions executes a block of code within a database transaction.
  9. func RunTransactionWithOptions(ctx context.Context, db *sql.DB, txOpts *sql.TxOptions, txWork TransactionScopedWork) error {
  10. tx, err := db.BeginTx(ctx, txOpts)
  11. if err != nil {
  12. return err
  13. }
  14. if err = txWork(ctx, tx); err != nil {
  15. if txErr := tx.Rollback(); txErr != nil {
  16. return txErr
  17. }
  18. return err
  19. }
  20. return tx.Commit()
  21. }