package main

import (
	"errors"
	"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"`
//	}
//type Account struct {
//	ID      uint `gorm:"primaryKey"`
//	UserID  uint
//	Balance int
//}

func main() {
	db, _ := gorm.Open(sqlite.Open("test.db"), &gorm.Config{})
	db.AutoMigrate(&User{}, &Account{})

	// 故意触发错误，测试回滚
	err := db.Transaction(func(tx *gorm.DB) error {
		user := User{Name: "Charlie", Email: "charlie@example.com"}
		if err := tx.Create(&user).Error; err != nil {
			return err
		}

		fmt.Println("User created, ID:", user.ID)

		// 故意返回错误，触发回滚
		return errors.New("something went wrong")
	})

	if err != nil {
		fmt.Println("Transaction rolled back:", err)
	}

	// 检查用户是否存在
	var count int64
	db.Model(&User{}).Where("name = ?", "Charlie").Count(&count)
	fmt.Printf("User 'Charlie' count: %d (should be 0)\n", count)
}
