Skip to content

Commit 9302eba

Browse files
authored
DBContext is just a Context (#17100)
* DBContext is just a Context This PR removes some of the specialness from the DBContext and makes it context This allows us to simplify the GetEngine code to wrap around any context in future and means that we can change our loadRepo(e Engine) functions to simply take contexts. Signed-off-by: Andrew Thornton <[email protected]> * fix unit tests Signed-off-by: Andrew Thornton <[email protected]> * another place that needs to set the initial context Signed-off-by: Andrew Thornton <[email protected]> * avoid race Signed-off-by: Andrew Thornton <[email protected]> * change attachment error Signed-off-by: Andrew Thornton <[email protected]>
1 parent b22be7f commit 9302eba

File tree

129 files changed

+1112
-1022
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

129 files changed

+1112
-1022
lines changed

models/access.go

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -116,7 +116,7 @@ func (repoAccess) TableName() string {
116116

117117
// GetRepositoryAccesses finds all repositories with their access mode where a user has access but does not own.
118118
func (user *User) GetRepositoryAccesses() (map[*Repository]AccessMode, error) {
119-
rows, err := db.DefaultContext().Engine().
119+
rows, err := db.GetEngine(db.DefaultContext).
120120
Join("INNER", "repository", "repository.id = access.repo_id").
121121
Where("access.user_id = ?", user.ID).
122122
And("repository.owner_id <> ?", user.ID).
@@ -151,7 +151,7 @@ func (user *User) GetRepositoryAccesses() (map[*Repository]AccessMode, error) {
151151
// GetAccessibleRepositories finds repositories which the user has access but does not own.
152152
// If limit is smaller than 1 means returns all found results.
153153
func (user *User) GetAccessibleRepositories(limit int) (repos []*Repository, _ error) {
154-
sess := db.DefaultContext().Engine().
154+
sess := db.GetEngine(db.DefaultContext).
155155
Where("owner_id !=? ", user.ID).
156156
Desc("updated_unix")
157157
if limit > 0 {
@@ -342,5 +342,5 @@ func (repo *Repository) recalculateAccesses(e db.Engine) error {
342342

343343
// RecalculateAccesses recalculates all accesses for repository.
344344
func (repo *Repository) RecalculateAccesses() error {
345-
return repo.recalculateAccesses(db.DefaultContext().Engine())
345+
return repo.recalculateAccesses(db.GetEngine(db.DefaultContext))
346346
}

models/access_test.go

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -127,12 +127,12 @@ func TestRepository_RecalculateAccesses(t *testing.T) {
127127
repo1 := db.AssertExistsAndLoadBean(t, &Repository{ID: 3}).(*Repository)
128128
assert.NoError(t, repo1.GetOwner())
129129

130-
_, err := db.DefaultContext().Engine().Delete(&Collaboration{UserID: 2, RepoID: 3})
130+
_, err := db.GetEngine(db.DefaultContext).Delete(&Collaboration{UserID: 2, RepoID: 3})
131131
assert.NoError(t, err)
132132
assert.NoError(t, repo1.RecalculateAccesses())
133133

134134
access := &Access{UserID: 2, RepoID: 3}
135-
has, err := db.DefaultContext().Engine().Get(access)
135+
has, err := db.GetEngine(db.DefaultContext).Get(access)
136136
assert.NoError(t, err)
137137
assert.True(t, has)
138138
assert.Equal(t, AccessModeOwner, access.Mode)
@@ -144,11 +144,11 @@ func TestRepository_RecalculateAccesses2(t *testing.T) {
144144
repo1 := db.AssertExistsAndLoadBean(t, &Repository{ID: 4}).(*Repository)
145145
assert.NoError(t, repo1.GetOwner())
146146

147-
_, err := db.DefaultContext().Engine().Delete(&Collaboration{UserID: 4, RepoID: 4})
147+
_, err := db.GetEngine(db.DefaultContext).Delete(&Collaboration{UserID: 4, RepoID: 4})
148148
assert.NoError(t, err)
149149
assert.NoError(t, repo1.RecalculateAccesses())
150150

151-
has, err := db.DefaultContext().Engine().Get(&Access{UserID: 4, RepoID: 4})
151+
has, err := db.GetEngine(db.DefaultContext).Get(&Access{UserID: 4, RepoID: 4})
152152
assert.NoError(t, err)
153153
assert.False(t, has)
154154
}
@@ -158,15 +158,15 @@ func TestRepository_RecalculateAccesses3(t *testing.T) {
158158
team5 := db.AssertExistsAndLoadBean(t, &Team{ID: 5}).(*Team)
159159
user29 := db.AssertExistsAndLoadBean(t, &User{ID: 29}).(*User)
160160

161-
has, err := db.DefaultContext().Engine().Get(&Access{UserID: 29, RepoID: 23})
161+
has, err := db.GetEngine(db.DefaultContext).Get(&Access{UserID: 29, RepoID: 23})
162162
assert.NoError(t, err)
163163
assert.False(t, has)
164164

165165
// adding user29 to team5 should add an explicit access row for repo 23
166166
// even though repo 23 is public
167167
assert.NoError(t, AddTeamMember(team5, user29.ID))
168168

169-
has, err = db.DefaultContext().Engine().Get(&Access{UserID: 29, RepoID: 23})
169+
has, err = db.GetEngine(db.DefaultContext).Get(&Access{UserID: 29, RepoID: 23})
170170
assert.NoError(t, err)
171171
assert.True(t, has)
172172
}

models/action.go

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -208,7 +208,7 @@ func GetRepositoryFromMatch(ownerName, repoName string) (*Repository, error) {
208208

209209
// GetCommentLink returns link to action comment.
210210
func (a *Action) GetCommentLink() string {
211-
return a.getCommentLink(db.DefaultContext().Engine())
211+
return a.getCommentLink(db.GetEngine(db.DefaultContext))
212212
}
213213

214214
func (a *Action) getCommentLink(e db.Engine) string {
@@ -317,7 +317,7 @@ func GetFeeds(opts GetFeedsOptions) ([]*Action, error) {
317317

318318
actions := make([]*Action, 0, setting.UI.FeedPagingNum)
319319

320-
if err := db.DefaultContext().Engine().Limit(setting.UI.FeedPagingNum).Desc("created_unix").Where(cond).Find(&actions); err != nil {
320+
if err := db.GetEngine(db.DefaultContext).Limit(setting.UI.FeedPagingNum).Desc("created_unix").Where(cond).Find(&actions); err != nil {
321321
return nil, fmt.Errorf("Find: %v", err)
322322
}
323323

@@ -408,6 +408,6 @@ func DeleteOldActions(olderThan time.Duration) (err error) {
408408
return nil
409409
}
410410

411-
_, err = db.DefaultContext().Engine().Where("created_unix < ?", time.Now().Add(-olderThan).Unix()).Delete(&Action{})
411+
_, err = db.GetEngine(db.DefaultContext).Where("created_unix < ?", time.Now().Add(-olderThan).Unix()).Delete(&Action{})
412412
return
413413
}

models/action_list.go

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -45,7 +45,7 @@ func (actions ActionList) loadUsers(e db.Engine) ([]*User, error) {
4545

4646
// LoadUsers loads actions' all users
4747
func (actions ActionList) LoadUsers() ([]*User, error) {
48-
return actions.loadUsers(db.DefaultContext().Engine())
48+
return actions.loadUsers(db.GetEngine(db.DefaultContext))
4949
}
5050

5151
func (actions ActionList) getRepoIDs() []int64 {
@@ -80,7 +80,7 @@ func (actions ActionList) loadRepositories(e db.Engine) ([]*Repository, error) {
8080

8181
// LoadRepositories loads actions' all repositories
8282
func (actions ActionList) LoadRepositories() ([]*Repository, error) {
83-
return actions.loadRepositories(db.DefaultContext().Engine())
83+
return actions.loadRepositories(db.GetEngine(db.DefaultContext))
8484
}
8585

8686
// loadAttributes loads all attributes
@@ -98,5 +98,5 @@ func (actions ActionList) loadAttributes(e db.Engine) (err error) {
9898

9999
// LoadAttributes loads attributes of the actions
100100
func (actions ActionList) LoadAttributes() error {
101-
return actions.loadAttributes(db.DefaultContext().Engine())
101+
return actions.loadAttributes(db.GetEngine(db.DefaultContext))
102102
}

models/admin.go

Lines changed: 11 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -44,7 +44,7 @@ func (n *Notice) TrStr() string {
4444

4545
// CreateNotice creates new system notice.
4646
func CreateNotice(tp NoticeType, desc string, args ...interface{}) error {
47-
return createNotice(db.DefaultContext().Engine(), tp, desc, args...)
47+
return createNotice(db.GetEngine(db.DefaultContext), tp, desc, args...)
4848
}
4949

5050
func createNotice(e db.Engine, tp NoticeType, desc string, args ...interface{}) error {
@@ -61,19 +61,19 @@ func createNotice(e db.Engine, tp NoticeType, desc string, args ...interface{})
6161

6262
// CreateRepositoryNotice creates new system notice with type NoticeRepository.
6363
func CreateRepositoryNotice(desc string, args ...interface{}) error {
64-
return createNotice(db.DefaultContext().Engine(), NoticeRepository, desc, args...)
64+
return createNotice(db.GetEngine(db.DefaultContext), NoticeRepository, desc, args...)
6565
}
6666

6767
// RemoveAllWithNotice removes all directories in given path and
6868
// creates a system notice when error occurs.
6969
func RemoveAllWithNotice(title, path string) {
70-
removeAllWithNotice(db.DefaultContext().Engine(), title, path)
70+
removeAllWithNotice(db.GetEngine(db.DefaultContext), title, path)
7171
}
7272

7373
// RemoveStorageWithNotice removes a file from the storage and
7474
// creates a system notice when error occurs.
7575
func RemoveStorageWithNotice(bucket storage.ObjectStorage, title, path string) {
76-
removeStorageWithNotice(db.DefaultContext().Engine(), bucket, title, path)
76+
removeStorageWithNotice(db.GetEngine(db.DefaultContext), bucket, title, path)
7777
}
7878

7979
func removeStorageWithNotice(e db.Engine, bucket storage.ObjectStorage, title, path string) {
@@ -98,33 +98,33 @@ func removeAllWithNotice(e db.Engine, title, path string) {
9898

9999
// CountNotices returns number of notices.
100100
func CountNotices() int64 {
101-
count, _ := db.DefaultContext().Engine().Count(new(Notice))
101+
count, _ := db.GetEngine(db.DefaultContext).Count(new(Notice))
102102
return count
103103
}
104104

105105
// Notices returns notices in given page.
106106
func Notices(page, pageSize int) ([]*Notice, error) {
107107
notices := make([]*Notice, 0, pageSize)
108-
return notices, db.DefaultContext().Engine().
108+
return notices, db.GetEngine(db.DefaultContext).
109109
Limit(pageSize, (page-1)*pageSize).
110110
Desc("id").
111111
Find(&notices)
112112
}
113113

114114
// DeleteNotice deletes a system notice by given ID.
115115
func DeleteNotice(id int64) error {
116-
_, err := db.DefaultContext().Engine().ID(id).Delete(new(Notice))
116+
_, err := db.GetEngine(db.DefaultContext).ID(id).Delete(new(Notice))
117117
return err
118118
}
119119

120120
// DeleteNotices deletes all notices with ID from start to end (inclusive).
121121
func DeleteNotices(start, end int64) error {
122122
if start == 0 && end == 0 {
123-
_, err := db.DefaultContext().Engine().Exec("DELETE FROM notice")
123+
_, err := db.GetEngine(db.DefaultContext).Exec("DELETE FROM notice")
124124
return err
125125
}
126126

127-
sess := db.DefaultContext().Engine().Where("id >= ?", start)
127+
sess := db.GetEngine(db.DefaultContext).Where("id >= ?", start)
128128
if end > 0 {
129129
sess.And("id <= ?", end)
130130
}
@@ -137,7 +137,7 @@ func DeleteNoticesByIDs(ids []int64) error {
137137
if len(ids) == 0 {
138138
return nil
139139
}
140-
_, err := db.DefaultContext().Engine().
140+
_, err := db.GetEngine(db.DefaultContext).
141141
In("id", ids).
142142
Delete(new(Notice))
143143
return err
@@ -146,7 +146,7 @@ func DeleteNoticesByIDs(ids []int64) error {
146146
// GetAdminUser returns the first administrator
147147
func GetAdminUser() (*User, error) {
148148
var admin User
149-
has, err := db.DefaultContext().Engine().Where("is_admin=?", true).Get(&admin)
149+
has, err := db.GetEngine(db.DefaultContext).Where("is_admin=?", true).Get(&admin)
150150
if err != nil {
151151
return nil, err
152152
} else if !has {

models/attachment.go

Lines changed: 23 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
package models
66

77
import (
8+
"context"
89
"fmt"
910
"path"
1011

@@ -38,7 +39,7 @@ func init() {
3839
// IncreaseDownloadCount is update download count + 1
3940
func (a *Attachment) IncreaseDownloadCount() error {
4041
// Update download count.
41-
if _, err := db.DefaultContext().Engine().Exec("UPDATE `attachment` SET download_count=download_count+1 WHERE id=?", a.ID); err != nil {
42+
if _, err := db.GetEngine(db.DefaultContext).Exec("UPDATE `attachment` SET download_count=download_count+1 WHERE id=?", a.ID); err != nil {
4243
return fmt.Errorf("increase attachment count: %v", err)
4344
}
4445

@@ -86,7 +87,7 @@ func (a *Attachment) LinkedRepository() (*Repository, UnitType, error) {
8687

8788
// GetAttachmentByID returns attachment by given id
8889
func GetAttachmentByID(id int64) (*Attachment, error) {
89-
return getAttachmentByID(db.DefaultContext().Engine(), id)
90+
return getAttachmentByID(db.GetEngine(db.DefaultContext), id)
9091
}
9192

9293
func getAttachmentByID(e db.Engine, id int64) (*Attachment, error) {
@@ -111,8 +112,8 @@ func getAttachmentByUUID(e db.Engine, uuid string) (*Attachment, error) {
111112
}
112113

113114
// GetAttachmentsByUUIDs returns attachment by given UUID list.
114-
func GetAttachmentsByUUIDs(ctx *db.Context, uuids []string) ([]*Attachment, error) {
115-
return getAttachmentsByUUIDs(ctx.Engine(), uuids)
115+
func GetAttachmentsByUUIDs(ctx context.Context, uuids []string) ([]*Attachment, error) {
116+
return getAttachmentsByUUIDs(db.GetEngine(ctx), uuids)
116117
}
117118

118119
func getAttachmentsByUUIDs(e db.Engine, uuids []string) ([]*Attachment, error) {
@@ -127,17 +128,17 @@ func getAttachmentsByUUIDs(e db.Engine, uuids []string) ([]*Attachment, error) {
127128

128129
// GetAttachmentByUUID returns attachment by given UUID.
129130
func GetAttachmentByUUID(uuid string) (*Attachment, error) {
130-
return getAttachmentByUUID(db.DefaultContext().Engine(), uuid)
131+
return getAttachmentByUUID(db.GetEngine(db.DefaultContext), uuid)
131132
}
132133

133134
// ExistAttachmentsByUUID returns true if attachment is exist by given UUID
134135
func ExistAttachmentsByUUID(uuid string) (bool, error) {
135-
return db.DefaultContext().Engine().Where("`uuid`=?", uuid).Exist(new(Attachment))
136+
return db.GetEngine(db.DefaultContext).Where("`uuid`=?", uuid).Exist(new(Attachment))
136137
}
137138

138139
// GetAttachmentByReleaseIDFileName returns attachment by given releaseId and fileName.
139140
func GetAttachmentByReleaseIDFileName(releaseID int64, fileName string) (*Attachment, error) {
140-
return getAttachmentByReleaseIDFileName(db.DefaultContext().Engine(), releaseID, fileName)
141+
return getAttachmentByReleaseIDFileName(db.GetEngine(db.DefaultContext), releaseID, fileName)
141142
}
142143

143144
func getAttachmentsByIssueID(e db.Engine, issueID int64) ([]*Attachment, error) {
@@ -147,12 +148,12 @@ func getAttachmentsByIssueID(e db.Engine, issueID int64) ([]*Attachment, error)
147148

148149
// GetAttachmentsByIssueID returns all attachments of an issue.
149150
func GetAttachmentsByIssueID(issueID int64) ([]*Attachment, error) {
150-
return getAttachmentsByIssueID(db.DefaultContext().Engine(), issueID)
151+
return getAttachmentsByIssueID(db.GetEngine(db.DefaultContext), issueID)
151152
}
152153

153154
// GetAttachmentsByCommentID returns all attachments if comment by given ID.
154155
func GetAttachmentsByCommentID(commentID int64) ([]*Attachment, error) {
155-
return getAttachmentsByCommentID(db.DefaultContext().Engine(), commentID)
156+
return getAttachmentsByCommentID(db.GetEngine(db.DefaultContext), commentID)
156157
}
157158

158159
func getAttachmentsByCommentID(e db.Engine, commentID int64) ([]*Attachment, error) {
@@ -174,12 +175,12 @@ func getAttachmentByReleaseIDFileName(e db.Engine, releaseID int64, fileName str
174175

175176
// DeleteAttachment deletes the given attachment and optionally the associated file.
176177
func DeleteAttachment(a *Attachment, remove bool) error {
177-
_, err := DeleteAttachments(db.DefaultContext(), []*Attachment{a}, remove)
178+
_, err := DeleteAttachments(db.DefaultContext, []*Attachment{a}, remove)
178179
return err
179180
}
180181

181182
// DeleteAttachments deletes the given attachments and optionally the associated files.
182-
func DeleteAttachments(ctx *db.Context, attachments []*Attachment, remove bool) (int, error) {
183+
func DeleteAttachments(ctx context.Context, attachments []*Attachment, remove bool) (int, error) {
183184
if len(attachments) == 0 {
184185
return 0, nil
185186
}
@@ -189,7 +190,7 @@ func DeleteAttachments(ctx *db.Context, attachments []*Attachment, remove bool)
189190
ids = append(ids, a.ID)
190191
}
191192

192-
cnt, err := ctx.Engine().In("id", ids).NoAutoCondition().Delete(attachments[0])
193+
cnt, err := db.GetEngine(ctx).In("id", ids).NoAutoCondition().Delete(attachments[0])
193194
if err != nil {
194195
return 0, err
195196
}
@@ -211,7 +212,7 @@ func DeleteAttachmentsByIssue(issueID int64, remove bool) (int, error) {
211212
return 0, err
212213
}
213214

214-
return DeleteAttachments(db.DefaultContext(), attachments, remove)
215+
return DeleteAttachments(db.DefaultContext, attachments, remove)
215216
}
216217

217218
// DeleteAttachmentsByComment deletes all attachments associated with the given comment.
@@ -221,20 +222,20 @@ func DeleteAttachmentsByComment(commentID int64, remove bool) (int, error) {
221222
return 0, err
222223
}
223224

224-
return DeleteAttachments(db.DefaultContext(), attachments, remove)
225+
return DeleteAttachments(db.DefaultContext, attachments, remove)
225226
}
226227

227228
// UpdateAttachment updates the given attachment in database
228229
func UpdateAttachment(atta *Attachment) error {
229-
return updateAttachment(db.DefaultContext().Engine(), atta)
230+
return updateAttachment(db.GetEngine(db.DefaultContext), atta)
230231
}
231232

232233
// UpdateAttachmentByUUID Updates attachment via uuid
233-
func UpdateAttachmentByUUID(ctx *db.Context, attach *Attachment, cols ...string) error {
234+
func UpdateAttachmentByUUID(ctx context.Context, attach *Attachment, cols ...string) error {
234235
if attach.UUID == "" {
235-
return fmt.Errorf("Attachement uuid should not blank")
236+
return fmt.Errorf("attachment uuid should be not blank")
236237
}
237-
_, err := ctx.Engine().Where("uuid=?", attach.UUID).Cols(cols...).Update(attach)
238+
_, err := db.GetEngine(ctx).Where("uuid=?", attach.UUID).Cols(cols...).Update(attach)
238239
return err
239240
}
240241

@@ -252,7 +253,7 @@ func updateAttachment(e db.Engine, atta *Attachment) error {
252253

253254
// DeleteAttachmentsByRelease deletes all attachments associated with the given release.
254255
func DeleteAttachmentsByRelease(releaseID int64) error {
255-
_, err := db.DefaultContext().Engine().Where("release_id = ?", releaseID).Delete(&Attachment{})
256+
_, err := db.GetEngine(db.DefaultContext).Where("release_id = ?", releaseID).Delete(&Attachment{})
256257
return err
257258
}
258259

@@ -262,7 +263,7 @@ func IterateAttachment(f func(attach *Attachment) error) error {
262263
const batchSize = 100
263264
for {
264265
attachments := make([]*Attachment, 0, batchSize)
265-
if err := db.DefaultContext().Engine().Limit(batchSize, start).Find(&attachments); err != nil {
266+
if err := db.GetEngine(db.DefaultContext).Limit(batchSize, start).Find(&attachments); err != nil {
266267
return err
267268
}
268269
if len(attachments) == 0 {
@@ -280,13 +281,13 @@ func IterateAttachment(f func(attach *Attachment) error) error {
280281

281282
// CountOrphanedAttachments returns the number of bad attachments
282283
func CountOrphanedAttachments() (int64, error) {
283-
return db.DefaultContext().Engine().Where("(issue_id > 0 and issue_id not in (select id from issue)) or (release_id > 0 and release_id not in (select id from `release`))").
284+
return db.GetEngine(db.DefaultContext).Where("(issue_id > 0 and issue_id not in (select id from issue)) or (release_id > 0 and release_id not in (select id from `release`))").
284285
Count(new(Attachment))
285286
}
286287

287288
// DeleteOrphanedAttachments delete all bad attachments
288289
func DeleteOrphanedAttachments() error {
289-
_, err := db.DefaultContext().Engine().Where("(issue_id > 0 and issue_id not in (select id from issue)) or (release_id > 0 and release_id not in (select id from `release`))").
290+
_, err := db.GetEngine(db.DefaultContext).Where("(issue_id > 0 and issue_id not in (select id from issue)) or (release_id > 0 and release_id not in (select id from `release`))").
290291
Delete(new(Attachment))
291292
return err
292293
}

models/attachment_test.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -92,7 +92,7 @@ func TestUpdateAttachment(t *testing.T) {
9292
func TestGetAttachmentsByUUIDs(t *testing.T) {
9393
assert.NoError(t, db.PrepareTestDatabase())
9494

95-
attachList, err := GetAttachmentsByUUIDs(db.DefaultContext(), []string{"a0eebc99-9c0b-4ef8-bb6d-6bb9bd380a11", "a0eebc99-9c0b-4ef8-bb6d-6bb9bd380a17", "not-existing-uuid"})
95+
attachList, err := GetAttachmentsByUUIDs(db.DefaultContext, []string{"a0eebc99-9c0b-4ef8-bb6d-6bb9bd380a11", "a0eebc99-9c0b-4ef8-bb6d-6bb9bd380a17", "not-existing-uuid"})
9696
assert.NoError(t, err)
9797
assert.Len(t, attachList, 2)
9898
assert.Equal(t, "a0eebc99-9c0b-4ef8-bb6d-6bb9bd380a11", attachList[0].UUID)

0 commit comments

Comments
 (0)