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

v96.go 1.6KB

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