38 lines
722 B
Go
38 lines
722 B
Go
package main
|
|
|
|
import (
|
|
"fmt"
|
|
|
|
"gorm.io/driver/sqlite"
|
|
"gorm.io/gorm"
|
|
)
|
|
|
|
//type User struct {
|
|
// ID uint `gorm:"primaryKey"`
|
|
// Name string `gorm:"size:100"`
|
|
// Email string `gorm:"size:100;unique"`
|
|
//}
|
|
|
|
func main() {
|
|
db, _ := gorm.Open(sqlite.Open("test.db"), &gorm.Config{})
|
|
db.AutoMigrate(&User{})
|
|
|
|
db.Transaction(func(tx *gorm.DB) error {
|
|
tx.Create(&User{Name: "Alice", Email: "alice@example.com"})
|
|
|
|
// 创建 SavePoint
|
|
tx.SavePoint("sp1")
|
|
tx.Create(&User{Name: "Bob", Email: "bob@example.com"})
|
|
|
|
// 回滚到 SavePoint
|
|
tx.RollbackTo("sp1")
|
|
|
|
return nil
|
|
})
|
|
|
|
// 检查结果
|
|
var count int64
|
|
db.Model(&User{}).Count(&count)
|
|
fmt.Printf("Total users: %d (should be 1, only Alice)\n", count)
|
|
}
|