Sobes.tech
Middle — Middle+

Kuidas hallata tehinguid ühes meetodis, kui kasutatakse mitmeid tehinguoperatsioone, arvestades täitmise konteksti?

sobes.tech AI

Vastus AI-lt

In Go, to manage transactions within a single method with multiple transactional operations, a transaction object obtained from the database context (e.g., *sql.Tx) is usually used. It is important to pass this object to each function performing database operations so that all are part of the same transaction.

Example:

func doComplexOperation(db *sql.DB) 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 = operation1(tx)
    if err != nil {
        return err
    }

    err = operation2(tx)
    if err != nil {
        return err
    }

    return nil
}

func operation1(tx *sql.Tx) error {
    // Execute SQL queries using tx.Exec or tx.Query
    return nil
}

func operation2(tx *sql.Tx) error {
    // Similar
    return nil
}

This way, all operations are performed within a single transaction, and in case of an error, a rollback is performed. The execution context (context.Context) can be used for cancellation or timeout setting, passing it to query methods, but the transaction object must be explicitly passed.