Last active
August 20, 2022 11:41
-
-
Save SamWhited/4d7ee797d728e761550d78504f03c9cd to your computer and use it in GitHub Desktop.
Example of wrapping up database transactions with a closure.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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() | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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