aboutsummaryrefslogtreecommitdiffstats
path: root/models/migrations/v61.go
blob: 8d9b7e2d23398717c041389a7549e7feda95b163 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
// Copyright 2018 The Gitea Authors. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.

package migrations

import (
	"fmt"
	"os"
	"path"

	"code.gitea.io/gitea/modules/log"
	"code.gitea.io/gitea/modules/setting"

	"github.com/go-xorm/xorm"
)

func addSizeToAttachment(x *xorm.Engine) error {
	type Attachment struct {
		ID   int64  `xorm:"pk autoincr"`
		UUID string `xorm:"uuid UNIQUE"`
		Size int64  `xorm:"DEFAULT 0"`
	}
	if err := x.Sync2(new(Attachment)); err != nil {
		return fmt.Errorf("Sync2: %v", err)
	}

	attachments := make([]Attachment, 0, 100)
	if err := x.Find(&attachments); err != nil {
		return fmt.Errorf("query attachments: %v", err)
	}
	for _, attach := range attachments {
		localPath := path.Join(setting.AttachmentPath, attach.UUID[0:1], attach.UUID[1:2], attach.UUID)
		fi, err := os.Stat(localPath)
		if err != nil {
			log.Error("calculate file size of attachment[UUID: %s]: %v", attach.UUID, err)
			continue
		}
		attach.Size = fi.Size()
		if _, err := x.ID(attach.ID).Cols("size").Update(attach); err != nil {
			return fmt.Errorf("update size column: %v", err)
		}
	}
	return nil
}