You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

v96.go 1.5 kB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. // Copyright 2019 The Gitea 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. "path"
  7. "code.gitea.io/gitea/modules/setting"
  8. "code.gitea.io/gitea/modules/storage"
  9. "xorm.io/xorm"
  10. )
  11. func relativePath(uuid string) string {
  12. return path.Join(uuid[0:1], uuid[1:2], uuid)
  13. }
  14. func deleteOrphanedAttachments(x *xorm.Engine) error {
  15. type Attachment struct {
  16. ID int64 `xorm:"pk autoincr"`
  17. UUID string `xorm:"uuid UNIQUE"`
  18. IssueID int64 `xorm:"INDEX"`
  19. ReleaseID int64 `xorm:"INDEX"`
  20. CommentID int64
  21. }
  22. sess := x.NewSession()
  23. defer sess.Close()
  24. var limit = setting.Database.IterateBufferSize
  25. if limit <= 0 {
  26. limit = 50
  27. }
  28. for {
  29. attachements := make([]Attachment, 0, limit)
  30. if err := sess.Where("`issue_id` = 0 and (`release_id` = 0 or `release_id` not in (select `id` from `release`))").
  31. Cols("id, uuid").Limit(limit).
  32. Asc("id").
  33. Find(&attachements); err != nil {
  34. return err
  35. }
  36. if len(attachements) == 0 {
  37. return nil
  38. }
  39. var ids = make([]int64, 0, limit)
  40. for _, attachment := range attachements {
  41. ids = append(ids, attachment.ID)
  42. }
  43. if len(ids) > 0 {
  44. if _, err := sess.In("id", ids).Delete(new(Attachment)); err != nil {
  45. return err
  46. }
  47. }
  48. for _, attachment := range attachements {
  49. if err := storage.Attachments.Delete(relativePath(attachment.UUID)); err != nil {
  50. return err
  51. }
  52. }
  53. if len(attachements) < limit {
  54. return nil
  55. }
  56. }
  57. }