Skip to content

Instantly share code, notes, and snippets.

@SamWhited
Last active August 20, 2022 11:41
Show Gist options
  • Save SamWhited/4d7ee797d728e761550d78504f03c9cd to your computer and use it in GitHub Desktop.
Save SamWhited/4d7ee797d728e761550d78504f03c9cd to your computer and use it in GitHub Desktop.
Example of wrapping up database transactions with a closure.
package transaction
import (
"context"
"database/sql"
)
// Exec creates a transaction and calls f.
// When it is finished, it cleans up the transaction. If an error occured it
// attempts to rollback, if not it commits.
func Exec(ctx context.Context, db *sql.DB, f func(context.Context, *sql.Tx) error) error {
tx, err := db.Begin()
if err != nil {
return err
}
err = f(ctx, tx)
if err != nil {
_ = tx.Rollback()
return err
}
return tx.Commit()
}
package main
func main() {
stmt := db.PrepareContext(ctx, `whatever`)
stmt2 := db.PrepareContext(ctx, `whatever`)
transaction.Exec(ctx, db, func(ctx context.Context, tx *sql.Tx) error {
tx.Stmt(stmt).ExecContext(ctx)
tx.Stmt(stmt2).ExecContext(ctx)
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment