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"`
//	Age       int
//	CreatedAt time.Time
//}

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

	// 先插入测试数据
	db.AutoMigrate(&User{})
	db.Create(&User{Name: "Alice", Email: "alice@example.com", Age: 30})
	db.Create(&User{Name: "Bob", Email: "bob@example.com", Age: 25})
	db.Create(&User{Name: "Charlie", Email: "charlie@example.com", Age: 35})

	// 1. 根据 ID 查询
	var user User
	db.First(&user, 1) // 查询 ID=1 的用户
	fmt.Printf("User ID=1: %s (%s)\n", user.Name, user.Email)

	// 2. 按条件查询单条
	var user2 User
	db.Where("email = ?", "bob@example.com").First(&user2)
	fmt.Printf("User by email: %s (age=%d)\n", user2.Name, user2.Age)

	// 3. 查询所有
	var users []User
	db.Find(&users)
	fmt.Printf("Total users: %d\n", len(users))

	// 4. 按条件查询多条
	var adults []User
	db.Where("age >= ?", 30).Find(&adults)
	fmt.Printf("Users age >= 30: %d\n", len(adults))

	// 5. 使用 IN 查询
	var selectedUsers []User
	db.Where("id IN ?", []int{1, 2}).Find(&selectedUsers)
	fmt.Printf("Selected users: %d\n", len(selectedUsers))

	// 6. 排序查询
	var sortedUsers []User
	db.Order("age DESC").Find(&sortedUsers)
	fmt.Println("Users sorted by age (DESC):")
	for _, u := range sortedUsers {
		fmt.Printf("  - %s (age=%d)\n", u.Name, u.Age)
	}

	// 7. 分页查询
	var pageUsers []User
	db.Offset(0).Limit(2).Find(&pageUsers)
	fmt.Printf("Page 1 (limit 2): %d users\n", len(pageUsers))

	// 8. 组合查询
	var combinedUsers []User
	db.Where("age > ?", 25).
		Order("age DESC").
		Limit(2).
		Find(&combinedUsers)
	fmt.Printf("Combined query: %d users\n", len(combinedUsers))
}
