Middle — Middle+
How to manage transactions within a single method when multiple transactional operations are used, considering the execution context?
sobes.tech AI
Answer from AI
In Go, managing transactions within a single method with multiple transactional operations typically involves using a transaction object obtained from the database context (for example, *sql.Tx). It is important to pass this object to each function that performs database operations so that all of them are part of the same transaction.
Example:
func doComplexOperation(db *sql.DB) error {
tx, err := db.Begin()
if err != nil {
return err
}
defer func() {
if p := recover(); p != nil {
tx.Rollback()
panic(p)
} else if err != nil {
tx.Rollback()
} else {
err = tx.Commit()
}
}()
err = operation1(tx)
if err != nil {
return err
}
err = operation2(tx)
if err != nil {
return err
}
return nil
}
func operation1(tx *sql.Tx) error {
// Execute SQL queries via tx.Exec or tx.Query
return nil
}
func operation2(tx *sql.Tx) error {
// Similarly
return nil
}
Thus, all operations are performed within a single transaction, and in case of an error, a rollback occurs. The execution context (context.Context) can be used for cancellation or timeout by passing it to query methods, but the transaction object itself should be passed explicitly.