初始化Go学习项目

This commit is contained in:
liumangmang
2025-12-26 17:56:02 +08:00
commit 7f4527d501
90 changed files with 3436 additions and 0 deletions

View File

@@ -0,0 +1,56 @@
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
// DeletedAt gorm.DeletedAt `gorm:"index"` // 软删除字段
//}
func main() {
db, _ := gorm.Open(sqlite.Open("test.db"), &gorm.Config{})
db.AutoMigrate(&User{})
//// 插入测试数据
//users := []User{
// {Name: "Alice", Email: "alice@example.com", Age: 30},
// {Name: "Bob", Email: "bob@example.com", Age: 25},
// {Name: "Charlie", Email: "charlie@example.com", Age: 35},
//}
//db.Create(users)
// 1. 软删除(标记 deleted_at
db.Delete(&User{}, 11) // 删除 ID=1 的用户
fmt.Println("Soft deleted user ID=1")
// 2. 查询时默认不包括已删除的
var activeUsers []User
db.Find(&activeUsers)
fmt.Printf("Active users: %d\n", len(activeUsers))
// 3. 查询所有记录(包括已删除的)
var allUsers []User
db.Unscoped().Find(&allUsers)
fmt.Printf("All users (including deleted): %d\n", len(allUsers))
// 4. 永久删除(硬删除)
db.Unscoped().Delete(&User{}, 12)
fmt.Println("Permanently deleted user ID=2")
// 5. 批量删除
db.Where("age < ?", 30).Delete(&User{})
fmt.Println("Batch delete completed")
// 最终统计
var finalCount int64
db.Model(&User{}).Count(&finalCount)
fmt.Printf("Final active users: %d\n", finalCount)
}