migrate_only.go 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. // +build ignore
  2. package main
  3. import (
  4. _ "app/commons/config"
  5. "app/commons/core"
  6. "app/commons/model/entity"
  7. "fmt"
  8. "gorm.io/gorm"
  9. )
  10. func main() {
  11. fmt.Println("=== 数据库迁移工具 ===")
  12. // 获取数据库连接
  13. db := core.MainDb()
  14. currentDB := db.Migrator().CurrentDatabase()
  15. fmt.Printf("当前数据库: %s\n", currentDB)
  16. // 定义要迁移的表
  17. tables := []interface{}{
  18. // Telegram 红包模块
  19. &entity.TgRedPacket{},
  20. &entity.TgRedPacketRecord{},
  21. &entity.TgUserBind{},
  22. &entity.TgRedPacketConfig{},
  23. }
  24. // 执行迁移
  25. for _, table := range tables {
  26. if err := migrateTable(db, table); err != nil {
  27. fmt.Printf("❌ 迁移失败: %v\n", err)
  28. return
  29. }
  30. }
  31. fmt.Println("✅ 数据库迁移完成")
  32. }
  33. func migrateTable(db *gorm.DB, model interface{}) error {
  34. tableName := getTableName(model)
  35. fmt.Printf("正在迁移表: %s\n", tableName)
  36. if err := db.AutoMigrate(model); err != nil {
  37. return err
  38. }
  39. fmt.Printf("✓ %s 迁移成功\n", tableName)
  40. return nil
  41. }
  42. func getTableName(model interface{}) string {
  43. if t, ok := model.(interface{ TableName() string }); ok {
  44. return t.TableName()
  45. }
  46. return "unknown"
  47. }