Sobes.tech
Junior — Middle

Kuidas saab ühe tehingu raames tehtud muudatusi tagasi võtta?

sobes.tech AI

Vastus AI-lt

In Go, the database/sql package is commonly used for working with transactions. To rollback changes within a transaction, you need to call the Rollback() method on the transaction object. This is usually done in case of an error, to undo all changes made within the transaction.

Example:

trx, err := db.Begin()
if err != nil {
    // error handling
}

// Perform operations within the transaction
_, err = trx.Exec("INSERT INTO users(name) VALUES(?)", "John")
if err != nil {
    trx.Rollback() // rollback transaction on error
    return err
}

// If everything is successful, commit the transaction
err = trx.Commit()
if err != nil {
    return err
}

This way, calling trx.Rollback() cancels all changes made within the current transaction.