v23.go 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. // Copyright 2025 Huan-Gogs Authors. All rights reserved.
  2. // Use of this source code is governed by a MIT-style
  3. // license that can be found in the LICENSE file.
  4. package migrations
  5. import (
  6. "fmt"
  7. "gorm.io/gorm"
  8. )
  9. func addUserPublicEmail(db *gorm.DB) error {
  10. type User struct {
  11. PublicEmail string // 不能使用NOT NULL
  12. }
  13. type UserNotNull struct {
  14. PublicEmail string `xorm:"NOT NULL" gorm:"not null"`
  15. }
  16. if db.Migrator().HasColumn(&User{}, "PublicEmail") {
  17. return errMigrationSkipped
  18. }
  19. return db.Transaction(func(tx *gorm.DB) error {
  20. err := tx.Migrator().AddColumn(&User{}, "PublicEmail")
  21. if err != nil {
  22. return fmt.Errorf("add column user.public_email error: %s", err.Error())
  23. }
  24. err = tx.Exec("UPDATE `user` SET `public_email` = `email` WHERE `public_email` = '' AND `type` = 0").Error
  25. if err != nil {
  26. return fmt.Errorf("update public_email error: %s", err.Error())
  27. }
  28. err = tx.Debug().Migrator().AlterColumn(&UserNotNull{}, "PublicEmail")
  29. if err != nil {
  30. return fmt.Errorf("alter column user.public_email error: %s", err.Error())
  31. }
  32. return nil
  33. })
  34. }