Sobes.tech
Middle+

What is a transaction and what are the principles of ACID?

sobes.tech AI

Answer from AI

A transaction is a sequence of operations on a database that is executed as a single unit. If one of the operations fails, all changes are rolled back to maintain data integrity.

The ACID principles ensure the reliability of transactions:

  • Atomicity: The transaction is either fully completed or not executed at all.
  • Consistency: After the transaction, the database remains in a correct state.
  • Isolation: Parallel transactions do not affect each other.
  • Durability: Once a transaction is committed, changes are saved even in case of failures.

In Go, when working with a database via database/sql, a transaction is created as follows:

trx, err := db.Begin()
if err != nil {
    // handle error
}
_, err = trx.Exec("INSERT INTO users(name) VALUES(?)", "Alice")
if err != nil {
    trx.Rollback()
    // handle error
}
err = trx.Commit()
if err != nil {
    // handle error
}