bun
bun copied to clipboard
Transactions within a transaction
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?
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
@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