Skip to content

Transactions

Derevtsov Konstantin edited this page Jul 10, 2020 · 5 revisions

By default, when calling session.Flush, all generated insert, delete and update queries will run in one transaction per Flush, and by default, commit will be called it after session.Flush end without error. But, you can manipulate transactions manually. D3D3 provides transaction API for doing this.

Begin new transaction
// get session from context
session := orm.Session(ctx)
// start transaction
if err := session.BeginTx(); err != nil {
    log.Fatal(err)
}
Commit transaction
session.CommitTx()
Rollback transaction
session.RollbackTx()
Example of usage

In the example bellow all SQL queries generated by Flush methods executed in one transaction.

session := orm.Session(ctx)
if err := session.BeginTx(); err != nil {
    log.Fatal(err)
}

repository.Persists(ctx, user1, user2)
if err = session.Flush(); err != nil {
    log.Fatal(err)
}

repository.Persists(ctx, user3, user4)
if err = session.Flush(); err != nil {
    // rollback all changes
    session.RollbackTx()
    log.Fatal(err)
}

// commit all changes
session.CommitTx()
Clone this wiki locally