How do I use transactions and rollbacks using GORM?

In Go language, using GORM for database operations involves handling transactions efficiently. Transactions ensure that a series of operations either all succeed or all fail, maintaining data integrity. In GORM, you can manage transactions and rollbacks by using the `DB.Begin()`, `Commit()`, and `Rollback()` methods.

Example of Using Transactions in GORM

package main import ( "gorm.io/driver/sqlite" "gorm.io/gorm" "log" ) type Product struct { ID uint `gorm:"primaryKey"` Code string `gorm:"unique"` Price uint } func main() { db, err := gorm.Open(sqlite.Open("test.db"), &gorm.Config{}) if err != nil { log.Fatal(err) } // Start a new transaction tx := db.Begin() // Create a product product := Product{Code: "L1212", Price: 1000} if err := tx.Create(&product).Error; err != nil { // Rollback transaction if there is an error tx.Rollback() log.Fatal(err) } // If everything is fine, commit the transaction // Uncomment to induce an error for rollback demonstration // product.Code = "L1212" // This would violate unique constraint if err := tx.Commit().Error; err != nil { tx.Rollback() log.Fatal(err) } log.Println("Transaction committed successfully") }

Go GORM transactions rollbacks database SQLite data integrity