2.fix_site_and_stream_unique.go 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. package migrate
  2. import (
  3. "github.com/0xJacky/Nginx-UI/model"
  4. "github.com/go-gormigrate/gormigrate/v2"
  5. "gorm.io/gorm"
  6. )
  7. var FixSiteAndStreamPathUnique = &gormigrate.Migration{
  8. ID: "202505070000001",
  9. Migrate: func(tx *gorm.DB) error {
  10. // Check if sites table exists
  11. if tx.Migrator().HasTable(&model.Site{}) {
  12. // Find duplicated paths in sites table
  13. var siteDuplicates []struct {
  14. Path string
  15. Count int
  16. }
  17. if err := tx.Model(&model.Site{}).
  18. Select("path, count(*) as count").
  19. Group("path").
  20. Having("count(*) > 1").
  21. Unscoped().
  22. Find(&siteDuplicates).Error; err != nil {
  23. return err
  24. }
  25. // For each duplicated path, delete all but the one with max id
  26. for _, dup := range siteDuplicates {
  27. if err := tx.Exec(`DELETE FROM sites WHERE path = ? AND id NOT IN
  28. (SELECT max(id) FROM sites WHERE path = ?)`, dup.Path, dup.Path).Error; err != nil {
  29. return err
  30. }
  31. }
  32. }
  33. // Check if streams table exists
  34. if tx.Migrator().HasTable(&model.Stream{}) {
  35. // Find duplicated paths in streams table
  36. var streamDuplicates []struct {
  37. Path string
  38. Count int
  39. }
  40. if err := tx.Model(&model.Stream{}).
  41. Select("path, count(*) as count").
  42. Group("path").
  43. Having("count(*) > 1").
  44. Unscoped().
  45. Find(&streamDuplicates).Error; err != nil {
  46. return err
  47. }
  48. // For each duplicated path, delete all but the one with max id
  49. for _, dup := range streamDuplicates {
  50. if err := tx.Exec(`DELETE FROM streams WHERE path = ? AND id NOT IN
  51. (SELECT max(id) FROM streams WHERE path = ?)`, dup.Path, dup.Path).Error; err != nil {
  52. return err
  53. }
  54. }
  55. }
  56. return nil
  57. },
  58. }