Interesting GORM features
Transactions are a fundamental part of database operations. They let you make sure that all SQL operations that are part of the transaction are performed, or none of them are. Of course, GORM allows you to handle them elegantly. You only need to call the Transaction function and make all your calls inside the function passed as a parameter. Let’s see an example:
err := db.Transaction(func(tx *gorm.DB) error {
user := User{
Username: "johndoe",
Password: "password123",
Role: "user",
}
if err := tx.Create(&user).Error; err != nil {
return err
}
session := Session{
Token: "xyz789",
Expires: time.Now().Add(24 * time.Hour),
UserID: user.ID,
}
if err := tx.Create(&session).Error; err != nil {
return err
}
return nil
})
This code starts a transaction and executes different operations as part of the transaction. You can use db.Begin(), db.Rollback(), and...