Middle
What is a transaction in a database?
sobes.tech AI
Answer from AI
A database transaction is a logically connected sequence of operations (such as insert, update, delete) that is executed as a single unit. A transaction has four main properties (ACID):
- Atomicity: all operations within the transaction are either fully completed or not executed at all.
- Consistency: the transaction transforms the database from one correct state to another.
- Isolation: concurrent transactions do not affect each other, and their results are not mixed.
- Durability: after a transaction successfully completes, the changes are saved in the database and are not lost.
Example in Go using a database and transactions:
import (
"database/sql"
_ "github.com/lib/pq" // PostgreSQL driver
"log"
)
func transferFunds(db *sql.DB, fromAccount, toAccount string, amount float64) 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 = tx.Exec("UPDATE accounts SET balance = balance - $1 WHERE id = $2", amount, fromAccount)
if err != nil {
return err
}
_, err = tx.Exec("UPDATE accounts SET balance = balance + $1 WHERE id = $2", amount, toAccount)
if err != nil {
return err
}
return err
}
Here, the withdrawal and deposit operations are performed within a single transaction to prevent partial data updates.