2.fix_site_and_stream_unique.go 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  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: "20250405000003",
  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. Find(&siteDuplicates).Error; err != nil {
  22. return err
  23. }
  24. // For each duplicated path, delete all but the one with max id
  25. for _, dup := range siteDuplicates {
  26. if err := tx.Exec(`DELETE FROM sites WHERE path = ? AND id NOT IN
  27. (SELECT max(id) FROM sites WHERE path = ?)`, dup.Path, dup.Path).Error; err != nil {
  28. return err
  29. }
  30. }
  31. }
  32. // Check if streams table exists
  33. if tx.Migrator().HasTable(&model.Stream{}) {
  34. // Find duplicated paths in streams table
  35. var streamDuplicates []struct {
  36. Path string
  37. Count int
  38. }
  39. if err := tx.Model(&model.Stream{}).
  40. Select("path, count(*) as count").
  41. Group("path").
  42. Having("count(*) > 1").
  43. Find(&streamDuplicates).Error; err != nil {
  44. return err
  45. }
  46. // For each duplicated path, delete all but the one with max id
  47. for _, dup := range streamDuplicates {
  48. if err := tx.Exec(`DELETE FROM streams WHERE path = ? AND id NOT IN
  49. (SELECT max(id) FROM streams WHERE path = ?)`, dup.Path, dup.Path).Error; err != nil {
  50. return err
  51. }
  52. }
  53. }
  54. return nil
  55. },
  56. }