stak banget
stak banget

Reputation: 53

how to use transaction in golang

i have a code insert to db
and this my model :

func (samethodattach *Product_gallery) SaveGalleri(db *gorm.DB) (*Product_gallery, error) {
    var err error
    err = db.Debug().Create(&samethodattach).Error
    if err != nil {
        return &Product_gallery{}, err
    }
    return samethodattach, nil
}

and I want to use the transaction inside the insert .

Upvotes: 3

Views: 1770

Answers (1)

mohammad mobasher
mohammad mobasher

Reputation: 777

There are some points on this:

Disable Default Transaction

You can disable it during initialization if it is not required, after that you will gain about 30%+ performance improvement.

// Globally disable
db, err := gorm.Open(sqlite.Open("gorm.db"), &gorm.Config{
  SkipDefaultTransaction: true,
})

// Continuous session mode
tx := db.Session(&Session{SkipDefaultTransaction: true})
tx.First(&user, 1)
tx.Find(&users)
tx.Model(&user).Update("Age", 18)

Transaction

the general flow To perform a set of operations within a transaction:

db.Transaction(func(tx *gorm.DB) error {
  // do some database operations in the transaction (use 'tx' from this point, not 'db')
  if err := tx.Create(&Animal{Name: "Giraffe"}).Error; err != nil {
    // return any error will rollback
    return err
  }

  if err := tx.Create(&Animal{Name: "Lion"}).Error; err != nil {
    return err
  }

  // return nil will commit the whole transaction
  return nil
})

Control transaction manually

Also Gorm support manually transaction, GORM provides SavePoint, RollbackTo to save points and roll back to a savepoint, for example: like this:

// begin a transaction
tx := db.Begin()

// do some database operations in the transaction (use 'tx' from this point, not 'db')
tx.Create(...)

// ...

// rollback the transaction in case of error
tx.Rollback()

// Or commit the transaction
tx.Commit()

Example

func CreateAnimals(db *gorm.DB) error {
  // Note the use of tx as the database handle once you are within a transaction
  tx := db.Begin()
  defer func() {
    if r := recover(); r != nil {
      tx.Rollback()
    }
  }()

  if err := tx.Error; err != nil {
    return err
  }

  if err := tx.Create(&Animal{Name: "Giraffe"}).Error; err != nil {
     tx.Rollback()
     return err
  }

  if err := tx.Create(&Animal{Name: "Lion"}).Error; err != nil {
     tx.Rollback()
     return err
  }

  return tx.Commit().Error
}

Upvotes: 2

Related Questions