gitea源码

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. // Copyright 2019 The Gitea Authors. All rights reserved.
  2. // SPDX-License-Identifier: MIT
  3. package v1_10
  4. import (
  5. "path/filepath"
  6. "code.gitea.io/gitea/modules/setting"
  7. "code.gitea.io/gitea/modules/util"
  8. "xorm.io/xorm"
  9. )
  10. func DeleteOrphanedAttachments(x *xorm.Engine) error {
  11. type Attachment struct {
  12. ID int64 `xorm:"pk autoincr"`
  13. UUID string `xorm:"uuid UNIQUE"`
  14. IssueID int64 `xorm:"INDEX"`
  15. ReleaseID int64 `xorm:"INDEX"`
  16. CommentID int64
  17. }
  18. sess := x.NewSession()
  19. defer sess.Close()
  20. limit := setting.Database.IterateBufferSize
  21. if limit <= 0 {
  22. limit = 50
  23. }
  24. for {
  25. attachments := make([]Attachment, 0, limit)
  26. if err := sess.Where("`issue_id` = 0 and (`release_id` = 0 or `release_id` not in (select `id` from `release`))").
  27. Cols("id, uuid").Limit(limit).
  28. Asc("id").
  29. Find(&attachments); err != nil {
  30. return err
  31. }
  32. if len(attachments) == 0 {
  33. return nil
  34. }
  35. ids := make([]int64, 0, limit)
  36. for _, attachment := range attachments {
  37. ids = append(ids, attachment.ID)
  38. }
  39. if len(ids) > 0 {
  40. if _, err := sess.In("id", ids).Delete(new(Attachment)); err != nil {
  41. return err
  42. }
  43. }
  44. for _, attachment := range attachments {
  45. uuid := attachment.UUID
  46. if err := util.RemoveAll(filepath.Join(setting.Attachment.Storage.Path, uuid[0:1], uuid[1:2], uuid)); err != nil {
  47. return err
  48. }
  49. }
  50. if len(attachments) < limit {
  51. return nil
  52. }
  53. }
  54. }