bun icon indicating copy to clipboard operation
bun copied to clipboard

Transactions within a transaction

Open denggj28 opened this issue 1 year ago • 2 comments

I recently had the need to transaction at a point that happened to be inside another transaction. All my tests seem to indicate this is working out fine, but I can't find any documentation on this usage.

err := db.RunInTx(ctx, &sql.Options{}, func(tx bun.Tx) error {
    // below lines in another library, like call a function, use the same db connection
    subErr := db.RunInTx(ctx, &sql.Options{}, func(tx bun.Tx) error {
        // do something
    }
    // end

    if subErr != nil {
        return subErr
    }

    // do someing in this transaction
    txErr := tx.NewUpdate().Model(&m).WherePK().Exec(ctx)
    if txErr != nil {
        return txErr
    }

    return nil
}

I want to be sure - are transactions within a transaction valid in mysql or postgresql?

denggj28 avatar Mar 30 '23 20:03 denggj28

No, it's not. For nested transactions in MySQL and PostgreSQL, you should use savepoints. But RunInTx does not utilize savepoint. You can refer to source

hhuseyinpay avatar May 18 '23 13:05 hhuseyinpay

@denggj28 nested transactions are already implemented via savepoint. You don't need another library. So, you can just begin pseudo-nested transaction in RunInTx see https://github.com/uptrace/bun/blob/d2e0ef06e225732ec68372771b77161aad8144d5/db.go#L602

slava-nikulin avatar Aug 24 '23 15:08 slava-nikulin