The usual transaction operation methods are Begin/Commit/Rollback, with each method specifying a specific transaction operation. A transaction operation can be initiated by executing the db.Begin method, which returns an interface for transaction operations, with the type gdb.Tx. You can perform subsequent database operations through this object, and you can submit changes with tx.Commit or rollback changes with tx.Rollback.

ORM Transaction - Methods - 图1warning

Common Issues to Note: After initiating a transaction operation, be sure to close the transaction when no longer needed using Commit/Rollback operations. It is advisable to make good use of the defer method. If the transaction is not closed after use, it can lead to uncontrolled growth in goroutines on the application side and saturation of transaction threads on the database side, causing subsequent transaction requests to timeout. Furthermore, it is recommended to use the Transaction closure method introduced later for safely implementing transaction operations: ORM Transaction - Closure

1. Initiating a Transaction

  1. db := g.DB()
  2. if tx, err := db.Begin(ctx); err == nil {
  3. fmt.Println("Initiating a transaction")
  4. }

The transaction operation object can perform all methods of the db object. For more details, please refer to the API documentation.

2. Transaction Rollback Operation

  1. if tx, err := db.Begin(ctx); err == nil {
  2. r, err := tx.Save("user", g.Map{
  3. "id" : 1,
  4. "name" : "john",
  5. })
  6. if err != nil {
  7. tx.Rollback()
  8. }
  9. fmt.Println(r)
  10. }

3. Transaction Commit Operation

  1. if tx, err := db.Begin(ctx); err == nil {
  2. r, err := tx.Save("user", g.Map{
  3. "id" : 1,
  4. "name" : "john",
  5. })
  6. if err == nil {
  7. tx.Commit()
  8. }
  9. fmt.Println(r)
  10. }

4. Transaction Chain Operations

The transaction operation object can still return a chain operation object via the tx.Model method. This object is the same as the one returned by the db.Model method, except that database operations are performed on the transaction and can be committed or rolled back.

  1. if tx, err := db.Begin(); err == nil {
  2. r, err := tx.Model("user").Data(g.Map{"id":1, "name": "john_1"}).Save()
  3. if err == nil {
  4. tx.Commit()
  5. }
  6. fmt.Println(r)
  7. }

For other chain operations, please refer to the ORM - Model 🔥 section.