Sobes.tech
Junior — Middle

Kas saaksite nimetada tüüpilisi vigu, mida tehingute kasutamisel tehakse?

sobes.tech AI

Vastus AI-lt

Common mistakes when working with transactions in Go:

  1. Implicitly ignoring errors — forgetting to check errors after transaction operations (e.g., after tx.Commit() or tx.Rollback()), which can lead to unnoticed issues.

  2. Lack of rollback on errors — if an error occurs during the transaction, not calling tx.Rollback(), which can cause locks or data inconsistencies.

  3. Double calling Commit or Rollback — calling these methods multiple times can cause panic or errors.

  4. Holding a transaction open for too long — keeping a transaction open for too long blocks other operations and reduces performance.

  5. Using transactions without context — not passing context.Context to 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.