Junior — Middle
Kas süsteemis on võimalik rakendada sisemisi tehinguid ja millal see on lubatav?
sobes.tech AI
Vastus AI-lt
In the standard Go library (package database/sql), nested transactions are not directly supported, as most database management systems (DBMS) do not implement full nested transactions. Instead, savepoints are often used, which allow rolling back to a specific point within a transaction.
Possible options:
- Use savepoints if supported by the DBMS (e.g., PostgreSQL, MySQL). In Go, this can be done by executing SQL commands
SAVEPOINT,ROLLBACK TO SAVEPOINT. - Mimic nested transactions through separate transactions, but this is not always correct from a business logic perspective.
When is it allowed:
- When you need to partially rollback changes within a large transaction without aborting the entire transaction.
- In complex operations with multiple steps, where each step can be rolled back separately.
Example of using savepoints in Go:
trx, err := db.Begin()
if err != nil {
// error handling
}
_, err = trx.Exec("SAVEPOINT sp1")
if err != nil {
trx.Rollback()
return err
}
// Execute operations
// On error:
_, err = trx.Exec("ROLLBACK TO SAVEPOINT sp1")
// Continue or commit fully
err = trx.Commit()
Thus, nested transactions are implemented via savepoints, not through nested Begin/Commit calls.