3.rename_auths_to_users.go 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. package migrate
  2. import (
  3. "github.com/go-gormigrate/gormigrate/v2"
  4. "gorm.io/gorm"
  5. )
  6. var RenameAuthsToUsers = &gormigrate.Migration{
  7. ID: "20250405000002",
  8. Migrate: func(tx *gorm.DB) error {
  9. // Check if both tables exist
  10. hasAuthsTable := tx.Migrator().HasTable("auths")
  11. hasUsersTable := tx.Migrator().HasTable("users")
  12. if hasAuthsTable {
  13. if hasUsersTable {
  14. // Both tables exist - we need to check if users table is empty
  15. var count int64
  16. if err := tx.Table("users").Count(&count).Error; err != nil {
  17. return err
  18. }
  19. if count > 0 {
  20. // Users table has data - drop auths table as users table is now the source of truth
  21. return tx.Migrator().DropTable("auths")
  22. } else {
  23. // Users table is empty - drop it and rename auths to users
  24. return tx.Transaction(func(ttx *gorm.DB) error {
  25. if err := ttx.Migrator().DropTable("users"); err != nil {
  26. return err
  27. }
  28. return ttx.Migrator().RenameTable("auths", "users")
  29. })
  30. }
  31. } else {
  32. // Only auths table exists - simply rename it
  33. return tx.Migrator().RenameTable("auths", "users")
  34. }
  35. }
  36. // If auths table doesn't exist, nothing to do
  37. return nil
  38. },
  39. }