v23.go 939 B

123456789101112131415161718192021222324252627282930313233343536373839
  1. package migrations
  2. import (
  3. "fmt"
  4. "gorm.io/gorm"
  5. )
  6. func addUserPublicEmail(db *gorm.DB) error {
  7. type User struct {
  8. PublicEmail string // 不能使用NOT NULL
  9. }
  10. type UserNotNull struct {
  11. PublicEmail string `xorm:"NOT NULL" gorm:"not null"`
  12. }
  13. if db.Migrator().HasColumn(&User{}, "PublicEmail") {
  14. return errMigrationSkipped
  15. }
  16. return db.Transaction(func(tx *gorm.DB) error {
  17. err := tx.Migrator().AddColumn(&User{}, "PublicEmail")
  18. if err != nil {
  19. return fmt.Errorf("add column user.public_email error: %s", err.Error())
  20. }
  21. err = tx.Exec("UPDATE `user` SET `public_email` = `email` WHERE `public_email` = '' AND `type` = 0").Error
  22. if err != nil {
  23. return fmt.Errorf("update public_email error: %s", err.Error())
  24. }
  25. err = tx.Debug().Migrator().AlterColumn(&UserNotNull{}, "PublicEmail")
  26. if err != nil {
  27. return fmt.Errorf("alter column user.public_email error: %s", err.Error())
  28. }
  29. return nil
  30. })
  31. }