v24.go 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  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. gouuid "github.com/satori/go.uuid"
  8. "gorm.io/gorm"
  9. )
  10. func addUserLocalEmail(db *gorm.DB) error {
  11. type User struct {
  12. ID int64 `gorm:"primaryKey"`
  13. LocalEmail string
  14. }
  15. type UserNotNULL struct {
  16. ID int64 `gorm:"primaryKey"`
  17. LocalEmail string
  18. }
  19. if db.Migrator().HasColumn(&User{}, "LocalEmail") {
  20. return errMigrationSkipped
  21. }
  22. return db.Transaction(func(tx *gorm.DB) error {
  23. err := tx.Migrator().AddColumn(&User{}, "LocalEmail")
  24. if err != nil {
  25. return fmt.Errorf("add column user.local_email error: %s", err.Error())
  26. }
  27. const limit = 100
  28. for {
  29. var res []User
  30. err := tx.Table("user").Where("type = ?", 0).Where("local_email = ''").Limit(limit).Find(&res).Error
  31. if err != nil {
  32. return fmt.Errorf("query user error: %s", err.Error())
  33. }
  34. for _, r := range res {
  35. r.LocalEmail = gouuid.NewV4().String() + "@fake.localhost"
  36. err = tx.Save(&r).Error
  37. if err != nil {
  38. return fmt.Errorf("save column user.local_email error: %s", err)
  39. }
  40. }
  41. if len(res) < limit {
  42. break
  43. }
  44. }
  45. err = tx.Migrator().AlterColumn(&User{}, "LocalEmail")
  46. if err != nil {
  47. return fmt.Errorf("alter column user.local_email error: %s", err.Error())
  48. }
  49. return nil
  50. })
  51. }