Kas saaksite nimetada tüüpilisi vigu, mida tehingute kasutamisel tehakse?
sobes.tech AI
Vastus AI-lt
Common mistakes when working with transactions in Go:
-
Implicitly ignoring errors — forgetting to check errors after transaction operations (e.g., after
tx.Commit()ortx.Rollback()), which can lead to unnoticed issues. -
Lack of rollback on errors — if an error occurs during the transaction, not calling
tx.Rollback(), which can cause locks or data inconsistencies. -
Double calling
CommitorRollback— calling these methods multiple times can cause panic or errors. -
Holding a transaction open for too long — keeping a transaction open for too long blocks other operations and reduces performance.
-
Using transactions without context — not passing
context.Contextto methods, which complicates cancellation or timeouts.
Example of correct transaction usage:
ctx := context.Background()
tx, err := db.BeginTx(ctx, nil)
if err != nil {
// handle error
}
// Execute operations
if _, err := tx.ExecContext(ctx, "INSERT INTO ..."); err != nil {
tx.Rollback()
return err
}
if err := tx.Commit(); err != nil {
return err
}
It is always important to handle errors and properly conclude the transaction.