From 9302eba971611601c3ebf6024e22a11c63f4e151 Mon Sep 17 00:00:00 2001 From: zeripath Date: Thu, 23 Sep 2021 16:45:36 +0100 Subject: [PATCH] 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 * fix unit tests Signed-off-by: Andrew Thornton * another place that needs to set the initial context Signed-off-by: Andrew Thornton * avoid race Signed-off-by: Andrew Thornton * change attachment error Signed-off-by: Andrew Thornton --- models/access.go | 6 +- models/access_test.go | 12 +- models/action.go | 6 +- models/action_list.go | 6 +- models/admin.go | 22 ++-- models/attachment.go | 45 +++---- models/attachment_test.go | 2 +- models/avatar.go | 9 +- models/branches.go | 32 ++--- models/commit_status.go | 12 +- models/consistency.go | 72 +++++----- models/consistency_test.go | 6 +- models/db/context.go | 85 ++++++++++-- models/db/engine.go | 5 + models/db/unit_tests.go | 6 + models/engine_test.go | 2 +- models/external_login_user.go | 18 +-- models/fixture_generation.go | 4 +- models/gpg_key.go | 10 +- models/gpg_key_add.go | 4 +- models/gpg_key_import.go | 2 +- models/gpg_key_verify.go | 4 +- models/issue.go | 147 ++++++++++----------- models/issue_assignees.go | 10 +- models/issue_comment.go | 58 ++++----- models/issue_comment_list.go | 8 +- models/issue_dependency.go | 8 +- models/issue_label.go | 53 ++++---- models/issue_list.go | 14 +- models/issue_lock.go | 2 +- models/issue_milestone.go | 40 +++--- models/issue_milestone_test.go | 12 +- models/issue_reaction.go | 12 +- models/issue_reaction_test.go | 2 +- models/issue_stopwatch.go | 12 +- models/issue_test.go | 14 +- models/issue_tracked_time.go | 16 +-- models/issue_user.go | 11 +- models/issue_user_test.go | 4 +- models/issue_watch.go | 16 +-- models/issue_xref.go | 4 +- models/issue_xref_test.go | 4 +- models/lfs.go | 18 +-- models/lfs_lock.go | 12 +- models/list_options.go | 2 +- models/login_source.go | 28 ++-- models/migrate.go | 12 +- models/notification.go | 36 ++--- models/oauth2.go | 4 +- models/oauth2_application.go | 36 ++--- models/org.go | 62 ++++----- models/org_team.go | 56 ++++---- models/org_test.go | 2 +- models/project.go | 14 +- models/project_board.go | 16 +-- models/project_issue.go | 16 +-- models/protected_tag.go | 10 +- models/pull.go | 40 +++--- models/pull_list.go | 12 +- models/release.go | 43 +++--- models/repo.go | 166 ++++++++++++------------ models/repo_activity.go | 6 +- models/repo_archiver.go | 17 +-- models/repo_avatar.go | 10 +- models/repo_collaboration.go | 18 +-- models/repo_collaboration_test.go | 2 +- models/repo_generate.go | 21 +-- models/repo_indexer.go | 6 +- models/repo_language_stats.go | 8 +- models/repo_list.go | 8 +- models/repo_mirror.go | 10 +- models/repo_permission.go | 16 +-- models/repo_permission_test.go | 8 +- models/repo_pushmirror.go | 14 +- models/repo_redirect.go | 2 +- models/repo_redirect_test.go | 6 +- models/repo_test.go | 2 +- models/repo_transfer.go | 8 +- models/repo_watch.go | 20 +-- models/review.go | 60 ++++----- models/session.go | 14 +- models/ssh_key.go | 24 ++-- models/ssh_key_authorized_keys.go | 6 +- models/ssh_key_authorized_principals.go | 6 +- models/ssh_key_deploy.go | 18 +-- models/ssh_key_principals.go | 4 +- models/star.go | 12 +- models/statistic.go | 32 ++--- models/task.go | 18 +-- models/token.go | 16 +-- models/topic.go | 14 +- models/twofactor.go | 8 +- models/u2f.go | 10 +- models/update.go | 13 +- models/upload.go | 8 +- models/user.go | 86 ++++++------ models/user_avatar.go | 6 +- models/user_follow.go | 6 +- models/user_heatmap.go | 2 +- models/user_mail.go | 28 ++-- models/user_openid.go | 12 +- models/user_redirect.go | 2 +- models/user_redirect_test.go | 6 +- models/user_test.go | 8 +- models/userlist.go | 4 +- models/webhook.go | 40 +++--- modules/doctor/mergebase.go | 2 +- modules/doctor/misc.go | 2 +- modules/repository/adopt.go | 3 +- modules/repository/check.go | 8 +- modules/repository/create.go | 3 +- modules/repository/fork.go | 7 +- modules/repository/generate.go | 8 +- modules/repository/hooks.go | 2 +- modules/repository/init.go | 8 +- modules/repository/repo.go | 2 +- modules/repository/update.go | 5 +- routers/web/org/org_labels.go | 2 +- routers/web/repo/issue_label.go | 2 +- routers/web/repo/repo.go | 8 +- services/attachment/attachment.go | 3 +- services/comments/comments.go | 2 +- services/issue/issue.go | 2 +- services/mirror/mirror_pull.go | 2 +- services/pull/pull.go | 2 +- services/pull/review.go | 4 +- services/release/release.go | 4 +- services/repository/generate.go | 4 +- services/repository/push.go | 2 +- 129 files changed, 1112 insertions(+), 1022 deletions(-) diff --git a/models/access.go b/models/access.go index e230629040b..88fbe8189fa 100644 --- a/models/access.go +++ b/models/access.go @@ -116,7 +116,7 @@ func (repoAccess) TableName() string { // GetRepositoryAccesses finds all repositories with their access mode where a user has access but does not own. func (user *User) GetRepositoryAccesses() (map[*Repository]AccessMode, error) { - rows, err := db.DefaultContext().Engine(). + rows, err := db.GetEngine(db.DefaultContext). Join("INNER", "repository", "repository.id = access.repo_id"). Where("access.user_id = ?", user.ID). And("repository.owner_id <> ?", user.ID). @@ -151,7 +151,7 @@ func (user *User) GetRepositoryAccesses() (map[*Repository]AccessMode, error) { // GetAccessibleRepositories finds repositories which the user has access but does not own. // If limit is smaller than 1 means returns all found results. func (user *User) GetAccessibleRepositories(limit int) (repos []*Repository, _ error) { - sess := db.DefaultContext().Engine(). + sess := db.GetEngine(db.DefaultContext). Where("owner_id !=? ", user.ID). Desc("updated_unix") if limit > 0 { @@ -342,5 +342,5 @@ func (repo *Repository) recalculateAccesses(e db.Engine) error { // RecalculateAccesses recalculates all accesses for repository. func (repo *Repository) RecalculateAccesses() error { - return repo.recalculateAccesses(db.DefaultContext().Engine()) + return repo.recalculateAccesses(db.GetEngine(db.DefaultContext)) } diff --git a/models/access_test.go b/models/access_test.go index 875b2a0c1ab..2f641bb9b57 100644 --- a/models/access_test.go +++ b/models/access_test.go @@ -127,12 +127,12 @@ func TestRepository_RecalculateAccesses(t *testing.T) { repo1 := db.AssertExistsAndLoadBean(t, &Repository{ID: 3}).(*Repository) assert.NoError(t, repo1.GetOwner()) - _, err := db.DefaultContext().Engine().Delete(&Collaboration{UserID: 2, RepoID: 3}) + _, err := db.GetEngine(db.DefaultContext).Delete(&Collaboration{UserID: 2, RepoID: 3}) assert.NoError(t, err) assert.NoError(t, repo1.RecalculateAccesses()) access := &Access{UserID: 2, RepoID: 3} - has, err := db.DefaultContext().Engine().Get(access) + has, err := db.GetEngine(db.DefaultContext).Get(access) assert.NoError(t, err) assert.True(t, has) assert.Equal(t, AccessModeOwner, access.Mode) @@ -144,11 +144,11 @@ func TestRepository_RecalculateAccesses2(t *testing.T) { repo1 := db.AssertExistsAndLoadBean(t, &Repository{ID: 4}).(*Repository) assert.NoError(t, repo1.GetOwner()) - _, err := db.DefaultContext().Engine().Delete(&Collaboration{UserID: 4, RepoID: 4}) + _, err := db.GetEngine(db.DefaultContext).Delete(&Collaboration{UserID: 4, RepoID: 4}) assert.NoError(t, err) assert.NoError(t, repo1.RecalculateAccesses()) - has, err := db.DefaultContext().Engine().Get(&Access{UserID: 4, RepoID: 4}) + has, err := db.GetEngine(db.DefaultContext).Get(&Access{UserID: 4, RepoID: 4}) assert.NoError(t, err) assert.False(t, has) } @@ -158,7 +158,7 @@ func TestRepository_RecalculateAccesses3(t *testing.T) { team5 := db.AssertExistsAndLoadBean(t, &Team{ID: 5}).(*Team) user29 := db.AssertExistsAndLoadBean(t, &User{ID: 29}).(*User) - has, err := db.DefaultContext().Engine().Get(&Access{UserID: 29, RepoID: 23}) + has, err := db.GetEngine(db.DefaultContext).Get(&Access{UserID: 29, RepoID: 23}) assert.NoError(t, err) assert.False(t, has) @@ -166,7 +166,7 @@ func TestRepository_RecalculateAccesses3(t *testing.T) { // even though repo 23 is public assert.NoError(t, AddTeamMember(team5, user29.ID)) - has, err = db.DefaultContext().Engine().Get(&Access{UserID: 29, RepoID: 23}) + has, err = db.GetEngine(db.DefaultContext).Get(&Access{UserID: 29, RepoID: 23}) assert.NoError(t, err) assert.True(t, has) } diff --git a/models/action.go b/models/action.go index f17f75779bd..7c970e1fdb6 100644 --- a/models/action.go +++ b/models/action.go @@ -208,7 +208,7 @@ func GetRepositoryFromMatch(ownerName, repoName string) (*Repository, error) { // GetCommentLink returns link to action comment. func (a *Action) GetCommentLink() string { - return a.getCommentLink(db.DefaultContext().Engine()) + return a.getCommentLink(db.GetEngine(db.DefaultContext)) } func (a *Action) getCommentLink(e db.Engine) string { @@ -317,7 +317,7 @@ func GetFeeds(opts GetFeedsOptions) ([]*Action, error) { actions := make([]*Action, 0, setting.UI.FeedPagingNum) - if err := db.DefaultContext().Engine().Limit(setting.UI.FeedPagingNum).Desc("created_unix").Where(cond).Find(&actions); err != nil { + if err := db.GetEngine(db.DefaultContext).Limit(setting.UI.FeedPagingNum).Desc("created_unix").Where(cond).Find(&actions); err != nil { return nil, fmt.Errorf("Find: %v", err) } @@ -408,6 +408,6 @@ func DeleteOldActions(olderThan time.Duration) (err error) { return nil } - _, err = db.DefaultContext().Engine().Where("created_unix < ?", time.Now().Add(-olderThan).Unix()).Delete(&Action{}) + _, err = db.GetEngine(db.DefaultContext).Where("created_unix < ?", time.Now().Add(-olderThan).Unix()).Delete(&Action{}) return } diff --git a/models/action_list.go b/models/action_list.go index a0ceef6bee5..69e6aa73121 100644 --- a/models/action_list.go +++ b/models/action_list.go @@ -45,7 +45,7 @@ func (actions ActionList) loadUsers(e db.Engine) ([]*User, error) { // LoadUsers loads actions' all users func (actions ActionList) LoadUsers() ([]*User, error) { - return actions.loadUsers(db.DefaultContext().Engine()) + return actions.loadUsers(db.GetEngine(db.DefaultContext)) } func (actions ActionList) getRepoIDs() []int64 { @@ -80,7 +80,7 @@ func (actions ActionList) loadRepositories(e db.Engine) ([]*Repository, error) { // LoadRepositories loads actions' all repositories func (actions ActionList) LoadRepositories() ([]*Repository, error) { - return actions.loadRepositories(db.DefaultContext().Engine()) + return actions.loadRepositories(db.GetEngine(db.DefaultContext)) } // loadAttributes loads all attributes @@ -98,5 +98,5 @@ func (actions ActionList) loadAttributes(e db.Engine) (err error) { // LoadAttributes loads attributes of the actions func (actions ActionList) LoadAttributes() error { - return actions.loadAttributes(db.DefaultContext().Engine()) + return actions.loadAttributes(db.GetEngine(db.DefaultContext)) } diff --git a/models/admin.go b/models/admin.go index 084942ff5e4..27a2032e2cf 100644 --- a/models/admin.go +++ b/models/admin.go @@ -44,7 +44,7 @@ func (n *Notice) TrStr() string { // CreateNotice creates new system notice. func CreateNotice(tp NoticeType, desc string, args ...interface{}) error { - return createNotice(db.DefaultContext().Engine(), tp, desc, args...) + return createNotice(db.GetEngine(db.DefaultContext), tp, desc, args...) } 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{}) // CreateRepositoryNotice creates new system notice with type NoticeRepository. func CreateRepositoryNotice(desc string, args ...interface{}) error { - return createNotice(db.DefaultContext().Engine(), NoticeRepository, desc, args...) + return createNotice(db.GetEngine(db.DefaultContext), NoticeRepository, desc, args...) } // RemoveAllWithNotice removes all directories in given path and // creates a system notice when error occurs. func RemoveAllWithNotice(title, path string) { - removeAllWithNotice(db.DefaultContext().Engine(), title, path) + removeAllWithNotice(db.GetEngine(db.DefaultContext), title, path) } // RemoveStorageWithNotice removes a file from the storage and // creates a system notice when error occurs. func RemoveStorageWithNotice(bucket storage.ObjectStorage, title, path string) { - removeStorageWithNotice(db.DefaultContext().Engine(), bucket, title, path) + removeStorageWithNotice(db.GetEngine(db.DefaultContext), bucket, title, path) } func removeStorageWithNotice(e db.Engine, bucket storage.ObjectStorage, title, path string) { @@ -98,14 +98,14 @@ func removeAllWithNotice(e db.Engine, title, path string) { // CountNotices returns number of notices. func CountNotices() int64 { - count, _ := db.DefaultContext().Engine().Count(new(Notice)) + count, _ := db.GetEngine(db.DefaultContext).Count(new(Notice)) return count } // Notices returns notices in given page. func Notices(page, pageSize int) ([]*Notice, error) { notices := make([]*Notice, 0, pageSize) - return notices, db.DefaultContext().Engine(). + return notices, db.GetEngine(db.DefaultContext). Limit(pageSize, (page-1)*pageSize). Desc("id"). Find(¬ices) @@ -113,18 +113,18 @@ func Notices(page, pageSize int) ([]*Notice, error) { // DeleteNotice deletes a system notice by given ID. func DeleteNotice(id int64) error { - _, err := db.DefaultContext().Engine().ID(id).Delete(new(Notice)) + _, err := db.GetEngine(db.DefaultContext).ID(id).Delete(new(Notice)) return err } // DeleteNotices deletes all notices with ID from start to end (inclusive). func DeleteNotices(start, end int64) error { if start == 0 && end == 0 { - _, err := db.DefaultContext().Engine().Exec("DELETE FROM notice") + _, err := db.GetEngine(db.DefaultContext).Exec("DELETE FROM notice") return err } - sess := db.DefaultContext().Engine().Where("id >= ?", start) + sess := db.GetEngine(db.DefaultContext).Where("id >= ?", start) if end > 0 { sess.And("id <= ?", end) } @@ -137,7 +137,7 @@ func DeleteNoticesByIDs(ids []int64) error { if len(ids) == 0 { return nil } - _, err := db.DefaultContext().Engine(). + _, err := db.GetEngine(db.DefaultContext). In("id", ids). Delete(new(Notice)) return err @@ -146,7 +146,7 @@ func DeleteNoticesByIDs(ids []int64) error { // GetAdminUser returns the first administrator func GetAdminUser() (*User, error) { var admin User - has, err := db.DefaultContext().Engine().Where("is_admin=?", true).Get(&admin) + has, err := db.GetEngine(db.DefaultContext).Where("is_admin=?", true).Get(&admin) if err != nil { return nil, err } else if !has { diff --git a/models/attachment.go b/models/attachment.go index 36f318db6db..f06b389dc69 100644 --- a/models/attachment.go +++ b/models/attachment.go @@ -5,6 +5,7 @@ package models import ( + "context" "fmt" "path" @@ -38,7 +39,7 @@ func init() { // IncreaseDownloadCount is update download count + 1 func (a *Attachment) IncreaseDownloadCount() error { // Update download count. - if _, err := db.DefaultContext().Engine().Exec("UPDATE `attachment` SET download_count=download_count+1 WHERE id=?", a.ID); err != nil { + if _, err := db.GetEngine(db.DefaultContext).Exec("UPDATE `attachment` SET download_count=download_count+1 WHERE id=?", a.ID); err != nil { return fmt.Errorf("increase attachment count: %v", err) } @@ -86,7 +87,7 @@ func (a *Attachment) LinkedRepository() (*Repository, UnitType, error) { // GetAttachmentByID returns attachment by given id func GetAttachmentByID(id int64) (*Attachment, error) { - return getAttachmentByID(db.DefaultContext().Engine(), id) + return getAttachmentByID(db.GetEngine(db.DefaultContext), id) } func getAttachmentByID(e db.Engine, id int64) (*Attachment, error) { @@ -111,8 +112,8 @@ func getAttachmentByUUID(e db.Engine, uuid string) (*Attachment, error) { } // GetAttachmentsByUUIDs returns attachment by given UUID list. -func GetAttachmentsByUUIDs(ctx *db.Context, uuids []string) ([]*Attachment, error) { - return getAttachmentsByUUIDs(ctx.Engine(), uuids) +func GetAttachmentsByUUIDs(ctx context.Context, uuids []string) ([]*Attachment, error) { + return getAttachmentsByUUIDs(db.GetEngine(ctx), uuids) } func getAttachmentsByUUIDs(e db.Engine, uuids []string) ([]*Attachment, error) { @@ -127,17 +128,17 @@ func getAttachmentsByUUIDs(e db.Engine, uuids []string) ([]*Attachment, error) { // GetAttachmentByUUID returns attachment by given UUID. func GetAttachmentByUUID(uuid string) (*Attachment, error) { - return getAttachmentByUUID(db.DefaultContext().Engine(), uuid) + return getAttachmentByUUID(db.GetEngine(db.DefaultContext), uuid) } // ExistAttachmentsByUUID returns true if attachment is exist by given UUID func ExistAttachmentsByUUID(uuid string) (bool, error) { - return db.DefaultContext().Engine().Where("`uuid`=?", uuid).Exist(new(Attachment)) + return db.GetEngine(db.DefaultContext).Where("`uuid`=?", uuid).Exist(new(Attachment)) } // GetAttachmentByReleaseIDFileName returns attachment by given releaseId and fileName. func GetAttachmentByReleaseIDFileName(releaseID int64, fileName string) (*Attachment, error) { - return getAttachmentByReleaseIDFileName(db.DefaultContext().Engine(), releaseID, fileName) + return getAttachmentByReleaseIDFileName(db.GetEngine(db.DefaultContext), releaseID, fileName) } func getAttachmentsByIssueID(e db.Engine, issueID int64) ([]*Attachment, error) { @@ -147,12 +148,12 @@ func getAttachmentsByIssueID(e db.Engine, issueID int64) ([]*Attachment, error) // GetAttachmentsByIssueID returns all attachments of an issue. func GetAttachmentsByIssueID(issueID int64) ([]*Attachment, error) { - return getAttachmentsByIssueID(db.DefaultContext().Engine(), issueID) + return getAttachmentsByIssueID(db.GetEngine(db.DefaultContext), issueID) } // GetAttachmentsByCommentID returns all attachments if comment by given ID. func GetAttachmentsByCommentID(commentID int64) ([]*Attachment, error) { - return getAttachmentsByCommentID(db.DefaultContext().Engine(), commentID) + return getAttachmentsByCommentID(db.GetEngine(db.DefaultContext), commentID) } func getAttachmentsByCommentID(e db.Engine, commentID int64) ([]*Attachment, error) { @@ -174,12 +175,12 @@ func getAttachmentByReleaseIDFileName(e db.Engine, releaseID int64, fileName str // DeleteAttachment deletes the given attachment and optionally the associated file. func DeleteAttachment(a *Attachment, remove bool) error { - _, err := DeleteAttachments(db.DefaultContext(), []*Attachment{a}, remove) + _, err := DeleteAttachments(db.DefaultContext, []*Attachment{a}, remove) return err } // DeleteAttachments deletes the given attachments and optionally the associated files. -func DeleteAttachments(ctx *db.Context, attachments []*Attachment, remove bool) (int, error) { +func DeleteAttachments(ctx context.Context, attachments []*Attachment, remove bool) (int, error) { if len(attachments) == 0 { return 0, nil } @@ -189,7 +190,7 @@ func DeleteAttachments(ctx *db.Context, attachments []*Attachment, remove bool) ids = append(ids, a.ID) } - cnt, err := ctx.Engine().In("id", ids).NoAutoCondition().Delete(attachments[0]) + cnt, err := db.GetEngine(ctx).In("id", ids).NoAutoCondition().Delete(attachments[0]) if err != nil { return 0, err } @@ -211,7 +212,7 @@ func DeleteAttachmentsByIssue(issueID int64, remove bool) (int, error) { return 0, err } - return DeleteAttachments(db.DefaultContext(), attachments, remove) + return DeleteAttachments(db.DefaultContext, attachments, remove) } // DeleteAttachmentsByComment deletes all attachments associated with the given comment. @@ -221,20 +222,20 @@ func DeleteAttachmentsByComment(commentID int64, remove bool) (int, error) { return 0, err } - return DeleteAttachments(db.DefaultContext(), attachments, remove) + return DeleteAttachments(db.DefaultContext, attachments, remove) } // UpdateAttachment updates the given attachment in database func UpdateAttachment(atta *Attachment) error { - return updateAttachment(db.DefaultContext().Engine(), atta) + return updateAttachment(db.GetEngine(db.DefaultContext), atta) } // UpdateAttachmentByUUID Updates attachment via uuid -func UpdateAttachmentByUUID(ctx *db.Context, attach *Attachment, cols ...string) error { +func UpdateAttachmentByUUID(ctx context.Context, attach *Attachment, cols ...string) error { if attach.UUID == "" { - return fmt.Errorf("Attachement uuid should not blank") + return fmt.Errorf("attachment uuid should be not blank") } - _, err := ctx.Engine().Where("uuid=?", attach.UUID).Cols(cols...).Update(attach) + _, err := db.GetEngine(ctx).Where("uuid=?", attach.UUID).Cols(cols...).Update(attach) return err } @@ -252,7 +253,7 @@ func updateAttachment(e db.Engine, atta *Attachment) error { // DeleteAttachmentsByRelease deletes all attachments associated with the given release. func DeleteAttachmentsByRelease(releaseID int64) error { - _, err := db.DefaultContext().Engine().Where("release_id = ?", releaseID).Delete(&Attachment{}) + _, err := db.GetEngine(db.DefaultContext).Where("release_id = ?", releaseID).Delete(&Attachment{}) return err } @@ -262,7 +263,7 @@ func IterateAttachment(f func(attach *Attachment) error) error { const batchSize = 100 for { attachments := make([]*Attachment, 0, batchSize) - if err := db.DefaultContext().Engine().Limit(batchSize, start).Find(&attachments); err != nil { + if err := db.GetEngine(db.DefaultContext).Limit(batchSize, start).Find(&attachments); err != nil { return err } if len(attachments) == 0 { @@ -280,13 +281,13 @@ func IterateAttachment(f func(attach *Attachment) error) error { // CountOrphanedAttachments returns the number of bad attachments func CountOrphanedAttachments() (int64, error) { - 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`))"). + 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`))"). Count(new(Attachment)) } // DeleteOrphanedAttachments delete all bad attachments func DeleteOrphanedAttachments() error { - _, 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`))"). + _, 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`))"). Delete(new(Attachment)) return err } diff --git a/models/attachment_test.go b/models/attachment_test.go index 3e8e78a0a31..725d5a40c0b 100644 --- a/models/attachment_test.go +++ b/models/attachment_test.go @@ -92,7 +92,7 @@ func TestUpdateAttachment(t *testing.T) { func TestGetAttachmentsByUUIDs(t *testing.T) { assert.NoError(t, db.PrepareTestDatabase()) - attachList, err := GetAttachmentsByUUIDs(db.DefaultContext(), []string{"a0eebc99-9c0b-4ef8-bb6d-6bb9bd380a11", "a0eebc99-9c0b-4ef8-bb6d-6bb9bd380a17", "not-existing-uuid"}) + attachList, err := GetAttachmentsByUUIDs(db.DefaultContext, []string{"a0eebc99-9c0b-4ef8-bb6d-6bb9bd380a11", "a0eebc99-9c0b-4ef8-bb6d-6bb9bd380a17", "not-existing-uuid"}) assert.NoError(t, err) assert.Len(t, attachList, 2) assert.Equal(t, "a0eebc99-9c0b-4ef8-bb6d-6bb9bd380a11", attachList[0].UUID) diff --git a/models/avatar.go b/models/avatar.go index e81b876667a..71b14ad915b 100644 --- a/models/avatar.go +++ b/models/avatar.go @@ -5,6 +5,7 @@ package models import ( + "context" "crypto/md5" "fmt" "net/url" @@ -64,7 +65,7 @@ func GetEmailForHash(md5Sum string) (string, error) { Hash: strings.ToLower(strings.TrimSpace(md5Sum)), } - _, err := db.DefaultContext().Engine().Get(&emailHash) + _, err := db.GetEngine(db.DefaultContext).Get(&emailHash) return emailHash.Email, err }) } @@ -95,13 +96,13 @@ func HashedAvatarLink(email string, size int) string { Hash: sum, } // OK we're going to open a session just because I think that that might hide away any problems with postgres reporting errors - if err := db.WithTx(func(ctx *db.Context) error { - has, err := ctx.Engine().Where("email = ? AND hash = ?", emailHash.Email, emailHash.Hash).Get(new(EmailHash)) + if err := db.WithTx(func(ctx context.Context) error { + has, err := db.GetEngine(ctx).Where("email = ? AND hash = ?", emailHash.Email, emailHash.Hash).Get(new(EmailHash)) if has || err != nil { // Seriously we don't care about any DB problems just return the lowerEmail - we expect the transaction to fail most of the time return nil } - _, _ = ctx.Engine().Insert(emailHash) + _, _ = db.GetEngine(ctx).Insert(emailHash) return nil }); err != nil { // Seriously we don't care about any DB problems just return the lowerEmail - we expect the transaction to fail most of the time diff --git a/models/branches.go b/models/branches.go index 617dfe488d8..8eaa4b6fd74 100644 --- a/models/branches.go +++ b/models/branches.go @@ -122,7 +122,7 @@ func (protectBranch *ProtectedBranch) IsUserMergeWhitelisted(userID int64, permi // IsUserOfficialReviewer check if user is official reviewer for the branch (counts towards required approvals) func (protectBranch *ProtectedBranch) IsUserOfficialReviewer(user *User) (bool, error) { - return protectBranch.isUserOfficialReviewer(db.DefaultContext().Engine(), user) + return protectBranch.isUserOfficialReviewer(db.GetEngine(db.DefaultContext), user) } func (protectBranch *ProtectedBranch) isUserOfficialReviewer(e db.Engine, user *User) (bool, error) { @@ -162,7 +162,7 @@ func (protectBranch *ProtectedBranch) HasEnoughApprovals(pr *PullRequest) bool { // GetGrantedApprovalsCount returns the number of granted approvals for pr. A granted approval must be authored by a user in an approval whitelist. func (protectBranch *ProtectedBranch) GetGrantedApprovalsCount(pr *PullRequest) int64 { - sess := db.DefaultContext().Engine().Where("issue_id = ?", pr.IssueID). + sess := db.GetEngine(db.DefaultContext).Where("issue_id = ?", pr.IssueID). And("type = ?", ReviewTypeApprove). And("official = ?", true). And("dismissed = ?", false) @@ -183,7 +183,7 @@ func (protectBranch *ProtectedBranch) MergeBlockedByRejectedReview(pr *PullReque if !protectBranch.BlockOnRejectedReviews { return false } - rejectExist, err := db.DefaultContext().Engine().Where("issue_id = ?", pr.IssueID). + rejectExist, err := db.GetEngine(db.DefaultContext).Where("issue_id = ?", pr.IssueID). And("type = ?", ReviewTypeReject). And("official = ?", true). And("dismissed = ?", false). @@ -202,7 +202,7 @@ func (protectBranch *ProtectedBranch) MergeBlockedByOfficialReviewRequests(pr *P if !protectBranch.BlockOnOfficialReviewRequests { return false } - has, err := db.DefaultContext().Engine().Where("issue_id = ?", pr.IssueID). + has, err := db.GetEngine(db.DefaultContext).Where("issue_id = ?", pr.IssueID). And("type = ?", ReviewTypeRequest). And("official = ?", true). Exist(new(Review)) @@ -300,7 +300,7 @@ func (protectBranch *ProtectedBranch) IsUnprotectedFile(patterns []glob.Glob, pa // GetProtectedBranchBy getting protected branch by ID/Name func GetProtectedBranchBy(repoID int64, branchName string) (*ProtectedBranch, error) { - return getProtectedBranchBy(db.DefaultContext().Engine(), repoID, branchName) + return getProtectedBranchBy(db.GetEngine(db.DefaultContext), repoID, branchName) } func getProtectedBranchBy(e db.Engine, repoID int64, branchName string) (*ProtectedBranch, error) { @@ -375,13 +375,13 @@ func UpdateProtectBranch(repo *Repository, protectBranch *ProtectedBranch, opts // Make sure protectBranch.ID is not 0 for whitelists if protectBranch.ID == 0 { - if _, err = db.DefaultContext().Engine().Insert(protectBranch); err != nil { + if _, err = db.GetEngine(db.DefaultContext).Insert(protectBranch); err != nil { return fmt.Errorf("Insert: %v", err) } return nil } - if _, err = db.DefaultContext().Engine().ID(protectBranch.ID).AllCols().Update(protectBranch); err != nil { + if _, err = db.GetEngine(db.DefaultContext).ID(protectBranch.ID).AllCols().Update(protectBranch); err != nil { return fmt.Errorf("Update: %v", err) } @@ -391,7 +391,7 @@ func UpdateProtectBranch(repo *Repository, protectBranch *ProtectedBranch, opts // GetProtectedBranches get all protected branches func (repo *Repository) GetProtectedBranches() ([]*ProtectedBranch, error) { protectedBranches := make([]*ProtectedBranch, 0) - return protectedBranches, db.DefaultContext().Engine().Find(&protectedBranches, &ProtectedBranch{RepoID: repo.ID}) + return protectedBranches, db.GetEngine(db.DefaultContext).Find(&protectedBranches, &ProtectedBranch{RepoID: repo.ID}) } // GetBranchProtection get the branch protection of a branch @@ -406,7 +406,7 @@ func (repo *Repository) IsProtectedBranch(branchName string) (bool, error) { BranchName: branchName, } - has, err := db.DefaultContext().Engine().Exist(protectedBranch) + has, err := db.GetEngine(db.DefaultContext).Exist(protectedBranch) if err != nil { return true, err } @@ -493,7 +493,7 @@ func (repo *Repository) DeleteProtectedBranch(id int64) (err error) { ID: id, } - if affected, err := db.DefaultContext().Engine().Delete(protectedBranch); err != nil { + if affected, err := db.GetEngine(db.DefaultContext).Delete(protectedBranch); err != nil { return err } else if affected != 1 { return fmt.Errorf("delete protected branch ID(%v) failed", id) @@ -522,20 +522,20 @@ func (repo *Repository) AddDeletedBranch(branchName, commit string, deletedByID DeletedByID: deletedByID, } - _, err := db.DefaultContext().Engine().InsertOne(deletedBranch) + _, err := db.GetEngine(db.DefaultContext).InsertOne(deletedBranch) return err } // GetDeletedBranches returns all the deleted branches func (repo *Repository) GetDeletedBranches() ([]*DeletedBranch, error) { deletedBranches := make([]*DeletedBranch, 0) - return deletedBranches, db.DefaultContext().Engine().Where("repo_id = ?", repo.ID).Desc("deleted_unix").Find(&deletedBranches) + return deletedBranches, db.GetEngine(db.DefaultContext).Where("repo_id = ?", repo.ID).Desc("deleted_unix").Find(&deletedBranches) } // GetDeletedBranchByID get a deleted branch by its ID func (repo *Repository) GetDeletedBranchByID(id int64) (*DeletedBranch, error) { deletedBranch := &DeletedBranch{} - has, err := db.DefaultContext().Engine().ID(id).Get(deletedBranch) + has, err := db.GetEngine(db.DefaultContext).ID(id).Get(deletedBranch) if err != nil { return nil, err } @@ -552,7 +552,7 @@ func (repo *Repository) RemoveDeletedBranch(id int64) (err error) { ID: id, } - if affected, err := db.DefaultContext().Engine().Delete(deletedBranch); err != nil { + if affected, err := db.GetEngine(db.DefaultContext).Delete(deletedBranch); err != nil { return err } else if affected != 1 { return fmt.Errorf("remove deleted branch ID(%v) failed", id) @@ -573,7 +573,7 @@ func (deletedBranch *DeletedBranch) LoadUser() { // RemoveDeletedBranch removes all deleted branches func RemoveDeletedBranch(repoID int64, branch string) error { - _, err := db.DefaultContext().Engine().Where("repo_id=? AND name=?", repoID, branch).Delete(new(DeletedBranch)) + _, err := db.GetEngine(db.DefaultContext).Where("repo_id=? AND name=?", repoID, branch).Delete(new(DeletedBranch)) return err } @@ -583,7 +583,7 @@ func RemoveOldDeletedBranches(ctx context.Context, olderThan time.Duration) { log.Trace("Doing: DeletedBranchesCleanup") deleteBefore := time.Now().Add(-olderThan) - _, err := db.DefaultContext().Engine().Where("deleted_unix < ?", deleteBefore.Unix()).Delete(new(DeletedBranch)) + _, err := db.GetEngine(db.DefaultContext).Where("deleted_unix < ?", deleteBefore.Unix()).Delete(new(DeletedBranch)) if err != nil { log.Error("DeletedBranchesCleanup: %v", err) } diff --git a/models/commit_status.go b/models/commit_status.go index 7ec233e80d0..ada94667ccc 100644 --- a/models/commit_status.go +++ b/models/commit_status.go @@ -136,7 +136,7 @@ func (status *CommitStatus) loadAttributes(e db.Engine) (err error) { // APIURL returns the absolute APIURL to this commit-status. func (status *CommitStatus) APIURL() string { - _ = status.loadAttributes(db.DefaultContext().Engine()) + _ = status.loadAttributes(db.GetEngine(db.DefaultContext)) return fmt.Sprintf("%sapi/v1/repos/%s/statuses/%s", setting.AppURL, status.Repo.FullName(), status.SHA) } @@ -193,7 +193,7 @@ func GetCommitStatuses(repo *Repository, sha string, opts *CommitStatusOptions) } func listCommitStatusesStatement(repo *Repository, sha string, opts *CommitStatusOptions) *xorm.Session { - sess := db.DefaultContext().Engine().Where("repo_id = ?", repo.ID).And("sha = ?", sha) + sess := db.GetEngine(db.DefaultContext).Where("repo_id = ?", repo.ID).And("sha = ?", sha) switch opts.State { case "pending", "success", "error", "failure", "warning": sess.And("state = ?", opts.State) @@ -228,7 +228,7 @@ type CommitStatusIndex struct { // GetLatestCommitStatus returns all statuses with a unique context for a given commit. func GetLatestCommitStatus(repoID int64, sha string, listOptions ListOptions) ([]*CommitStatus, error) { - return getLatestCommitStatus(db.DefaultContext().Engine(), repoID, sha, listOptions) + return getLatestCommitStatus(db.GetEngine(db.DefaultContext), repoID, sha, listOptions) } func getLatestCommitStatus(e db.Engine, repoID int64, sha string, listOptions ListOptions) ([]*CommitStatus, error) { @@ -255,7 +255,7 @@ func getLatestCommitStatus(e db.Engine, repoID int64, sha string, listOptions Li func FindRepoRecentCommitStatusContexts(repoID int64, before time.Duration) ([]string, error) { start := timeutil.TimeStampNow().AddDuration(-before) ids := make([]int64, 0, 10) - if err := db.DefaultContext().Engine().Table("commit_status"). + if err := db.GetEngine(db.DefaultContext).Table("commit_status"). Where("repo_id = ?", repoID). And("updated_unix >= ?", start). Select("max( id ) as id"). @@ -268,7 +268,7 @@ func FindRepoRecentCommitStatusContexts(repoID int64, before time.Duration) ([]s if len(ids) == 0 { return contexts, nil } - return contexts, db.DefaultContext().Engine().Select("context").Table("commit_status").In("id", ids).Find(&contexts) + return contexts, db.GetEngine(db.DefaultContext).Select("context").Table("commit_status").In("id", ids).Find(&contexts) } // NewCommitStatusOptions holds options for creating a CommitStatus @@ -314,7 +314,7 @@ func NewCommitStatus(opts NewCommitStatusOptions) error { opts.CommitStatus.ContextHash = hashCommitStatusContext(opts.CommitStatus.Context) // Insert new CommitStatus - if _, err = ctx.Engine().Insert(opts.CommitStatus); err != nil { + if _, err = db.GetEngine(ctx).Insert(opts.CommitStatus); err != nil { return fmt.Errorf("Insert CommitStatus[%s, %s]: %v", repoPath, opts.SHA, err) } diff --git a/models/consistency.go b/models/consistency.go index cc02e32de44..8af884365eb 100644 --- a/models/consistency.go +++ b/models/consistency.go @@ -41,7 +41,7 @@ func CheckConsistencyFor(t *testing.T, beansToCheck ...interface{}) { ptrToSliceValue := reflect.New(sliceType) ptrToSliceValue.Elem().Set(sliceValue) - assert.NoError(t, db.DefaultContext().Engine().Table(bean).Find(ptrToSliceValue.Interface())) + assert.NoError(t, db.GetEngine(db.DefaultContext).Table(bean).Find(ptrToSliceValue.Interface())) sliceValue = ptrToSliceValue.Elem() for i := 0; i < sliceValue.Len(); i++ { @@ -66,7 +66,7 @@ func getCount(t *testing.T, e db.Engine, bean interface{}) int64 { // assertCount test the count of database entries matching bean func assertCount(t *testing.T, bean interface{}, expected int) { - assert.EqualValues(t, expected, getCount(t, db.DefaultContext().Engine(), bean), + assert.EqualValues(t, expected, getCount(t, db.GetEngine(db.DefaultContext), bean), "Failed consistency test, the counted bean (of type %T) was %+v", bean, bean) } @@ -92,33 +92,33 @@ func (repo *Repository) checkForConsistency(t *testing.T) { db.AssertExistsAndLoadBean(t, &Repository{ID: repo.ForkID}) } - actual := getCount(t, db.DefaultContext().Engine().Where("Mode<>?", RepoWatchModeDont), &Watch{RepoID: repo.ID}) + actual := getCount(t, db.GetEngine(db.DefaultContext).Where("Mode<>?", RepoWatchModeDont), &Watch{RepoID: repo.ID}) assert.EqualValues(t, repo.NumWatches, actual, "Unexpected number of watches for repo %+v", repo) - actual = getCount(t, db.DefaultContext().Engine().Where("is_pull=?", false), &Issue{RepoID: repo.ID}) + actual = getCount(t, db.GetEngine(db.DefaultContext).Where("is_pull=?", false), &Issue{RepoID: repo.ID}) assert.EqualValues(t, repo.NumIssues, actual, "Unexpected number of issues for repo %+v", repo) - actual = getCount(t, db.DefaultContext().Engine().Where("is_pull=? AND is_closed=?", false, true), &Issue{RepoID: repo.ID}) + actual = getCount(t, db.GetEngine(db.DefaultContext).Where("is_pull=? AND is_closed=?", false, true), &Issue{RepoID: repo.ID}) assert.EqualValues(t, repo.NumClosedIssues, actual, "Unexpected number of closed issues for repo %+v", repo) - actual = getCount(t, db.DefaultContext().Engine().Where("is_pull=?", true), &Issue{RepoID: repo.ID}) + actual = getCount(t, db.GetEngine(db.DefaultContext).Where("is_pull=?", true), &Issue{RepoID: repo.ID}) assert.EqualValues(t, repo.NumPulls, actual, "Unexpected number of pulls for repo %+v", repo) - actual = getCount(t, db.DefaultContext().Engine().Where("is_pull=? AND is_closed=?", true, true), &Issue{RepoID: repo.ID}) + actual = getCount(t, db.GetEngine(db.DefaultContext).Where("is_pull=? AND is_closed=?", true, true), &Issue{RepoID: repo.ID}) assert.EqualValues(t, repo.NumClosedPulls, actual, "Unexpected number of closed pulls for repo %+v", repo) - actual = getCount(t, db.DefaultContext().Engine().Where("is_closed=?", true), &Milestone{RepoID: repo.ID}) + actual = getCount(t, db.GetEngine(db.DefaultContext).Where("is_closed=?", true), &Milestone{RepoID: repo.ID}) assert.EqualValues(t, repo.NumClosedMilestones, actual, "Unexpected number of closed milestones for repo %+v", repo) } func (issue *Issue) checkForConsistency(t *testing.T) { - actual := getCount(t, db.DefaultContext().Engine().Where("type=?", CommentTypeComment), &Comment{IssueID: issue.ID}) + actual := getCount(t, db.GetEngine(db.DefaultContext).Where("type=?", CommentTypeComment), &Comment{IssueID: issue.ID}) assert.EqualValues(t, issue.NumComments, actual, "Unexpected number of comments for issue %+v", issue) if issue.IsPull { @@ -136,7 +136,7 @@ func (pr *PullRequest) checkForConsistency(t *testing.T) { func (milestone *Milestone) checkForConsistency(t *testing.T) { assertCount(t, &Issue{MilestoneID: milestone.ID}, milestone.NumIssues) - actual := getCount(t, db.DefaultContext().Engine().Where("is_closed=?", true), &Issue{MilestoneID: milestone.ID}) + actual := getCount(t, db.GetEngine(db.DefaultContext).Where("is_closed=?", true), &Issue{MilestoneID: milestone.ID}) assert.EqualValues(t, milestone.NumClosedIssues, actual, "Unexpected number of closed issues for milestone %+v", milestone) @@ -149,7 +149,7 @@ func (milestone *Milestone) checkForConsistency(t *testing.T) { func (label *Label) checkForConsistency(t *testing.T) { issueLabels := make([]*IssueLabel, 0, 10) - assert.NoError(t, db.DefaultContext().Engine().Find(&issueLabels, &IssueLabel{LabelID: label.ID})) + assert.NoError(t, db.GetEngine(db.DefaultContext).Find(&issueLabels, &IssueLabel{LabelID: label.ID})) assert.EqualValues(t, label.NumIssues, len(issueLabels), "Unexpected number of issue for label %+v", label) @@ -160,7 +160,7 @@ func (label *Label) checkForConsistency(t *testing.T) { expected := int64(0) if len(issueIDs) > 0 { - expected = getCount(t, db.DefaultContext().Engine().In("id", issueIDs).Where("is_closed=?", true), &Issue{}) + expected = getCount(t, db.GetEngine(db.DefaultContext).In("id", issueIDs).Where("is_closed=?", true), &Issue{}) } assert.EqualValues(t, expected, label.NumClosedIssues, "Unexpected number of closed issues for label %+v", label) @@ -178,12 +178,12 @@ func (action *Action) checkForConsistency(t *testing.T) { // CountOrphanedLabels return count of labels witch are broken and not accessible via ui anymore func CountOrphanedLabels() (int64, error) { - noref, err := db.DefaultContext().Engine().Table("label").Where("repo_id=? AND org_id=?", 0, 0).Count("label.id") + noref, err := db.GetEngine(db.DefaultContext).Table("label").Where("repo_id=? AND org_id=?", 0, 0).Count("label.id") if err != nil { return 0, err } - norepo, err := db.DefaultContext().Engine().Table("label"). + norepo, err := db.GetEngine(db.DefaultContext).Table("label"). Where(builder.And( builder.Gt{"repo_id": 0}, builder.NotIn("repo_id", builder.Select("id").From("repository")), @@ -193,7 +193,7 @@ func CountOrphanedLabels() (int64, error) { return 0, err } - noorg, err := db.DefaultContext().Engine().Table("label"). + noorg, err := db.GetEngine(db.DefaultContext).Table("label"). Where(builder.And( builder.Gt{"org_id": 0}, builder.NotIn("org_id", builder.Select("id").From("user")), @@ -209,12 +209,12 @@ func CountOrphanedLabels() (int64, error) { // DeleteOrphanedLabels delete labels witch are broken and not accessible via ui anymore func DeleteOrphanedLabels() error { // delete labels with no reference - if _, err := db.DefaultContext().Engine().Table("label").Where("repo_id=? AND org_id=?", 0, 0).Delete(new(Label)); err != nil { + if _, err := db.GetEngine(db.DefaultContext).Table("label").Where("repo_id=? AND org_id=?", 0, 0).Delete(new(Label)); err != nil { return err } // delete labels with none existing repos - if _, err := db.DefaultContext().Engine(). + if _, err := db.GetEngine(db.DefaultContext). Where(builder.And( builder.Gt{"repo_id": 0}, builder.NotIn("repo_id", builder.Select("id").From("repository")), @@ -224,7 +224,7 @@ func DeleteOrphanedLabels() error { } // delete labels with none existing orgs - if _, err := db.DefaultContext().Engine(). + if _, err := db.GetEngine(db.DefaultContext). Where(builder.And( builder.Gt{"org_id": 0}, builder.NotIn("org_id", builder.Select("id").From("user")), @@ -238,14 +238,14 @@ func DeleteOrphanedLabels() error { // CountOrphanedIssueLabels return count of IssueLabels witch have no label behind anymore func CountOrphanedIssueLabels() (int64, error) { - return db.DefaultContext().Engine().Table("issue_label"). + return db.GetEngine(db.DefaultContext).Table("issue_label"). NotIn("label_id", builder.Select("id").From("label")). Count() } // DeleteOrphanedIssueLabels delete IssueLabels witch have no label behind anymore func DeleteOrphanedIssueLabels() error { - _, err := db.DefaultContext().Engine(). + _, err := db.GetEngine(db.DefaultContext). NotIn("label_id", builder.Select("id").From("label")). Delete(IssueLabel{}) @@ -254,7 +254,7 @@ func DeleteOrphanedIssueLabels() error { // CountOrphanedIssues count issues without a repo func CountOrphanedIssues() (int64, error) { - return db.DefaultContext().Engine().Table("issue"). + return db.GetEngine(db.DefaultContext).Table("issue"). Join("LEFT", "repository", "issue.repo_id=repository.id"). Where(builder.IsNull{"repository.id"}). Count("id") @@ -270,7 +270,7 @@ func DeleteOrphanedIssues() error { var ids []int64 - if err := ctx.Engine().Table("issue").Distinct("issue.repo_id"). + if err := db.GetEngine(ctx).Table("issue").Distinct("issue.repo_id"). Join("LEFT", "repository", "issue.repo_id=repository.id"). Where(builder.IsNull{"repository.id"}).GroupBy("issue.repo_id"). Find(&ids); err != nil { @@ -279,7 +279,7 @@ func DeleteOrphanedIssues() error { var attachmentPaths []string for i := range ids { - paths, err := deleteIssuesByRepoID(ctx.Engine(), ids[i]) + paths, err := deleteIssuesByRepoID(db.GetEngine(ctx), ids[i]) if err != nil { return err } @@ -293,14 +293,14 @@ func DeleteOrphanedIssues() error { // Remove issue attachment files. for i := range attachmentPaths { - removeAllWithNotice(db.DefaultContext().Engine(), "Delete issue attachment", attachmentPaths[i]) + removeAllWithNotice(db.GetEngine(db.DefaultContext), "Delete issue attachment", attachmentPaths[i]) } return nil } // CountOrphanedObjects count subjects with have no existing refobject anymore func CountOrphanedObjects(subject, refobject, joinCond string) (int64, error) { - return db.DefaultContext().Engine().Table("`"+subject+"`"). + return db.GetEngine(db.DefaultContext).Table("`"+subject+"`"). Join("LEFT", refobject, joinCond). Where(builder.IsNull{"`" + refobject + "`.id"}). Count("id") @@ -316,45 +316,45 @@ func DeleteOrphanedObjects(subject, refobject, joinCond string) error { if err != nil { return err } - _, err = db.DefaultContext().Engine().Exec(append([]interface{}{sql}, args...)...) + _, err = db.GetEngine(db.DefaultContext).Exec(append([]interface{}{sql}, args...)...) return err } // CountNullArchivedRepository counts the number of repositories with is_archived is null func CountNullArchivedRepository() (int64, error) { - return db.DefaultContext().Engine().Where(builder.IsNull{"is_archived"}).Count(new(Repository)) + return db.GetEngine(db.DefaultContext).Where(builder.IsNull{"is_archived"}).Count(new(Repository)) } // FixNullArchivedRepository sets is_archived to false where it is null func FixNullArchivedRepository() (int64, error) { - return db.DefaultContext().Engine().Where(builder.IsNull{"is_archived"}).Cols("is_archived").NoAutoTime().Update(&Repository{ + return db.GetEngine(db.DefaultContext).Where(builder.IsNull{"is_archived"}).Cols("is_archived").NoAutoTime().Update(&Repository{ IsArchived: false, }) } // CountWrongUserType count OrgUser who have wrong type func CountWrongUserType() (int64, error) { - return db.DefaultContext().Engine().Where(builder.Eq{"type": 0}.And(builder.Neq{"num_teams": 0})).Count(new(User)) + return db.GetEngine(db.DefaultContext).Where(builder.Eq{"type": 0}.And(builder.Neq{"num_teams": 0})).Count(new(User)) } // FixWrongUserType fix OrgUser who have wrong type func FixWrongUserType() (int64, error) { - return db.DefaultContext().Engine().Where(builder.Eq{"type": 0}.And(builder.Neq{"num_teams": 0})).Cols("type").NoAutoTime().Update(&User{Type: 1}) + return db.GetEngine(db.DefaultContext).Where(builder.Eq{"type": 0}.And(builder.Neq{"num_teams": 0})).Cols("type").NoAutoTime().Update(&User{Type: 1}) } // CountCommentTypeLabelWithEmptyLabel count label comments with empty label func CountCommentTypeLabelWithEmptyLabel() (int64, error) { - return db.DefaultContext().Engine().Where(builder.Eq{"type": CommentTypeLabel, "label_id": 0}).Count(new(Comment)) + return db.GetEngine(db.DefaultContext).Where(builder.Eq{"type": CommentTypeLabel, "label_id": 0}).Count(new(Comment)) } // FixCommentTypeLabelWithEmptyLabel count label comments with empty label func FixCommentTypeLabelWithEmptyLabel() (int64, error) { - return db.DefaultContext().Engine().Where(builder.Eq{"type": CommentTypeLabel, "label_id": 0}).Delete(new(Comment)) + return db.GetEngine(db.DefaultContext).Where(builder.Eq{"type": CommentTypeLabel, "label_id": 0}).Delete(new(Comment)) } // CountCommentTypeLabelWithOutsideLabels count label comments with outside label func CountCommentTypeLabelWithOutsideLabels() (int64, error) { - return db.DefaultContext().Engine().Where("comment.type = ? AND ((label.org_id = 0 AND issue.repo_id != label.repo_id) OR (label.repo_id = 0 AND label.org_id != repository.owner_id))", CommentTypeLabel). + return db.GetEngine(db.DefaultContext).Where("comment.type = ? AND ((label.org_id = 0 AND issue.repo_id != label.repo_id) OR (label.repo_id = 0 AND label.org_id != repository.owner_id))", CommentTypeLabel). Table("comment"). Join("inner", "label", "label.id = comment.label_id"). Join("inner", "issue", "issue.id = comment.issue_id "). @@ -364,7 +364,7 @@ func CountCommentTypeLabelWithOutsideLabels() (int64, error) { // FixCommentTypeLabelWithOutsideLabels count label comments with outside label func FixCommentTypeLabelWithOutsideLabels() (int64, error) { - res, err := db.DefaultContext().Engine().Exec(`DELETE FROM comment WHERE comment.id IN ( + res, err := db.GetEngine(db.DefaultContext).Exec(`DELETE FROM comment WHERE comment.id IN ( SELECT il_too.id FROM ( SELECT com.id FROM comment AS com @@ -383,7 +383,7 @@ func FixCommentTypeLabelWithOutsideLabels() (int64, error) { // CountIssueLabelWithOutsideLabels count label comments with outside label func CountIssueLabelWithOutsideLabels() (int64, error) { - return db.DefaultContext().Engine().Where(builder.Expr("(label.org_id = 0 AND issue.repo_id != label.repo_id) OR (label.repo_id = 0 AND label.org_id != repository.owner_id)")). + return db.GetEngine(db.DefaultContext).Where(builder.Expr("(label.org_id = 0 AND issue.repo_id != label.repo_id) OR (label.repo_id = 0 AND label.org_id != repository.owner_id)")). Table("issue_label"). Join("inner", "label", "issue_label.label_id = label.id "). Join("inner", "issue", "issue.id = issue_label.issue_id "). @@ -393,7 +393,7 @@ func CountIssueLabelWithOutsideLabels() (int64, error) { // FixIssueLabelWithOutsideLabels fix label comments with outside label func FixIssueLabelWithOutsideLabels() (int64, error) { - res, err := db.DefaultContext().Engine().Exec(`DELETE FROM issue_label WHERE issue_label.id IN ( + res, err := db.GetEngine(db.DefaultContext).Exec(`DELETE FROM issue_label WHERE issue_label.id IN ( SELECT il_too.id FROM ( SELECT il_too_too.id FROM issue_label AS il_too_too diff --git a/models/consistency_test.go b/models/consistency_test.go index 25acb467b61..8332b5d7619 100644 --- a/models/consistency_test.go +++ b/models/consistency_test.go @@ -14,10 +14,10 @@ import ( func TestDeleteOrphanedObjects(t *testing.T) { assert.NoError(t, db.PrepareTestDatabase()) - countBefore, err := db.DefaultContext().Engine().Count(&PullRequest{}) + countBefore, err := db.GetEngine(db.DefaultContext).Count(&PullRequest{}) assert.NoError(t, err) - _, err = db.DefaultContext().Engine().Insert(&PullRequest{IssueID: 1000}, &PullRequest{IssueID: 1001}, &PullRequest{IssueID: 1003}) + _, err = db.GetEngine(db.DefaultContext).Insert(&PullRequest{IssueID: 1000}, &PullRequest{IssueID: 1001}, &PullRequest{IssueID: 1003}) assert.NoError(t, err) orphaned, err := CountOrphanedObjects("pull_request", "issue", "pull_request.issue_id=issue.id") @@ -27,7 +27,7 @@ func TestDeleteOrphanedObjects(t *testing.T) { err = DeleteOrphanedObjects("pull_request", "issue", "pull_request.issue_id=issue.id") assert.NoError(t, err) - countAfter, err := db.DefaultContext().Engine().Count(&PullRequest{}) + countAfter, err := db.GetEngine(db.DefaultContext).Count(&PullRequest{}) assert.NoError(t, err) assert.EqualValues(t, countBefore, countAfter) } diff --git a/models/db/context.go b/models/db/context.go index 9b1a3010b6f..0037bb198dd 100644 --- a/models/db/context.go +++ b/models/db/context.go @@ -5,14 +5,29 @@ package db import ( + "context" + "code.gitea.io/gitea/modules/setting" "xorm.io/builder" "xorm.io/xorm" ) +// DefaultContext is the default context to run xorm queries in +// will be overwritten by Init with HammerContext +var DefaultContext context.Context + +// contextKey is a value for use with context.WithValue. +type contextKey struct { + name string +} + +// EnginedContextKey is a context key. It is used with context.Value() to get the current Engined for the context +var EnginedContextKey = &contextKey{"engined"} + // Context represents a db context type Context struct { + context.Context e Engine } @@ -30,9 +45,48 @@ func (ctx *Context) NewSession() *xorm.Session { return nil } -// DefaultContext represents a Context with default Engine -func DefaultContext() *Context { - return &Context{x} +// Value shadows Value for context.Context but allows us to get ourselves and an Engined object +func (ctx *Context) Value(key interface{}) interface{} { + if key == EnginedContextKey { + return ctx + } + return ctx.Context.Value(key) +} + +// Engined structs provide an Engine +type Engined interface { + Engine() Engine + NewSession() *xorm.Session +} + +// GetEngine will get a db Engine from this context or return an Engine restricted to this context +func GetEngine(ctx context.Context) Engine { + if engined, ok := ctx.(Engined); ok { + return engined.Engine() + } + enginedInterface := ctx.Value(EnginedContextKey) + if enginedInterface != nil { + return enginedInterface.(Engined).Engine() + } + return x.Context(ctx) +} + +// NewSession will get a db Session from this context or return a session restricted to this context +func NewSession(ctx context.Context) *xorm.Session { + if engined, ok := ctx.(Engined); ok { + return engined.NewSession() + } + + enginedInterface := ctx.Value(EnginedContextKey) + if enginedInterface != nil { + sess := enginedInterface.(Engined).NewSession() + if sess != nil { + return sess.Context(ctx) + } + return nil + } + + return x.NewSession().Context(ctx) } // Committer represents an interface to Commit or Close the Context @@ -49,23 +103,32 @@ func TxContext() (*Context, Committer, error) { return nil, nil, err } - return &Context{sess}, sess, nil + return &Context{ + Context: DefaultContext, + e: sess, + }, sess, nil } // WithContext represents executing database operations func WithContext(f func(ctx *Context) error) error { - return f(&Context{x}) + return f(&Context{ + Context: DefaultContext, + e: x, + }) } // WithTx represents executing database operations on a transaction -func WithTx(f func(ctx *Context) error) error { +func WithTx(f func(ctx context.Context) error) error { sess := x.NewSession() defer sess.Close() if err := sess.Begin(); err != nil { return err } - if err := f(&Context{sess}); err != nil { + if err := f(&Context{ + Context: DefaultContext, + e: sess, + }); err != nil { return err } @@ -73,14 +136,14 @@ func WithTx(f func(ctx *Context) error) error { } // Iterate iterates the databases and doing something -func Iterate(ctx *Context, tableBean interface{}, cond builder.Cond, fun func(idx int, bean interface{}) error) error { - return ctx.e.Where(cond). +func Iterate(ctx context.Context, tableBean interface{}, cond builder.Cond, fun func(idx int, bean interface{}) error) error { + return GetEngine(ctx).Where(cond). BufferSize(setting.Database.IterateBufferSize). Iterate(tableBean, fun) } // Insert inserts records into database -func Insert(ctx *Context, beans ...interface{}) error { - _, err := ctx.e.Insert(beans...) +func Insert(ctx context.Context, beans ...interface{}) error { + _, err := GetEngine(ctx).Insert(beans...) return err } diff --git a/models/db/engine.go b/models/db/engine.go index e71b6fdc59a..256eb2f3fc7 100755 --- a/models/db/engine.go +++ b/models/db/engine.go @@ -169,6 +169,11 @@ func NewEngine(ctx context.Context, migrateFunc func(*xorm.Engine) error) (err e return err } + DefaultContext = &Context{ + Context: ctx, + e: x, + } + x.SetDefaultContext(ctx) if err = x.Ping(); err != nil { diff --git a/models/db/unit_tests.go b/models/db/unit_tests.go index 0540c9ba8ac..781f0ecca20 100644 --- a/models/db/unit_tests.go +++ b/models/db/unit_tests.go @@ -5,6 +5,7 @@ package db import ( + "context" "fmt" "math" "net/url" @@ -117,6 +118,11 @@ func CreateTestEngine(fixturesDir string) error { x.ShowSQL(true) } + DefaultContext = &Context{ + Context: context.Background(), + e: x, + } + return InitFixtures(fixturesDir) } diff --git a/models/engine_test.go b/models/engine_test.go index 66e3ef099f0..d97fc3cc197 100644 --- a/models/engine_test.go +++ b/models/engine_test.go @@ -25,7 +25,7 @@ func TestDumpDatabase(t *testing.T) { ID int64 `xorm:"pk autoincr"` Version int64 } - assert.NoError(t, db.DefaultContext().Engine().Sync2(new(Version))) + assert.NoError(t, db.GetEngine(db.DefaultContext).Sync2(new(Version))) for _, dbName := range setting.SupportedDatabases { dbType := setting.GetDBTypeByName(dbName) diff --git a/models/external_login_user.go b/models/external_login_user.go index 5bfdad69935..c6a4b71b53e 100644 --- a/models/external_login_user.go +++ b/models/external_login_user.go @@ -41,13 +41,13 @@ func init() { // GetExternalLogin checks if a externalID in loginSourceID scope already exists func GetExternalLogin(externalLoginUser *ExternalLoginUser) (bool, error) { - return db.DefaultContext().Engine().Get(externalLoginUser) + return db.GetEngine(db.DefaultContext).Get(externalLoginUser) } // ListAccountLinks returns a map with the ExternalLoginUser and its LoginSource func ListAccountLinks(user *User) ([]*ExternalLoginUser, error) { externalAccounts := make([]*ExternalLoginUser, 0, 5) - err := db.DefaultContext().Engine().Where("user_id=?", user.ID). + err := db.GetEngine(db.DefaultContext).Where("user_id=?", user.ID). Desc("login_source_id"). Find(&externalAccounts) if err != nil { @@ -59,7 +59,7 @@ func ListAccountLinks(user *User) ([]*ExternalLoginUser, error) { // LinkExternalToUser link the external user to the user func LinkExternalToUser(user *User, externalLoginUser *ExternalLoginUser) error { - has, err := db.DefaultContext().Engine().Where("external_id=? AND login_source_id=?", externalLoginUser.ExternalID, externalLoginUser.LoginSourceID). + has, err := db.GetEngine(db.DefaultContext).Where("external_id=? AND login_source_id=?", externalLoginUser.ExternalID, externalLoginUser.LoginSourceID). NoAutoCondition(). Exist(externalLoginUser) if err != nil { @@ -68,13 +68,13 @@ func LinkExternalToUser(user *User, externalLoginUser *ExternalLoginUser) error return ErrExternalLoginUserAlreadyExist{externalLoginUser.ExternalID, user.ID, externalLoginUser.LoginSourceID} } - _, err = db.DefaultContext().Engine().Insert(externalLoginUser) + _, err = db.GetEngine(db.DefaultContext).Insert(externalLoginUser) return err } // RemoveAccountLink will remove all external login sources for the given user func RemoveAccountLink(user *User, loginSourceID int64) (int64, error) { - deleted, err := db.DefaultContext().Engine().Delete(&ExternalLoginUser{UserID: user.ID, LoginSourceID: loginSourceID}) + deleted, err := db.GetEngine(db.DefaultContext).Delete(&ExternalLoginUser{UserID: user.ID, LoginSourceID: loginSourceID}) if err != nil { return deleted, err } @@ -93,7 +93,7 @@ func removeAllAccountLinks(e db.Engine, user *User) error { // GetUserIDByExternalUserID get user id according to provider and userID func GetUserIDByExternalUserID(provider, userID string) (int64, error) { var id int64 - _, err := db.DefaultContext().Engine().Table("external_login_user"). + _, err := db.GetEngine(db.DefaultContext).Table("external_login_user"). Select("user_id"). Where("provider=?", provider). And("external_id=?", userID). @@ -130,7 +130,7 @@ func UpdateExternalUser(user *User, gothUser goth.User) error { ExpiresAt: gothUser.ExpiresAt, } - has, err := db.DefaultContext().Engine().Where("external_id=? AND login_source_id=?", gothUser.UserID, loginSource.ID). + has, err := db.GetEngine(db.DefaultContext).Where("external_id=? AND login_source_id=?", gothUser.UserID, loginSource.ID). NoAutoCondition(). Exist(externalLoginUser) if err != nil { @@ -139,7 +139,7 @@ func UpdateExternalUser(user *User, gothUser goth.User) error { return ErrExternalLoginUserNotExist{user.ID, loginSource.ID} } - _, err = db.DefaultContext().Engine().Where("external_id=? AND login_source_id=?", gothUser.UserID, loginSource.ID).AllCols().Update(externalLoginUser) + _, err = db.GetEngine(db.DefaultContext).Where("external_id=? AND login_source_id=?", gothUser.UserID, loginSource.ID).AllCols().Update(externalLoginUser) return err } @@ -161,7 +161,7 @@ func (opts FindExternalUserOptions) toConds() builder.Cond { // FindExternalUsersByProvider represents external users via provider func FindExternalUsersByProvider(opts FindExternalUserOptions) ([]ExternalLoginUser, error) { var users []ExternalLoginUser - err := db.DefaultContext().Engine().Where(opts.toConds()). + err := db.GetEngine(db.DefaultContext).Where(opts.toConds()). Limit(opts.Limit, opts.Start). OrderBy("login_source_id ASC, external_id ASC"). Find(&users) diff --git a/models/fixture_generation.go b/models/fixture_generation.go index 49cf5ad6a60..c87909d01ba 100644 --- a/models/fixture_generation.go +++ b/models/fixture_generation.go @@ -15,7 +15,7 @@ import ( // for the access table, as recalculated using repo.RecalculateAccesses() func GetYamlFixturesAccess() (string, error) { repos := make([]*Repository, 0, 50) - if err := db.DefaultContext().Engine().Find(&repos); err != nil { + if err := db.GetEngine(db.DefaultContext).Find(&repos); err != nil { return "", err } @@ -29,7 +29,7 @@ func GetYamlFixturesAccess() (string, error) { var b strings.Builder accesses := make([]*Access, 0, 200) - if err := db.DefaultContext().Engine().OrderBy("user_id, repo_id").Find(&accesses); err != nil { + if err := db.GetEngine(db.DefaultContext).OrderBy("user_id, repo_id").Find(&accesses); err != nil { return "", err } diff --git a/models/gpg_key.go b/models/gpg_key.go index fabb3d5c913..d8dd79c2853 100644 --- a/models/gpg_key.go +++ b/models/gpg_key.go @@ -63,7 +63,7 @@ func (key *GPGKey) AfterLoad(session *xorm.Session) { // ListGPGKeys returns a list of public keys belongs to given user. func ListGPGKeys(uid int64, listOptions ListOptions) ([]*GPGKey, error) { - return listGPGKeys(db.DefaultContext().Engine(), uid, listOptions) + return listGPGKeys(db.GetEngine(db.DefaultContext), uid, listOptions) } func listGPGKeys(e db.Engine, uid int64, listOptions ListOptions) ([]*GPGKey, error) { @@ -78,13 +78,13 @@ func listGPGKeys(e db.Engine, uid int64, listOptions ListOptions) ([]*GPGKey, er // CountUserGPGKeys return number of gpg keys a user own func CountUserGPGKeys(userID int64) (int64, error) { - return db.DefaultContext().Engine().Where("owner_id=? AND primary_key_id=''", userID).Count(&GPGKey{}) + return db.GetEngine(db.DefaultContext).Where("owner_id=? AND primary_key_id=''", userID).Count(&GPGKey{}) } // GetGPGKeyByID returns public key by given ID. func GetGPGKeyByID(keyID int64) (*GPGKey, error) { key := new(GPGKey) - has, err := db.DefaultContext().Engine().ID(keyID).Get(key) + has, err := db.GetEngine(db.DefaultContext).ID(keyID).Get(key) if err != nil { return nil, err } else if !has { @@ -96,7 +96,7 @@ func GetGPGKeyByID(keyID int64) (*GPGKey, error) { // GetGPGKeysByKeyID returns public key by given ID. func GetGPGKeysByKeyID(keyID string) ([]*GPGKey, error) { keys := make([]*GPGKey, 0, 1) - return keys, db.DefaultContext().Engine().Where("key_id=?", keyID).Find(&keys) + return keys, db.GetEngine(db.DefaultContext).Where("key_id=?", keyID).Find(&keys) } // GPGKeyToEntity retrieve the imported key and the traducted entity @@ -233,7 +233,7 @@ func DeleteGPGKey(doer *User, id int64) (err error) { } defer committer.Close() - if _, err = deleteGPGKey(ctx.Engine(), key.KeyID); err != nil { + if _, err = deleteGPGKey(db.GetEngine(ctx), key.KeyID); err != nil { return err } diff --git a/models/gpg_key_add.go b/models/gpg_key_add.go index 91a30120a61..635872c920f 100644 --- a/models/gpg_key_add.go +++ b/models/gpg_key_add.go @@ -103,7 +103,7 @@ func AddGPGKey(ownerID int64, content, token, signature string) ([]*GPGKey, erro for _, ekey := range ekeys { // Key ID cannot be duplicated. - has, err := ctx.Engine().Where("key_id=?", ekey.PrimaryKey.KeyIdString()). + has, err := db.GetEngine(ctx).Where("key_id=?", ekey.PrimaryKey.KeyIdString()). Get(new(GPGKey)) if err != nil { return nil, err @@ -118,7 +118,7 @@ func AddGPGKey(ownerID int64, content, token, signature string) ([]*GPGKey, erro return nil, err } - if err = addGPGKey(ctx.Engine(), key, content); err != nil { + if err = addGPGKey(db.GetEngine(ctx), key, content); err != nil { return nil, err } keys = append(keys, key) diff --git a/models/gpg_key_import.go b/models/gpg_key_import.go index 73d46b4cb42..1eed9296272 100644 --- a/models/gpg_key_import.go +++ b/models/gpg_key_import.go @@ -34,7 +34,7 @@ func init() { // GetGPGImportByKeyID returns the import public armored key by given KeyID. func GetGPGImportByKeyID(keyID string) (*GPGKeyImport, error) { key := new(GPGKeyImport) - has, err := db.DefaultContext().Engine().ID(keyID).Get(key) + has, err := db.GetEngine(db.DefaultContext).ID(keyID).Get(key) if err != nil { return nil, err } else if !has { diff --git a/models/gpg_key_verify.go b/models/gpg_key_verify.go index 050bee0bca7..1c6b79ec5f6 100644 --- a/models/gpg_key_verify.go +++ b/models/gpg_key_verify.go @@ -38,7 +38,7 @@ func VerifyGPGKey(ownerID int64, keyID, token, signature string) (string, error) key := new(GPGKey) - has, err := ctx.Engine().Where("owner_id = ? AND key_id = ?", ownerID, keyID).Get(key) + has, err := db.GetEngine(ctx).Where("owner_id = ? AND key_id = ?", ownerID, keyID).Get(key) if err != nil { return "", err } else if !has { @@ -92,7 +92,7 @@ func VerifyGPGKey(ownerID int64, keyID, token, signature string) (string, error) } key.Verified = true - if _, err := ctx.Engine().ID(key.ID).SetExpr("verified", true).Update(new(GPGKey)); err != nil { + if _, err := db.GetEngine(ctx).ID(key.ID).SetExpr("verified", true).Update(new(GPGKey)); err != nil { return "", err } diff --git a/models/issue.go b/models/issue.go index a1f5373583a..cafd996ac51 100644 --- a/models/issue.go +++ b/models/issue.go @@ -6,6 +6,7 @@ package models import ( + "context" "fmt" "regexp" "sort" @@ -113,7 +114,7 @@ func (issue *Issue) IsOverdue() bool { // LoadRepo loads issue's repository func (issue *Issue) LoadRepo() error { - return issue.loadRepo(db.DefaultContext().Engine()) + return issue.loadRepo(db.GetEngine(db.DefaultContext)) } func (issue *Issue) loadRepo(e db.Engine) (err error) { @@ -128,7 +129,7 @@ func (issue *Issue) loadRepo(e db.Engine) (err error) { // IsTimetrackerEnabled returns true if the repo enables timetracking func (issue *Issue) IsTimetrackerEnabled() bool { - return issue.isTimetrackerEnabled(db.DefaultContext().Engine()) + return issue.isTimetrackerEnabled(db.GetEngine(db.DefaultContext)) } func (issue *Issue) isTimetrackerEnabled(e db.Engine) bool { @@ -145,7 +146,7 @@ func (issue *Issue) GetPullRequest() (pr *PullRequest, err error) { return nil, fmt.Errorf("Issue is not a pull request") } - pr, err = getPullRequestByIssueID(db.DefaultContext().Engine(), issue.ID) + pr, err = getPullRequestByIssueID(db.GetEngine(db.DefaultContext), issue.ID) if err != nil { return nil, err } @@ -155,7 +156,7 @@ func (issue *Issue) GetPullRequest() (pr *PullRequest, err error) { // LoadLabels loads labels func (issue *Issue) LoadLabels() error { - return issue.loadLabels(db.DefaultContext().Engine()) + return issue.loadLabels(db.GetEngine(db.DefaultContext)) } func (issue *Issue) loadLabels(e db.Engine) (err error) { @@ -170,7 +171,7 @@ func (issue *Issue) loadLabels(e db.Engine) (err error) { // LoadPoster loads poster func (issue *Issue) LoadPoster() error { - return issue.loadPoster(db.DefaultContext().Engine()) + return issue.loadPoster(db.GetEngine(db.DefaultContext)) } func (issue *Issue) loadPoster(e db.Engine) (err error) { @@ -205,7 +206,7 @@ func (issue *Issue) loadPullRequest(e db.Engine) (err error) { // LoadPullRequest loads pull request info func (issue *Issue) LoadPullRequest() error { - return issue.loadPullRequest(db.DefaultContext().Engine()) + return issue.loadPullRequest(db.GetEngine(db.DefaultContext)) } func (issue *Issue) loadComments(e db.Engine) (err error) { @@ -214,7 +215,7 @@ func (issue *Issue) loadComments(e db.Engine) (err error) { // LoadDiscussComments loads discuss comments func (issue *Issue) LoadDiscussComments() error { - return issue.loadCommentsByType(db.DefaultContext().Engine(), CommentTypeComment) + return issue.loadCommentsByType(db.GetEngine(db.DefaultContext), CommentTypeComment) } func (issue *Issue) loadCommentsByType(e db.Engine, tp CommentType) (err error) { @@ -327,18 +328,18 @@ func (issue *Issue) loadAttributes(e db.Engine) (err error) { // LoadAttributes loads the attribute of this issue. func (issue *Issue) LoadAttributes() error { - return issue.loadAttributes(db.DefaultContext().Engine()) + return issue.loadAttributes(db.GetEngine(db.DefaultContext)) } // LoadMilestone load milestone of this issue. func (issue *Issue) LoadMilestone() error { - return issue.loadMilestone(db.DefaultContext().Engine()) + return issue.loadMilestone(db.GetEngine(db.DefaultContext)) } // GetIsRead load the `IsRead` field of the issue func (issue *Issue) GetIsRead(userID int64) error { issueUser := &IssueUser{IssueID: issue.ID, UID: userID} - if has, err := db.DefaultContext().Engine().Get(issueUser); err != nil { + if has, err := db.GetEngine(db.DefaultContext).Get(issueUser); err != nil { return err } else if !has { issue.IsRead = false @@ -411,7 +412,7 @@ func (issue *Issue) hasLabel(e db.Engine, labelID int64) bool { // HasLabel returns true if issue has been labeled by given ID. func (issue *Issue) HasLabel(labelID int64) bool { - return issue.hasLabel(db.DefaultContext().Engine(), labelID) + return issue.hasLabel(db.GetEngine(db.DefaultContext), labelID) } // ReplyReference returns tokenized address to use for email reply headers @@ -473,13 +474,13 @@ func (issue *Issue) ClearLabels(doer *User) (err error) { } defer committer.Close() - if err := issue.loadRepo(ctx.Engine()); err != nil { + if err := issue.loadRepo(db.GetEngine(ctx)); err != nil { return err - } else if err = issue.loadPullRequest(ctx.Engine()); err != nil { + } else if err = issue.loadPullRequest(db.GetEngine(ctx)); err != nil { return err } - perm, err := getUserRepoPermission(ctx.Engine(), issue.Repo, doer) + perm, err := getUserRepoPermission(db.GetEngine(ctx), issue.Repo, doer) if err != nil { return err } @@ -487,7 +488,7 @@ func (issue *Issue) ClearLabels(doer *User) (err error) { return ErrRepoLabelNotExist{} } - if err = issue.clearLabels(ctx.Engine(), doer); err != nil { + if err = issue.clearLabels(db.GetEngine(ctx), doer); err != nil { return err } @@ -521,11 +522,11 @@ func (issue *Issue) ReplaceLabels(labels []*Label, doer *User) (err error) { } defer committer.Close() - if err = issue.loadRepo(ctx.Engine()); err != nil { + if err = issue.loadRepo(db.GetEngine(ctx)); err != nil { return err } - if err = issue.loadLabels(ctx.Engine()); err != nil { + if err = issue.loadLabels(db.GetEngine(ctx)); err != nil { return err } @@ -561,19 +562,19 @@ func (issue *Issue) ReplaceLabels(labels []*Label, doer *User) (err error) { toRemove = append(toRemove, issue.Labels[removeIndex:]...) if len(toAdd) > 0 { - if err = issue.addLabels(ctx.Engine(), toAdd, doer); err != nil { + if err = issue.addLabels(db.GetEngine(ctx), toAdd, doer); err != nil { return fmt.Errorf("addLabels: %v", err) } } for _, l := range toRemove { - if err = issue.removeLabel(ctx.Engine(), doer, l); err != nil { + if err = issue.removeLabel(db.GetEngine(ctx), doer, l); err != nil { return fmt.Errorf("removeLabel: %v", err) } } issue.Labels = nil - if err = issue.loadLabels(ctx.Engine()); err != nil { + if err = issue.loadLabels(db.GetEngine(ctx)); err != nil { return err } @@ -586,7 +587,7 @@ func (issue *Issue) ReadBy(userID int64) error { return err } - return setIssueNotificationStatusReadIfUnread(db.DefaultContext().Engine(), userID, issue.ID) + return setIssueNotificationStatusReadIfUnread(db.GetEngine(db.DefaultContext), userID, issue.ID) } func updateIssueCols(e db.Engine, issue *Issue, cols ...string) error { @@ -688,14 +689,14 @@ func (issue *Issue) ChangeStatus(doer *User, isClosed bool) (*Comment, error) { } defer committer.Close() - if err := issue.loadRepo(ctx.Engine()); err != nil { + if err := issue.loadRepo(db.GetEngine(ctx)); err != nil { return nil, err } - if err := issue.loadPoster(ctx.Engine()); err != nil { + if err := issue.loadPoster(db.GetEngine(ctx)); err != nil { return nil, err } - comment, err := issue.changeStatus(ctx.Engine(), doer, isClosed, false) + comment, err := issue.changeStatus(db.GetEngine(ctx), doer, isClosed, false) if err != nil { return nil, err } @@ -715,11 +716,11 @@ func (issue *Issue) ChangeTitle(doer *User, oldTitle string) (err error) { } defer committer.Close() - if err = updateIssueCols(ctx.Engine(), issue, "name"); err != nil { + if err = updateIssueCols(db.GetEngine(ctx), issue, "name"); err != nil { return fmt.Errorf("updateIssueCols: %v", err) } - if err = issue.loadRepo(ctx.Engine()); err != nil { + if err = issue.loadRepo(db.GetEngine(ctx)); err != nil { return fmt.Errorf("loadRepo: %v", err) } @@ -731,10 +732,10 @@ func (issue *Issue) ChangeTitle(doer *User, oldTitle string) (err error) { OldTitle: oldTitle, NewTitle: issue.Title, } - if _, err = createComment(ctx.Engine(), opts); err != nil { + if _, err = createComment(db.GetEngine(ctx), opts); err != nil { return fmt.Errorf("createComment: %v", err) } - if err = issue.addCrossReferences(ctx.Engine(), doer, true); err != nil { + if err = issue.addCrossReferences(db.GetEngine(ctx), doer, true); err != nil { return err } @@ -749,7 +750,7 @@ func (issue *Issue) ChangeRef(doer *User, oldRef string) (err error) { } defer committer.Close() - if err = updateIssueCols(ctx.Engine(), issue, "ref"); err != nil { + if err = updateIssueCols(db.GetEngine(ctx), issue, "ref"); err != nil { return fmt.Errorf("updateIssueCols: %v", err) } @@ -758,7 +759,7 @@ func (issue *Issue) ChangeRef(doer *User, oldRef string) (err error) { // AddDeletePRBranchComment adds delete branch comment for pull request issue func AddDeletePRBranchComment(doer *User, repo *Repository, issueID int64, branchName string) error { - issue, err := getIssueByID(db.DefaultContext().Engine(), issueID) + issue, err := getIssueByID(db.GetEngine(db.DefaultContext), issueID) if err != nil { return err } @@ -774,7 +775,7 @@ func AddDeletePRBranchComment(doer *User, repo *Repository, issueID int64, branc Issue: issue, OldRef: branchName, } - if _, err = createComment(ctx.Engine(), opts); err != nil { + if _, err = createComment(db.GetEngine(ctx), opts); err != nil { return err } @@ -788,13 +789,13 @@ func (issue *Issue) UpdateAttachments(uuids []string) (err error) { return err } defer committer.Close() - attachments, err := getAttachmentsByUUIDs(ctx.Engine(), uuids) + attachments, err := getAttachmentsByUUIDs(db.GetEngine(ctx), uuids) if err != nil { return fmt.Errorf("getAttachmentsByUUIDs [uuids: %v]: %v", uuids, err) } for i := 0; i < len(attachments); i++ { attachments[i].IssueID = issue.ID - if err := updateAttachment(ctx.Engine(), attachments[i]); err != nil { + if err := updateAttachment(db.GetEngine(ctx), attachments[i]); err != nil { return fmt.Errorf("update attachment [id: %d]: %v", attachments[i].ID, err) } } @@ -811,11 +812,11 @@ func (issue *Issue) ChangeContent(doer *User, content string) (err error) { } defer committer.Close() - if err = updateIssueCols(ctx.Engine(), issue, "content"); err != nil { + if err = updateIssueCols(db.GetEngine(ctx), issue, "content"); err != nil { return fmt.Errorf("UpdateIssueCols: %v", err) } - if err = issue.addCrossReferences(ctx.Engine(), doer, true); err != nil { + if err = issue.addCrossReferences(db.GetEngine(ctx), doer, true); err != nil { return err } @@ -854,7 +855,7 @@ func (issue *Issue) GetLastEventLabel() string { // GetLastComment return last comment for the current issue. func (issue *Issue) GetLastComment() (*Comment, error) { var c Comment - exist, err := db.DefaultContext().Engine().Where("type = ?", CommentTypeComment). + exist, err := db.GetEngine(db.DefaultContext).Where("type = ?", CommentTypeComment). And("issue_id = ?", issue.ID).Desc("id").Get(&c) if err != nil { return nil, err @@ -996,16 +997,16 @@ func RecalculateIssueIndexForRepo(repoID int64) error { } defer committer.Close() - if err := db.UpsertResourceIndex(ctx.Engine(), "issue_index", repoID); err != nil { + if err := db.UpsertResourceIndex(db.GetEngine(ctx), "issue_index", repoID); err != nil { return err } var max int64 - if _, err := ctx.Engine().Select(" MAX(`index`)").Table("issue").Where("repo_id=?", repoID).Get(&max); err != nil { + if _, err := db.GetEngine(ctx).Select(" MAX(`index`)").Table("issue").Where("repo_id=?", repoID).Get(&max); err != nil { return err } - if _, err := ctx.Engine().Exec("UPDATE `issue_index` SET max_index=? WHERE group_id=?", max, repoID); err != nil { + if _, err := db.GetEngine(ctx).Exec("UPDATE `issue_index` SET max_index=? WHERE group_id=?", max, repoID); err != nil { return err } @@ -1027,7 +1028,7 @@ func NewIssue(repo *Repository, issue *Issue, labelIDs []int64, uuids []string) } defer committer.Close() - if err = newIssue(ctx.Engine(), issue.Poster, NewIssueOptions{ + if err = newIssue(db.GetEngine(ctx), issue.Poster, NewIssueOptions{ Repo: repo, Issue: issue, LabelIDs: labelIDs, @@ -1055,7 +1056,7 @@ func GetIssueByIndex(repoID, index int64) (*Issue, error) { RepoID: repoID, Index: index, } - has, err := db.DefaultContext().Engine().Get(issue) + has, err := db.GetEngine(db.DefaultContext).Get(issue) if err != nil { return nil, err } else if !has { @@ -1086,16 +1087,16 @@ func getIssueByID(e db.Engine, id int64) (*Issue, error) { // GetIssueWithAttrsByID returns an issue with attributes by given ID. func GetIssueWithAttrsByID(id int64) (*Issue, error) { - issue, err := getIssueByID(db.DefaultContext().Engine(), id) + issue, err := getIssueByID(db.GetEngine(db.DefaultContext), id) if err != nil { return nil, err } - return issue, issue.loadAttributes(db.DefaultContext().Engine()) + return issue, issue.loadAttributes(db.GetEngine(db.DefaultContext)) } // GetIssueByID returns an issue by given ID. func GetIssueByID(id int64) (*Issue, error) { - return getIssueByID(db.DefaultContext().Engine(), id) + return getIssueByID(db.GetEngine(db.DefaultContext), id) } func getIssuesByIDs(e db.Engine, issueIDs []int64) ([]*Issue, error) { @@ -1111,12 +1112,12 @@ func getIssueIDsByRepoID(e db.Engine, repoID int64) ([]int64, error) { // GetIssueIDsByRepoID returns all issue ids by repo id func GetIssueIDsByRepoID(repoID int64) ([]int64, error) { - return getIssueIDsByRepoID(db.DefaultContext().Engine(), repoID) + return getIssueIDsByRepoID(db.GetEngine(db.DefaultContext), repoID) } // GetIssuesByIDs return issues with the given IDs. func GetIssuesByIDs(issueIDs []int64) ([]*Issue, error) { - return getIssuesByIDs(db.DefaultContext().Engine(), issueIDs) + return getIssuesByIDs(db.GetEngine(db.DefaultContext), issueIDs) } // IssuesOptions represents options of an issue. @@ -1316,7 +1317,7 @@ func applyReviewRequestedCondition(sess *xorm.Session, reviewRequestedID int64) // CountIssuesByRepo map from repoID to number of issues matching the options func CountIssuesByRepo(opts *IssuesOptions) (map[int64]int64, error) { - sess := db.DefaultContext().NewSession() + sess := db.NewSession(db.DefaultContext) defer sess.Close() sess.Join("INNER", "repository", "`issue`.repo_id = `repository`.id") @@ -1344,7 +1345,7 @@ func CountIssuesByRepo(opts *IssuesOptions) (map[int64]int64, error) { // GetRepoIDsForIssuesOptions find all repo ids for the given options func GetRepoIDsForIssuesOptions(opts *IssuesOptions, user *User) ([]int64, error) { repoIDs := make([]int64, 0, 5) - sess := db.DefaultContext().NewSession() + sess := db.NewSession(db.DefaultContext) defer sess.Close() sess.Join("INNER", "repository", "`issue`.repo_id = `repository`.id") @@ -1364,7 +1365,7 @@ func GetRepoIDsForIssuesOptions(opts *IssuesOptions, user *User) ([]int64, error // Issues returns a list of issues by given conditions. func Issues(opts *IssuesOptions) ([]*Issue, error) { - sess := db.DefaultContext().NewSession() + sess := db.NewSession(db.DefaultContext) defer sess.Close() sess.Join("INNER", "repository", "`issue`.repo_id = `repository`.id") @@ -1386,7 +1387,7 @@ func Issues(opts *IssuesOptions) ([]*Issue, error) { // CountIssues number return of issues by given conditions. func CountIssues(opts *IssuesOptions) (int64, error) { - sess := db.DefaultContext().NewSession() + sess := db.NewSession(db.DefaultContext) defer sess.Close() countsSlice := make([]*struct { @@ -1411,7 +1412,7 @@ func CountIssues(opts *IssuesOptions) (int64, error) { // User permissions must be verified elsewhere if required. func GetParticipantsIDsByIssueID(issueID int64) ([]int64, error) { userIDs := make([]int64, 0, 5) - return userIDs, db.DefaultContext().Engine().Table("comment"). + return userIDs, db.GetEngine(db.DefaultContext).Table("comment"). Cols("poster_id"). Where("issue_id = ?", issueID). And("type in (?,?,?)", CommentTypeComment, CommentTypeCode, CommentTypeReview). @@ -1421,7 +1422,7 @@ func GetParticipantsIDsByIssueID(issueID int64) ([]int64, error) { // IsUserParticipantsOfIssue return true if user is participants of an issue func IsUserParticipantsOfIssue(user *User, issue *Issue) bool { - userIDs, err := issue.getParticipantIDsByIssue(db.DefaultContext().Engine()) + userIDs, err := issue.getParticipantIDsByIssue(db.GetEngine(db.DefaultContext)) if err != nil { log.Error(err.Error()) return false @@ -1430,7 +1431,7 @@ func IsUserParticipantsOfIssue(user *User, issue *Issue) bool { } // UpdateIssueMentions updates issue-user relations for mentioned users. -func UpdateIssueMentions(ctx *db.Context, issueID int64, mentions []*User) error { +func UpdateIssueMentions(ctx context.Context, issueID int64, mentions []*User) error { if len(mentions) == 0 { return nil } @@ -1529,7 +1530,7 @@ func getIssueStatsChunk(opts *IssueStatsOptions, issueIDs []int64) (*IssueStats, stats := &IssueStats{} countSession := func(opts *IssueStatsOptions) *xorm.Session { - sess := db.DefaultContext().Engine(). + sess := db.GetEngine(db.DefaultContext). Where("issue.repo_id = ?", opts.RepoID) if len(opts.IssueIDs) > 0 { @@ -1623,7 +1624,7 @@ func GetUserIssueStats(opts UserIssueStatsOptions) (*IssueStats, error) { } sess := func(cond builder.Cond) *xorm.Session { - s := db.DefaultContext().Engine().Where(cond) + s := db.GetEngine(db.DefaultContext).Where(cond) if len(opts.LabelIDs) > 0 { s.Join("INNER", "issue_label", "issue_label.issue_id = issue.id"). In("issue_label.label_id", opts.LabelIDs) @@ -1735,7 +1736,7 @@ func GetUserIssueStats(opts UserIssueStatsOptions) (*IssueStats, error) { // GetRepoIssueStats returns number of open and closed repository issues by given filter mode. func GetRepoIssueStats(repoID, uid int64, filterMode int, isPull bool) (numOpen, numClosed int64) { countSession := func(isClosed, isPull bool, repoID int64) *xorm.Session { - sess := db.DefaultContext().Engine(). + sess := db.GetEngine(db.DefaultContext). Where("is_closed = ?", isClosed). And("is_pull = ?", isPull). And("repo_id = ?", repoID) @@ -1787,7 +1788,7 @@ func SearchIssueIDsByKeyword(kw string, repoIDs []int64, limit, start int) (int6 ID int64 UpdatedUnix int64 }, 0, limit) - err := db.DefaultContext().Engine().Distinct("id", "updated_unix").Table("issue").Where(cond). + err := db.GetEngine(db.DefaultContext).Distinct("id", "updated_unix").Table("issue").Where(cond). OrderBy("`updated_unix` DESC").Limit(limit, start). Find(&res) if err != nil { @@ -1797,7 +1798,7 @@ func SearchIssueIDsByKeyword(kw string, repoIDs []int64, limit, start int) (int6 ids = append(ids, r.ID) } - total, err := db.DefaultContext().Engine().Distinct("id").Table("issue").Where(cond).Count() + total, err := db.GetEngine(db.DefaultContext).Distinct("id").Table("issue").Where(cond).Count() if err != nil { return 0, nil, err } @@ -1809,7 +1810,7 @@ func SearchIssueIDsByKeyword(kw string, repoIDs []int64, limit, start int) (int6 // If the issue status is changed a statusChangeComment is returned // similarly if the title is changed the titleChanged bool is set to true func UpdateIssueByAPI(issue *Issue, doer *User) (statusChangeComment *Comment, titleChanged bool, err error) { - sess := db.DefaultContext().NewSession() + sess := db.NewSession(db.DefaultContext) defer sess.Close() if err := sess.Begin(); err != nil { return nil, false, err @@ -1868,7 +1869,7 @@ func UpdateIssueDeadline(issue *Issue, deadlineUnix timeutil.TimeStamp, doer *Us return nil } - sess := db.DefaultContext().NewSession() + sess := db.NewSession(db.DefaultContext) defer sess.Close() if err := sess.Begin(); err != nil { return err @@ -1941,12 +1942,12 @@ func (issue *Issue) getBlockingDependencies(e db.Engine) (issueDeps []*Dependenc // BlockedByDependencies finds all Dependencies an issue is blocked by func (issue *Issue) BlockedByDependencies() ([]*DependencyInfo, error) { - return issue.getBlockedByDependencies(db.DefaultContext().Engine()) + return issue.getBlockedByDependencies(db.GetEngine(db.DefaultContext)) } // BlockingDependencies returns all blocking dependencies, aka all other issues a given issue blocks func (issue *Issue) BlockingDependencies() ([]*DependencyInfo, error) { - return issue.getBlockingDependencies(db.DefaultContext().Engine()) + return issue.getBlockingDependencies(db.GetEngine(db.DefaultContext)) } func (issue *Issue) updateClosedNum(e db.Engine) (err error) { @@ -1969,7 +1970,7 @@ func (issue *Issue) updateClosedNum(e db.Engine) (err error) { } // FindAndUpdateIssueMentions finds users mentioned in the given content string, and saves them in the database. -func (issue *Issue) FindAndUpdateIssueMentions(ctx *db.Context, doer *User, content string) (mentions []*User, err error) { +func (issue *Issue) FindAndUpdateIssueMentions(ctx context.Context, doer *User, content string) (mentions []*User, err error) { rawMentions := references.FindAllMentionsMarkdown(content) mentions, err = issue.ResolveMentionsByVisibility(ctx, doer, rawMentions) if err != nil { @@ -1983,18 +1984,18 @@ func (issue *Issue) FindAndUpdateIssueMentions(ctx *db.Context, doer *User, cont // ResolveMentionsByVisibility returns the users mentioned in an issue, removing those that // don't have access to reading it. Teams are expanded into their users, but organizations are ignored. -func (issue *Issue) ResolveMentionsByVisibility(ctx *db.Context, doer *User, mentions []string) (users []*User, err error) { +func (issue *Issue) ResolveMentionsByVisibility(ctx context.Context, doer *User, mentions []string) (users []*User, err error) { if len(mentions) == 0 { return } - if err = issue.loadRepo(ctx.Engine()); err != nil { + if err = issue.loadRepo(db.GetEngine(ctx)); err != nil { return } resolved := make(map[string]bool, 10) var mentionTeams []string - if err := issue.Repo.getOwner(ctx.Engine()); err != nil { + if err := issue.Repo.getOwner(db.GetEngine(ctx)); err != nil { return nil, err } @@ -2023,7 +2024,7 @@ func (issue *Issue) ResolveMentionsByVisibility(ctx *db.Context, doer *User, men if issue.Repo.Owner.IsOrganization() && len(mentionTeams) > 0 { teams := make([]*Team, 0, len(mentionTeams)) - if err := ctx.Engine(). + if err := db.GetEngine(ctx). Join("INNER", "team_repo", "team_repo.team_id = team.id"). Where("team_repo.repo_id=?", issue.Repo.ID). In("team.lower_name", mentionTeams). @@ -2042,7 +2043,7 @@ func (issue *Issue) ResolveMentionsByVisibility(ctx *db.Context, doer *User, men resolved[issue.Repo.Owner.LowerName+"/"+team.LowerName] = true continue } - has, err := ctx.Engine().Get(&TeamUnit{OrgID: issue.Repo.Owner.ID, TeamID: team.ID, Type: unittype}) + has, err := db.GetEngine(ctx).Get(&TeamUnit{OrgID: issue.Repo.Owner.ID, TeamID: team.ID, Type: unittype}) if err != nil { return nil, fmt.Errorf("get team units (%d): %v", team.ID, err) } @@ -2053,7 +2054,7 @@ func (issue *Issue) ResolveMentionsByVisibility(ctx *db.Context, doer *User, men } if len(checked) != 0 { teamusers := make([]*User, 0, 20) - if err := ctx.Engine(). + if err := db.GetEngine(ctx). Join("INNER", "team_user", "team_user.uid = `user`.id"). In("`team_user`.team_id", checked). And("`user`.is_active = ?", true). @@ -2090,7 +2091,7 @@ func (issue *Issue) ResolveMentionsByVisibility(ctx *db.Context, doer *User, men } unchecked := make([]*User, 0, len(mentionUsers)) - if err := ctx.Engine(). + if err := db.GetEngine(ctx). Where("`user`.is_active = ?", true). And("`user`.prohibit_login = ?", false). In("`user`.lower_name", mentionUsers). @@ -2102,7 +2103,7 @@ func (issue *Issue) ResolveMentionsByVisibility(ctx *db.Context, doer *User, men continue } // Normal users must have read access to the referencing issue - perm, err := getUserRepoPermission(ctx.Engine(), issue.Repo, user) + perm, err := getUserRepoPermission(db.GetEngine(ctx), issue.Repo, user) if err != nil { return nil, fmt.Errorf("getUserRepoPermission [%d]: %v", user.ID, err) } @@ -2117,7 +2118,7 @@ func (issue *Issue) ResolveMentionsByVisibility(ctx *db.Context, doer *User, men // UpdateIssuesMigrationsByType updates all migrated repositories' issues from gitServiceType to replace originalAuthorID to posterID func UpdateIssuesMigrationsByType(gitServiceType structs.GitServiceType, originalAuthorID string, posterID int64) error { - _, err := db.DefaultContext().Engine().Table("issue"). + _, err := db.GetEngine(db.DefaultContext).Table("issue"). Where("repo_id IN (SELECT id FROM repository WHERE original_service_type = ?)", gitServiceType). And("original_author_id = ?", originalAuthorID). Update(map[string]interface{}{ @@ -2130,7 +2131,7 @@ func UpdateIssuesMigrationsByType(gitServiceType structs.GitServiceType, origina // UpdateReactionsMigrationsByType updates all migrated repositories' reactions from gitServiceType to replace originalAuthorID to posterID func UpdateReactionsMigrationsByType(gitServiceType structs.GitServiceType, originalAuthorID string, userID int64) error { - _, err := db.DefaultContext().Engine().Table("reaction"). + _, err := db.GetEngine(db.DefaultContext).Table("reaction"). Where("original_author_id = ?", originalAuthorID). And(migratedIssueCond(gitServiceType)). Update(map[string]interface{}{ diff --git a/models/issue_assignees.go b/models/issue_assignees.go index 6b2d8bb3479..0f7ba2d7022 100644 --- a/models/issue_assignees.go +++ b/models/issue_assignees.go @@ -26,7 +26,7 @@ func init() { // LoadAssignees load assignees of this issue. func (issue *Issue) LoadAssignees() error { - return issue.loadAssignees(db.DefaultContext().Engine()) + return issue.loadAssignees(db.GetEngine(db.DefaultContext)) } // This loads all assignees of an issue @@ -56,7 +56,7 @@ func (issue *Issue) loadAssignees(e db.Engine) (err error) { // User permissions must be verified elsewhere if required. func GetAssigneeIDsByIssue(issueID int64) ([]int64, error) { userIDs := make([]int64, 0, 5) - return userIDs, db.DefaultContext().Engine().Table("issue_assignees"). + return userIDs, db.GetEngine(db.DefaultContext).Table("issue_assignees"). Cols("assignee_id"). Where("issue_id = ?", issueID). Distinct("assignee_id"). @@ -65,7 +65,7 @@ func GetAssigneeIDsByIssue(issueID int64) ([]int64, error) { // GetAssigneesByIssue returns everyone assigned to that issue func GetAssigneesByIssue(issue *Issue) (assignees []*User, err error) { - return getAssigneesByIssue(db.DefaultContext().Engine(), issue) + return getAssigneesByIssue(db.GetEngine(db.DefaultContext), issue) } func getAssigneesByIssue(e db.Engine, issue *Issue) (assignees []*User, err error) { @@ -79,7 +79,7 @@ func getAssigneesByIssue(e db.Engine, issue *Issue) (assignees []*User, err erro // IsUserAssignedToIssue returns true when the user is assigned to the issue func IsUserAssignedToIssue(issue *Issue, user *User) (isAssigned bool, err error) { - return isUserAssignedToIssue(db.DefaultContext().Engine(), issue, user) + return isUserAssignedToIssue(db.GetEngine(db.DefaultContext), issue, user) } func isUserAssignedToIssue(e db.Engine, issue *Issue, user *User) (isAssigned bool, err error) { @@ -94,7 +94,7 @@ func clearAssigneeByUserID(sess db.Engine, userID int64) (err error) { // ToggleAssignee changes a user between assigned and not assigned for this issue, and make issue comment for it. func (issue *Issue) ToggleAssignee(doer *User, assigneeID int64) (removed bool, comment *Comment, err error) { - sess := db.DefaultContext().NewSession() + sess := db.NewSession(db.DefaultContext) defer sess.Close() if err := sess.Begin(); err != nil { diff --git a/models/issue_comment.go b/models/issue_comment.go index 059d5b08a76..d8f8e36df28 100644 --- a/models/issue_comment.go +++ b/models/issue_comment.go @@ -210,7 +210,7 @@ type PushActionContent struct { // LoadIssue loads issue from database func (c *Comment) LoadIssue() (err error) { - return c.loadIssue(db.DefaultContext().Engine()) + return c.loadIssue(db.GetEngine(db.DefaultContext)) } func (c *Comment) loadIssue(e db.Engine) (err error) { @@ -284,7 +284,7 @@ func (c *Comment) HTMLURL() string { log.Error("LoadIssue(%d): %v", c.IssueID, err) return "" } - err = c.Issue.loadRepo(db.DefaultContext().Engine()) + err = c.Issue.loadRepo(db.GetEngine(db.DefaultContext)) if err != nil { // Silently dropping errors :unamused: log.Error("loadRepo(%d): %v", c.Issue.RepoID, err) return "" @@ -313,7 +313,7 @@ func (c *Comment) APIURL() string { log.Error("LoadIssue(%d): %v", c.IssueID, err) return "" } - err = c.Issue.loadRepo(db.DefaultContext().Engine()) + err = c.Issue.loadRepo(db.GetEngine(db.DefaultContext)) if err != nil { // Silently dropping errors :unamused: log.Error("loadRepo(%d): %v", c.Issue.RepoID, err) return "" @@ -334,7 +334,7 @@ func (c *Comment) IssueURL() string { return "" } - err = c.Issue.loadRepo(db.DefaultContext().Engine()) + err = c.Issue.loadRepo(db.GetEngine(db.DefaultContext)) if err != nil { // Silently dropping errors :unamused: log.Error("loadRepo(%d): %v", c.Issue.RepoID, err) return "" @@ -350,7 +350,7 @@ func (c *Comment) PRURL() string { return "" } - err = c.Issue.loadRepo(db.DefaultContext().Engine()) + err = c.Issue.loadRepo(db.GetEngine(db.DefaultContext)) if err != nil { // Silently dropping errors :unamused: log.Error("loadRepo(%d): %v", c.Issue.RepoID, err) return "" @@ -380,7 +380,7 @@ func (c *Comment) EventTag() string { // LoadLabel if comment.Type is CommentTypeLabel, then load Label func (c *Comment) LoadLabel() error { var label Label - has, err := db.DefaultContext().Engine().ID(c.LabelID).Get(&label) + has, err := db.GetEngine(db.DefaultContext).ID(c.LabelID).Get(&label) if err != nil { return err } else if has { @@ -397,7 +397,7 @@ func (c *Comment) LoadLabel() error { func (c *Comment) LoadProject() error { if c.OldProjectID > 0 { var oldProject Project - has, err := db.DefaultContext().Engine().ID(c.OldProjectID).Get(&oldProject) + has, err := db.GetEngine(db.DefaultContext).ID(c.OldProjectID).Get(&oldProject) if err != nil { return err } else if has { @@ -407,7 +407,7 @@ func (c *Comment) LoadProject() error { if c.ProjectID > 0 { var project Project - has, err := db.DefaultContext().Engine().ID(c.ProjectID).Get(&project) + has, err := db.GetEngine(db.DefaultContext).ID(c.ProjectID).Get(&project) if err != nil { return err } else if has { @@ -422,7 +422,7 @@ func (c *Comment) LoadProject() error { func (c *Comment) LoadMilestone() error { if c.OldMilestoneID > 0 { var oldMilestone Milestone - has, err := db.DefaultContext().Engine().ID(c.OldMilestoneID).Get(&oldMilestone) + has, err := db.GetEngine(db.DefaultContext).ID(c.OldMilestoneID).Get(&oldMilestone) if err != nil { return err } else if has { @@ -432,7 +432,7 @@ func (c *Comment) LoadMilestone() error { if c.MilestoneID > 0 { var milestone Milestone - has, err := db.DefaultContext().Engine().ID(c.MilestoneID).Get(&milestone) + has, err := db.GetEngine(db.DefaultContext).ID(c.MilestoneID).Get(&milestone) if err != nil { return err } else if has { @@ -444,7 +444,7 @@ func (c *Comment) LoadMilestone() error { // LoadPoster loads comment poster func (c *Comment) LoadPoster() error { - return c.loadPoster(db.DefaultContext().Engine()) + return c.loadPoster(db.GetEngine(db.DefaultContext)) } // LoadAttachments loads attachments @@ -454,7 +454,7 @@ func (c *Comment) LoadAttachments() error { } var err error - c.Attachments, err = getAttachmentsByCommentID(db.DefaultContext().Engine(), c.ID) + c.Attachments, err = getAttachmentsByCommentID(db.GetEngine(db.DefaultContext), c.ID) if err != nil { log.Error("getAttachmentsByCommentID[%d]: %v", c.ID, err) } @@ -463,7 +463,7 @@ func (c *Comment) LoadAttachments() error { // UpdateAttachments update attachments by UUIDs for the comment func (c *Comment) UpdateAttachments(uuids []string) error { - sess := db.DefaultContext().NewSession() + sess := db.NewSession(db.DefaultContext) defer sess.Close() if err := sess.Begin(); err != nil { return err @@ -487,7 +487,7 @@ func (c *Comment) LoadAssigneeUserAndTeam() error { var err error if c.AssigneeID > 0 && c.Assignee == nil { - c.Assignee, err = getUserByID(db.DefaultContext().Engine(), c.AssigneeID) + c.Assignee, err = getUserByID(db.GetEngine(db.DefaultContext), c.AssigneeID) if err != nil { if !IsErrUserNotExist(err) { return err @@ -522,7 +522,7 @@ func (c *Comment) LoadResolveDoer() (err error) { if c.ResolveDoerID == 0 || c.Type != CommentTypeCode { return nil } - c.ResolveDoer, err = getUserByID(db.DefaultContext().Engine(), c.ResolveDoerID) + c.ResolveDoer, err = getUserByID(db.GetEngine(db.DefaultContext), c.ResolveDoerID) if err != nil { if IsErrUserNotExist(err) { c.ResolveDoer = NewGhostUser() @@ -542,7 +542,7 @@ func (c *Comment) LoadDepIssueDetails() (err error) { if c.DependentIssueID <= 0 || c.DependentIssue != nil { return nil } - c.DependentIssue, err = getIssueByID(db.DefaultContext().Engine(), c.DependentIssueID) + c.DependentIssue, err = getIssueByID(db.GetEngine(db.DefaultContext), c.DependentIssueID) return err } @@ -576,7 +576,7 @@ func (c *Comment) loadReactions(e db.Engine, repo *Repository) (err error) { // LoadReactions loads comment reactions func (c *Comment) LoadReactions(repo *Repository) error { - return c.loadReactions(db.DefaultContext().Engine(), repo) + return c.loadReactions(db.GetEngine(db.DefaultContext), repo) } func (c *Comment) loadReview(e db.Engine) (err error) { @@ -591,7 +591,7 @@ func (c *Comment) loadReview(e db.Engine) (err error) { // LoadReview loads the associated review func (c *Comment) LoadReview() error { - return c.loadReview(db.DefaultContext().Engine()) + return c.loadReview(db.GetEngine(db.DefaultContext)) } var notEnoughLines = regexp.MustCompile(`fatal: file .* has only \d+ lines?`) @@ -642,7 +642,7 @@ func (c *Comment) CodeCommentURL() string { log.Error("LoadIssue(%d): %v", c.IssueID, err) return "" } - err = c.Issue.loadRepo(db.DefaultContext().Engine()) + err = c.Issue.loadRepo(db.GetEngine(db.DefaultContext)) if err != nil { // Silently dropping errors :unamused: log.Error("loadRepo(%d): %v", c.Issue.RepoID, err) return "" @@ -899,7 +899,7 @@ type CreateCommentOptions struct { // CreateComment creates comment of issue or commit. func CreateComment(opts *CreateCommentOptions) (comment *Comment, err error) { - sess := db.DefaultContext().NewSession() + sess := db.NewSession(db.DefaultContext) defer sess.Close() if err = sess.Begin(); err != nil { return nil, err @@ -924,7 +924,7 @@ func CreateRefComment(doer *User, repo *Repository, issue *Issue, content, commi } // Check if same reference from same commit has already existed. - has, err := db.DefaultContext().Engine().Get(&Comment{ + has, err := db.GetEngine(db.DefaultContext).Get(&Comment{ Type: CommentTypeCommitRef, IssueID: issue.ID, CommitSHA: commitSHA, @@ -948,7 +948,7 @@ func CreateRefComment(doer *User, repo *Repository, issue *Issue, content, commi // GetCommentByID returns the comment by given ID. func GetCommentByID(id int64) (*Comment, error) { - return getCommentByID(db.DefaultContext().Engine(), id) + return getCommentByID(db.GetEngine(db.DefaultContext), id) } func getCommentByID(e db.Engine, id int64) (*Comment, error) { @@ -1025,12 +1025,12 @@ func findComments(e db.Engine, opts *FindCommentsOptions) ([]*Comment, error) { // FindComments returns all comments according options func FindComments(opts *FindCommentsOptions) ([]*Comment, error) { - return findComments(db.DefaultContext().Engine(), opts) + return findComments(db.GetEngine(db.DefaultContext), opts) } // CountComments count all comments according options by ignoring pagination func CountComments(opts *FindCommentsOptions) (int64, error) { - sess := db.DefaultContext().Engine().Where(opts.toConds()) + sess := db.GetEngine(db.DefaultContext).Where(opts.toConds()) if opts.RepoID > 0 { sess.Join("INNER", "issue", "issue.id = comment.issue_id") } @@ -1039,7 +1039,7 @@ func CountComments(opts *FindCommentsOptions) (int64, error) { // UpdateComment updates information of comment. func UpdateComment(c *Comment, doer *User) error { - sess := db.DefaultContext().NewSession() + sess := db.NewSession(db.DefaultContext) defer sess.Close() if err := sess.Begin(); err != nil { return err @@ -1063,7 +1063,7 @@ func UpdateComment(c *Comment, doer *User) error { // DeleteComment deletes the comment func DeleteComment(comment *Comment) error { - sess := db.DefaultContext().NewSession() + sess := db.NewSession(db.DefaultContext) defer sess.Close() if err := sess.Begin(); err != nil { return err @@ -1207,17 +1207,17 @@ func FetchCodeCommentsByLine(issue *Issue, currentUser *User, treePath string, l TreePath: treePath, Line: line, } - return findCodeComments(db.DefaultContext().Engine(), opts, issue, currentUser, nil) + return findCodeComments(db.GetEngine(db.DefaultContext), opts, issue, currentUser, nil) } // FetchCodeComments will return a 2d-map: ["Path"]["Line"] = Comments at line func FetchCodeComments(issue *Issue, currentUser *User) (CodeComments, error) { - return fetchCodeComments(db.DefaultContext().Engine(), issue, currentUser) + return fetchCodeComments(db.GetEngine(db.DefaultContext), issue, currentUser) } // UpdateCommentsMigrationsByType updates comments' migrations information via given git service type and original id and poster id func UpdateCommentsMigrationsByType(tp structs.GitServiceType, originalAuthorID string, posterID int64) error { - _, err := db.DefaultContext().Engine().Table("comment"). + _, err := db.GetEngine(db.DefaultContext).Table("comment"). Where(builder.In("issue_id", builder.Select("issue.id"). From("issue"). diff --git a/models/issue_comment_list.go b/models/issue_comment_list.go index b80fa129e2b..bd1b48f8e5b 100644 --- a/models/issue_comment_list.go +++ b/models/issue_comment_list.go @@ -526,20 +526,20 @@ func (comments CommentList) loadAttributes(e db.Engine) (err error) { // LoadAttributes loads attributes of the comments, except for attachments and // comments func (comments CommentList) LoadAttributes() error { - return comments.loadAttributes(db.DefaultContext().Engine()) + return comments.loadAttributes(db.GetEngine(db.DefaultContext)) } // LoadAttachments loads attachments func (comments CommentList) LoadAttachments() error { - return comments.loadAttachments(db.DefaultContext().Engine()) + return comments.loadAttachments(db.GetEngine(db.DefaultContext)) } // LoadPosters loads posters func (comments CommentList) LoadPosters() error { - return comments.loadPosters(db.DefaultContext().Engine()) + return comments.loadPosters(db.GetEngine(db.DefaultContext)) } // LoadIssues loads issues of comments func (comments CommentList) LoadIssues() error { - return comments.loadIssues(db.DefaultContext().Engine()) + return comments.loadIssues(db.GetEngine(db.DefaultContext)) } diff --git a/models/issue_dependency.go b/models/issue_dependency.go index 42ec5715f8a..0dfb99ca014 100644 --- a/models/issue_dependency.go +++ b/models/issue_dependency.go @@ -36,7 +36,7 @@ const ( // CreateIssueDependency creates a new dependency for an issue func CreateIssueDependency(user *User, issue, dep *Issue) error { - sess := db.DefaultContext().NewSession() + sess := db.NewSession(db.DefaultContext) defer sess.Close() if err := sess.Begin(); err != nil { return err @@ -77,7 +77,7 @@ func CreateIssueDependency(user *User, issue, dep *Issue) error { // RemoveIssueDependency removes a dependency from an issue func RemoveIssueDependency(user *User, issue, dep *Issue, depType DependencyType) (err error) { - sess := db.DefaultContext().NewSession() + sess := db.NewSession(db.DefaultContext) defer sess.Close() if err = sess.Begin(); err != nil { return err @@ -118,7 +118,7 @@ func issueDepExists(e db.Engine, issueID, depID int64) (bool, error) { // IssueNoDependenciesLeft checks if issue can be closed func IssueNoDependenciesLeft(issue *Issue) (bool, error) { - return issueNoDependenciesLeft(db.DefaultContext().Engine(), issue) + return issueNoDependenciesLeft(db.GetEngine(db.DefaultContext), issue) } func issueNoDependenciesLeft(e db.Engine, issue *Issue) (bool, error) { @@ -135,7 +135,7 @@ func issueNoDependenciesLeft(e db.Engine, issue *Issue) (bool, error) { // IsDependenciesEnabled returns if dependencies are enabled and returns the default setting if not set. func (repo *Repository) IsDependenciesEnabled() bool { - return repo.isDependenciesEnabled(db.DefaultContext().Engine()) + return repo.isDependenciesEnabled(db.GetEngine(db.DefaultContext)) } func (repo *Repository) isDependenciesEnabled(e db.Engine) bool { diff --git a/models/issue_label.go b/models/issue_label.go index 5d7555e2bf2..87d7eb92212 100644 --- a/models/issue_label.go +++ b/models/issue_label.go @@ -6,6 +6,7 @@ package models import ( + "context" "fmt" "html/template" "math" @@ -242,8 +243,8 @@ func initializeLabels(e db.Engine, id int64, labelTemplate string, isOrg bool) e } // InitializeLabels adds a label set to a repository using a template -func InitializeLabels(ctx *db.Context, repoID int64, labelTemplate string, isOrg bool) error { - return initializeLabels(ctx.Engine(), repoID, labelTemplate, isOrg) +func InitializeLabels(ctx context.Context, repoID int64, labelTemplate string, isOrg bool) error { + return initializeLabels(db.GetEngine(ctx), repoID, labelTemplate, isOrg) } func newLabel(e db.Engine, label *Label) error { @@ -256,7 +257,7 @@ func NewLabel(label *Label) error { if !LabelColorPattern.MatchString(label.Color) { return fmt.Errorf("bad color code: %s", label.Color) } - return newLabel(db.DefaultContext().Engine(), label) + return newLabel(db.GetEngine(db.DefaultContext), label) } // NewLabels creates new labels @@ -271,7 +272,7 @@ func NewLabels(labels ...*Label) error { if !LabelColorPattern.MatchString(label.Color) { return fmt.Errorf("bad color code: %s", label.Color) } - if err := newLabel(ctx.Engine(), label); err != nil { + if err := newLabel(db.GetEngine(ctx), label); err != nil { return err } } @@ -283,7 +284,7 @@ func UpdateLabel(l *Label) error { if !LabelColorPattern.MatchString(l.Color) { return fmt.Errorf("bad color code: %s", l.Color) } - return updateLabelCols(db.DefaultContext().Engine(), l, "name", "description", "color") + return updateLabelCols(db.GetEngine(db.DefaultContext), l, "name", "description", "color") } // DeleteLabel delete a label @@ -296,7 +297,7 @@ func DeleteLabel(id, labelID int64) error { return err } - sess := db.DefaultContext().NewSession() + sess := db.NewSession(db.DefaultContext) defer sess.Close() if err = sess.Begin(); err != nil { return err @@ -343,13 +344,13 @@ func getLabelByID(e db.Engine, labelID int64) (*Label, error) { // GetLabelByID returns a label by given ID. func GetLabelByID(id int64) (*Label, error) { - return getLabelByID(db.DefaultContext().Engine(), id) + return getLabelByID(db.GetEngine(db.DefaultContext), id) } // GetLabelsByIDs returns a list of labels by IDs func GetLabelsByIDs(labelIDs []int64) ([]*Label, error) { labels := make([]*Label, 0, len(labelIDs)) - return labels, db.DefaultContext().Engine().Table("label"). + return labels, db.GetEngine(db.DefaultContext).Table("label"). In("id", labelIDs). Asc("name"). Cols("id", "repo_id", "org_id"). @@ -403,7 +404,7 @@ func getLabelInRepoByID(e db.Engine, repoID, labelID int64) (*Label, error) { // GetLabelInRepoByName returns a label by name in given repository. func GetLabelInRepoByName(repoID int64, labelName string) (*Label, error) { - return getLabelInRepoByName(db.DefaultContext().Engine(), repoID, labelName) + return getLabelInRepoByName(db.GetEngine(db.DefaultContext), repoID, labelName) } // GetLabelIDsInRepoByNames returns a list of labelIDs by names in a given @@ -411,7 +412,7 @@ func GetLabelInRepoByName(repoID int64, labelName string) (*Label, error) { // it silently ignores label names that do not belong to the repository. func GetLabelIDsInRepoByNames(repoID int64, labelNames []string) ([]int64, error) { labelIDs := make([]int64, 0, len(labelNames)) - return labelIDs, db.DefaultContext().Engine().Table("label"). + return labelIDs, db.GetEngine(db.DefaultContext).Table("label"). Where("repo_id = ?", repoID). In("name", labelNames). Asc("name"). @@ -432,14 +433,14 @@ func BuildLabelNamesIssueIDsCondition(labelNames []string) *builder.Builder { // GetLabelInRepoByID returns a label by ID in given repository. func GetLabelInRepoByID(repoID, labelID int64) (*Label, error) { - return getLabelInRepoByID(db.DefaultContext().Engine(), repoID, labelID) + return getLabelInRepoByID(db.GetEngine(db.DefaultContext), repoID, labelID) } // GetLabelsInRepoByIDs returns a list of labels by IDs in given repository, // it silently ignores label IDs that do not belong to the repository. func GetLabelsInRepoByIDs(repoID int64, labelIDs []int64) ([]*Label, error) { labels := make([]*Label, 0, len(labelIDs)) - return labels, db.DefaultContext().Engine(). + return labels, db.GetEngine(db.DefaultContext). Where("repo_id = ?", repoID). In("id", labelIDs). Asc("name"). @@ -473,12 +474,12 @@ func getLabelsByRepoID(e db.Engine, repoID int64, sortType string, listOptions L // GetLabelsByRepoID returns all labels that belong to given repository by ID. func GetLabelsByRepoID(repoID int64, sortType string, listOptions ListOptions) ([]*Label, error) { - return getLabelsByRepoID(db.DefaultContext().Engine(), repoID, sortType, listOptions) + return getLabelsByRepoID(db.GetEngine(db.DefaultContext), repoID, sortType, listOptions) } // CountLabelsByRepoID count number of all labels that belong to given repository by ID. func CountLabelsByRepoID(repoID int64) (int64, error) { - return db.DefaultContext().Engine().Where("repo_id = ?", repoID).Count(&Label{}) + return db.GetEngine(db.DefaultContext).Where("repo_id = ?", repoID).Count(&Label{}) } // ________ @@ -528,7 +529,7 @@ func getLabelInOrgByID(e db.Engine, orgID, labelID int64) (*Label, error) { // GetLabelInOrgByName returns a label by name in given organization. func GetLabelInOrgByName(orgID int64, labelName string) (*Label, error) { - return getLabelInOrgByName(db.DefaultContext().Engine(), orgID, labelName) + return getLabelInOrgByName(db.GetEngine(db.DefaultContext), orgID, labelName) } // GetLabelIDsInOrgByNames returns a list of labelIDs by names in a given @@ -539,7 +540,7 @@ func GetLabelIDsInOrgByNames(orgID int64, labelNames []string) ([]int64, error) } labelIDs := make([]int64, 0, len(labelNames)) - return labelIDs, db.DefaultContext().Engine().Table("label"). + return labelIDs, db.GetEngine(db.DefaultContext).Table("label"). Where("org_id = ?", orgID). In("name", labelNames). Asc("name"). @@ -549,14 +550,14 @@ func GetLabelIDsInOrgByNames(orgID int64, labelNames []string) ([]int64, error) // GetLabelInOrgByID returns a label by ID in given organization. func GetLabelInOrgByID(orgID, labelID int64) (*Label, error) { - return getLabelInOrgByID(db.DefaultContext().Engine(), orgID, labelID) + return getLabelInOrgByID(db.GetEngine(db.DefaultContext), orgID, labelID) } // GetLabelsInOrgByIDs returns a list of labels by IDs in given organization, // it silently ignores label IDs that do not belong to the organization. func GetLabelsInOrgByIDs(orgID int64, labelIDs []int64) ([]*Label, error) { labels := make([]*Label, 0, len(labelIDs)) - return labels, db.DefaultContext().Engine(). + return labels, db.GetEngine(db.DefaultContext). Where("org_id = ?", orgID). In("id", labelIDs). Asc("name"). @@ -590,12 +591,12 @@ func getLabelsByOrgID(e db.Engine, orgID int64, sortType string, listOptions Lis // GetLabelsByOrgID returns all labels that belong to given organization by ID. func GetLabelsByOrgID(orgID int64, sortType string, listOptions ListOptions) ([]*Label, error) { - return getLabelsByOrgID(db.DefaultContext().Engine(), orgID, sortType, listOptions) + return getLabelsByOrgID(db.GetEngine(db.DefaultContext), orgID, sortType, listOptions) } // CountLabelsByOrgID count all labels that belong to given organization by ID. func CountLabelsByOrgID(orgID int64) (int64, error) { - return db.DefaultContext().Engine().Where("org_id = ?", orgID).Count(&Label{}) + return db.GetEngine(db.DefaultContext).Where("org_id = ?", orgID).Count(&Label{}) } // .___ @@ -615,7 +616,7 @@ func getLabelsByIssueID(e db.Engine, issueID int64) ([]*Label, error) { // GetLabelsByIssueID returns all labels that belong to given issue by ID. func GetLabelsByIssueID(issueID int64) ([]*Label, error) { - return getLabelsByIssueID(db.DefaultContext().Engine(), issueID) + return getLabelsByIssueID(db.GetEngine(db.DefaultContext), issueID) } func updateLabelCols(e db.Engine, l *Label, cols ...string) error { @@ -657,7 +658,7 @@ func hasIssueLabel(e db.Engine, issueID, labelID int64) bool { // HasIssueLabel returns true if issue has been labeled. func HasIssueLabel(issueID, labelID int64) bool { - return hasIssueLabel(db.DefaultContext().Engine(), issueID, labelID) + return hasIssueLabel(db.GetEngine(db.DefaultContext), issueID, labelID) } // newIssueLabel this function creates a new label it does not check if the label is valid for the issue @@ -695,7 +696,7 @@ func NewIssueLabel(issue *Issue, label *Label, doer *User) (err error) { return nil } - sess := db.DefaultContext().NewSession() + sess := db.NewSession(db.DefaultContext) defer sess.Close() if err = sess.Begin(); err != nil { return err @@ -750,12 +751,12 @@ func NewIssueLabels(issue *Issue, labels []*Label, doer *User) (err error) { } defer committer.Close() - if err = newIssueLabels(ctx.Engine(), issue, labels, doer); err != nil { + if err = newIssueLabels(db.GetEngine(ctx), issue, labels, doer); err != nil { return err } issue.Labels = nil - if err = issue.loadLabels(ctx.Engine()); err != nil { + if err = issue.loadLabels(db.GetEngine(ctx)); err != nil { return err } @@ -792,7 +793,7 @@ func deleteIssueLabel(e db.Engine, issue *Issue, label *Label, doer *User) (err // DeleteIssueLabel deletes issue-label relation. func DeleteIssueLabel(issue *Issue, label *Label, doer *User) (err error) { - sess := db.DefaultContext().NewSession() + sess := db.NewSession(db.DefaultContext) defer sess.Close() if err = sess.Begin(); err != nil { return err diff --git a/models/issue_list.go b/models/issue_list.go index bac0803d8a7..ac7ec7ccbf2 100644 --- a/models/issue_list.go +++ b/models/issue_list.go @@ -63,7 +63,7 @@ func (issues IssueList) loadRepositories(e db.Engine) ([]*Repository, error) { // LoadRepositories loads issues' all repositories func (issues IssueList) LoadRepositories() ([]*Repository, error) { - return issues.loadRepositories(db.DefaultContext().Engine()) + return issues.loadRepositories(db.GetEngine(db.DefaultContext)) } func (issues IssueList) getPosterIDs() []int64 { @@ -502,33 +502,33 @@ func (issues IssueList) loadAttributes(e db.Engine) error { // LoadAttributes loads attributes of the issues, except for attachments and // comments func (issues IssueList) LoadAttributes() error { - return issues.loadAttributes(db.DefaultContext().Engine()) + return issues.loadAttributes(db.GetEngine(db.DefaultContext)) } // LoadAttachments loads attachments func (issues IssueList) LoadAttachments() error { - return issues.loadAttachments(db.DefaultContext().Engine()) + return issues.loadAttachments(db.GetEngine(db.DefaultContext)) } // LoadComments loads comments func (issues IssueList) LoadComments() error { - return issues.loadComments(db.DefaultContext().Engine(), builder.NewCond()) + return issues.loadComments(db.GetEngine(db.DefaultContext), builder.NewCond()) } // LoadDiscussComments loads discuss comments func (issues IssueList) LoadDiscussComments() error { - return issues.loadComments(db.DefaultContext().Engine(), builder.Eq{"comment.type": CommentTypeComment}) + return issues.loadComments(db.GetEngine(db.DefaultContext), builder.Eq{"comment.type": CommentTypeComment}) } // LoadPullRequests loads pull requests func (issues IssueList) LoadPullRequests() error { - return issues.loadPullRequests(db.DefaultContext().Engine()) + return issues.loadPullRequests(db.GetEngine(db.DefaultContext)) } // GetApprovalCounts returns a map of issue ID to slice of approval counts // FIXME: only returns official counts due to double counting of non-official approvals func (issues IssueList) GetApprovalCounts() (map[int64][]*ReviewCount, error) { - return issues.getApprovalCounts(db.DefaultContext().Engine()) + return issues.getApprovalCounts(db.GetEngine(db.DefaultContext)) } func (issues IssueList) getApprovalCounts(e db.Engine) (map[int64][]*ReviewCount, error) { diff --git a/models/issue_lock.go b/models/issue_lock.go index f7474bfd1d7..d8e3b4c0aba 100644 --- a/models/issue_lock.go +++ b/models/issue_lock.go @@ -37,7 +37,7 @@ func updateIssueLock(opts *IssueLockOptions, lock bool) error { commentType = CommentTypeUnlock } - sess := db.DefaultContext().NewSession() + sess := db.NewSession(db.DefaultContext) defer sess.Close() if err := sess.Begin(); err != nil { return err diff --git a/models/issue_milestone.go b/models/issue_milestone.go index da321911f66..fb6ced5b41a 100644 --- a/models/issue_milestone.go +++ b/models/issue_milestone.go @@ -85,7 +85,7 @@ func (m *Milestone) State() api.StateType { // NewMilestone creates new milestone of repository. func NewMilestone(m *Milestone) (err error) { - sess := db.DefaultContext().NewSession() + sess := db.NewSession(db.DefaultContext) defer sess.Close() if err = sess.Begin(); err != nil { return err @@ -116,13 +116,13 @@ func getMilestoneByRepoID(e db.Engine, repoID, id int64) (*Milestone, error) { // GetMilestoneByRepoID returns the milestone in a repository. func GetMilestoneByRepoID(repoID, id int64) (*Milestone, error) { - return getMilestoneByRepoID(db.DefaultContext().Engine(), repoID, id) + return getMilestoneByRepoID(db.GetEngine(db.DefaultContext), repoID, id) } // GetMilestoneByRepoIDANDName return a milestone if one exist by name and repo func GetMilestoneByRepoIDANDName(repoID int64, name string) (*Milestone, error) { var mile Milestone - has, err := db.DefaultContext().Engine().Where("repo_id=? AND name=?", repoID, name).Get(&mile) + has, err := db.GetEngine(db.DefaultContext).Where("repo_id=? AND name=?", repoID, name).Get(&mile) if err != nil { return nil, err } @@ -134,7 +134,7 @@ func GetMilestoneByRepoIDANDName(repoID int64, name string) (*Milestone, error) // GetMilestoneByID returns the milestone via id . func GetMilestoneByID(id int64) (*Milestone, error) { - return getMilestoneByID(db.DefaultContext().Engine(), id) + return getMilestoneByID(db.GetEngine(db.DefaultContext), id) } func getMilestoneByID(e db.Engine, id int64) (*Milestone, error) { @@ -150,7 +150,7 @@ func getMilestoneByID(e db.Engine, id int64) (*Milestone, error) { // UpdateMilestone updates information of given milestone. func UpdateMilestone(m *Milestone, oldIsClosed bool) error { - sess := db.DefaultContext().NewSession() + sess := db.NewSession(db.DefaultContext) defer sess.Close() if err := sess.Begin(); err != nil { return err @@ -207,7 +207,7 @@ func updateMilestoneCounters(e db.Engine, id int64) error { // ChangeMilestoneStatusByRepoIDAndID changes a milestone open/closed status if the milestone ID is in the repo. func ChangeMilestoneStatusByRepoIDAndID(repoID, milestoneID int64, isClosed bool) error { - sess := db.DefaultContext().NewSession() + sess := db.NewSession(db.DefaultContext) defer sess.Close() if err := sess.Begin(); err != nil { return err @@ -234,7 +234,7 @@ func ChangeMilestoneStatusByRepoIDAndID(repoID, milestoneID int64, isClosed bool // ChangeMilestoneStatus changes the milestone open/closed status. func ChangeMilestoneStatus(m *Milestone, isClosed bool) (err error) { - sess := db.DefaultContext().NewSession() + sess := db.NewSession(db.DefaultContext) defer sess.Close() if err = sess.Begin(); err != nil { return err @@ -303,7 +303,7 @@ func changeMilestoneAssign(e *xorm.Session, doer *User, issue *Issue, oldMilesto // ChangeMilestoneAssign changes assignment of milestone for issue. func ChangeMilestoneAssign(issue *Issue, doer *User, oldMilestoneID int64) (err error) { - sess := db.DefaultContext().NewSession() + sess := db.NewSession(db.DefaultContext) defer sess.Close() if err = sess.Begin(); err != nil { return err @@ -334,7 +334,7 @@ func DeleteMilestoneByRepoID(repoID, id int64) error { return err } - sess := db.DefaultContext().NewSession() + sess := db.NewSession(db.DefaultContext) defer sess.Close() if err = sess.Begin(); err != nil { return err @@ -410,7 +410,7 @@ func (opts GetMilestonesOption) toCond() builder.Cond { // GetMilestones returns milestones filtered by GetMilestonesOption's func GetMilestones(opts GetMilestonesOption) (MilestoneList, int64, error) { - sess := db.DefaultContext().Engine().Where(opts.toCond()) + sess := db.GetEngine(db.DefaultContext).Where(opts.toCond()) if opts.Page != 0 { sess = setSessionPagination(sess, &opts) @@ -441,7 +441,7 @@ func GetMilestones(opts GetMilestonesOption) (MilestoneList, int64, error) { // SearchMilestones search milestones func SearchMilestones(repoCond builder.Cond, page int, isClosed bool, sortType string, keyword string) (MilestoneList, error) { miles := make([]*Milestone, 0, setting.UI.IssuePagingNum) - sess := db.DefaultContext().Engine().Where("is_closed = ?", isClosed) + sess := db.GetEngine(db.DefaultContext).Where("is_closed = ?", isClosed) if len(keyword) > 0 { sess = sess.And(builder.Like{"UPPER(name)", strings.ToUpper(keyword)}) } @@ -502,7 +502,7 @@ func GetMilestonesStatsByRepoCond(repoCond builder.Cond) (*MilestonesStats, erro var err error stats := &MilestonesStats{} - sess := db.DefaultContext().Engine().Where("is_closed = ?", false) + sess := db.GetEngine(db.DefaultContext).Where("is_closed = ?", false) if repoCond.IsValid() { sess.And(builder.In("repo_id", builder.Select("id").From("repository").Where(repoCond))) } @@ -511,7 +511,7 @@ func GetMilestonesStatsByRepoCond(repoCond builder.Cond) (*MilestonesStats, erro return nil, err } - sess = db.DefaultContext().Engine().Where("is_closed = ?", true) + sess = db.GetEngine(db.DefaultContext).Where("is_closed = ?", true) if repoCond.IsValid() { sess.And(builder.In("repo_id", builder.Select("id").From("repository").Where(repoCond))) } @@ -528,7 +528,7 @@ func GetMilestonesStatsByRepoCondAndKw(repoCond builder.Cond, keyword string) (* var err error stats := &MilestonesStats{} - sess := db.DefaultContext().Engine().Where("is_closed = ?", false) + sess := db.GetEngine(db.DefaultContext).Where("is_closed = ?", false) if len(keyword) > 0 { sess = sess.And(builder.Like{"UPPER(name)", strings.ToUpper(keyword)}) } @@ -540,7 +540,7 @@ func GetMilestonesStatsByRepoCondAndKw(repoCond builder.Cond, keyword string) (* return nil, err } - sess = db.DefaultContext().Engine().Where("is_closed = ?", true) + sess = db.GetEngine(db.DefaultContext).Where("is_closed = ?", true) if len(keyword) > 0 { sess = sess.And(builder.Like{"UPPER(name)", strings.ToUpper(keyword)}) } @@ -569,12 +569,12 @@ func countRepoClosedMilestones(e db.Engine, repoID int64) (int64, error) { // CountRepoClosedMilestones returns number of closed milestones in given repository. func CountRepoClosedMilestones(repoID int64) (int64, error) { - return countRepoClosedMilestones(db.DefaultContext().Engine(), repoID) + return countRepoClosedMilestones(db.GetEngine(db.DefaultContext), repoID) } // CountMilestonesByRepoCond map from repo conditions to number of milestones matching the options` func CountMilestonesByRepoCond(repoCond builder.Cond, isClosed bool) (map[int64]int64, error) { - sess := db.DefaultContext().Engine().Where("is_closed = ?", isClosed) + sess := db.GetEngine(db.DefaultContext).Where("is_closed = ?", isClosed) if repoCond.IsValid() { sess.In("repo_id", builder.Select("id").From("repository").Where(repoCond)) } @@ -599,7 +599,7 @@ func CountMilestonesByRepoCond(repoCond builder.Cond, isClosed bool) (map[int64] // CountMilestonesByRepoCondAndKw map from repo conditions and the keyword of milestones' name to number of milestones matching the options` func CountMilestonesByRepoCondAndKw(repoCond builder.Cond, keyword string, isClosed bool) (map[int64]int64, error) { - sess := db.DefaultContext().Engine().Where("is_closed = ?", isClosed) + sess := db.GetEngine(db.DefaultContext).Where("is_closed = ?", isClosed) if len(keyword) > 0 { sess = sess.And(builder.Like{"UPPER(name)", strings.ToUpper(keyword)}) } @@ -707,10 +707,10 @@ func (m *Milestone) loadTotalTrackedTime(e db.Engine) error { // LoadTotalTrackedTimes loads for every milestone in the list the TotalTrackedTime by a batch request func (milestones MilestoneList) LoadTotalTrackedTimes() error { - return milestones.loadTotalTrackedTimes(db.DefaultContext().Engine()) + return milestones.loadTotalTrackedTimes(db.GetEngine(db.DefaultContext)) } // LoadTotalTrackedTime loads the tracked time for the milestone func (m *Milestone) LoadTotalTrackedTime() error { - return m.loadTotalTrackedTime(db.DefaultContext().Engine()) + return m.loadTotalTrackedTime(db.GetEngine(db.DefaultContext)) } diff --git a/models/issue_milestone_test.go b/models/issue_milestone_test.go index fd12efb1467..519b65715d1 100644 --- a/models/issue_milestone_test.go +++ b/models/issue_milestone_test.go @@ -173,7 +173,7 @@ func TestCountRepoMilestones(t *testing.T) { assert.NoError(t, db.PrepareTestDatabase()) test := func(repoID int64) { repo := db.AssertExistsAndLoadBean(t, &Repository{ID: repoID}).(*Repository) - count, err := countRepoMilestones(db.DefaultContext().Engine(), repoID) + count, err := countRepoMilestones(db.GetEngine(db.DefaultContext), repoID) assert.NoError(t, err) assert.EqualValues(t, repo.NumMilestones, count) } @@ -181,7 +181,7 @@ func TestCountRepoMilestones(t *testing.T) { test(2) test(3) - count, err := countRepoMilestones(db.DefaultContext().Engine(), db.NonexistentID) + count, err := countRepoMilestones(db.GetEngine(db.DefaultContext), db.NonexistentID) assert.NoError(t, err) assert.EqualValues(t, 0, count) } @@ -223,16 +223,16 @@ func TestUpdateMilestoneCounters(t *testing.T) { issue.IsClosed = true issue.ClosedUnix = timeutil.TimeStampNow() - _, err := db.DefaultContext().Engine().ID(issue.ID).Cols("is_closed", "closed_unix").Update(issue) + _, err := db.GetEngine(db.DefaultContext).ID(issue.ID).Cols("is_closed", "closed_unix").Update(issue) assert.NoError(t, err) - assert.NoError(t, updateMilestoneCounters(db.DefaultContext().Engine(), issue.MilestoneID)) + assert.NoError(t, updateMilestoneCounters(db.GetEngine(db.DefaultContext), issue.MilestoneID)) CheckConsistencyFor(t, &Milestone{}) issue.IsClosed = false issue.ClosedUnix = 0 - _, err = db.DefaultContext().Engine().ID(issue.ID).Cols("is_closed", "closed_unix").Update(issue) + _, err = db.GetEngine(db.DefaultContext).ID(issue.ID).Cols("is_closed", "closed_unix").Update(issue) assert.NoError(t, err) - assert.NoError(t, updateMilestoneCounters(db.DefaultContext().Engine(), issue.MilestoneID)) + assert.NoError(t, updateMilestoneCounters(db.GetEngine(db.DefaultContext), issue.MilestoneID)) CheckConsistencyFor(t, &Milestone{}) } diff --git a/models/issue_reaction.go b/models/issue_reaction.go index 8fd22f6ca8c..4e49add5c2b 100644 --- a/models/issue_reaction.go +++ b/models/issue_reaction.go @@ -71,7 +71,7 @@ func (opts *FindReactionsOptions) toConds() builder.Cond { // FindCommentReactions returns a ReactionList of all reactions from an comment func FindCommentReactions(comment *Comment) (ReactionList, error) { - return findReactions(db.DefaultContext().Engine(), FindReactionsOptions{ + return findReactions(db.GetEngine(db.DefaultContext), FindReactionsOptions{ IssueID: comment.IssueID, CommentID: comment.ID, }) @@ -79,7 +79,7 @@ func FindCommentReactions(comment *Comment) (ReactionList, error) { // FindIssueReactions returns a ReactionList of all reactions from an issue func FindIssueReactions(issue *Issue, listOptions ListOptions) (ReactionList, error) { - return findReactions(db.DefaultContext().Engine(), FindReactionsOptions{ + return findReactions(db.GetEngine(db.DefaultContext), FindReactionsOptions{ ListOptions: listOptions, IssueID: issue.ID, CommentID: -1, @@ -148,7 +148,7 @@ func CreateReaction(opts *ReactionOptions) (*Reaction, error) { return nil, ErrForbiddenIssueReaction{opts.Type} } - sess := db.DefaultContext().NewSession() + sess := db.NewSession(db.DefaultContext) defer sess.Close() if err := sess.Begin(); err != nil { return nil, err @@ -203,7 +203,7 @@ func deleteReaction(e db.Engine, opts *ReactionOptions) error { // DeleteReaction deletes reaction for issue or comment. func DeleteReaction(opts *ReactionOptions) error { - sess := db.DefaultContext().NewSession() + sess := db.NewSession(db.DefaultContext) defer sess.Close() if err := sess.Begin(); err != nil { return err @@ -240,7 +240,7 @@ func (r *Reaction) LoadUser() (*User, error) { if r.User != nil { return r.User, nil } - user, err := getUserByID(db.DefaultContext().Engine(), r.UserID) + user, err := getUserByID(db.GetEngine(db.DefaultContext), r.UserID) if err != nil { return nil, err } @@ -314,7 +314,7 @@ func (list ReactionList) loadUsers(e db.Engine, repo *Repository) ([]*User, erro // LoadUsers loads reactions' all users func (list ReactionList) LoadUsers(repo *Repository) ([]*User, error) { - return list.loadUsers(db.DefaultContext().Engine(), repo) + return list.loadUsers(db.GetEngine(db.DefaultContext), repo) } // GetFirstUsers returns first reacted user display names separated by comma diff --git a/models/issue_reaction_test.go b/models/issue_reaction_test.go index b74d0ce9b88..dd15b816c73 100644 --- a/models/issue_reaction_test.go +++ b/models/issue_reaction_test.go @@ -93,7 +93,7 @@ func TestIssueReactionCount(t *testing.T) { addReaction(t, user4, issue, nil, "heart") addReaction(t, ghost, issue, nil, "-1") - err := issue.loadReactions(db.DefaultContext().Engine()) + err := issue.loadReactions(db.GetEngine(db.DefaultContext)) assert.NoError(t, err) assert.Len(t, issue.Reactions, 7) diff --git a/models/issue_stopwatch.go b/models/issue_stopwatch.go index 1e8cf4c6a65..157658e182d 100644 --- a/models/issue_stopwatch.go +++ b/models/issue_stopwatch.go @@ -48,7 +48,7 @@ func getStopwatch(e db.Engine, userID, issueID int64) (sw *Stopwatch, exists boo // GetUserStopwatches return list of all stopwatches of a user func GetUserStopwatches(userID int64, listOptions ListOptions) ([]*Stopwatch, error) { sws := make([]*Stopwatch, 0, 8) - sess := db.DefaultContext().Engine().Where("stopwatch.user_id = ?", userID) + sess := db.GetEngine(db.DefaultContext).Where("stopwatch.user_id = ?", userID) if listOptions.Page != 0 { sess = setSessionPagination(sess, &listOptions) } @@ -62,18 +62,18 @@ func GetUserStopwatches(userID int64, listOptions ListOptions) ([]*Stopwatch, er // CountUserStopwatches return count of all stopwatches of a user func CountUserStopwatches(userID int64) (int64, error) { - return db.DefaultContext().Engine().Where("user_id = ?", userID).Count(&Stopwatch{}) + return db.GetEngine(db.DefaultContext).Where("user_id = ?", userID).Count(&Stopwatch{}) } // StopwatchExists returns true if the stopwatch exists func StopwatchExists(userID, issueID int64) bool { - _, exists, _ := getStopwatch(db.DefaultContext().Engine(), userID, issueID) + _, exists, _ := getStopwatch(db.GetEngine(db.DefaultContext), userID, issueID) return exists } // HasUserStopwatch returns true if the user has a stopwatch func HasUserStopwatch(userID int64) (exists bool, sw *Stopwatch, err error) { - return hasUserStopwatch(db.DefaultContext().Engine(), userID) + return hasUserStopwatch(db.GetEngine(db.DefaultContext), userID) } func hasUserStopwatch(e db.Engine, userID int64) (exists bool, sw *Stopwatch, err error) { @@ -86,7 +86,7 @@ func hasUserStopwatch(e db.Engine, userID int64) (exists bool, sw *Stopwatch, er // CreateOrStopIssueStopwatch will create or remove a stopwatch and will log it into issue's timeline. func CreateOrStopIssueStopwatch(user *User, issue *Issue) error { - sess := db.DefaultContext().NewSession() + sess := db.NewSession(db.DefaultContext) defer sess.Close() if err := sess.Begin(); err != nil { return err @@ -175,7 +175,7 @@ func createOrStopIssueStopwatch(e *xorm.Session, user *User, issue *Issue) error // CancelStopwatch removes the given stopwatch and logs it into issue's timeline. func CancelStopwatch(user *User, issue *Issue) error { - sess := db.DefaultContext().NewSession() + sess := db.NewSession(db.DefaultContext) defer sess.Close() if err := sess.Begin(); err != nil { return err diff --git a/models/issue_test.go b/models/issue_test.go index a0ced775584..d5f6f36e9c6 100644 --- a/models/issue_test.go +++ b/models/issue_test.go @@ -77,7 +77,7 @@ func TestGetParticipantIDsByIssue(t *testing.T) { checkParticipants := func(issueID int64, userIDs []int) { issue, err := GetIssueByID(issueID) assert.NoError(t, err) - participants, err := issue.getParticipantIDsByIssue(db.DefaultContext().Engine()) + participants, err := issue.getParticipantIDsByIssue(db.GetEngine(db.DefaultContext)) if assert.NoError(t, err) { participantsIDs := make([]int, len(participants)) for i, uid := range participants { @@ -125,7 +125,7 @@ func TestUpdateIssueCols(t *testing.T) { issue.Content = "This should have no effect" now := time.Now().Unix() - assert.NoError(t, updateIssueCols(db.DefaultContext().Engine(), issue, "name")) + assert.NoError(t, updateIssueCols(db.GetEngine(db.DefaultContext), issue, "name")) then := time.Now().Unix() updatedIssue := db.AssertExistsAndLoadBean(t, &Issue{ID: issue.ID}).(*Issue) @@ -290,7 +290,7 @@ func TestIssue_loadTotalTimes(t *testing.T) { assert.NoError(t, db.PrepareTestDatabase()) ms, err := GetIssueByID(2) assert.NoError(t, err) - assert.NoError(t, ms.loadTotalTimes(db.DefaultContext().Engine())) + assert.NoError(t, ms.loadTotalTimes(db.GetEngine(db.DefaultContext))) assert.Equal(t, int64(3682), ms.TotalTrackedTime) } @@ -363,7 +363,7 @@ func testInsertIssue(t *testing.T, title, content string, expectIndex int64) *Is err := NewIssue(repo, &issue, nil, nil) assert.NoError(t, err) - has, err := db.DefaultContext().Engine().ID(issue.ID).Get(&newIssue) + has, err := db.GetEngine(db.DefaultContext).ID(issue.ID).Get(&newIssue) assert.NoError(t, err) assert.True(t, has) assert.EqualValues(t, issue.Title, newIssue.Title) @@ -380,11 +380,11 @@ func TestIssue_InsertIssue(t *testing.T) { // there are 5 issues and max index is 5 on repository 1, so this one should 6 issue := testInsertIssue(t, "my issue1", "special issue's comments?", 6) - _, err := db.DefaultContext().Engine().ID(issue.ID).Delete(new(Issue)) + _, err := db.GetEngine(db.DefaultContext).ID(issue.ID).Delete(new(Issue)) assert.NoError(t, err) issue = testInsertIssue(t, `my issue2, this is my son's love \n \r \ `, "special issue's '' comments?", 7) - _, err = db.DefaultContext().Engine().ID(issue.ID).Delete(new(Issue)) + _, err = db.GetEngine(db.DefaultContext).ID(issue.ID).Delete(new(Issue)) assert.NoError(t, err) } @@ -397,7 +397,7 @@ func TestIssue_ResolveMentions(t *testing.T) { r := db.AssertExistsAndLoadBean(t, &Repository{OwnerID: o.ID, LowerName: repo}).(*Repository) issue := &Issue{RepoID: r.ID} d := db.AssertExistsAndLoadBean(t, &User{LowerName: doer}).(*User) - resolved, err := issue.ResolveMentionsByVisibility(db.DefaultContext(), d, mentions) + resolved, err := issue.ResolveMentionsByVisibility(db.DefaultContext, d, mentions) assert.NoError(t, err) ids := make([]int64, len(resolved)) for i, user := range resolved { diff --git a/models/issue_tracked_time.go b/models/issue_tracked_time.go index 77b44df1ee3..d024c6896f6 100644 --- a/models/issue_tracked_time.go +++ b/models/issue_tracked_time.go @@ -40,7 +40,7 @@ func (t *TrackedTime) AfterLoad() { // LoadAttributes load Issue, User func (t *TrackedTime) LoadAttributes() (err error) { - return t.loadAttributes(db.DefaultContext().Engine()) + return t.loadAttributes(db.GetEngine(db.DefaultContext)) } func (t *TrackedTime) loadAttributes(e db.Engine) (err error) { @@ -131,12 +131,12 @@ func getTrackedTimes(e db.Engine, options *FindTrackedTimesOptions) (trackedTime // GetTrackedTimes returns all tracked times that fit to the given options. func GetTrackedTimes(opts *FindTrackedTimesOptions) (TrackedTimeList, error) { - return getTrackedTimes(db.DefaultContext().Engine(), opts) + return getTrackedTimes(db.GetEngine(db.DefaultContext), opts) } // CountTrackedTimes returns count of tracked times that fit to the given options. func CountTrackedTimes(opts *FindTrackedTimesOptions) (int64, error) { - sess := db.DefaultContext().Engine().Where(opts.toCond()) + sess := db.GetEngine(db.DefaultContext).Where(opts.toCond()) if opts.RepositoryID > 0 || opts.MilestoneID > 0 { sess = sess.Join("INNER", "issue", "issue.id = tracked_time.issue_id") } @@ -149,12 +149,12 @@ func getTrackedSeconds(e db.Engine, opts FindTrackedTimesOptions) (trackedSecond // GetTrackedSeconds return sum of seconds func GetTrackedSeconds(opts FindTrackedTimesOptions) (int64, error) { - return getTrackedSeconds(db.DefaultContext().Engine(), opts) + return getTrackedSeconds(db.GetEngine(db.DefaultContext), opts) } // AddTime will add the given time (in seconds) to the issue func AddTime(user *User, issue *Issue, amount int64, created time.Time) (*TrackedTime, error) { - sess := db.DefaultContext().NewSession() + sess := db.NewSession(db.DefaultContext) defer sess.Close() if err := sess.Begin(); err != nil { @@ -230,7 +230,7 @@ func TotalTimes(options *FindTrackedTimesOptions) (map[*User]string, error) { // DeleteIssueUserTimes deletes times for issue func DeleteIssueUserTimes(issue *Issue, user *User) error { - sess := db.DefaultContext().NewSession() + sess := db.NewSession(db.DefaultContext) defer sess.Close() if err := sess.Begin(); err != nil { @@ -268,7 +268,7 @@ func DeleteIssueUserTimes(issue *Issue, user *User) error { // DeleteTime delete a specific Time func DeleteTime(t *TrackedTime) error { - sess := db.DefaultContext().NewSession() + sess := db.NewSession(db.DefaultContext) defer sess.Close() if err := sess.Begin(); err != nil { @@ -318,7 +318,7 @@ func deleteTime(e db.Engine, t *TrackedTime) error { // GetTrackedTimeByID returns raw TrackedTime without loading attributes by id func GetTrackedTimeByID(id int64) (*TrackedTime, error) { time := new(TrackedTime) - has, err := db.DefaultContext().Engine().ID(id).Get(time) + has, err := db.GetEngine(db.DefaultContext).ID(id).Get(time) if err != nil { return nil, err } else if !has { diff --git a/models/issue_user.go b/models/issue_user.go index 6f9b7591cd2..b112441e5b1 100644 --- a/models/issue_user.go +++ b/models/issue_user.go @@ -5,6 +5,7 @@ package models import ( + "context" "fmt" "code.gitea.io/gitea/models/db" @@ -57,27 +58,27 @@ func newIssueUsers(e db.Engine, repo *Repository, issue *Issue) error { // UpdateIssueUserByRead updates issue-user relation for reading. func UpdateIssueUserByRead(uid, issueID int64) error { - _, err := db.DefaultContext().Engine().Exec("UPDATE `issue_user` SET is_read=? WHERE uid=? AND issue_id=?", true, uid, issueID) + _, err := db.GetEngine(db.DefaultContext).Exec("UPDATE `issue_user` SET is_read=? WHERE uid=? AND issue_id=?", true, uid, issueID) return err } // UpdateIssueUsersByMentions updates issue-user pairs by mentioning. -func UpdateIssueUsersByMentions(ctx *db.Context, issueID int64, uids []int64) error { +func UpdateIssueUsersByMentions(ctx context.Context, issueID int64, uids []int64) error { for _, uid := range uids { iu := &IssueUser{ UID: uid, IssueID: issueID, } - has, err := ctx.Engine().Get(iu) + has, err := db.GetEngine(ctx).Get(iu) if err != nil { return err } iu.IsMentioned = true if has { - _, err = ctx.Engine().ID(iu.ID).Cols("is_mentioned").Update(iu) + _, err = db.GetEngine(ctx).ID(iu.ID).Cols("is_mentioned").Update(iu) } else { - _, err = ctx.Engine().Insert(iu) + _, err = db.GetEngine(ctx).Insert(iu) } if err != nil { return err diff --git a/models/issue_user_test.go b/models/issue_user_test.go index ca45d065635..d4e504719fc 100644 --- a/models/issue_user_test.go +++ b/models/issue_user_test.go @@ -26,7 +26,7 @@ func Test_newIssueUsers(t *testing.T) { // artificially insert new issue db.AssertSuccessfulInsert(t, newIssue) - assert.NoError(t, newIssueUsers(db.DefaultContext().Engine(), repo, newIssue)) + assert.NoError(t, newIssueUsers(db.GetEngine(db.DefaultContext), repo, newIssue)) // issue_user table should now have entries for new issue db.AssertExistsAndLoadBean(t, &IssueUser{IssueID: newIssue.ID, UID: newIssue.PosterID}) @@ -51,7 +51,7 @@ func TestUpdateIssueUsersByMentions(t *testing.T) { issue := db.AssertExistsAndLoadBean(t, &Issue{ID: 1}).(*Issue) uids := []int64{2, 5} - assert.NoError(t, UpdateIssueUsersByMentions(db.DefaultContext(), issue.ID, uids)) + assert.NoError(t, UpdateIssueUsersByMentions(db.DefaultContext, issue.ID, uids)) for _, uid := range uids { db.AssertExistsAndLoadBean(t, &IssueUser{IssueID: issue.ID, UID: uid}, "is_mentioned=1") } diff --git a/models/issue_watch.go b/models/issue_watch.go index dd693f82f58..cc1edcba1b6 100644 --- a/models/issue_watch.go +++ b/models/issue_watch.go @@ -28,7 +28,7 @@ type IssueWatchList []*IssueWatch // CreateOrUpdateIssueWatch set watching for a user and issue func CreateOrUpdateIssueWatch(userID, issueID int64, isWatching bool) error { - iw, exists, err := getIssueWatch(db.DefaultContext().Engine(), userID, issueID) + iw, exists, err := getIssueWatch(db.GetEngine(db.DefaultContext), userID, issueID) if err != nil { return err } @@ -40,13 +40,13 @@ func CreateOrUpdateIssueWatch(userID, issueID int64, isWatching bool) error { IsWatching: isWatching, } - if _, err := db.DefaultContext().Engine().Insert(iw); err != nil { + if _, err := db.GetEngine(db.DefaultContext).Insert(iw); err != nil { return err } } else { iw.IsWatching = isWatching - if _, err := db.DefaultContext().Engine().ID(iw.ID).Cols("is_watching", "updated_unix").Update(iw); err != nil { + if _, err := db.GetEngine(db.DefaultContext).ID(iw.ID).Cols("is_watching", "updated_unix").Update(iw); err != nil { return err } } @@ -56,7 +56,7 @@ func CreateOrUpdateIssueWatch(userID, issueID int64, isWatching bool) error { // GetIssueWatch returns all IssueWatch objects from db by user and issue // the current Web-UI need iw object for watchers AND explicit non-watchers func GetIssueWatch(userID, issueID int64) (iw *IssueWatch, exists bool, err error) { - return getIssueWatch(db.DefaultContext().Engine(), userID, issueID) + return getIssueWatch(db.GetEngine(db.DefaultContext), userID, issueID) } // Return watcher AND explicit non-watcher if entry in db exist @@ -72,14 +72,14 @@ func getIssueWatch(e db.Engine, userID, issueID int64) (iw *IssueWatch, exists b // CheckIssueWatch check if an user is watching an issue // it takes participants and repo watch into account func CheckIssueWatch(user *User, issue *Issue) (bool, error) { - iw, exist, err := getIssueWatch(db.DefaultContext().Engine(), user.ID, issue.ID) + iw, exist, err := getIssueWatch(db.GetEngine(db.DefaultContext), user.ID, issue.ID) if err != nil { return false, err } if exist { return iw.IsWatching, nil } - w, err := getWatch(db.DefaultContext().Engine(), user.ID, issue.RepoID) + w, err := getWatch(db.GetEngine(db.DefaultContext), user.ID, issue.RepoID) if err != nil { return false, err } @@ -90,7 +90,7 @@ func CheckIssueWatch(user *User, issue *Issue) (bool, error) { // but avoids joining with `user` for performance reasons // User permissions must be verified elsewhere if required func GetIssueWatchersIDs(issueID int64, watching bool) ([]int64, error) { - return getIssueWatchersIDs(db.DefaultContext().Engine(), issueID, watching) + return getIssueWatchersIDs(db.GetEngine(db.DefaultContext), issueID, watching) } func getIssueWatchersIDs(e db.Engine, issueID int64, watching bool) ([]int64, error) { @@ -104,7 +104,7 @@ func getIssueWatchersIDs(e db.Engine, issueID int64, watching bool) ([]int64, er // GetIssueWatchers returns watchers/unwatchers of a given issue func GetIssueWatchers(issueID int64, listOptions ListOptions) (IssueWatchList, error) { - return getIssueWatchers(db.DefaultContext().Engine(), issueID, listOptions) + return getIssueWatchers(db.GetEngine(db.DefaultContext), issueID, listOptions) } func getIssueWatchers(e db.Engine, issueID int64, listOptions ListOptions) (IssueWatchList, error) { diff --git a/models/issue_xref.go b/models/issue_xref.go index 3f9c1e7f5ca..4630f4d3a48 100644 --- a/models/issue_xref.go +++ b/models/issue_xref.go @@ -277,7 +277,7 @@ func (comment *Comment) LoadRefIssue() (err error) { } comment.RefIssue, err = GetIssueByID(comment.RefIssueID) if err == nil { - err = comment.RefIssue.loadRepo(db.DefaultContext().Engine()) + err = comment.RefIssue.loadRepo(db.GetEngine(db.DefaultContext)) } return } @@ -337,7 +337,7 @@ func (comment *Comment) RefIssueIdent() string { // ResolveCrossReferences will return the list of references to close/reopen by this PR func (pr *PullRequest) ResolveCrossReferences() ([]*Comment, error) { unfiltered := make([]*Comment, 0, 5) - if err := db.DefaultContext().Engine(). + if err := db.GetEngine(db.DefaultContext). Where("ref_repo_id = ? AND ref_issue_id = ?", pr.Issue.RepoID, pr.Issue.ID). In("ref_action", []references.XRefAction{references.XRefActionCloses, references.XRefActionReopens}). OrderBy("id"). diff --git a/models/issue_xref_test.go b/models/issue_xref_test.go index 1ef9e347fa3..bf498e47107 100644 --- a/models/issue_xref_test.go +++ b/models/issue_xref_test.go @@ -139,7 +139,7 @@ func testCreateIssue(t *testing.T, repo, doer int64, title, content string, ispu Index: idx, } - sess := db.DefaultContext().NewSession() + sess := db.NewSession(db.DefaultContext) defer sess.Close() assert.NoError(t, sess.Begin()) @@ -170,7 +170,7 @@ func testCreateComment(t *testing.T, repo, doer, issue int64, content string) *C i := db.AssertExistsAndLoadBean(t, &Issue{ID: issue}).(*Issue) c := &Comment{Type: CommentTypeComment, PosterID: doer, Poster: d, IssueID: issue, Issue: i, Content: content} - sess := db.DefaultContext().NewSession() + sess := db.NewSession(db.DefaultContext) defer sess.Close() assert.NoError(t, sess.Begin()) _, err := sess.Insert(c) diff --git a/models/lfs.go b/models/lfs.go index a856873e754..87f7a2871f8 100644 --- a/models/lfs.go +++ b/models/lfs.go @@ -44,7 +44,7 @@ var ErrLFSObjectNotExist = errors.New("LFS Meta object does not exist") func NewLFSMetaObject(m *LFSMetaObject) (*LFSMetaObject, error) { var err error - sess := db.DefaultContext().NewSession() + sess := db.NewSession(db.DefaultContext) defer sess.Close() if err = sess.Begin(); err != nil { return nil, err @@ -76,7 +76,7 @@ func (repo *Repository) GetLFSMetaObjectByOid(oid string) (*LFSMetaObject, error } m := &LFSMetaObject{Pointer: lfs.Pointer{Oid: oid}, RepositoryID: repo.ID} - has, err := db.DefaultContext().Engine().Get(m) + has, err := db.GetEngine(db.DefaultContext).Get(m) if err != nil { return nil, err } else if !has { @@ -92,7 +92,7 @@ func (repo *Repository) RemoveLFSMetaObjectByOid(oid string) (int64, error) { return 0, ErrLFSObjectNotExist } - sess := db.DefaultContext().NewSession() + sess := db.NewSession(db.DefaultContext) defer sess.Close() if err := sess.Begin(); err != nil { return -1, err @@ -113,7 +113,7 @@ func (repo *Repository) RemoveLFSMetaObjectByOid(oid string) (int64, error) { // GetLFSMetaObjects returns all LFSMetaObjects associated with a repository func (repo *Repository) GetLFSMetaObjects(page, pageSize int) ([]*LFSMetaObject, error) { - sess := db.DefaultContext().NewSession() + sess := db.NewSession(db.DefaultContext) defer sess.Close() if page >= 0 && pageSize > 0 { @@ -129,23 +129,23 @@ func (repo *Repository) GetLFSMetaObjects(page, pageSize int) ([]*LFSMetaObject, // CountLFSMetaObjects returns a count of all LFSMetaObjects associated with a repository func (repo *Repository) CountLFSMetaObjects() (int64, error) { - return db.DefaultContext().Engine().Count(&LFSMetaObject{RepositoryID: repo.ID}) + return db.GetEngine(db.DefaultContext).Count(&LFSMetaObject{RepositoryID: repo.ID}) } // LFSObjectAccessible checks if a provided Oid is accessible to the user func LFSObjectAccessible(user *User, oid string) (bool, error) { if user.IsAdmin { - count, err := db.DefaultContext().Engine().Count(&LFSMetaObject{Pointer: lfs.Pointer{Oid: oid}}) + count, err := db.GetEngine(db.DefaultContext).Count(&LFSMetaObject{Pointer: lfs.Pointer{Oid: oid}}) return count > 0, err } cond := accessibleRepositoryCondition(user) - count, err := db.DefaultContext().Engine().Where(cond).Join("INNER", "repository", "`lfs_meta_object`.repository_id = `repository`.id").Count(&LFSMetaObject{Pointer: lfs.Pointer{Oid: oid}}) + count, err := db.GetEngine(db.DefaultContext).Where(cond).Join("INNER", "repository", "`lfs_meta_object`.repository_id = `repository`.id").Count(&LFSMetaObject{Pointer: lfs.Pointer{Oid: oid}}) return count > 0, err } // LFSAutoAssociate auto associates accessible LFSMetaObjects func LFSAutoAssociate(metas []*LFSMetaObject, user *User, repoID int64) error { - sess := db.DefaultContext().NewSession() + sess := db.NewSession(db.DefaultContext) defer sess.Close() if err := sess.Begin(); err != nil { return err @@ -184,7 +184,7 @@ func IterateLFS(f func(mo *LFSMetaObject) error) error { const batchSize = 100 for { mos := make([]*LFSMetaObject, 0, batchSize) - if err := db.DefaultContext().Engine().Limit(batchSize, start).Find(&mos); err != nil { + if err := db.GetEngine(db.DefaultContext).Limit(batchSize, start).Find(&mos); err != nil { return err } if len(mos) == 0 { diff --git a/models/lfs_lock.go b/models/lfs_lock.go index d7efdf4440a..ca49ab8a6a0 100644 --- a/models/lfs_lock.go +++ b/models/lfs_lock.go @@ -72,7 +72,7 @@ func CreateLFSLock(lock *LFSLock) (*LFSLock, error) { return nil, err } - _, err = db.DefaultContext().Engine().InsertOne(lock) + _, err = db.GetEngine(db.DefaultContext).InsertOne(lock) return lock, err } @@ -80,7 +80,7 @@ func CreateLFSLock(lock *LFSLock) (*LFSLock, error) { func GetLFSLock(repo *Repository, path string) (*LFSLock, error) { path = cleanPath(path) rel := &LFSLock{RepoID: repo.ID} - has, err := db.DefaultContext().Engine().Where("lower(path) = ?", strings.ToLower(path)).Get(rel) + has, err := db.GetEngine(db.DefaultContext).Where("lower(path) = ?", strings.ToLower(path)).Get(rel) if err != nil { return nil, err } @@ -93,7 +93,7 @@ func GetLFSLock(repo *Repository, path string) (*LFSLock, error) { // GetLFSLockByID returns release by given id. func GetLFSLockByID(id int64) (*LFSLock, error) { lock := new(LFSLock) - has, err := db.DefaultContext().Engine().ID(id).Get(lock) + has, err := db.GetEngine(db.DefaultContext).ID(id).Get(lock) if err != nil { return nil, err } else if !has { @@ -104,7 +104,7 @@ func GetLFSLockByID(id int64) (*LFSLock, error) { // GetLFSLockByRepoID returns a list of locks of repository. func GetLFSLockByRepoID(repoID int64, page, pageSize int) ([]*LFSLock, error) { - sess := db.DefaultContext().NewSession() + sess := db.NewSession(db.DefaultContext) defer sess.Close() if page >= 0 && pageSize > 0 { @@ -120,7 +120,7 @@ func GetLFSLockByRepoID(repoID int64, page, pageSize int) ([]*LFSLock, error) { // CountLFSLockByRepoID returns a count of all LFSLocks associated with a repository. func CountLFSLockByRepoID(repoID int64) (int64, error) { - return db.DefaultContext().Engine().Count(&LFSLock{RepoID: repoID}) + return db.GetEngine(db.DefaultContext).Count(&LFSLock{RepoID: repoID}) } // DeleteLFSLockByID deletes a lock by given ID. @@ -139,7 +139,7 @@ func DeleteLFSLockByID(id int64, u *User, force bool) (*LFSLock, error) { return nil, fmt.Errorf("user doesn't own lock and force flag is not set") } - _, err = db.DefaultContext().Engine().ID(id).Delete(new(LFSLock)) + _, err = db.GetEngine(db.DefaultContext).ID(id).Delete(new(LFSLock)) return lock, err } diff --git a/models/list_options.go b/models/list_options.go index 59bfa91678b..25b9a05f16e 100644 --- a/models/list_options.go +++ b/models/list_options.go @@ -21,7 +21,7 @@ type Paginator interface { func getPaginatedSession(p Paginator) *xorm.Session { skip, take := p.GetSkipTake() - return db.DefaultContext().Engine().Limit(take, skip) + return db.GetEngine(db.DefaultContext).Limit(take, skip) } // setSessionPagination sets pagination for a database session diff --git a/models/login_source.go b/models/login_source.go index 77a43fe4aec..e1f7a7e08e5 100644 --- a/models/login_source.go +++ b/models/login_source.go @@ -208,7 +208,7 @@ func (source *LoginSource) SkipVerify() bool { // CreateLoginSource inserts a LoginSource in the DB if not already // existing with the given name. func CreateLoginSource(source *LoginSource) error { - has, err := db.DefaultContext().Engine().Where("name=?", source.Name).Exist(new(LoginSource)) + has, err := db.GetEngine(db.DefaultContext).Where("name=?", source.Name).Exist(new(LoginSource)) if err != nil { return err } else if has { @@ -219,7 +219,7 @@ func CreateLoginSource(source *LoginSource) error { source.IsSyncEnabled = false } - _, err = db.DefaultContext().Engine().Insert(source) + _, err = db.GetEngine(db.DefaultContext).Insert(source) if err != nil { return err } @@ -240,7 +240,7 @@ func CreateLoginSource(source *LoginSource) error { err = registerableSource.RegisterSource() if err != nil { // remove the LoginSource in case of errors while registering configuration - if _, err := db.DefaultContext().Engine().Delete(source); err != nil { + if _, err := db.GetEngine(db.DefaultContext).Delete(source); err != nil { log.Error("CreateLoginSource: Error while wrapOpenIDConnectInitializeError: %v", err) } } @@ -250,13 +250,13 @@ func CreateLoginSource(source *LoginSource) error { // LoginSources returns a slice of all login sources found in DB. func LoginSources() ([]*LoginSource, error) { auths := make([]*LoginSource, 0, 6) - return auths, db.DefaultContext().Engine().Find(&auths) + return auths, db.GetEngine(db.DefaultContext).Find(&auths) } // LoginSourcesByType returns all sources of the specified type func LoginSourcesByType(loginType LoginType) ([]*LoginSource, error) { sources := make([]*LoginSource, 0, 1) - if err := db.DefaultContext().Engine().Where("type = ?", loginType).Find(&sources); err != nil { + if err := db.GetEngine(db.DefaultContext).Where("type = ?", loginType).Find(&sources); err != nil { return nil, err } return sources, nil @@ -265,7 +265,7 @@ func LoginSourcesByType(loginType LoginType) ([]*LoginSource, error) { // AllActiveLoginSources returns all active sources func AllActiveLoginSources() ([]*LoginSource, error) { sources := make([]*LoginSource, 0, 5) - if err := db.DefaultContext().Engine().Where("is_active = ?", true).Find(&sources); err != nil { + if err := db.GetEngine(db.DefaultContext).Where("is_active = ?", true).Find(&sources); err != nil { return nil, err } return sources, nil @@ -274,7 +274,7 @@ func AllActiveLoginSources() ([]*LoginSource, error) { // ActiveLoginSources returns all active sources of the specified type func ActiveLoginSources(loginType LoginType) ([]*LoginSource, error) { sources := make([]*LoginSource, 0, 1) - if err := db.DefaultContext().Engine().Where("is_active = ? and type = ?", true, loginType).Find(&sources); err != nil { + if err := db.GetEngine(db.DefaultContext).Where("is_active = ? and type = ?", true, loginType).Find(&sources); err != nil { return nil, err } return sources, nil @@ -305,7 +305,7 @@ func GetLoginSourceByID(id int64) (*LoginSource, error) { return source, nil } - has, err := db.DefaultContext().Engine().ID(id).Get(source) + has, err := db.GetEngine(db.DefaultContext).ID(id).Get(source) if err != nil { return nil, err } else if !has { @@ -325,7 +325,7 @@ func UpdateSource(source *LoginSource) error { } } - _, err := db.DefaultContext().Engine().ID(source.ID).AllCols().Update(source) + _, err := db.GetEngine(db.DefaultContext).ID(source.ID).AllCols().Update(source) if err != nil { return err } @@ -346,7 +346,7 @@ func UpdateSource(source *LoginSource) error { err = registerableSource.RegisterSource() if err != nil { // restore original values since we cannot update the provider it self - if _, err := db.DefaultContext().Engine().ID(source.ID).AllCols().Update(originalLoginSource); err != nil { + if _, err := db.GetEngine(db.DefaultContext).ID(source.ID).AllCols().Update(originalLoginSource); err != nil { log.Error("UpdateSource: Error while wrapOpenIDConnectInitializeError: %v", err) } } @@ -355,14 +355,14 @@ func UpdateSource(source *LoginSource) error { // DeleteSource deletes a LoginSource record in DB. func DeleteSource(source *LoginSource) error { - count, err := db.DefaultContext().Engine().Count(&User{LoginSource: source.ID}) + count, err := db.GetEngine(db.DefaultContext).Count(&User{LoginSource: source.ID}) if err != nil { return err } else if count > 0 { return ErrLoginSourceInUse{source.ID} } - count, err = db.DefaultContext().Engine().Count(&ExternalLoginUser{LoginSourceID: source.ID}) + count, err = db.GetEngine(db.DefaultContext).Count(&ExternalLoginUser{LoginSourceID: source.ID}) if err != nil { return err } else if count > 0 { @@ -375,12 +375,12 @@ func DeleteSource(source *LoginSource) error { } } - _, err = db.DefaultContext().Engine().ID(source.ID).Delete(new(LoginSource)) + _, err = db.GetEngine(db.DefaultContext).ID(source.ID).Delete(new(LoginSource)) return err } // CountLoginSources returns number of login sources. func CountLoginSources() int64 { - count, _ := db.DefaultContext().Engine().Count(new(LoginSource)) + count, _ := db.GetEngine(db.DefaultContext).Count(new(LoginSource)) return count } diff --git a/models/migrate.go b/models/migrate.go index 163573a1661..18b1b11e468 100644 --- a/models/migrate.go +++ b/models/migrate.go @@ -18,7 +18,7 @@ func InsertMilestones(ms ...*Milestone) (err error) { return nil } - sess := db.DefaultContext().NewSession() + sess := db.NewSession(db.DefaultContext) defer sess.Close() if err = sess.Begin(); err != nil { return err @@ -39,7 +39,7 @@ func InsertMilestones(ms ...*Milestone) (err error) { // InsertIssues insert issues to database func InsertIssues(issues ...*Issue) error { - sess := db.DefaultContext().NewSession() + sess := db.NewSession(db.DefaultContext) defer sess.Close() if err := sess.Begin(); err != nil { return err @@ -144,7 +144,7 @@ func InsertIssueComments(comments []*Comment) error { issueIDs[comment.IssueID] = true } - sess := db.DefaultContext().NewSession() + sess := db.NewSession(db.DefaultContext) defer sess.Close() if err := sess.Begin(); err != nil { return err @@ -175,7 +175,7 @@ func InsertIssueComments(comments []*Comment) error { // InsertPullRequests inserted pull requests func InsertPullRequests(prs ...*PullRequest) error { - sess := db.DefaultContext().NewSession() + sess := db.NewSession(db.DefaultContext) defer sess.Close() if err := sess.Begin(); err != nil { return err @@ -195,7 +195,7 @@ func InsertPullRequests(prs ...*PullRequest) error { // InsertReleases migrates release func InsertReleases(rels ...*Release) error { - sess := db.DefaultContext().NewSession() + sess := db.NewSession(db.DefaultContext) defer sess.Close() if err := sess.Begin(); err != nil { return err @@ -233,7 +233,7 @@ func migratedIssueCond(tp structs.GitServiceType) builder.Cond { // UpdateReviewsMigrationsByType updates reviews' migrations information via given git service type and original id and poster id func UpdateReviewsMigrationsByType(tp structs.GitServiceType, originalAuthorID string, posterID int64) error { - _, err := db.DefaultContext().Engine().Table("review"). + _, err := db.GetEngine(db.DefaultContext).Table("review"). Where("original_author_id = ?", originalAuthorID). And(migratedIssueCond(tp)). Update(map[string]interface{}{ diff --git a/models/notification.go b/models/notification.go index 2f34def0722..af24a6cf5a7 100644 --- a/models/notification.go +++ b/models/notification.go @@ -127,17 +127,17 @@ func getNotifications(e db.Engine, options *FindNotificationOptions) (nl Notific // GetNotifications returns all notifications that fit to the given options. func GetNotifications(opts *FindNotificationOptions) (NotificationList, error) { - return getNotifications(db.DefaultContext().Engine(), opts) + return getNotifications(db.GetEngine(db.DefaultContext), opts) } // CountNotifications count all notifications that fit to the given options and ignore pagination. func CountNotifications(opts *FindNotificationOptions) (int64, error) { - return db.DefaultContext().Engine().Where(opts.ToCond()).Count(&Notification{}) + return db.GetEngine(db.DefaultContext).Where(opts.ToCond()).Count(&Notification{}) } // CreateRepoTransferNotification creates notification for the user a repository was transferred to func CreateRepoTransferNotification(doer, newOwner *User, repo *Repository) error { - sess := db.DefaultContext().NewSession() + sess := db.NewSession(db.DefaultContext) defer sess.Close() if err := sess.Begin(); err != nil { return err @@ -179,7 +179,7 @@ func CreateRepoTransferNotification(doer, newOwner *User, repo *Repository) erro // for each watcher, or updates it if already exists // receiverID > 0 just send to reciver, else send to all watcher func CreateOrUpdateIssueNotifications(issueID, commentID, notificationAuthorID, receiverID int64) error { - sess := db.DefaultContext().NewSession() + sess := db.NewSession(db.DefaultContext) defer sess.Close() if err := sess.Begin(); err != nil { return err @@ -352,7 +352,7 @@ func getIssueNotification(e db.Engine, userID, issueID int64) (*Notification, er // NotificationsForUser returns notifications for a given user and status func NotificationsForUser(user *User, statuses []NotificationStatus, page, perPage int) (NotificationList, error) { - return notificationsForUser(db.DefaultContext().Engine(), user, statuses, page, perPage) + return notificationsForUser(db.GetEngine(db.DefaultContext), user, statuses, page, perPage) } func notificationsForUser(e db.Engine, user *User, statuses []NotificationStatus, page, perPage int) (notifications []*Notification, err error) { @@ -375,7 +375,7 @@ func notificationsForUser(e db.Engine, user *User, statuses []NotificationStatus // CountUnread count unread notifications for a user func CountUnread(user *User) int64 { - return countUnread(db.DefaultContext().Engine(), user.ID) + return countUnread(db.GetEngine(db.DefaultContext), user.ID) } func countUnread(e db.Engine, userID int64) int64 { @@ -389,7 +389,7 @@ func countUnread(e db.Engine, userID int64) int64 { // LoadAttributes load Repo Issue User and Comment if not loaded func (n *Notification) LoadAttributes() (err error) { - return n.loadAttributes(db.DefaultContext().Engine()) + return n.loadAttributes(db.GetEngine(db.DefaultContext)) } func (n *Notification) loadAttributes(e db.Engine) (err error) { @@ -451,12 +451,12 @@ func (n *Notification) loadUser(e db.Engine) (err error) { // GetRepo returns the repo of the notification func (n *Notification) GetRepo() (*Repository, error) { - return n.Repository, n.loadRepo(db.DefaultContext().Engine()) + return n.Repository, n.loadRepo(db.GetEngine(db.DefaultContext)) } // GetIssue returns the issue of the notification func (n *Notification) GetIssue() (*Issue, error) { - return n.Issue, n.loadIssue(db.DefaultContext().Engine()) + return n.Issue, n.loadIssue(db.GetEngine(db.DefaultContext)) } // HTMLURL formats a URL-string to the notification @@ -521,7 +521,7 @@ func (nl NotificationList) LoadRepos() (RepositoryList, []int, error) { if left < limit { limit = left } - rows, err := db.DefaultContext().Engine(). + rows, err := db.GetEngine(db.DefaultContext). In("id", repoIDs[:limit]). Rows(new(Repository)) if err != nil { @@ -597,7 +597,7 @@ func (nl NotificationList) LoadIssues() ([]int, error) { if left < limit { limit = left } - rows, err := db.DefaultContext().Engine(). + rows, err := db.GetEngine(db.DefaultContext). In("id", issueIDs[:limit]). Rows(new(Issue)) if err != nil { @@ -683,7 +683,7 @@ func (nl NotificationList) LoadComments() ([]int, error) { if left < limit { limit = left } - rows, err := db.DefaultContext().Engine(). + rows, err := db.GetEngine(db.DefaultContext). In("id", commentIDs[:limit]). Rows(new(Comment)) if err != nil { @@ -723,7 +723,7 @@ func (nl NotificationList) LoadComments() ([]int, error) { // GetNotificationCount returns the notification count for user func GetNotificationCount(user *User, status NotificationStatus) (int64, error) { - return getNotificationCount(db.DefaultContext().Engine(), user, status) + return getNotificationCount(db.GetEngine(db.DefaultContext), user, status) } func getNotificationCount(e db.Engine, user *User, status NotificationStatus) (count int64, err error) { @@ -746,7 +746,7 @@ func GetUIDsAndNotificationCounts(since, until timeutil.TimeStamp) ([]UserIDCoun `WHERE user_id IN (SELECT user_id FROM notification WHERE updated_unix >= ? AND ` + `updated_unix < ?) AND status = ? GROUP BY user_id` var res []UserIDCount - return res, db.DefaultContext().Engine().SQL(sql, since, until, NotificationStatusUnread).Find(&res) + return res, db.GetEngine(db.DefaultContext).SQL(sql, since, until, NotificationStatusUnread).Find(&res) } func setIssueNotificationStatusReadIfUnread(e db.Engine, userID, issueID int64) error { @@ -778,7 +778,7 @@ func setRepoNotificationStatusReadIfUnread(e db.Engine, userID, repoID int64) er // SetNotificationStatus change the notification status func SetNotificationStatus(notificationID int64, user *User, status NotificationStatus) (*Notification, error) { - notification, err := getNotificationByID(db.DefaultContext().Engine(), notificationID) + notification, err := getNotificationByID(db.GetEngine(db.DefaultContext), notificationID) if err != nil { return notification, err } @@ -789,13 +789,13 @@ func SetNotificationStatus(notificationID int64, user *User, status Notification notification.Status = status - _, err = db.DefaultContext().Engine().ID(notificationID).Update(notification) + _, err = db.GetEngine(db.DefaultContext).ID(notificationID).Update(notification) return notification, err } // GetNotificationByID return notification by ID func GetNotificationByID(notificationID int64) (*Notification, error) { - return getNotificationByID(db.DefaultContext().Engine(), notificationID) + return getNotificationByID(db.GetEngine(db.DefaultContext), notificationID) } func getNotificationByID(e db.Engine, notificationID int64) (*Notification, error) { @@ -817,7 +817,7 @@ func getNotificationByID(e db.Engine, notificationID int64) (*Notification, erro // UpdateNotificationStatuses updates the statuses of all of a user's notifications that are of the currentStatus type to the desiredStatus func UpdateNotificationStatuses(user *User, currentStatus, desiredStatus NotificationStatus) error { n := &Notification{Status: desiredStatus, UpdatedBy: user.ID} - _, err := db.DefaultContext().Engine(). + _, err := db.GetEngine(db.DefaultContext). Where("user_id = ? AND status = ?", user.ID, currentStatus). Cols("status", "updated_by", "updated_unix"). Update(n) diff --git a/models/oauth2.go b/models/oauth2.go index ac14813ddd1..7fdd5309fb9 100644 --- a/models/oauth2.go +++ b/models/oauth2.go @@ -9,7 +9,7 @@ import "code.gitea.io/gitea/models/db" // GetActiveOAuth2ProviderLoginSources returns all actived LoginOAuth2 sources func GetActiveOAuth2ProviderLoginSources() ([]*LoginSource, error) { sources := make([]*LoginSource, 0, 1) - if err := db.DefaultContext().Engine().Where("is_active = ? and type = ?", true, LoginOAuth2).Find(&sources); err != nil { + if err := db.GetEngine(db.DefaultContext).Where("is_active = ? and type = ?", true, LoginOAuth2).Find(&sources); err != nil { return nil, err } return sources, nil @@ -18,7 +18,7 @@ func GetActiveOAuth2ProviderLoginSources() ([]*LoginSource, error) { // GetActiveOAuth2LoginSourceByName returns a OAuth2 LoginSource based on the given name func GetActiveOAuth2LoginSourceByName(name string) (*LoginSource, error) { loginSource := new(LoginSource) - has, err := db.DefaultContext().Engine().Where("name = ? and type = ? and is_active = ?", name, LoginOAuth2, true).Get(loginSource) + has, err := db.GetEngine(db.DefaultContext).Where("name = ? and type = ? and is_active = ?", name, LoginOAuth2, true).Get(loginSource) if !has || err != nil { return nil, err } diff --git a/models/oauth2_application.go b/models/oauth2_application.go index 850b09234c0..0fd2e38472e 100644 --- a/models/oauth2_application.go +++ b/models/oauth2_application.go @@ -81,7 +81,7 @@ func (app *OAuth2Application) GenerateClientSecret() (string, error) { return "", err } app.ClientSecret = string(hashedSecret) - if _, err := db.DefaultContext().Engine().ID(app.ID).Cols("client_secret").Update(app); err != nil { + if _, err := db.GetEngine(db.DefaultContext).ID(app.ID).Cols("client_secret").Update(app); err != nil { return "", err } return clientSecret, nil @@ -94,7 +94,7 @@ func (app *OAuth2Application) ValidateClientSecret(secret []byte) bool { // GetGrantByUserID returns a OAuth2Grant by its user and application ID func (app *OAuth2Application) GetGrantByUserID(userID int64) (*OAuth2Grant, error) { - return app.getGrantByUserID(db.DefaultContext().Engine(), userID) + return app.getGrantByUserID(db.GetEngine(db.DefaultContext), userID) } func (app *OAuth2Application) getGrantByUserID(e db.Engine, userID int64) (grant *OAuth2Grant, err error) { @@ -109,7 +109,7 @@ func (app *OAuth2Application) getGrantByUserID(e db.Engine, userID int64) (grant // CreateGrant generates a grant for an user func (app *OAuth2Application) CreateGrant(userID int64, scope string) (*OAuth2Grant, error) { - return app.createGrant(db.DefaultContext().Engine(), userID, scope) + return app.createGrant(db.GetEngine(db.DefaultContext), userID, scope) } func (app *OAuth2Application) createGrant(e db.Engine, userID int64, scope string) (*OAuth2Grant, error) { @@ -127,7 +127,7 @@ func (app *OAuth2Application) createGrant(e db.Engine, userID int64, scope strin // GetOAuth2ApplicationByClientID returns the oauth2 application with the given client_id. Returns an error if not found. func GetOAuth2ApplicationByClientID(clientID string) (app *OAuth2Application, err error) { - return getOAuth2ApplicationByClientID(db.DefaultContext().Engine(), clientID) + return getOAuth2ApplicationByClientID(db.GetEngine(db.DefaultContext), clientID) } func getOAuth2ApplicationByClientID(e db.Engine, clientID string) (app *OAuth2Application, err error) { @@ -141,7 +141,7 @@ func getOAuth2ApplicationByClientID(e db.Engine, clientID string) (app *OAuth2Ap // GetOAuth2ApplicationByID returns the oauth2 application with the given id. Returns an error if not found. func GetOAuth2ApplicationByID(id int64) (app *OAuth2Application, err error) { - return getOAuth2ApplicationByID(db.DefaultContext().Engine(), id) + return getOAuth2ApplicationByID(db.GetEngine(db.DefaultContext), id) } func getOAuth2ApplicationByID(e db.Engine, id int64) (app *OAuth2Application, err error) { @@ -158,7 +158,7 @@ func getOAuth2ApplicationByID(e db.Engine, id int64) (app *OAuth2Application, er // GetOAuth2ApplicationsByUserID returns all oauth2 applications owned by the user func GetOAuth2ApplicationsByUserID(userID int64) (apps []*OAuth2Application, err error) { - return getOAuth2ApplicationsByUserID(db.DefaultContext().Engine(), userID) + return getOAuth2ApplicationsByUserID(db.GetEngine(db.DefaultContext), userID) } func getOAuth2ApplicationsByUserID(e db.Engine, userID int64) (apps []*OAuth2Application, err error) { @@ -176,7 +176,7 @@ type CreateOAuth2ApplicationOptions struct { // CreateOAuth2Application inserts a new oauth2 application func CreateOAuth2Application(opts CreateOAuth2ApplicationOptions) (*OAuth2Application, error) { - return createOAuth2Application(db.DefaultContext().Engine(), opts) + return createOAuth2Application(db.GetEngine(db.DefaultContext), opts) } func createOAuth2Application(e db.Engine, opts CreateOAuth2ApplicationOptions) (*OAuth2Application, error) { @@ -203,7 +203,7 @@ type UpdateOAuth2ApplicationOptions struct { // UpdateOAuth2Application updates an oauth2 application func UpdateOAuth2Application(opts UpdateOAuth2ApplicationOptions) (*OAuth2Application, error) { - sess := db.DefaultContext().NewSession() + sess := db.NewSession(db.DefaultContext) if err := sess.Begin(); err != nil { return nil, err } @@ -264,7 +264,7 @@ func deleteOAuth2Application(sess *xorm.Session, id, userid int64) error { // DeleteOAuth2Application deletes the application with the given id and the grants and auth codes related to it. It checks if the userid was the creator of the app. func DeleteOAuth2Application(id, userid int64) error { - sess := db.DefaultContext().NewSession() + sess := db.NewSession(db.DefaultContext) defer sess.Close() if err := sess.Begin(); err != nil { return err @@ -277,7 +277,7 @@ func DeleteOAuth2Application(id, userid int64) error { // ListOAuth2Applications returns a list of oauth2 applications belongs to given user. func ListOAuth2Applications(uid int64, listOptions ListOptions) ([]*OAuth2Application, int64, error) { - sess := db.DefaultContext().Engine(). + sess := db.GetEngine(db.DefaultContext). Where("uid=?", uid). Desc("id") @@ -329,7 +329,7 @@ func (code *OAuth2AuthorizationCode) GenerateRedirectURI(state string) (redirect // Invalidate deletes the auth code from the database to invalidate this code func (code *OAuth2AuthorizationCode) Invalidate() error { - return code.invalidate(db.DefaultContext().Engine()) + return code.invalidate(db.GetEngine(db.DefaultContext)) } func (code *OAuth2AuthorizationCode) invalidate(e db.Engine) error { @@ -361,7 +361,7 @@ func (code *OAuth2AuthorizationCode) validateCodeChallenge(verifier string) bool // GetOAuth2AuthorizationByCode returns an authorization by its code func GetOAuth2AuthorizationByCode(code string) (*OAuth2AuthorizationCode, error) { - return getOAuth2AuthorizationByCode(db.DefaultContext().Engine(), code) + return getOAuth2AuthorizationByCode(db.GetEngine(db.DefaultContext), code) } func getOAuth2AuthorizationByCode(e db.Engine, code string) (auth *OAuth2AuthorizationCode, err error) { @@ -402,7 +402,7 @@ func (grant *OAuth2Grant) TableName() string { // GenerateNewAuthorizationCode generates a new authorization code for a grant and saves it to the database func (grant *OAuth2Grant) GenerateNewAuthorizationCode(redirectURI, codeChallenge, codeChallengeMethod string) (*OAuth2AuthorizationCode, error) { - return grant.generateNewAuthorizationCode(db.DefaultContext().Engine(), redirectURI, codeChallenge, codeChallengeMethod) + return grant.generateNewAuthorizationCode(db.GetEngine(db.DefaultContext), redirectURI, codeChallenge, codeChallengeMethod) } func (grant *OAuth2Grant) generateNewAuthorizationCode(e db.Engine, redirectURI, codeChallenge, codeChallengeMethod string) (code *OAuth2AuthorizationCode, err error) { @@ -426,7 +426,7 @@ func (grant *OAuth2Grant) generateNewAuthorizationCode(e db.Engine, redirectURI, // IncreaseCounter increases the counter and updates the grant func (grant *OAuth2Grant) IncreaseCounter() error { - return grant.increaseCount(db.DefaultContext().Engine()) + return grant.increaseCount(db.GetEngine(db.DefaultContext)) } func (grant *OAuth2Grant) increaseCount(e db.Engine) error { @@ -454,7 +454,7 @@ func (grant *OAuth2Grant) ScopeContains(scope string) bool { // SetNonce updates the current nonce value of a grant func (grant *OAuth2Grant) SetNonce(nonce string) error { - return grant.setNonce(db.DefaultContext().Engine(), nonce) + return grant.setNonce(db.GetEngine(db.DefaultContext), nonce) } func (grant *OAuth2Grant) setNonce(e db.Engine, nonce string) error { @@ -468,7 +468,7 @@ func (grant *OAuth2Grant) setNonce(e db.Engine, nonce string) error { // GetOAuth2GrantByID returns the grant with the given ID func GetOAuth2GrantByID(id int64) (*OAuth2Grant, error) { - return getOAuth2GrantByID(db.DefaultContext().Engine(), id) + return getOAuth2GrantByID(db.GetEngine(db.DefaultContext), id) } func getOAuth2GrantByID(e db.Engine, id int64) (grant *OAuth2Grant, err error) { @@ -483,7 +483,7 @@ func getOAuth2GrantByID(e db.Engine, id int64) (grant *OAuth2Grant, err error) { // GetOAuth2GrantsByUserID lists all grants of a certain user func GetOAuth2GrantsByUserID(uid int64) ([]*OAuth2Grant, error) { - return getOAuth2GrantsByUserID(db.DefaultContext().Engine(), uid) + return getOAuth2GrantsByUserID(db.GetEngine(db.DefaultContext), uid) } func getOAuth2GrantsByUserID(e db.Engine, uid int64) ([]*OAuth2Grant, error) { @@ -515,7 +515,7 @@ func getOAuth2GrantsByUserID(e db.Engine, uid int64) ([]*OAuth2Grant, error) { // RevokeOAuth2Grant deletes the grant with grantID and userID func RevokeOAuth2Grant(grantID, userID int64) error { - return revokeOAuth2Grant(db.DefaultContext().Engine(), grantID, userID) + return revokeOAuth2Grant(db.GetEngine(db.DefaultContext), grantID, userID) } func revokeOAuth2Grant(e db.Engine, grantID, userID int64) error { diff --git a/models/org.go b/models/org.go index 3b1d9f50ece..bc6c47fd456 100644 --- a/models/org.go +++ b/models/org.go @@ -41,7 +41,7 @@ func (org *User) getTeam(e db.Engine, name string) (*Team, error) { // GetTeam returns named team of organization. func (org *User) GetTeam(name string) (*Team, error) { - return org.getTeam(db.DefaultContext().Engine(), name) + return org.getTeam(db.GetEngine(db.DefaultContext), name) } func (org *User) getOwnerTeam(e db.Engine) (*Team, error) { @@ -50,7 +50,7 @@ func (org *User) getOwnerTeam(e db.Engine) (*Team, error) { // GetOwnerTeam returns owner team of organization. func (org *User) GetOwnerTeam() (*Team, error) { - return org.getOwnerTeam(db.DefaultContext().Engine()) + return org.getOwnerTeam(db.GetEngine(db.DefaultContext)) } func (org *User) loadTeams(e db.Engine) error { @@ -65,7 +65,7 @@ func (org *User) loadTeams(e db.Engine) error { // LoadTeams load teams if not loaded. func (org *User) LoadTeams() error { - return org.loadTeams(db.DefaultContext().Engine()) + return org.loadTeams(db.GetEngine(db.DefaultContext)) } // GetMembers returns all members of organization. @@ -85,7 +85,7 @@ type FindOrgMembersOpts struct { // CountOrgMembers counts the organization's members func CountOrgMembers(opts *FindOrgMembersOpts) (int64, error) { - sess := db.DefaultContext().Engine().Where("org_id=?", opts.OrgID) + sess := db.GetEngine(db.DefaultContext).Where("org_id=?", opts.OrgID) if opts.PublicOnly { sess.And("is_public = ?", true) } @@ -129,7 +129,7 @@ func (org *User) removeOrgRepo(e db.Engine, repoID int64) error { // RemoveOrgRepo removes all team-repository relations of organization. func (org *User) RemoveOrgRepo(repoID int64) error { - return org.removeOrgRepo(db.DefaultContext().Engine(), repoID) + return org.removeOrgRepo(db.GetEngine(db.DefaultContext), repoID) } // CreateOrganization creates record of a new organization. @@ -162,7 +162,7 @@ func CreateOrganization(org, owner *User) (err error) { org.NumMembers = 1 org.Type = UserTypeOrganization - sess := db.DefaultContext().NewSession() + sess := db.NewSession(db.DefaultContext) defer sess.Close() if err = sess.Begin(); err != nil { return err @@ -238,7 +238,7 @@ func GetOrgByName(name string) (*User, error) { LowerName: strings.ToLower(name), Type: UserTypeOrganization, } - has, err := db.DefaultContext().Engine().Get(u) + has, err := db.GetEngine(db.DefaultContext).Get(u) if err != nil { return nil, err } else if !has { @@ -249,7 +249,7 @@ func GetOrgByName(name string) (*User, error) { // CountOrganizations returns number of organizations. func CountOrganizations() int64 { - count, _ := db.DefaultContext().Engine(). + count, _ := db.GetEngine(db.DefaultContext). Where("type=1"). Count(new(User)) return count @@ -261,7 +261,7 @@ func DeleteOrganization(org *User) (err error) { return fmt.Errorf("%s is a user not an organization", org.Name) } - sess := db.DefaultContext().NewSession() + sess := db.NewSession(db.DefaultContext) defer sess.Close() if err = sess.Begin(); err != nil { @@ -353,12 +353,12 @@ func isOrganizationOwner(e db.Engine, orgID, uid int64) (bool, error) { // IsOrganizationOwner returns true if given user is in the owner team. func IsOrganizationOwner(orgID, uid int64) (bool, error) { - return isOrganizationOwner(db.DefaultContext().Engine(), orgID, uid) + return isOrganizationOwner(db.GetEngine(db.DefaultContext), orgID, uid) } // IsOrganizationMember returns true if given user is member of organization. func IsOrganizationMember(orgID, uid int64) (bool, error) { - return isOrganizationMember(db.DefaultContext().Engine(), orgID, uid) + return isOrganizationMember(db.GetEngine(db.DefaultContext), orgID, uid) } func isOrganizationMember(e db.Engine, orgID, uid int64) (bool, error) { @@ -371,7 +371,7 @@ func isOrganizationMember(e db.Engine, orgID, uid int64) (bool, error) { // IsPublicMembership returns true if given user public his/her membership. func IsPublicMembership(orgID, uid int64) (bool, error) { - return db.DefaultContext().Engine(). + return db.GetEngine(db.DefaultContext). Where("uid=?", uid). And("org_id=?", orgID). And("is_public=?", true). @@ -384,7 +384,7 @@ func CanCreateOrgRepo(orgID, uid int64) (bool, error) { if owner, err := IsOrganizationOwner(orgID, uid); owner || err != nil { return owner, err } - return db.DefaultContext().Engine(). + return db.GetEngine(db.DefaultContext). Where(builder.Eq{"team.can_create_org_repo": true}). Join("INNER", "team_user", "team_user.team_id = team.id"). And("team_user.uid = ?", uid). @@ -394,12 +394,12 @@ func CanCreateOrgRepo(orgID, uid int64) (bool, error) { // GetUsersWhoCanCreateOrgRepo returns users which are able to create repo in organization func GetUsersWhoCanCreateOrgRepo(orgID int64) ([]*User, error) { - return getUsersWhoCanCreateOrgRepo(db.DefaultContext().Engine(), orgID) + return getUsersWhoCanCreateOrgRepo(db.GetEngine(db.DefaultContext), orgID) } func getUsersWhoCanCreateOrgRepo(e db.Engine, orgID int64) ([]*User, error) { users := make([]*User, 0, 10) - return users, db.DefaultContext().Engine(). + return users, db.GetEngine(db.DefaultContext). Join("INNER", "`team_user`", "`team_user`.uid=`user`.id"). Join("INNER", "`team`", "`team`.id=`team_user`.team_id"). Where(builder.Eq{"team.can_create_org_repo": true}.Or(builder.Eq{"team.authorize": AccessModeOwner})). @@ -421,7 +421,7 @@ func getOrgsByUserID(sess *xorm.Session, userID int64, showAll bool) ([]*User, e // GetOrgsByUserID returns a list of organizations that the given user ID // has joined. func GetOrgsByUserID(userID int64, showAll bool) ([]*User, error) { - sess := db.DefaultContext().NewSession() + sess := db.NewSession(db.DefaultContext) defer sess.Close() return getOrgsByUserID(sess, userID, showAll) } @@ -431,7 +431,7 @@ type MinimalOrg = User // GetUserOrgsList returns one user's all orgs list func GetUserOrgsList(user *User) ([]*MinimalOrg, error) { - sess := db.DefaultContext().NewSession() + sess := db.NewSession(db.DefaultContext) defer sess.Close() schema, err := db.TableInfo(new(User)) @@ -502,7 +502,7 @@ func getOwnedOrgsByUserID(sess *xorm.Session, userID int64) ([]*User, error) { // HasOrgOrUserVisible tells if the given user can see the given org or user func HasOrgOrUserVisible(org, user *User) bool { - return hasOrgOrUserVisible(db.DefaultContext().Engine(), org, user) + return hasOrgOrUserVisible(db.GetEngine(db.DefaultContext), org, user) } func hasOrgOrUserVisible(e db.Engine, orgOrUser, user *User) bool { @@ -537,7 +537,7 @@ func HasOrgsVisible(orgs []*User, user *User) bool { // GetOwnedOrgsByUserID returns a list of organizations are owned by given user ID. func GetOwnedOrgsByUserID(userID int64) ([]*User, error) { - sess := db.DefaultContext().NewSession() + sess := db.NewSession(db.DefaultContext) defer sess.Close() return getOwnedOrgsByUserID(sess, userID) } @@ -545,7 +545,7 @@ func GetOwnedOrgsByUserID(userID int64) ([]*User, error) { // GetOwnedOrgsByUserIDDesc returns a list of organizations are owned by // given user ID, ordered descending by the given condition. func GetOwnedOrgsByUserIDDesc(userID int64, desc string) ([]*User, error) { - return getOwnedOrgsByUserID(db.DefaultContext().Engine().Desc(desc), userID) + return getOwnedOrgsByUserID(db.GetEngine(db.DefaultContext).Desc(desc), userID) } // GetOrgsCanCreateRepoByUserID returns a list of organizations where given user ID @@ -553,7 +553,7 @@ func GetOwnedOrgsByUserIDDesc(userID int64, desc string) ([]*User, error) { func GetOrgsCanCreateRepoByUserID(userID int64) ([]*User, error) { orgs := make([]*User, 0, 10) - return orgs, db.DefaultContext().Engine().Where(builder.In("id", builder.Select("`user`.id").From("`user`"). + return orgs, db.GetEngine(db.DefaultContext).Where(builder.In("id", builder.Select("`user`.id").From("`user`"). Join("INNER", "`team_user`", "`team_user`.org_id = `user`.id"). Join("INNER", "`team`", "`team`.id = `team_user`.team_id"). Where(builder.Eq{"`team_user`.uid": userID}). @@ -565,7 +565,7 @@ func GetOrgsCanCreateRepoByUserID(userID int64) ([]*User, error) { // GetOrgUsersByUserID returns all organization-user relations by user ID. func GetOrgUsersByUserID(uid int64, opts *SearchOrganizationsOptions) ([]*OrgUser, error) { ous := make([]*OrgUser, 0, 10) - sess := db.DefaultContext().Engine(). + sess := db.GetEngine(db.DefaultContext). Join("LEFT", "`user`", "`org_user`.org_id=`user`.id"). Where("`org_user`.uid=?", uid) if !opts.All { @@ -585,7 +585,7 @@ func GetOrgUsersByUserID(uid int64, opts *SearchOrganizationsOptions) ([]*OrgUse // GetOrgUsersByOrgID returns all organization-user relations by organization ID. func GetOrgUsersByOrgID(opts *FindOrgMembersOpts) ([]*OrgUser, error) { - return getOrgUsersByOrgID(db.DefaultContext().Engine(), opts) + return getOrgUsersByOrgID(db.GetEngine(db.DefaultContext), opts) } func getOrgUsersByOrgID(e db.Engine, opts *FindOrgMembersOpts) ([]*OrgUser, error) { @@ -607,7 +607,7 @@ func getOrgUsersByOrgID(e db.Engine, opts *FindOrgMembersOpts) ([]*OrgUser, erro // ChangeOrgUserStatus changes public or private membership status. func ChangeOrgUserStatus(orgID, uid int64, public bool) error { ou := new(OrgUser) - has, err := db.DefaultContext().Engine(). + has, err := db.GetEngine(db.DefaultContext). Where("uid=?", uid). And("org_id=?", orgID). Get(ou) @@ -618,7 +618,7 @@ func ChangeOrgUserStatus(orgID, uid int64, public bool) error { } ou.IsPublic = public - _, err = db.DefaultContext().Engine().ID(ou.ID).Cols("is_public").Update(ou) + _, err = db.GetEngine(db.DefaultContext).ID(ou.ID).Cols("is_public").Update(ou) return err } @@ -629,7 +629,7 @@ func AddOrgUser(orgID, uid int64) error { return err } - sess := db.DefaultContext().NewSession() + sess := db.NewSession(db.DefaultContext) defer sess.Close() if err := sess.Begin(); err != nil { return err @@ -738,7 +738,7 @@ func removeOrgUser(sess *xorm.Session, orgID, userID int64) error { // RemoveOrgUser removes user from given organization. func RemoveOrgUser(orgID, userID int64) error { - sess := db.DefaultContext().NewSession() + sess := db.NewSession(db.DefaultContext) defer sess.Close() if err := sess.Begin(); err != nil { return err @@ -805,13 +805,13 @@ func (org *User) TeamsWithAccessToRepo(repoID int64, mode AccessMode) ([]*Team, // GetUserTeamIDs returns of all team IDs of the organization that user is member of. func (org *User) GetUserTeamIDs(userID int64) ([]int64, error) { - return org.getUserTeamIDs(db.DefaultContext().Engine(), userID) + return org.getUserTeamIDs(db.GetEngine(db.DefaultContext), userID) } // GetUserTeams returns all teams that belong to user, // and that the user has joined. func (org *User) GetUserTeams(userID int64) ([]*Team, error) { - return org.getUserTeams(db.DefaultContext().Engine(), userID) + return org.getUserTeams(db.GetEngine(db.DefaultContext), userID) } // AccessibleReposEnvironment operations involving the repositories that are @@ -838,7 +838,7 @@ type accessibleReposEnv struct { // AccessibleReposEnv builds an AccessibleReposEnvironment for the repositories in `org` // that are accessible to the specified user. func (org *User) AccessibleReposEnv(userID int64) (AccessibleReposEnvironment, error) { - return org.accessibleReposEnv(db.DefaultContext().Engine(), userID) + return org.accessibleReposEnv(db.GetEngine(db.DefaultContext), userID) } func (org *User) accessibleReposEnv(e db.Engine, userID int64) (AccessibleReposEnvironment, error) { @@ -871,7 +871,7 @@ func (org *User) AccessibleTeamReposEnv(team *Team) AccessibleReposEnvironment { return &accessibleReposEnv{ org: org, team: team, - e: db.DefaultContext().Engine(), + e: db.GetEngine(db.DefaultContext), orderBy: SearchOrderByRecentUpdated, } } diff --git a/models/org_team.go b/models/org_team.go index 280d814eefe..7ca715bb789 100644 --- a/models/org_team.go +++ b/models/org_team.go @@ -82,7 +82,7 @@ func SearchTeam(opts *SearchTeamOptions) ([]*Team, int64, error) { cond = cond.And(builder.Eq{"org_id": opts.OrgID}) - sess := db.DefaultContext().NewSession() + sess := db.NewSession(db.DefaultContext) defer sess.Close() count, err := sess. @@ -120,7 +120,7 @@ func (t *Team) ColorFormat(s fmt.State) { // GetUnits return a list of available units for a team func (t *Team) GetUnits() error { - return t.getUnits(db.DefaultContext().Engine()) + return t.getUnits(db.GetEngine(db.DefaultContext)) } func (t *Team) getUnits(e db.Engine) (err error) { @@ -173,7 +173,7 @@ func (t *Team) getRepositories(e db.Engine) error { // GetRepositories returns paginated repositories in team of organization. func (t *Team) GetRepositories(opts *SearchTeamOptions) error { if opts.Page == 0 { - return t.getRepositories(db.DefaultContext().Engine()) + return t.getRepositories(db.GetEngine(db.DefaultContext)) } return t.getRepositories(getPaginatedSession(opts)) @@ -187,7 +187,7 @@ func (t *Team) getMembers(e db.Engine) (err error) { // GetMembers returns paginated members in team of organization. func (t *Team) GetMembers(opts *SearchMembersOptions) (err error) { if opts.Page == 0 { - return t.getMembers(db.DefaultContext().Engine()) + return t.getMembers(db.GetEngine(db.DefaultContext)) } return t.getMembers(getPaginatedSession(opts)) @@ -210,7 +210,7 @@ func (t *Team) hasRepository(e db.Engine, repoID int64) bool { // HasRepository returns true if given repository belong to team. func (t *Team) HasRepository(repoID int64) bool { - return t.hasRepository(db.DefaultContext().Engine(), repoID) + return t.hasRepository(db.GetEngine(db.DefaultContext), repoID) } func (t *Team) addRepository(e db.Engine, repo *Repository) (err error) { @@ -264,7 +264,7 @@ func (t *Team) addAllRepositories(e db.Engine) error { // AddAllRepositories adds all repositories to the team func (t *Team) AddAllRepositories() (err error) { - sess := db.DefaultContext().NewSession() + sess := db.NewSession(db.DefaultContext) defer sess.Close() if err = sess.Begin(); err != nil { return err @@ -285,7 +285,7 @@ func (t *Team) AddRepository(repo *Repository) (err error) { return nil } - sess := db.DefaultContext().NewSession() + sess := db.NewSession(db.DefaultContext) defer sess.Close() if err = sess.Begin(); err != nil { return err @@ -304,7 +304,7 @@ func (t *Team) RemoveAllRepositories() (err error) { return nil } - sess := db.DefaultContext().NewSession() + sess := db.NewSession(db.DefaultContext) defer sess.Close() if err = sess.Begin(); err != nil { return err @@ -421,7 +421,7 @@ func (t *Team) RemoveRepository(repoID int64) error { return err } - sess := db.DefaultContext().NewSession() + sess := db.NewSession(db.DefaultContext) defer sess.Close() if err = sess.Begin(); err != nil { return err @@ -436,7 +436,7 @@ func (t *Team) RemoveRepository(repoID int64) error { // UnitEnabled returns if the team has the given unit type enabled func (t *Team) UnitEnabled(tp UnitType) bool { - return t.unitEnabled(db.DefaultContext().Engine(), tp) + return t.unitEnabled(db.GetEngine(db.DefaultContext), tp) } func (t *Team) unitEnabled(e db.Engine, tp UnitType) bool { @@ -473,7 +473,7 @@ func NewTeam(t *Team) (err error) { return err } - has, err := db.DefaultContext().Engine().ID(t.OrgID).Get(new(User)) + has, err := db.GetEngine(db.DefaultContext).ID(t.OrgID).Get(new(User)) if err != nil { return err } @@ -482,7 +482,7 @@ func NewTeam(t *Team) (err error) { } t.LowerName = strings.ToLower(t.Name) - has, err = db.DefaultContext().Engine(). + has, err = db.GetEngine(db.DefaultContext). Where("org_id=?", t.OrgID). And("lower_name=?", t.LowerName). Get(new(Team)) @@ -493,7 +493,7 @@ func NewTeam(t *Team) (err error) { return ErrTeamAlreadyExist{t.OrgID, t.LowerName} } - sess := db.DefaultContext().NewSession() + sess := db.NewSession(db.DefaultContext) defer sess.Close() if err = sess.Begin(); err != nil { return err @@ -556,7 +556,7 @@ func getTeam(e db.Engine, orgID int64, name string) (*Team, error) { // GetTeam returns team by given team name and organization. func GetTeam(orgID int64, name string) (*Team, error) { - return getTeam(db.DefaultContext().Engine(), orgID, name) + return getTeam(db.GetEngine(db.DefaultContext), orgID, name) } // GetTeamIDsByNames returns a slice of team ids corresponds to names. @@ -594,7 +594,7 @@ func getTeamByID(e db.Engine, teamID int64) (*Team, error) { // GetTeamByID returns team by given ID. func GetTeamByID(teamID int64) (*Team, error) { - return getTeamByID(db.DefaultContext().Engine(), teamID) + return getTeamByID(db.GetEngine(db.DefaultContext), teamID) } // GetTeamNamesByID returns team's lower name from a list of team ids. @@ -604,7 +604,7 @@ func GetTeamNamesByID(teamIDs []int64) ([]string, error) { } var teamNames []string - err := db.DefaultContext().Engine().Table("team"). + err := db.GetEngine(db.DefaultContext).Table("team"). Select("lower_name"). In("id", teamIDs). Asc("name"). @@ -623,7 +623,7 @@ func UpdateTeam(t *Team, authChanged, includeAllChanged bool) (err error) { t.Description = t.Description[:255] } - sess := db.DefaultContext().NewSession() + sess := db.NewSession(db.DefaultContext) defer sess.Close() if err = sess.Begin(); err != nil { return err @@ -697,7 +697,7 @@ func DeleteTeam(t *Team) error { return err } - sess := db.DefaultContext().NewSession() + sess := db.NewSession(db.DefaultContext) defer sess.Close() if err := sess.Begin(); err != nil { return err @@ -764,7 +764,7 @@ func isTeamMember(e db.Engine, orgID, teamID, userID int64) (bool, error) { // IsTeamMember returns true if given user is a member of team. func IsTeamMember(orgID, teamID, userID int64) (bool, error) { - return isTeamMember(db.DefaultContext().Engine(), orgID, teamID, userID) + return isTeamMember(db.GetEngine(db.DefaultContext), orgID, teamID, userID) } func getTeamUsersByTeamID(e db.Engine, teamID int64) ([]*TeamUser, error) { @@ -795,7 +795,7 @@ func getTeamMembers(e db.Engine, teamID int64) (_ []*User, err error) { // GetTeamMembers returns all members in given team of organization. func GetTeamMembers(teamID int64) ([]*User, error) { - return getTeamMembers(db.DefaultContext().Engine(), teamID) + return getTeamMembers(db.GetEngine(db.DefaultContext), teamID) } func getUserOrgTeams(e db.Engine, orgID, userID int64) (teams []*Team, err error) { @@ -818,7 +818,7 @@ func getUserRepoTeams(e db.Engine, orgID, userID, repoID int64) (teams []*Team, // GetUserOrgTeams returns all teams that user belongs to in given organization. func GetUserOrgTeams(orgID, userID int64) ([]*Team, error) { - return getUserOrgTeams(db.DefaultContext().Engine(), orgID, userID) + return getUserOrgTeams(db.GetEngine(db.DefaultContext), orgID, userID) } // AddTeamMember adds new membership of given team to given organization, @@ -838,7 +838,7 @@ func AddTeamMember(team *Team, userID int64) error { return err } - sess := db.DefaultContext().NewSession() + sess := db.NewSession(db.DefaultContext) defer sess.Close() if err := sess.Begin(); err != nil { return err @@ -933,7 +933,7 @@ func removeTeamMember(e *xorm.Session, team *Team, userID int64) error { // RemoveTeamMember removes member from given team of given organization. func RemoveTeamMember(team *Team, userID int64) error { - sess := db.DefaultContext().NewSession() + sess := db.NewSession(db.DefaultContext) defer sess.Close() if err := sess.Begin(); err != nil { return err @@ -946,7 +946,7 @@ func RemoveTeamMember(team *Team, userID int64) error { // IsUserInTeams returns if a user in some teams func IsUserInTeams(userID int64, teamIDs []int64) (bool, error) { - return isUserInTeams(db.DefaultContext().Engine(), userID, teamIDs) + return isUserInTeams(db.GetEngine(db.DefaultContext), userID, teamIDs) } func isUserInTeams(e db.Engine, userID int64, teamIDs []int64) (bool, error) { @@ -956,7 +956,7 @@ func isUserInTeams(e db.Engine, userID int64, teamIDs []int64) (bool, error) { // UsersInTeamsCount counts the number of users which are in userIDs and teamIDs func UsersInTeamsCount(userIDs, teamIDs []int64) (int64, error) { var ids []int64 - if err := db.DefaultContext().Engine().In("uid", userIDs).In("team_id", teamIDs). + if err := db.GetEngine(db.DefaultContext).In("uid", userIDs).In("team_id", teamIDs). Table("team_user"). Cols("uid").GroupBy("uid").Find(&ids); err != nil { return 0, err @@ -990,7 +990,7 @@ func hasTeamRepo(e db.Engine, orgID, teamID, repoID int64) bool { // HasTeamRepo returns true if given repository belongs to team. func HasTeamRepo(orgID, teamID, repoID int64) bool { - return hasTeamRepo(db.DefaultContext().Engine(), orgID, teamID, repoID) + return hasTeamRepo(db.GetEngine(db.DefaultContext), orgID, teamID, repoID) } func addTeamRepo(e db.Engine, orgID, teamID, repoID int64) error { @@ -1013,7 +1013,7 @@ func removeTeamRepo(e db.Engine, teamID, repoID int64) error { // GetTeamsWithAccessToRepo returns all teams in an organization that have given access level to the repository. func GetTeamsWithAccessToRepo(orgID, repoID int64, mode AccessMode) ([]*Team, error) { teams := make([]*Team, 0, 5) - return teams, db.DefaultContext().Engine().Where("team.authorize >= ?", mode). + return teams, db.GetEngine(db.DefaultContext).Where("team.authorize >= ?", mode). Join("INNER", "team_repo", "team_repo.team_id = team.id"). And("team_repo.org_id = ?", orgID). And("team_repo.repo_id = ?", repoID). @@ -1046,7 +1046,7 @@ func getUnitsByTeamID(e db.Engine, teamID int64) (units []*TeamUnit, err error) // UpdateTeamUnits updates a teams's units func UpdateTeamUnits(team *Team, units []TeamUnit) (err error) { - sess := db.DefaultContext().NewSession() + sess := db.NewSession(db.DefaultContext) defer sess.Close() if err = sess.Begin(); err != nil { return err diff --git a/models/org_test.go b/models/org_test.go index 9990a9d9f1a..75dfc4262d5 100644 --- a/models/org_test.go +++ b/models/org_test.go @@ -255,7 +255,7 @@ func TestGetOrgByName(t *testing.T) { func TestCountOrganizations(t *testing.T) { assert.NoError(t, db.PrepareTestDatabase()) - expected, err := db.DefaultContext().Engine().Where("type=?", UserTypeOrganization).Count(&User{}) + expected, err := db.GetEngine(db.DefaultContext).Where("type=?", UserTypeOrganization).Count(&User{}) assert.NoError(t, err) assert.Equal(t, expected, CountOrganizations()) } diff --git a/models/project.go b/models/project.go index 1e520b877ef..8aaff50e151 100644 --- a/models/project.go +++ b/models/project.go @@ -90,7 +90,7 @@ type ProjectSearchOptions struct { // GetProjects returns a list of all projects that have been created in the repository func GetProjects(opts ProjectSearchOptions) ([]*Project, int64, error) { - return getProjects(db.DefaultContext().Engine(), opts) + return getProjects(db.GetEngine(db.DefaultContext), opts) } func getProjects(e db.Engine, opts ProjectSearchOptions) ([]*Project, int64, error) { @@ -143,7 +143,7 @@ func NewProject(p *Project) error { return errors.New("project type is not valid") } - sess := db.DefaultContext().NewSession() + sess := db.NewSession(db.DefaultContext) defer sess.Close() if err := sess.Begin(); err != nil { @@ -167,7 +167,7 @@ func NewProject(p *Project) error { // GetProjectByID returns the projects in a repository func GetProjectByID(id int64) (*Project, error) { - return getProjectByID(db.DefaultContext().Engine(), id) + return getProjectByID(db.GetEngine(db.DefaultContext), id) } func getProjectByID(e db.Engine, id int64) (*Project, error) { @@ -185,7 +185,7 @@ func getProjectByID(e db.Engine, id int64) (*Project, error) { // UpdateProject updates project properties func UpdateProject(p *Project) error { - return updateProject(db.DefaultContext().Engine(), p) + return updateProject(db.GetEngine(db.DefaultContext), p) } func updateProject(e db.Engine, p *Project) error { @@ -220,7 +220,7 @@ func updateRepositoryProjectCount(e db.Engine, repoID int64) error { // ChangeProjectStatusByRepoIDAndID toggles a project between opened and closed func ChangeProjectStatusByRepoIDAndID(repoID, projectID int64, isClosed bool) error { - sess := db.DefaultContext().NewSession() + sess := db.NewSession(db.DefaultContext) defer sess.Close() if err := sess.Begin(); err != nil { return err @@ -244,7 +244,7 @@ func ChangeProjectStatusByRepoIDAndID(repoID, projectID int64, isClosed bool) er // ChangeProjectStatus toggle a project between opened and closed func ChangeProjectStatus(p *Project, isClosed bool) error { - sess := db.DefaultContext().NewSession() + sess := db.NewSession(db.DefaultContext) defer sess.Close() if err := sess.Begin(); err != nil { return err @@ -273,7 +273,7 @@ func changeProjectStatus(e db.Engine, p *Project, isClosed bool) error { // DeleteProjectByID deletes a project from a repository. func DeleteProjectByID(id int64) error { - sess := db.DefaultContext().NewSession() + sess := db.NewSession(db.DefaultContext) defer sess.Close() if err := sess.Begin(); err != nil { return err diff --git a/models/project_board.go b/models/project_board.go index 901850e5110..6a358685113 100644 --- a/models/project_board.go +++ b/models/project_board.go @@ -100,13 +100,13 @@ func createBoardsForProjectsType(sess *xorm.Session, project *Project) error { // NewProjectBoard adds a new project board to a given project func NewProjectBoard(board *ProjectBoard) error { - _, err := db.DefaultContext().Engine().Insert(board) + _, err := db.GetEngine(db.DefaultContext).Insert(board) return err } // DeleteProjectBoardByID removes all issues references to the project board. func DeleteProjectBoardByID(boardID int64) error { - sess := db.DefaultContext().NewSession() + sess := db.NewSession(db.DefaultContext) defer sess.Close() if err := sess.Begin(); err != nil { return err @@ -146,7 +146,7 @@ func deleteProjectBoardByProjectID(e db.Engine, projectID int64) error { // GetProjectBoard fetches the current board of a project func GetProjectBoard(boardID int64) (*ProjectBoard, error) { - return getProjectBoard(db.DefaultContext().Engine(), boardID) + return getProjectBoard(db.GetEngine(db.DefaultContext), boardID) } func getProjectBoard(e db.Engine, boardID int64) (*ProjectBoard, error) { @@ -164,7 +164,7 @@ func getProjectBoard(e db.Engine, boardID int64) (*ProjectBoard, error) { // UpdateProjectBoard updates a project board func UpdateProjectBoard(board *ProjectBoard) error { - return updateProjectBoard(db.DefaultContext().Engine(), board) + return updateProjectBoard(db.GetEngine(db.DefaultContext), board) } func updateProjectBoard(e db.Engine, board *ProjectBoard) error { @@ -186,7 +186,7 @@ func updateProjectBoard(e db.Engine, board *ProjectBoard) error { // GetProjectBoards fetches all boards related to a project // if no default board set, first board is a temporary "Uncategorized" board func GetProjectBoards(projectID int64) (ProjectBoardList, error) { - return getProjectBoards(db.DefaultContext().Engine(), projectID) + return getProjectBoards(db.GetEngine(db.DefaultContext), projectID) } func getProjectBoards(e db.Engine, projectID int64) ([]*ProjectBoard, error) { @@ -226,7 +226,7 @@ func getDefaultBoard(e db.Engine, projectID int64) (*ProjectBoard, error) { // SetDefaultBoard represents a board for issues not assigned to one // if boardID is 0 unset default func SetDefaultBoard(projectID, boardID int64) error { - _, err := db.DefaultContext().Engine().Where(builder.Eq{ + _, err := db.GetEngine(db.DefaultContext).Where(builder.Eq{ "project_id": projectID, "`default`": true, }).Cols("`default`").Update(&ProjectBoard{Default: false}) @@ -235,7 +235,7 @@ func SetDefaultBoard(projectID, boardID int64) error { } if boardID > 0 { - _, err = db.DefaultContext().Engine().ID(boardID).Where(builder.Eq{"project_id": projectID}). + _, err = db.GetEngine(db.DefaultContext).ID(boardID).Where(builder.Eq{"project_id": projectID}). Cols("`default`").Update(&ProjectBoard{Default: true}) } @@ -293,7 +293,7 @@ func (bs ProjectBoardList) LoadIssues() (IssueList, error) { // UpdateProjectBoardSorting update project board sorting func UpdateProjectBoardSorting(bs ProjectBoardList) error { for i := range bs { - _, err := db.DefaultContext().Engine().ID(bs[i].ID).Cols( + _, err := db.GetEngine(db.DefaultContext).ID(bs[i].ID).Cols( "sorting", ).Update(bs[i]) if err != nil { diff --git a/models/project_issue.go b/models/project_issue.go index acc0a31e1eb..a3179507dc9 100644 --- a/models/project_issue.go +++ b/models/project_issue.go @@ -39,7 +39,7 @@ func deleteProjectIssuesByProjectID(e db.Engine, projectID int64) error { // LoadProject load the project the issue was assigned to func (i *Issue) LoadProject() (err error) { - return i.loadProject(db.DefaultContext().Engine()) + return i.loadProject(db.GetEngine(db.DefaultContext)) } func (i *Issue) loadProject(e db.Engine) (err error) { @@ -58,7 +58,7 @@ func (i *Issue) loadProject(e db.Engine) (err error) { // ProjectID return project id if issue was assigned to one func (i *Issue) ProjectID() int64 { - return i.projectID(db.DefaultContext().Engine()) + return i.projectID(db.GetEngine(db.DefaultContext)) } func (i *Issue) projectID(e db.Engine) int64 { @@ -72,7 +72,7 @@ func (i *Issue) projectID(e db.Engine) int64 { // ProjectBoardID return project board id if issue was assigned to one func (i *Issue) ProjectBoardID() int64 { - return i.projectBoardID(db.DefaultContext().Engine()) + return i.projectBoardID(db.GetEngine(db.DefaultContext)) } func (i *Issue) projectBoardID(e db.Engine) int64 { @@ -93,7 +93,7 @@ func (i *Issue) projectBoardID(e db.Engine) int64 { // NumIssues return counter of all issues assigned to a project func (p *Project) NumIssues() int { - c, err := db.DefaultContext().Engine().Table("project_issue"). + c, err := db.GetEngine(db.DefaultContext).Table("project_issue"). Where("project_id=?", p.ID). GroupBy("issue_id"). Cols("issue_id"). @@ -106,7 +106,7 @@ func (p *Project) NumIssues() int { // NumClosedIssues return counter of closed issues assigned to a project func (p *Project) NumClosedIssues() int { - c, err := db.DefaultContext().Engine().Table("project_issue"). + c, err := db.GetEngine(db.DefaultContext).Table("project_issue"). Join("INNER", "issue", "project_issue.issue_id=issue.id"). Where("project_issue.project_id=? AND issue.is_closed=?", p.ID, true). Cols("issue_id"). @@ -119,7 +119,7 @@ func (p *Project) NumClosedIssues() int { // NumOpenIssues return counter of open issues assigned to a project func (p *Project) NumOpenIssues() int { - c, err := db.DefaultContext().Engine().Table("project_issue"). + c, err := db.GetEngine(db.DefaultContext).Table("project_issue"). Join("INNER", "issue", "project_issue.issue_id=issue.id"). Where("project_issue.project_id=? AND issue.is_closed=?", p.ID, false).Count("issue.id") if err != nil { @@ -130,7 +130,7 @@ func (p *Project) NumOpenIssues() int { // ChangeProjectAssign changes the project associated with an issue func ChangeProjectAssign(issue *Issue, doer *User, newProjectID int64) error { - sess := db.DefaultContext().NewSession() + sess := db.NewSession(db.DefaultContext) defer sess.Close() if err := sess.Begin(); err != nil { return err @@ -183,7 +183,7 @@ func addUpdateIssueProject(e *xorm.Session, issue *Issue, doer *User, newProject // MoveIssueAcrossProjectBoards move a card from one board to another func MoveIssueAcrossProjectBoards(issue *Issue, board *ProjectBoard) error { - sess := db.DefaultContext().NewSession() + sess := db.NewSession(db.DefaultContext) defer sess.Close() if err := sess.Begin(); err != nil { return err diff --git a/models/protected_tag.go b/models/protected_tag.go index 0ce997e99a1..93318300e88 100644 --- a/models/protected_tag.go +++ b/models/protected_tag.go @@ -35,19 +35,19 @@ func init() { // InsertProtectedTag inserts a protected tag to database func InsertProtectedTag(pt *ProtectedTag) error { - _, err := db.DefaultContext().Engine().Insert(pt) + _, err := db.GetEngine(db.DefaultContext).Insert(pt) return err } // UpdateProtectedTag updates the protected tag func UpdateProtectedTag(pt *ProtectedTag) error { - _, err := db.DefaultContext().Engine().ID(pt.ID).AllCols().Update(pt) + _, err := db.GetEngine(db.DefaultContext).ID(pt.ID).AllCols().Update(pt) return err } // DeleteProtectedTag deletes a protected tag by ID func DeleteProtectedTag(pt *ProtectedTag) error { - _, err := db.DefaultContext().Engine().ID(pt.ID).Delete(&ProtectedTag{}) + _, err := db.GetEngine(db.DefaultContext).ID(pt.ID).Delete(&ProtectedTag{}) return err } @@ -86,13 +86,13 @@ func (pt *ProtectedTag) IsUserAllowed(userID int64) (bool, error) { // GetProtectedTags gets all protected tags of the repository func (repo *Repository) GetProtectedTags() ([]*ProtectedTag, error) { tags := make([]*ProtectedTag, 0) - return tags, db.DefaultContext().Engine().Find(&tags, &ProtectedTag{RepoID: repo.ID}) + return tags, db.GetEngine(db.DefaultContext).Find(&tags, &ProtectedTag{RepoID: repo.ID}) } // GetProtectedTagByID gets the protected tag with the specific id func GetProtectedTagByID(id int64) (*ProtectedTag, error) { tag := new(ProtectedTag) - has, err := db.DefaultContext().Engine().ID(id).Get(tag) + has, err := db.GetEngine(db.DefaultContext).ID(id).Get(tag) if err != nil { return nil, err } diff --git a/models/pull.go b/models/pull.go index 5cb7b57286f..004af62f035 100644 --- a/models/pull.go +++ b/models/pull.go @@ -122,7 +122,7 @@ func (pr *PullRequest) loadAttributes(e db.Engine) (err error) { // LoadAttributes loads pull request attributes from database func (pr *PullRequest) LoadAttributes() error { - return pr.loadAttributes(db.DefaultContext().Engine()) + return pr.loadAttributes(db.GetEngine(db.DefaultContext)) } func (pr *PullRequest) loadHeadRepo(e db.Engine) (err error) { @@ -148,12 +148,12 @@ func (pr *PullRequest) loadHeadRepo(e db.Engine) (err error) { // LoadHeadRepo loads the head repository func (pr *PullRequest) LoadHeadRepo() error { - return pr.loadHeadRepo(db.DefaultContext().Engine()) + return pr.loadHeadRepo(db.GetEngine(db.DefaultContext)) } // LoadBaseRepo loads the target repository func (pr *PullRequest) LoadBaseRepo() error { - return pr.loadBaseRepo(db.DefaultContext().Engine()) + return pr.loadBaseRepo(db.GetEngine(db.DefaultContext)) } func (pr *PullRequest) loadBaseRepo(e db.Engine) (err error) { @@ -180,7 +180,7 @@ func (pr *PullRequest) loadBaseRepo(e db.Engine) (err error) { // LoadIssue loads issue information from database func (pr *PullRequest) LoadIssue() (err error) { - return pr.loadIssue(db.DefaultContext().Engine()) + return pr.loadIssue(db.GetEngine(db.DefaultContext)) } func (pr *PullRequest) loadIssue(e db.Engine) (err error) { @@ -197,7 +197,7 @@ func (pr *PullRequest) loadIssue(e db.Engine) (err error) { // LoadProtectedBranch loads the protected branch of the base branch func (pr *PullRequest) LoadProtectedBranch() (err error) { - return pr.loadProtectedBranch(db.DefaultContext().Engine()) + return pr.loadProtectedBranch(db.GetEngine(db.DefaultContext)) } func (pr *PullRequest) loadProtectedBranch(e db.Engine) (err error) { @@ -257,7 +257,7 @@ type ReviewCount struct { // GetApprovalCounts returns the approval counts by type // FIXME: Only returns official counts due to double counting of non-official counts func (pr *PullRequest) GetApprovalCounts() ([]*ReviewCount, error) { - return pr.getApprovalCounts(db.DefaultContext().Engine()) + return pr.getApprovalCounts(db.GetEngine(db.DefaultContext)) } func (pr *PullRequest) getApprovalCounts(e db.Engine) ([]*ReviewCount, error) { @@ -284,7 +284,7 @@ func (pr *PullRequest) getReviewedByLines(writer io.Writer) error { return nil } - sess := db.DefaultContext().NewSession() + sess := db.NewSession(db.DefaultContext) defer sess.Close() if err := sess.Begin(); err != nil { return err @@ -393,7 +393,7 @@ func (pr *PullRequest) SetMerged() (bool, error) { pr.HasMerged = true - sess := db.DefaultContext().NewSession() + sess := db.NewSession(db.DefaultContext) defer sess.Close() if err := sess.Begin(); err != nil { return false, err @@ -455,7 +455,7 @@ func NewPullRequest(repo *Repository, issue *Issue, labelIDs []int64, uuids []st issue.Index = idx - sess := db.DefaultContext().NewSession() + sess := db.NewSession(db.DefaultContext) defer sess.Close() if err = sess.Begin(); err != nil { return err @@ -492,7 +492,7 @@ func NewPullRequest(repo *Repository, issue *Issue, labelIDs []int64, uuids []st // by given head/base and repo/branch. func GetUnmergedPullRequest(headRepoID, baseRepoID int64, headBranch, baseBranch string, flow PullRequestFlow) (*PullRequest, error) { pr := new(PullRequest) - has, err := db.DefaultContext().Engine(). + has, err := db.GetEngine(db.DefaultContext). Where("head_repo_id=? AND head_branch=? AND base_repo_id=? AND base_branch=? AND has_merged=? AND flow = ? AND issue.is_closed=?", headRepoID, headBranch, baseRepoID, baseBranch, false, flow, false). Join("INNER", "issue", "issue.id=pull_request.issue_id"). @@ -510,7 +510,7 @@ func GetUnmergedPullRequest(headRepoID, baseRepoID int64, headBranch, baseBranch // by given head information (repo and branch). func GetLatestPullRequestByHeadInfo(repoID int64, branch string) (*PullRequest, error) { pr := new(PullRequest) - has, err := db.DefaultContext().Engine(). + has, err := db.GetEngine(db.DefaultContext). Where("head_repo_id = ? AND head_branch = ? AND flow = ?", repoID, branch, PullRequestFlowGithub). OrderBy("id DESC"). Get(pr) @@ -527,7 +527,7 @@ func GetPullRequestByIndex(repoID, index int64) (*PullRequest, error) { Index: index, } - has, err := db.DefaultContext().Engine().Get(pr) + has, err := db.GetEngine(db.DefaultContext).Get(pr) if err != nil { return nil, err } else if !has { @@ -557,13 +557,13 @@ func getPullRequestByID(e db.Engine, id int64) (*PullRequest, error) { // GetPullRequestByID returns a pull request by given ID. func GetPullRequestByID(id int64) (*PullRequest, error) { - return getPullRequestByID(db.DefaultContext().Engine(), id) + return getPullRequestByID(db.GetEngine(db.DefaultContext), id) } // GetPullRequestByIssueIDWithNoAttributes returns pull request with no attributes loaded by given issue ID. func GetPullRequestByIssueIDWithNoAttributes(issueID int64) (*PullRequest, error) { var pr PullRequest - has, err := db.DefaultContext().Engine().Where("issue_id = ?", issueID).Get(&pr) + has, err := db.GetEngine(db.DefaultContext).Where("issue_id = ?", issueID).Get(&pr) if err != nil { return nil, err } @@ -591,7 +591,7 @@ func getPullRequestByIssueID(e db.Engine, issueID int64) (*PullRequest, error) { func GetAllUnmergedAgitPullRequestByPoster(uid int64) ([]*PullRequest, error) { pulls := make([]*PullRequest, 0, 10) - err := db.DefaultContext().Engine(). + err := db.GetEngine(db.DefaultContext). Where("has_merged=? AND flow = ? AND issue.is_closed=? AND issue.poster_id=?", false, PullRequestFlowAGit, false, uid). Join("INNER", "issue", "issue.id=pull_request.issue_id"). @@ -602,24 +602,24 @@ func GetAllUnmergedAgitPullRequestByPoster(uid int64) ([]*PullRequest, error) { // GetPullRequestByIssueID returns pull request by given issue ID. func GetPullRequestByIssueID(issueID int64) (*PullRequest, error) { - return getPullRequestByIssueID(db.DefaultContext().Engine(), issueID) + return getPullRequestByIssueID(db.GetEngine(db.DefaultContext), issueID) } // Update updates all fields of pull request. func (pr *PullRequest) Update() error { - _, err := db.DefaultContext().Engine().ID(pr.ID).AllCols().Update(pr) + _, err := db.GetEngine(db.DefaultContext).ID(pr.ID).AllCols().Update(pr) return err } // UpdateCols updates specific fields of pull request. func (pr *PullRequest) UpdateCols(cols ...string) error { - _, err := db.DefaultContext().Engine().ID(pr.ID).Cols(cols...).Update(pr) + _, err := db.GetEngine(db.DefaultContext).ID(pr.ID).Cols(cols...).Update(pr) return err } // UpdateColsIfNotMerged updates specific fields of a pull request if it has not been merged func (pr *PullRequest) UpdateColsIfNotMerged(cols ...string) error { - _, err := db.DefaultContext().Engine().Where("id = ? AND has_merged = ?", pr.ID, false).Cols(cols...).Update(pr) + _, err := db.GetEngine(db.DefaultContext).Where("id = ? AND has_merged = ?", pr.ID, false).Cols(cols...).Update(pr) return err } @@ -665,7 +665,7 @@ func (pr *PullRequest) GetWorkInProgressPrefix() string { // UpdateCommitDivergence update Divergence of a pull request func (pr *PullRequest) UpdateCommitDivergence(ahead, behind int) error { - return pr.updateCommitDivergence(db.DefaultContext().Engine(), ahead, behind) + return pr.updateCommitDivergence(db.GetEngine(db.DefaultContext), ahead, behind) } func (pr *PullRequest) updateCommitDivergence(e db.Engine, ahead, behind int) error { diff --git a/models/pull_list.go b/models/pull_list.go index ed8372658d3..57e2f9c85f7 100644 --- a/models/pull_list.go +++ b/models/pull_list.go @@ -25,7 +25,7 @@ type PullRequestsOptions struct { } func listPullRequestStatement(baseRepoID int64, opts *PullRequestsOptions) (*xorm.Session, error) { - sess := db.DefaultContext().Engine().Where("pull_request.base_repo_id=?", baseRepoID) + sess := db.GetEngine(db.DefaultContext).Where("pull_request.base_repo_id=?", baseRepoID) sess.Join("INNER", "issue", "pull_request.issue_id = issue.id") switch opts.State { @@ -51,7 +51,7 @@ func listPullRequestStatement(baseRepoID int64, opts *PullRequestsOptions) (*xor // by given head information (repo and branch). func GetUnmergedPullRequestsByHeadInfo(repoID int64, branch string) ([]*PullRequest, error) { prs := make([]*PullRequest, 0, 2) - return prs, db.DefaultContext().Engine(). + return prs, db.GetEngine(db.DefaultContext). Where("head_repo_id = ? AND head_branch = ? AND has_merged = ? AND issue.is_closed = ? AND flow = ?", repoID, branch, false, false, PullRequestFlowGithub). Join("INNER", "issue", "issue.id = pull_request.issue_id"). @@ -62,7 +62,7 @@ func GetUnmergedPullRequestsByHeadInfo(repoID int64, branch string) ([]*PullRequ // by given base information (repo and branch). func GetUnmergedPullRequestsByBaseInfo(repoID int64, branch string) ([]*PullRequest, error) { prs := make([]*PullRequest, 0, 2) - return prs, db.DefaultContext().Engine(). + return prs, db.GetEngine(db.DefaultContext). Where("base_repo_id=? AND base_branch=? AND has_merged=? AND issue.is_closed=?", repoID, branch, false, false). Join("INNER", "issue", "issue.id=pull_request.issue_id"). @@ -72,7 +72,7 @@ func GetUnmergedPullRequestsByBaseInfo(repoID int64, branch string) ([]*PullRequ // GetPullRequestIDsByCheckStatus returns all pull requests according the special checking status. func GetPullRequestIDsByCheckStatus(status PullRequestStatus) ([]int64, error) { prs := make([]int64, 0, 10) - return prs, db.DefaultContext().Engine().Table("pull_request"). + return prs, db.GetEngine(db.DefaultContext).Table("pull_request"). Where("status=?", status). Cols("pull_request.id"). Find(&prs) @@ -144,7 +144,7 @@ func (prs PullRequestList) getIssueIDs() []int64 { // LoadAttributes load all the prs attributes func (prs PullRequestList) LoadAttributes() error { - return prs.loadAttributes(db.DefaultContext().Engine()) + return prs.loadAttributes(db.GetEngine(db.DefaultContext)) } func (prs PullRequestList) invalidateCodeComments(e db.Engine, doer *User, repo *git.Repository, branch string) error { @@ -169,5 +169,5 @@ func (prs PullRequestList) invalidateCodeComments(e db.Engine, doer *User, repo // InvalidateCodeComments will lookup the prs for code comments which got invalidated by change func (prs PullRequestList) InvalidateCodeComments(doer *User, repo *git.Repository, branch string) error { - return prs.invalidateCodeComments(db.DefaultContext().Engine(), doer, repo, branch) + return prs.invalidateCodeComments(db.GetEngine(db.DefaultContext), doer, repo, branch) } diff --git a/models/release.go b/models/release.go index 2a6e9352f3b..d6b629cfe83 100644 --- a/models/release.go +++ b/models/release.go @@ -6,6 +6,7 @@ package models import ( + "context" "errors" "fmt" "sort" @@ -72,7 +73,7 @@ func (r *Release) loadAttributes(e db.Engine) error { // LoadAttributes load repo and publisher attributes for a release func (r *Release) LoadAttributes() error { - return r.loadAttributes(db.DefaultContext().Engine()) + return r.loadAttributes(db.GetEngine(db.DefaultContext)) } // APIURL the api url for a release. release must have attributes loaded @@ -102,31 +103,31 @@ func IsReleaseExist(repoID int64, tagName string) (bool, error) { return false, nil } - return db.DefaultContext().Engine().Get(&Release{RepoID: repoID, LowerTagName: strings.ToLower(tagName)}) + return db.GetEngine(db.DefaultContext).Get(&Release{RepoID: repoID, LowerTagName: strings.ToLower(tagName)}) } // InsertRelease inserts a release func InsertRelease(rel *Release) error { - _, err := db.DefaultContext().Engine().Insert(rel) + _, err := db.GetEngine(db.DefaultContext).Insert(rel) return err } // InsertReleasesContext insert releases -func InsertReleasesContext(ctx *db.Context, rels []*Release) error { - _, err := ctx.Engine().Insert(rels) +func InsertReleasesContext(ctx context.Context, rels []*Release) error { + _, err := db.GetEngine(ctx).Insert(rels) return err } // UpdateRelease updates all columns of a release -func UpdateRelease(ctx *db.Context, rel *Release) error { - _, err := ctx.Engine().ID(rel.ID).AllCols().Update(rel) +func UpdateRelease(ctx context.Context, rel *Release) error { + _, err := db.GetEngine(ctx).ID(rel.ID).AllCols().Update(rel) return err } // AddReleaseAttachments adds a release attachments -func AddReleaseAttachments(ctx *db.Context, releaseID int64, attachmentUUIDs []string) (err error) { +func AddReleaseAttachments(ctx context.Context, releaseID int64, attachmentUUIDs []string) (err error) { // Check attachments - attachments, err := getAttachmentsByUUIDs(ctx.Engine(), attachmentUUIDs) + attachments, err := getAttachmentsByUUIDs(db.GetEngine(ctx), attachmentUUIDs) if err != nil { return fmt.Errorf("GetAttachmentsByUUIDs [uuids: %v]: %v", attachmentUUIDs, err) } @@ -137,7 +138,7 @@ func AddReleaseAttachments(ctx *db.Context, releaseID int64, attachmentUUIDs []s } attachments[i].ReleaseID = releaseID // No assign value could be 0, so ignore AllCols(). - if _, err = ctx.Engine().ID(attachments[i].ID).Update(attachments[i]); err != nil { + if _, err = db.GetEngine(ctx).ID(attachments[i].ID).Update(attachments[i]); err != nil { return fmt.Errorf("update attachment [%d]: %v", attachments[i].ID, err) } } @@ -155,14 +156,14 @@ func GetRelease(repoID int64, tagName string) (*Release, error) { } rel := &Release{RepoID: repoID, LowerTagName: strings.ToLower(tagName)} - _, err = db.DefaultContext().Engine().Get(rel) + _, err = db.GetEngine(db.DefaultContext).Get(rel) return rel, err } // GetReleaseByID returns release with given ID. func GetReleaseByID(id int64) (*Release, error) { rel := new(Release) - has, err := db.DefaultContext().Engine(). + has, err := db.GetEngine(db.DefaultContext). ID(id). Get(rel) if err != nil { @@ -208,7 +209,7 @@ func (opts *FindReleasesOptions) toConds(repoID int64) builder.Cond { // GetReleasesByRepoID returns a list of releases of repository. func GetReleasesByRepoID(repoID int64, opts FindReleasesOptions) ([]*Release, error) { - sess := db.DefaultContext().Engine(). + sess := db.GetEngine(db.DefaultContext). Desc("created_unix", "id"). Where(opts.toConds(repoID)) @@ -222,7 +223,7 @@ func GetReleasesByRepoID(repoID int64, opts FindReleasesOptions) ([]*Release, er // CountReleasesByRepoID returns a number of releases matching FindReleaseOptions and RepoID. func CountReleasesByRepoID(repoID int64, opts FindReleasesOptions) (int64, error) { - return db.DefaultContext().Engine().Where(opts.toConds(repoID)).Count(new(Release)) + return db.GetEngine(db.DefaultContext).Where(opts.toConds(repoID)).Count(new(Release)) } // GetLatestReleaseByRepoID returns the latest release for a repository @@ -234,7 +235,7 @@ func GetLatestReleaseByRepoID(repoID int64) (*Release, error) { And(builder.Eq{"is_tag": false}) rel := new(Release) - has, err := db.DefaultContext().Engine(). + has, err := db.GetEngine(db.DefaultContext). Desc("created_unix", "id"). Where(cond). Get(rel) @@ -248,8 +249,8 @@ func GetLatestReleaseByRepoID(repoID int64) (*Release, error) { } // GetReleasesByRepoIDAndNames returns a list of releases of repository according repoID and tagNames. -func GetReleasesByRepoIDAndNames(ctx *db.Context, repoID int64, tagNames []string) (rels []*Release, err error) { - err = ctx.Engine(). +func GetReleasesByRepoIDAndNames(ctx context.Context, repoID int64, tagNames []string) (rels []*Release, err error) { + err = db.GetEngine(ctx). In("tag_name", tagNames). Desc("created_unix"). Find(&rels, Release{RepoID: repoID}) @@ -258,7 +259,7 @@ func GetReleasesByRepoIDAndNames(ctx *db.Context, repoID int64, tagNames []strin // GetReleaseCountByRepoID returns the count of releases of repository func GetReleaseCountByRepoID(repoID int64, opts FindReleasesOptions) (int64, error) { - return db.DefaultContext().Engine().Where(opts.toConds(repoID)).Count(&Release{}) + return db.GetEngine(db.DefaultContext).Where(opts.toConds(repoID)).Count(&Release{}) } type releaseMetaSearch struct { @@ -281,7 +282,7 @@ func (s releaseMetaSearch) Less(i, j int) bool { // GetReleaseAttachments retrieves the attachments for releases func GetReleaseAttachments(rels ...*Release) (err error) { - return getReleaseAttachments(db.DefaultContext().Engine(), rels...) + return getReleaseAttachments(db.GetEngine(db.DefaultContext), rels...) } func getReleaseAttachments(e db.Engine, rels ...*Release) (err error) { @@ -352,13 +353,13 @@ func SortReleases(rels []*Release) { // DeleteReleaseByID deletes a release from database by given ID. func DeleteReleaseByID(id int64) error { - _, err := db.DefaultContext().Engine().ID(id).Delete(new(Release)) + _, err := db.GetEngine(db.DefaultContext).ID(id).Delete(new(Release)) return err } // UpdateReleasesMigrationsByType updates all migrated repositories' releases from gitServiceType to replace originalAuthorID to posterID func UpdateReleasesMigrationsByType(gitServiceType structs.GitServiceType, originalAuthorID string, posterID int64) error { - _, err := db.DefaultContext().Engine().Table("release"). + _, err := db.GetEngine(db.DefaultContext).Table("release"). Where("repo_id IN (SELECT id FROM repository WHERE original_service_type = ?)", gitServiceType). And("original_author_id = ?", originalAuthorID). Update(map[string]interface{}{ diff --git a/models/repo.go b/models/repo.go index 39e5a089ebf..ae149f467d6 100644 --- a/models/repo.go +++ b/models/repo.go @@ -302,7 +302,7 @@ func (repo *Repository) AfterLoad() { // It creates a fake object that contains error details // when error occurs. func (repo *Repository) MustOwner() *User { - return repo.mustOwner(db.DefaultContext().Engine()) + return repo.mustOwner(db.GetEngine(db.DefaultContext)) } // FullName returns the repository full name @@ -354,7 +354,7 @@ func (repo *Repository) getUnits(e db.Engine) (err error) { // CheckUnitUser check whether user could visit the unit of this repository func (repo *Repository) CheckUnitUser(user *User, unitType UnitType) bool { - return repo.checkUnitUser(db.DefaultContext().Engine(), user, unitType) + return repo.checkUnitUser(db.GetEngine(db.DefaultContext), user, unitType) } func (repo *Repository) checkUnitUser(e db.Engine, user *User, unitType UnitType) bool { @@ -372,7 +372,7 @@ func (repo *Repository) checkUnitUser(e db.Engine, user *User, unitType UnitType // UnitEnabled if this repository has the given unit enabled func (repo *Repository) UnitEnabled(tp UnitType) bool { - if err := repo.getUnits(db.DefaultContext().Engine()); err != nil { + if err := repo.getUnits(db.GetEngine(db.DefaultContext)); err != nil { log.Warn("Error loading repository (ID: %d) units: %s", repo.ID, err.Error()) } for _, unit := range repo.Units { @@ -434,7 +434,7 @@ func (repo *Repository) MustGetUnit(tp UnitType) *RepoUnit { // GetUnit returns a RepoUnit object func (repo *Repository) GetUnit(tp UnitType) (*RepoUnit, error) { - return repo.getUnit(db.DefaultContext().Engine(), tp) + return repo.getUnit(db.GetEngine(db.DefaultContext), tp) } func (repo *Repository) getUnit(e db.Engine, tp UnitType) (*RepoUnit, error) { @@ -460,7 +460,7 @@ func (repo *Repository) getOwner(e db.Engine) (err error) { // GetOwner returns the repository owner func (repo *Repository) GetOwner() error { - return repo.getOwner(db.DefaultContext().Engine()) + return repo.getOwner(db.GetEngine(db.DefaultContext)) } func (repo *Repository) mustOwner(e db.Engine) *User { @@ -498,7 +498,7 @@ func (repo *Repository) ComposeMetas() map[string]string { repo.MustOwner() if repo.Owner.IsOrganization() { teams := make([]string, 0, 5) - _ = db.DefaultContext().Engine().Table("team_repo"). + _ = db.GetEngine(db.DefaultContext).Table("team_repo"). Join("INNER", "team", "team.id = team_repo.team_id"). Where("team_repo.repo_id = ?", repo.ID). Select("team.lower_name"). @@ -561,7 +561,7 @@ func (repo *Repository) getAssignees(e db.Engine) (_ []*User, err error) { // GetAssignees returns all users that have write access and can be assigned to issues // of the repository, func (repo *Repository) GetAssignees() (_ []*User, err error) { - return repo.getAssignees(db.DefaultContext().Engine()) + return repo.getAssignees(db.GetEngine(db.DefaultContext)) } func (repo *Repository) getReviewers(e db.Engine, doerID, posterID int64) ([]*User, error) { @@ -613,7 +613,7 @@ func (repo *Repository) getReviewers(e db.Engine, doerID, posterID int64) ([]*Us // all repo watchers and all organization members. // TODO: may be we should have a busy choice for users to block review request to them. func (repo *Repository) GetReviewers(doerID, posterID int64) ([]*User, error) { - return repo.getReviewers(db.DefaultContext().Engine(), doerID, posterID) + return repo.getReviewers(db.GetEngine(db.DefaultContext), doerID, posterID) } // GetReviewerTeams get all teams can be requested to review @@ -659,7 +659,7 @@ func (repo *Repository) LoadPushMirrors() (err error) { // returns an error on failure (NOTE: no error is returned for // non-fork repositories, and BaseRepo will be left untouched) func (repo *Repository) GetBaseRepo() (err error) { - return repo.getBaseRepo(db.DefaultContext().Engine()) + return repo.getBaseRepo(db.GetEngine(db.DefaultContext)) } func (repo *Repository) getBaseRepo(e db.Engine) (err error) { @@ -680,7 +680,7 @@ func (repo *Repository) IsGenerated() bool { // returns an error on failure (NOTE: no error is returned for // non-generated repositories, and TemplateRepo will be left untouched) func (repo *Repository) GetTemplateRepo() (err error) { - return repo.getTemplateRepo(db.DefaultContext().Engine()) + return repo.getTemplateRepo(db.GetEngine(db.DefaultContext)) } func (repo *Repository) getTemplateRepo(e db.Engine) (err error) { @@ -724,7 +724,7 @@ func (repo *Repository) ComposeCompareURL(oldCommitID, newCommitID string) strin // UpdateDefaultBranch updates the default branch func (repo *Repository) UpdateDefaultBranch() error { - _, err := db.DefaultContext().Engine().ID(repo.ID).Cols("default_branch").Update(repo) + _, err := db.GetEngine(db.DefaultContext).ID(repo.ID).Cols("default_branch").Update(repo) return err } @@ -750,8 +750,8 @@ func (repo *Repository) updateSize(e db.Engine) error { } // UpdateSize updates the repository size, calculating it using util.GetDirectorySize -func (repo *Repository) UpdateSize(ctx *db.Context) error { - return repo.updateSize(ctx.Engine()) +func (repo *Repository) UpdateSize(ctx context.Context) error { + return repo.updateSize(db.GetEngine(ctx)) } // CanUserFork returns true if specified user can fork repository. @@ -812,12 +812,12 @@ func (repo *Repository) CanEnableEditor() bool { // GetReaders returns all users that have explicit read access or higher to the repository. func (repo *Repository) GetReaders() (_ []*User, err error) { - return repo.getUsersWithAccessMode(db.DefaultContext().Engine(), AccessModeRead) + return repo.getUsersWithAccessMode(db.GetEngine(db.DefaultContext), AccessModeRead) } // GetWriters returns all users that have write access to the repository. func (repo *Repository) GetWriters() (_ []*User, err error) { - return repo.getUsersWithAccessMode(db.DefaultContext().Engine(), AccessModeWrite) + return repo.getUsersWithAccessMode(db.GetEngine(db.DefaultContext), AccessModeWrite) } // IsReader returns true if user has explicit read access or higher to the repository. @@ -825,7 +825,7 @@ func (repo *Repository) IsReader(userID int64) (bool, error) { if repo.OwnerID == userID { return true, nil } - return db.DefaultContext().Engine().Where("repo_id = ? AND user_id = ? AND mode >= ?", repo.ID, userID, AccessModeRead).Get(&Access{}) + return db.GetEngine(db.DefaultContext).Where("repo_id = ? AND user_id = ? AND mode >= ?", repo.ID, userID, AccessModeRead).Get(&Access{}) } // getUsersWithAccessMode returns users that have at least given access mode to the repository. @@ -874,7 +874,7 @@ func (repo *Repository) DescriptionHTML() template.HTML { // ReadBy sets repo to be visited by given user. func (repo *Repository) ReadBy(userID int64) error { - return setRepoNotificationStatusReadIfUnread(db.DefaultContext().Engine(), userID, repo.ID) + return setRepoNotificationStatusReadIfUnread(db.GetEngine(db.DefaultContext), userID, repo.ID) } func isRepositoryExist(e db.Engine, u *User, repoName string) (bool, error) { @@ -891,7 +891,7 @@ func isRepositoryExist(e db.Engine, u *User, repoName string) (bool, error) { // IsRepositoryExist returns true if the repository with given name under user has already existed. func IsRepositoryExist(u *User, repoName string) (bool, error) { - return isRepositoryExist(db.DefaultContext().Engine(), u, repoName) + return isRepositoryExist(db.GetEngine(db.DefaultContext), u, repoName) } // CloneLink represents different types of clone URLs of repository. @@ -953,7 +953,7 @@ func CheckCreateRepository(doer, u *User, name string, overwriteOrAdopt bool) er return err } - has, err := isRepositoryExist(db.DefaultContext().Engine(), u, name) + has, err := isRepositoryExist(db.GetEngine(db.DefaultContext), u, name) if err != nil { return fmt.Errorf("IsRepositoryExist: %v", err) } else if has { @@ -1042,12 +1042,12 @@ func IsUsableRepoName(name string) error { } // CreateRepository creates a repository for the user/organization. -func CreateRepository(ctx *db.Context, doer, u *User, repo *Repository, overwriteOrAdopt bool) (err error) { +func CreateRepository(ctx context.Context, doer, u *User, repo *Repository, overwriteOrAdopt bool) (err error) { if err = IsUsableRepoName(repo.Name); err != nil { return err } - has, err := isRepositoryExist(ctx.Engine(), u, repo.Name) + has, err := isRepositoryExist(db.GetEngine(ctx), u, repo.Name) if err != nil { return fmt.Errorf("IsRepositoryExist: %v", err) } else if has { @@ -1068,10 +1068,10 @@ func CreateRepository(ctx *db.Context, doer, u *User, repo *Repository, overwrit } } - if _, err = ctx.Engine().Insert(repo); err != nil { + if _, err = db.GetEngine(ctx).Insert(repo); err != nil { return err } - if err = deleteRepoRedirect(ctx.Engine(), u.ID, repo.Name); err != nil { + if err = deleteRepoRedirect(db.GetEngine(ctx), u.ID, repo.Name); err != nil { return err } @@ -1102,46 +1102,46 @@ func CreateRepository(ctx *db.Context, doer, u *User, repo *Repository, overwrit } } - if _, err = ctx.Engine().Insert(&units); err != nil { + if _, err = db.GetEngine(ctx).Insert(&units); err != nil { return err } // Remember visibility preference. u.LastRepoVisibility = repo.IsPrivate - if err = updateUserCols(ctx.Engine(), u, "last_repo_visibility"); err != nil { + if err = updateUserCols(db.GetEngine(ctx), u, "last_repo_visibility"); err != nil { return fmt.Errorf("updateUser: %v", err) } - if _, err = ctx.Engine().Incr("num_repos").ID(u.ID).Update(new(User)); err != nil { + if _, err = db.GetEngine(ctx).Incr("num_repos").ID(u.ID).Update(new(User)); err != nil { return fmt.Errorf("increment user total_repos: %v", err) } u.NumRepos++ // Give access to all members in teams with access to all repositories. if u.IsOrganization() { - if err := u.loadTeams(ctx.Engine()); err != nil { + if err := u.loadTeams(db.GetEngine(ctx)); err != nil { return fmt.Errorf("loadTeams: %v", err) } for _, t := range u.Teams { if t.IncludesAllRepositories { - if err := t.addRepository(ctx.Engine(), repo); err != nil { + if err := t.addRepository(db.GetEngine(ctx), repo); err != nil { return fmt.Errorf("addRepository: %v", err) } } } - if isAdmin, err := isUserRepoAdmin(ctx.Engine(), repo, doer); err != nil { + if isAdmin, err := isUserRepoAdmin(db.GetEngine(ctx), repo, doer); err != nil { return fmt.Errorf("isUserRepoAdmin: %v", err) } else if !isAdmin { // Make creator repo admin if it wan't assigned automatically - if err = repo.addCollaborator(ctx.Engine(), doer); err != nil { + if err = repo.addCollaborator(db.GetEngine(ctx), doer); err != nil { return fmt.Errorf("AddCollaborator: %v", err) } - if err = repo.changeCollaborationAccessMode(ctx.Engine(), doer.ID, AccessModeAdmin); err != nil { + if err = repo.changeCollaborationAccessMode(db.GetEngine(ctx), doer.ID, AccessModeAdmin); err != nil { return fmt.Errorf("ChangeCollaborationAccessMode: %v", err) } } - } else if err = repo.recalculateAccesses(ctx.Engine()); err != nil { + } else if err = repo.recalculateAccesses(db.GetEngine(ctx)); err != nil { // Organization automatically called this in addRepository method. return fmt.Errorf("recalculateAccesses: %v", err) } @@ -1157,12 +1157,12 @@ func CreateRepository(ctx *db.Context, doer, u *User, repo *Repository, overwrit } if setting.Service.AutoWatchNewRepos { - if err = watchRepo(ctx.Engine(), doer.ID, repo.ID, true); err != nil { + if err = watchRepo(db.GetEngine(ctx), doer.ID, repo.ID, true); err != nil { return fmt.Errorf("watchRepo: %v", err) } } - if err = copyDefaultWebhooksToRepo(ctx.Engine(), repo.ID); err != nil { + if err = copyDefaultWebhooksToRepo(db.GetEngine(ctx), repo.ID); err != nil { return fmt.Errorf("copyDefaultWebhooksToRepo: %v", err) } @@ -1170,7 +1170,7 @@ func CreateRepository(ctx *db.Context, doer, u *User, repo *Repository, overwrit } func countRepositories(userID int64, private bool) int64 { - sess := db.DefaultContext().Engine().Where("id > 0") + sess := db.GetEngine(db.DefaultContext).Where("id > 0") if userID > 0 { sess.And("owner_id = ?", userID) @@ -1206,14 +1206,14 @@ func RepoPath(userName, repoName string) string { } // IncrementRepoForkNum increment repository fork number -func IncrementRepoForkNum(ctx *db.Context, repoID int64) error { - _, err := ctx.Engine().Exec("UPDATE `repository` SET num_forks=num_forks+1 WHERE id=?", repoID) +func IncrementRepoForkNum(ctx context.Context, repoID int64) error { + _, err := db.GetEngine(ctx).Exec("UPDATE `repository` SET num_forks=num_forks+1 WHERE id=?", repoID) return err } // DecrementRepoForkNum decrement repository fork number -func DecrementRepoForkNum(ctx *db.Context, repoID int64) error { - _, err := ctx.Engine().Exec("UPDATE `repository` SET num_forks=num_forks-1 WHERE id=?", repoID) +func DecrementRepoForkNum(ctx context.Context, repoID int64) error { + _, err := db.GetEngine(ctx).Exec("UPDATE `repository` SET num_forks=num_forks-1 WHERE id=?", repoID) return err } @@ -1253,7 +1253,7 @@ func ChangeRepositoryName(doer *User, repo *Repository, newRepoName string) (err } } - sess := db.DefaultContext().NewSession() + sess := db.NewSession(db.DefaultContext) defer sess.Close() if err = sess.Begin(); err != nil { return fmt.Errorf("sess.Begin: %v", err) @@ -1275,7 +1275,7 @@ func getRepositoriesByForkID(e db.Engine, forkID int64) ([]*Repository, error) { // GetRepositoriesByForkID returns all repositories with given fork ID. func GetRepositoriesByForkID(forkID int64) ([]*Repository, error) { - return getRepositoriesByForkID(db.DefaultContext().Engine(), forkID) + return getRepositoriesByForkID(db.GetEngine(db.DefaultContext), forkID) } func updateRepository(e db.Engine, repo *Repository, visibilityChanged bool) (err error) { @@ -1353,13 +1353,13 @@ func updateRepository(e db.Engine, repo *Repository, visibilityChanged bool) (er } // UpdateRepositoryCtx updates a repository with db context -func UpdateRepositoryCtx(ctx *db.Context, repo *Repository, visibilityChanged bool) error { - return updateRepository(ctx.Engine(), repo, visibilityChanged) +func UpdateRepositoryCtx(ctx context.Context, repo *Repository, visibilityChanged bool) error { + return updateRepository(db.GetEngine(ctx), repo, visibilityChanged) } // UpdateRepository updates a repository func UpdateRepository(repo *Repository, visibilityChanged bool) (err error) { - sess := db.DefaultContext().NewSession() + sess := db.NewSession(db.DefaultContext) defer sess.Close() if err = sess.Begin(); err != nil { return err @@ -1377,7 +1377,7 @@ func UpdateRepositoryOwnerNames(ownerID int64, ownerName string) error { if ownerID == 0 { return nil } - sess := db.DefaultContext().NewSession() + sess := db.NewSession(db.DefaultContext) defer sess.Close() if err := sess.Begin(); err != nil { return err @@ -1394,13 +1394,13 @@ func UpdateRepositoryOwnerNames(ownerID int64, ownerName string) error { // UpdateRepositoryUpdatedTime updates a repository's updated time func UpdateRepositoryUpdatedTime(repoID int64, updateTime time.Time) error { - _, err := db.DefaultContext().Engine().Exec("UPDATE repository SET updated_unix = ? WHERE id = ?", updateTime.Unix(), repoID) + _, err := db.GetEngine(db.DefaultContext).Exec("UPDATE repository SET updated_unix = ? WHERE id = ?", updateTime.Unix(), repoID) return err } // UpdateRepositoryUnits updates a repository's units func UpdateRepositoryUnits(repo *Repository, units []RepoUnit, deleteUnitTypes []UnitType) (err error) { - sess := db.DefaultContext().NewSession() + sess := db.NewSession(db.DefaultContext) defer sess.Close() if err = sess.Begin(); err != nil { return err @@ -1427,7 +1427,7 @@ func UpdateRepositoryUnits(repo *Repository, units []RepoUnit, deleteUnitTypes [ // DeleteRepository deletes a repository for a user or organization. // make sure if you call this func to close open sessions (sqlite will otherwise get a deadlock) func DeleteRepository(doer *User, uid, repoID int64) error { - sess := db.DefaultContext().NewSession() + sess := db.NewSession(db.DefaultContext) defer sess.Close() if err := sess.Begin(); err != nil { return err @@ -1643,21 +1643,21 @@ func DeleteRepository(doer *User, uid, repoID int64) error { // Remove repository files. repoPath := repo.RepoPath() - removeAllWithNotice(db.DefaultContext().Engine(), "Delete repository files", repoPath) + removeAllWithNotice(db.GetEngine(db.DefaultContext), "Delete repository files", repoPath) // Remove wiki files if repo.HasWiki() { - removeAllWithNotice(db.DefaultContext().Engine(), "Delete repository wiki", repo.WikiPath()) + removeAllWithNotice(db.GetEngine(db.DefaultContext), "Delete repository wiki", repo.WikiPath()) } // Remove archives for i := range archivePaths { - removeStorageWithNotice(db.DefaultContext().Engine(), storage.RepoArchives, "Delete repo archive file", archivePaths[i]) + removeStorageWithNotice(db.GetEngine(db.DefaultContext), storage.RepoArchives, "Delete repo archive file", archivePaths[i]) } // Remove lfs objects for i := range lfsPaths { - removeStorageWithNotice(db.DefaultContext().Engine(), storage.LFS, "Delete orphaned LFS file", lfsPaths[i]) + removeStorageWithNotice(db.GetEngine(db.DefaultContext), storage.LFS, "Delete orphaned LFS file", lfsPaths[i]) } // Remove issue attachment files. @@ -1686,7 +1686,7 @@ func DeleteRepository(doer *User, uid, repoID int64) error { // GetRepositoryByOwnerAndName returns the repository by given ownername and reponame. func GetRepositoryByOwnerAndName(ownerName, repoName string) (*Repository, error) { - return getRepositoryByOwnerAndName(db.DefaultContext().Engine(), ownerName, repoName) + return getRepositoryByOwnerAndName(db.GetEngine(db.DefaultContext), ownerName, repoName) } func getRepositoryByOwnerAndName(e db.Engine, ownerName, repoName string) (*Repository, error) { @@ -1710,7 +1710,7 @@ func GetRepositoryByName(ownerID int64, name string) (*Repository, error) { OwnerID: ownerID, LowerName: strings.ToLower(name), } - has, err := db.DefaultContext().Engine().Get(repo) + has, err := db.GetEngine(db.DefaultContext).Get(repo) if err != nil { return nil, err } else if !has { @@ -1732,18 +1732,18 @@ func getRepositoryByID(e db.Engine, id int64) (*Repository, error) { // GetRepositoryByID returns the repository by given id if exists. func GetRepositoryByID(id int64) (*Repository, error) { - return getRepositoryByID(db.DefaultContext().Engine(), id) + return getRepositoryByID(db.GetEngine(db.DefaultContext), id) } // GetRepositoryByIDCtx returns the repository by given id if exists. -func GetRepositoryByIDCtx(ctx *db.Context, id int64) (*Repository, error) { - return getRepositoryByID(ctx.Engine(), id) +func GetRepositoryByIDCtx(ctx context.Context, id int64) (*Repository, error) { + return getRepositoryByID(db.GetEngine(ctx), id) } // GetRepositoriesMapByIDs returns the repositories by given id slice. func GetRepositoriesMapByIDs(ids []int64) (map[int64]*Repository, error) { repos := make(map[int64]*Repository, len(ids)) - return repos, db.DefaultContext().Engine().In("id", ids).Find(&repos) + return repos, db.GetEngine(db.DefaultContext).In("id", ids).Find(&repos) } // GetUserRepositories returns a list of repositories of given user. @@ -1762,7 +1762,7 @@ func GetUserRepositories(opts *SearchRepoOptions) ([]*Repository, int64, error) cond = cond.And(builder.In("lower_name", opts.LowerNames)) } - sess := db.DefaultContext().NewSession() + sess := db.NewSession(db.DefaultContext) defer sess.Close() count, err := sess.Where(cond).Count(new(Repository)) @@ -1778,7 +1778,7 @@ func GetUserRepositories(opts *SearchRepoOptions) ([]*Repository, int64, error) // GetUserMirrorRepositories returns a list of mirror repositories of given user. func GetUserMirrorRepositories(userID int64) ([]*Repository, error) { repos := make([]*Repository, 0, 10) - return repos, db.DefaultContext().Engine(). + return repos, db.GetEngine(db.DefaultContext). Where("owner_id = ?", userID). And("is_mirror = ?", true). Find(&repos) @@ -1798,17 +1798,17 @@ func getPrivateRepositoryCount(e db.Engine, u *User) (int64, error) { // GetRepositoryCount returns the total number of repositories of user. func GetRepositoryCount(u *User) (int64, error) { - return getRepositoryCount(db.DefaultContext().Engine(), u) + return getRepositoryCount(db.GetEngine(db.DefaultContext), u) } // GetPublicRepositoryCount returns the total number of public repositories of user. func GetPublicRepositoryCount(u *User) (int64, error) { - return getPublicRepositoryCount(db.DefaultContext().Engine(), u) + return getPublicRepositoryCount(db.GetEngine(db.DefaultContext), u) } // GetPrivateRepositoryCount returns the total number of private repositories of user. func GetPrivateRepositoryCount(u *User) (int64, error) { - return getPrivateRepositoryCount(db.DefaultContext().Engine(), u) + return getPrivateRepositoryCount(db.GetEngine(db.DefaultContext), u) } // DeleteOldRepositoryArchives deletes old repository archives. @@ -1817,7 +1817,7 @@ func DeleteOldRepositoryArchives(ctx context.Context, olderThan time.Duration) e for { var archivers []RepoArchiver - err := db.DefaultContext().Engine().Where("created_unix < ?", time.Now().Add(-olderThan).Unix()). + err := db.GetEngine(db.DefaultContext).Where("created_unix < ?", time.Now().Add(-olderThan).Unix()). Asc("created_unix"). Limit(100). Find(&archivers) @@ -1847,7 +1847,7 @@ func deleteOldRepoArchiver(ctx context.Context, archiver *RepoArchiver) error { if err != nil { return err } - _, err = db.DefaultContext().Engine().ID(archiver.ID).Delete(delRepoArchiver) + _, err = db.GetEngine(db.DefaultContext).ID(archiver.ID).Delete(delRepoArchiver) if err != nil { return err } @@ -1863,7 +1863,7 @@ type repoChecker struct { } func repoStatsCheck(ctx context.Context, checker *repoChecker) { - results, err := db.DefaultContext().Engine().Query(checker.querySQL) + results, err := db.GetEngine(db.DefaultContext).Query(checker.querySQL) if err != nil { log.Error("Select %s: %v", checker.desc, err) return @@ -1877,7 +1877,7 @@ func repoStatsCheck(ctx context.Context, checker *repoChecker) { default: } log.Trace("Updating %s: %d", checker.desc, id) - _, err = db.DefaultContext().Engine().Exec(checker.correctSQL, id, id) + _, err = db.GetEngine(db.DefaultContext).Exec(checker.correctSQL, id, id) if err != nil { log.Error("Update %s[%d]: %v", checker.desc, id, err) } @@ -1932,7 +1932,7 @@ func CheckRepoStats(ctx context.Context) error { // ***** START: Repository.NumClosedIssues ***** desc := "repository count 'num_closed_issues'" - results, err := db.DefaultContext().Engine().Query("SELECT repo.id FROM `repository` repo WHERE repo.num_closed_issues!=(SELECT COUNT(*) FROM `issue` WHERE repo_id=repo.id AND is_closed=? AND is_pull=?)", true, false) + results, err := db.GetEngine(db.DefaultContext).Query("SELECT repo.id FROM `repository` repo WHERE repo.num_closed_issues!=(SELECT COUNT(*) FROM `issue` WHERE repo_id=repo.id AND is_closed=? AND is_pull=?)", true, false) if err != nil { log.Error("Select %s: %v", desc, err) } else { @@ -1945,7 +1945,7 @@ func CheckRepoStats(ctx context.Context) error { default: } log.Trace("Updating %s: %d", desc, id) - _, err = db.DefaultContext().Engine().Exec("UPDATE `repository` SET num_closed_issues=(SELECT COUNT(*) FROM `issue` WHERE repo_id=? AND is_closed=? AND is_pull=?) WHERE id=?", id, true, false, id) + _, err = db.GetEngine(db.DefaultContext).Exec("UPDATE `repository` SET num_closed_issues=(SELECT COUNT(*) FROM `issue` WHERE repo_id=? AND is_closed=? AND is_pull=?) WHERE id=?", id, true, false, id) if err != nil { log.Error("Update %s[%d]: %v", desc, id, err) } @@ -1955,7 +1955,7 @@ func CheckRepoStats(ctx context.Context) error { // ***** START: Repository.NumClosedPulls ***** desc = "repository count 'num_closed_pulls'" - results, err = db.DefaultContext().Engine().Query("SELECT repo.id FROM `repository` repo WHERE repo.num_closed_pulls!=(SELECT COUNT(*) FROM `issue` WHERE repo_id=repo.id AND is_closed=? AND is_pull=?)", true, true) + results, err = db.GetEngine(db.DefaultContext).Query("SELECT repo.id FROM `repository` repo WHERE repo.num_closed_pulls!=(SELECT COUNT(*) FROM `issue` WHERE repo_id=repo.id AND is_closed=? AND is_pull=?)", true, true) if err != nil { log.Error("Select %s: %v", desc, err) } else { @@ -1968,7 +1968,7 @@ func CheckRepoStats(ctx context.Context) error { default: } log.Trace("Updating %s: %d", desc, id) - _, err = db.DefaultContext().Engine().Exec("UPDATE `repository` SET num_closed_pulls=(SELECT COUNT(*) FROM `issue` WHERE repo_id=? AND is_closed=? AND is_pull=?) WHERE id=?", id, true, true, id) + _, err = db.GetEngine(db.DefaultContext).Exec("UPDATE `repository` SET num_closed_pulls=(SELECT COUNT(*) FROM `issue` WHERE repo_id=? AND is_closed=? AND is_pull=?) WHERE id=?", id, true, true, id) if err != nil { log.Error("Update %s[%d]: %v", desc, id, err) } @@ -1978,7 +1978,7 @@ func CheckRepoStats(ctx context.Context) error { // FIXME: use checker when stop supporting old fork repo format. // ***** START: Repository.NumForks ***** - results, err = db.DefaultContext().Engine().Query("SELECT repo.id FROM `repository` repo WHERE repo.num_forks!=(SELECT COUNT(*) FROM `repository` WHERE fork_id=repo.id)") + results, err = db.GetEngine(db.DefaultContext).Query("SELECT repo.id FROM `repository` repo WHERE repo.num_forks!=(SELECT COUNT(*) FROM `repository` WHERE fork_id=repo.id)") if err != nil { log.Error("Select repository count 'num_forks': %v", err) } else { @@ -1998,7 +1998,7 @@ func CheckRepoStats(ctx context.Context) error { continue } - rawResult, err := db.DefaultContext().Engine().Query("SELECT COUNT(*) FROM `repository` WHERE fork_id=?", repo.ID) + rawResult, err := db.GetEngine(db.DefaultContext).Query("SELECT COUNT(*) FROM `repository` WHERE fork_id=?", repo.ID) if err != nil { log.Error("Select count of forks[%d]: %v", repo.ID, err) continue @@ -2018,7 +2018,7 @@ func CheckRepoStats(ctx context.Context) error { // SetArchiveRepoState sets if a repo is archived func (repo *Repository) SetArchiveRepoState(isArchived bool) (err error) { repo.IsArchived = isArchived - _, err = db.DefaultContext().Engine().Where("id = ?", repo.ID).Cols("is_archived").NoAutoTime().Update(repo) + _, err = db.GetEngine(db.DefaultContext).Where("id = ?", repo.ID).Cols("is_archived").NoAutoTime().Update(repo) return } @@ -2032,23 +2032,23 @@ func (repo *Repository) SetArchiveRepoState(isArchived bool) (err error) { // HasForkedRepo checks if given user has already forked a repository with given ID. func HasForkedRepo(ownerID, repoID int64) (*Repository, bool) { repo := new(Repository) - has, _ := db.DefaultContext().Engine(). + has, _ := db.GetEngine(db.DefaultContext). Where("owner_id=? AND fork_id=?", ownerID, repoID). Get(repo) return repo, has } // CopyLFS copies LFS data from one repo to another -func CopyLFS(ctx *db.Context, newRepo, oldRepo *Repository) error { +func CopyLFS(ctx context.Context, newRepo, oldRepo *Repository) error { var lfsObjects []*LFSMetaObject - if err := ctx.Engine().Where("repository_id=?", oldRepo.ID).Find(&lfsObjects); err != nil { + if err := db.GetEngine(ctx).Where("repository_id=?", oldRepo.ID).Find(&lfsObjects); err != nil { return err } for _, v := range lfsObjects { v.ID = 0 v.RepositoryID = newRepo.ID - if _, err := ctx.Engine().Insert(v); err != nil { + if _, err := db.GetEngine(ctx).Insert(v); err != nil { return err } } @@ -2060,7 +2060,7 @@ func CopyLFS(ctx *db.Context, newRepo, oldRepo *Repository) error { func (repo *Repository) GetForks(listOptions ListOptions) ([]*Repository, error) { if listOptions.Page == 0 { forks := make([]*Repository, 0, repo.NumForks) - return forks, db.DefaultContext().Engine().Find(&forks, &Repository{ForkID: repo.ID}) + return forks, db.GetEngine(db.DefaultContext).Find(&forks, &Repository{ForkID: repo.ID}) } sess := getPaginatedSession(&listOptions) @@ -2071,7 +2071,7 @@ func (repo *Repository) GetForks(listOptions ListOptions) ([]*Repository, error) // GetUserFork return user forked repository from this repository, if not forked return nil func (repo *Repository) GetUserFork(userID int64) (*Repository, error) { var forkedRepo Repository - has, err := db.DefaultContext().Engine().Where("fork_id = ?", repo.ID).And("owner_id = ?", userID).Get(&forkedRepo) + has, err := db.GetEngine(db.DefaultContext).Where("fork_id = ?", repo.ID).And("owner_id = ?", userID).Get(&forkedRepo) if err != nil { return nil, err } @@ -2114,7 +2114,7 @@ func updateRepositoryCols(e db.Engine, repo *Repository, cols ...string) error { // UpdateRepositoryCols updates repository's columns func UpdateRepositoryCols(repo *Repository, cols ...string) error { - return updateRepositoryCols(db.DefaultContext().Engine(), repo, cols...) + return updateRepositoryCols(db.GetEngine(db.DefaultContext), repo, cols...) } // GetTrustModel will get the TrustModel for the repo or the default trust model @@ -2132,7 +2132,7 @@ func (repo *Repository) GetTrustModel() TrustModelType { // DoctorUserStarNum recalculate Stars number for all user func DoctorUserStarNum() (err error) { const batchSize = 100 - sess := db.DefaultContext().NewSession() + sess := db.NewSession(db.DefaultContext) defer sess.Close() for start := 0; ; start += batchSize { @@ -2170,7 +2170,7 @@ func IterateRepository(f func(repo *Repository) error) error { batchSize := setting.Database.IterateBufferSize for { repos := make([]*Repository, 0, batchSize) - if err := db.DefaultContext().Engine().Limit(batchSize, start).Find(&repos); err != nil { + if err := db.GetEngine(db.DefaultContext).Limit(batchSize, start).Find(&repos); err != nil { return err } if len(repos) == 0 { diff --git a/models/repo_activity.go b/models/repo_activity.go index cfbda21411d..5986da7e77a 100644 --- a/models/repo_activity.go +++ b/models/repo_activity.go @@ -246,7 +246,7 @@ func (stats *ActivityStats) FillPullRequests(repoID int64, fromTime time.Time) e } func pullRequestsForActivityStatement(repoID int64, fromTime time.Time, merged bool) *xorm.Session { - sess := db.DefaultContext().Engine().Where("pull_request.base_repo_id=?", repoID). + sess := db.GetEngine(db.DefaultContext).Where("pull_request.base_repo_id=?", repoID). Join("INNER", "issue", "pull_request.issue_id = issue.id") if merged { @@ -314,7 +314,7 @@ func (stats *ActivityStats) FillUnresolvedIssues(repoID int64, fromTime time.Tim } func issuesForActivityStatement(repoID int64, fromTime time.Time, closed, unresolved bool) *xorm.Session { - sess := db.DefaultContext().Engine().Where("issue.repo_id = ?", repoID). + sess := db.GetEngine(db.DefaultContext).Where("issue.repo_id = ?", repoID). And("issue.is_closed = ?", closed) if !unresolved { @@ -356,7 +356,7 @@ func (stats *ActivityStats) FillReleases(repoID int64, fromTime time.Time) error } func releasesForActivityStatement(repoID int64, fromTime time.Time) *xorm.Session { - return db.DefaultContext().Engine().Where("release.repo_id = ?", repoID). + return db.GetEngine(db.DefaultContext).Where("release.repo_id = ?", repoID). And("release.is_draft = ?", false). And("release.created_unix >= ?", fromTime.Unix()) } diff --git a/models/repo_archiver.go b/models/repo_archiver.go index b268e65e0dc..647a3b47be3 100644 --- a/models/repo_archiver.go +++ b/models/repo_archiver.go @@ -5,6 +5,7 @@ package models import ( + "context" "fmt" "code.gitea.io/gitea/models/db" @@ -43,7 +44,7 @@ func (archiver *RepoArchiver) LoadRepo() (*Repository, error) { } var repo Repository - has, err := db.DefaultContext().Engine().ID(archiver.RepoID).Get(&repo) + has, err := db.GetEngine(db.DefaultContext).ID(archiver.RepoID).Get(&repo) if err != nil { return nil, err } @@ -61,9 +62,9 @@ func (archiver *RepoArchiver) RelativePath() (string, error) { } // GetRepoArchiver get an archiver -func GetRepoArchiver(ctx *db.Context, repoID int64, tp git.ArchiveType, commitID string) (*RepoArchiver, error) { +func GetRepoArchiver(ctx context.Context, repoID int64, tp git.ArchiveType, commitID string) (*RepoArchiver, error) { var archiver RepoArchiver - has, err := ctx.Engine().Where("repo_id=?", repoID).And("`type`=?", tp).And("commit_id=?", commitID).Get(&archiver) + has, err := db.GetEngine(ctx).Where("repo_id=?", repoID).And("`type`=?", tp).And("commit_id=?", commitID).Get(&archiver) if err != nil { return nil, err } @@ -74,19 +75,19 @@ func GetRepoArchiver(ctx *db.Context, repoID int64, tp git.ArchiveType, commitID } // AddRepoArchiver adds an archiver -func AddRepoArchiver(ctx *db.Context, archiver *RepoArchiver) error { - _, err := ctx.Engine().Insert(archiver) +func AddRepoArchiver(ctx context.Context, archiver *RepoArchiver) error { + _, err := db.GetEngine(ctx).Insert(archiver) return err } // UpdateRepoArchiverStatus updates archiver's status -func UpdateRepoArchiverStatus(ctx *db.Context, archiver *RepoArchiver) error { - _, err := ctx.Engine().ID(archiver.ID).Cols("status").Update(archiver) +func UpdateRepoArchiverStatus(ctx context.Context, archiver *RepoArchiver) error { + _, err := db.GetEngine(ctx).ID(archiver.ID).Cols("status").Update(archiver) return err } // DeleteAllRepoArchives deletes all repo archives records func DeleteAllRepoArchives() error { - _, err := db.DefaultContext().Engine().Where("1=1").Delete(new(RepoArchiver)) + _, err := db.GetEngine(db.DefaultContext).Where("1=1").Delete(new(RepoArchiver)) return err } diff --git a/models/repo_avatar.go b/models/repo_avatar.go index 8133cdc7065..bb5f083dd5e 100644 --- a/models/repo_avatar.go +++ b/models/repo_avatar.go @@ -57,7 +57,7 @@ func (repo *Repository) generateRandomAvatar(e db.Engine) error { // RemoveRandomAvatars removes the randomly generated avatars that were created for repositories func RemoveRandomAvatars(ctx context.Context) error { - return db.DefaultContext().Engine(). + return db.GetEngine(db.DefaultContext). Where("id > 0").BufferSize(setting.Database.IterateBufferSize). Iterate(new(Repository), func(idx int, bean interface{}) error { @@ -77,7 +77,7 @@ func RemoveRandomAvatars(ctx context.Context) error { // RelAvatarLink returns a relative link to the repository's avatar. func (repo *Repository) RelAvatarLink() string { - return repo.relAvatarLink(db.DefaultContext().Engine()) + return repo.relAvatarLink(db.GetEngine(db.DefaultContext)) } func (repo *Repository) relAvatarLink(e db.Engine) string { @@ -101,7 +101,7 @@ func (repo *Repository) relAvatarLink(e db.Engine) string { // AvatarLink returns a link to the repository's avatar. func (repo *Repository) AvatarLink() string { - return repo.avatarLink(db.DefaultContext().Engine()) + return repo.avatarLink(db.GetEngine(db.DefaultContext)) } // avatarLink returns user avatar absolute link. @@ -129,7 +129,7 @@ func (repo *Repository) UploadAvatar(data []byte) error { return nil } - sess := db.DefaultContext().NewSession() + sess := db.NewSession(db.DefaultContext) defer sess.Close() if err = sess.Begin(); err != nil { return err @@ -172,7 +172,7 @@ func (repo *Repository) DeleteAvatar() error { avatarPath := repo.CustomAvatarRelativePath() log.Trace("DeleteAvatar[%d]: %s", repo.ID, avatarPath) - sess := db.DefaultContext().NewSession() + sess := db.NewSession(db.DefaultContext) defer sess.Close() if err := sess.Begin(); err != nil { return err diff --git a/models/repo_collaboration.go b/models/repo_collaboration.go index 1199a564049..08d2062dbba 100644 --- a/models/repo_collaboration.go +++ b/models/repo_collaboration.go @@ -51,7 +51,7 @@ func (repo *Repository) addCollaborator(e db.Engine, u *User) error { // AddCollaborator adds new collaboration to a repository with default access mode. func (repo *Repository) AddCollaborator(u *User) error { - sess := db.DefaultContext().NewSession() + sess := db.NewSession(db.DefaultContext) defer sess.Close() if err := sess.Begin(); err != nil { return err @@ -104,12 +104,12 @@ func (repo *Repository) getCollaborators(e db.Engine, listOptions ListOptions) ( // GetCollaborators returns the collaborators for a repository func (repo *Repository) GetCollaborators(listOptions ListOptions) ([]*Collaborator, error) { - return repo.getCollaborators(db.DefaultContext().Engine(), listOptions) + return repo.getCollaborators(db.GetEngine(db.DefaultContext), listOptions) } // CountCollaborators returns total number of collaborators for a repository func (repo *Repository) CountCollaborators() (int64, error) { - return db.DefaultContext().Engine().Where("repo_id = ? ", repo.ID).Count(&Collaboration{}) + return db.GetEngine(db.DefaultContext).Where("repo_id = ? ", repo.ID).Count(&Collaboration{}) } func (repo *Repository) getCollaboration(e db.Engine, uid int64) (*Collaboration, error) { @@ -130,7 +130,7 @@ func (repo *Repository) isCollaborator(e db.Engine, userID int64) (bool, error) // IsCollaborator check if a user is a collaborator of a repository func (repo *Repository) IsCollaborator(userID int64) (bool, error) { - return repo.isCollaborator(db.DefaultContext().Engine(), userID) + return repo.isCollaborator(db.GetEngine(db.DefaultContext), userID) } func (repo *Repository) changeCollaborationAccessMode(e db.Engine, uid int64, mode AccessMode) error { @@ -169,7 +169,7 @@ func (repo *Repository) changeCollaborationAccessMode(e db.Engine, uid int64, mo // ChangeCollaborationAccessMode sets new access mode for the collaboration. func (repo *Repository) ChangeCollaborationAccessMode(uid int64, mode AccessMode) error { - sess := db.DefaultContext().NewSession() + sess := db.NewSession(db.DefaultContext) defer sess.Close() if err := sess.Begin(); err != nil { return err @@ -189,7 +189,7 @@ func (repo *Repository) DeleteCollaboration(uid int64) (err error) { UserID: uid, } - sess := db.DefaultContext().NewSession() + sess := db.NewSession(db.DefaultContext) defer sess.Close() if err = sess.Begin(); err != nil { return err @@ -259,7 +259,7 @@ func (repo *Repository) getRepoTeams(e db.Engine) (teams []*Team, err error) { // GetRepoTeams gets the list of teams that has access to the repository func (repo *Repository) GetRepoTeams() ([]*Team, error) { - return repo.getRepoTeams(db.DefaultContext().Engine()) + return repo.getRepoTeams(db.GetEngine(db.DefaultContext)) } // IsOwnerMemberCollaborator checks if a provided user is the owner, a collaborator or a member of a team in a repository @@ -267,7 +267,7 @@ func (repo *Repository) IsOwnerMemberCollaborator(userID int64) (bool, error) { if repo.OwnerID == userID { return true, nil } - teamMember, err := db.DefaultContext().Engine().Join("INNER", "team_repo", "team_repo.team_id = team_user.team_id"). + teamMember, err := db.GetEngine(db.DefaultContext).Join("INNER", "team_repo", "team_repo.team_id = team_user.team_id"). Join("INNER", "team_unit", "team_unit.team_id = team_user.team_id"). Where("team_repo.repo_id = ?", repo.ID). And("team_unit.`type` = ?", UnitTypeCode). @@ -279,5 +279,5 @@ func (repo *Repository) IsOwnerMemberCollaborator(userID int64) (bool, error) { return true, nil } - return db.DefaultContext().Engine().Get(&Collaboration{RepoID: repo.ID, UserID: userID}) + return db.GetEngine(db.DefaultContext).Get(&Collaboration{RepoID: repo.ID, UserID: userID}) } diff --git a/models/repo_collaboration_test.go b/models/repo_collaboration_test.go index 32dd2ef5a8f..5a3ffef5fae 100644 --- a/models/repo_collaboration_test.go +++ b/models/repo_collaboration_test.go @@ -32,7 +32,7 @@ func TestRepository_GetCollaborators(t *testing.T) { repo := db.AssertExistsAndLoadBean(t, &Repository{ID: repoID}).(*Repository) collaborators, err := repo.GetCollaborators(ListOptions{}) assert.NoError(t, err) - expectedLen, err := db.DefaultContext().Engine().Count(&Collaboration{RepoID: repoID}) + expectedLen, err := db.GetEngine(db.DefaultContext).Count(&Collaboration{RepoID: repoID}) assert.NoError(t, err) assert.Len(t, collaborators, int(expectedLen)) for _, collaborator := range collaborators { diff --git a/models/repo_generate.go b/models/repo_generate.go index e5f5c7e7fe4..cb8bf45184f 100644 --- a/models/repo_generate.go +++ b/models/repo_generate.go @@ -7,6 +7,7 @@ package models import ( "bufio" "bytes" + "context" "strconv" "strings" @@ -68,9 +69,9 @@ func (gt GiteaTemplate) Globs() []glob.Glob { } // GenerateTopics generates topics from a template repository -func GenerateTopics(ctx *db.Context, templateRepo, generateRepo *Repository) error { +func GenerateTopics(ctx context.Context, templateRepo, generateRepo *Repository) error { for _, topic := range templateRepo.Topics { - if _, err := addTopicByNameToRepo(ctx.Engine(), generateRepo.ID, topic); err != nil { + if _, err := addTopicByNameToRepo(db.GetEngine(ctx), generateRepo.ID, topic); err != nil { return err } } @@ -78,7 +79,7 @@ func GenerateTopics(ctx *db.Context, templateRepo, generateRepo *Repository) err } // GenerateGitHooks generates git hooks from a template repository -func GenerateGitHooks(ctx *db.Context, templateRepo, generateRepo *Repository) error { +func GenerateGitHooks(ctx context.Context, templateRepo, generateRepo *Repository) error { generateGitRepo, err := git.OpenRepository(generateRepo.RepoPath()) if err != nil { return err @@ -111,7 +112,7 @@ func GenerateGitHooks(ctx *db.Context, templateRepo, generateRepo *Repository) e } // GenerateWebhooks generates webhooks from a template repository -func GenerateWebhooks(ctx *db.Context, templateRepo, generateRepo *Repository) error { +func GenerateWebhooks(ctx context.Context, templateRepo, generateRepo *Repository) error { templateWebhooks, err := ListWebhooksByOpts(&ListWebhookOptions{RepoID: templateRepo.ID}) if err != nil { return err @@ -131,7 +132,7 @@ func GenerateWebhooks(ctx *db.Context, templateRepo, generateRepo *Repository) e Events: templateWebhook.Events, Meta: templateWebhook.Meta, } - if err := createWebhook(ctx.Engine(), generateWebhook); err != nil { + if err := createWebhook(db.GetEngine(ctx), generateWebhook); err != nil { return err } } @@ -139,18 +140,18 @@ func GenerateWebhooks(ctx *db.Context, templateRepo, generateRepo *Repository) e } // GenerateAvatar generates the avatar from a template repository -func GenerateAvatar(ctx *db.Context, templateRepo, generateRepo *Repository) error { +func GenerateAvatar(ctx context.Context, templateRepo, generateRepo *Repository) error { generateRepo.Avatar = strings.Replace(templateRepo.Avatar, strconv.FormatInt(templateRepo.ID, 10), strconv.FormatInt(generateRepo.ID, 10), 1) if _, err := storage.Copy(storage.RepoAvatars, generateRepo.CustomAvatarRelativePath(), storage.RepoAvatars, templateRepo.CustomAvatarRelativePath()); err != nil { return err } - return updateRepositoryCols(ctx.Engine(), generateRepo, "avatar") + return updateRepositoryCols(db.GetEngine(ctx), generateRepo, "avatar") } // GenerateIssueLabels generates issue labels from a template repository -func GenerateIssueLabels(ctx *db.Context, templateRepo, generateRepo *Repository) error { - templateLabels, err := getLabelsByRepoID(ctx.Engine(), templateRepo.ID, "", ListOptions{}) +func GenerateIssueLabels(ctx context.Context, templateRepo, generateRepo *Repository) error { + templateLabels, err := getLabelsByRepoID(db.GetEngine(ctx), templateRepo.ID, "", ListOptions{}) if err != nil { return err } @@ -162,7 +163,7 @@ func GenerateIssueLabels(ctx *db.Context, templateRepo, generateRepo *Repository Description: templateLabel.Description, Color: templateLabel.Color, } - if err := newLabel(ctx.Engine(), generateLabel); err != nil { + if err := newLabel(db.GetEngine(ctx), generateLabel); err != nil { return err } } diff --git a/models/repo_indexer.go b/models/repo_indexer.go index 4d3d18cac3f..7029b0922b0 100644 --- a/models/repo_indexer.go +++ b/models/repo_indexer.go @@ -42,7 +42,7 @@ func GetUnindexedRepos(indexerType RepoIndexerType, maxRepoID int64, page, pageS }).And(builder.Eq{ "repository.is_empty": false, }) - sess := db.DefaultContext().Engine().Table("repository").Join("LEFT OUTER", "repo_indexer_status", "repository.id = repo_indexer_status.repo_id AND repo_indexer_status.indexer_type = ?", indexerType) + sess := db.GetEngine(db.DefaultContext).Table("repository").Join("LEFT OUTER", "repo_indexer_status", "repository.id = repo_indexer_status.repo_id AND repo_indexer_status.indexer_type = ?", indexerType) if maxRepoID > 0 { cond = builder.And(cond, builder.Lte{ "repository.id": maxRepoID, @@ -91,7 +91,7 @@ func (repo *Repository) getIndexerStatus(e db.Engine, indexerType RepoIndexerTyp // GetIndexerStatus loads repo codes indxer status func (repo *Repository) GetIndexerStatus(indexerType RepoIndexerType) (*RepoIndexerStatus, error) { - return repo.getIndexerStatus(db.DefaultContext().Engine(), indexerType) + return repo.getIndexerStatus(db.GetEngine(db.DefaultContext), indexerType) } // updateIndexerStatus updates indexer status @@ -120,5 +120,5 @@ func (repo *Repository) updateIndexerStatus(e db.Engine, indexerType RepoIndexer // UpdateIndexerStatus updates indexer status func (repo *Repository) UpdateIndexerStatus(indexerType RepoIndexerType, sha string) error { - return repo.updateIndexerStatus(db.DefaultContext().Engine(), indexerType, sha) + return repo.updateIndexerStatus(db.GetEngine(db.DefaultContext), indexerType, sha) } diff --git a/models/repo_language_stats.go b/models/repo_language_stats.go index c7af7dc9b5d..2f126aa3d2a 100644 --- a/models/repo_language_stats.go +++ b/models/repo_language_stats.go @@ -75,12 +75,12 @@ func (repo *Repository) getLanguageStats(e db.Engine) (LanguageStatList, error) // GetLanguageStats returns the language statistics for a repository func (repo *Repository) GetLanguageStats() (LanguageStatList, error) { - return repo.getLanguageStats(db.DefaultContext().Engine()) + return repo.getLanguageStats(db.GetEngine(db.DefaultContext)) } // GetTopLanguageStats returns the top language statistics for a repository func (repo *Repository) GetTopLanguageStats(limit int) (LanguageStatList, error) { - stats, err := repo.getLanguageStats(db.DefaultContext().Engine()) + stats, err := repo.getLanguageStats(db.GetEngine(db.DefaultContext)) if err != nil { return nil, err } @@ -112,7 +112,7 @@ func (repo *Repository) GetTopLanguageStats(limit int) (LanguageStatList, error) // UpdateLanguageStats updates the language statistics for repository func (repo *Repository) UpdateLanguageStats(commitID string, stats map[string]int64) error { - sess := db.DefaultContext().NewSession() + sess := db.NewSession(db.DefaultContext) if err := sess.Begin(); err != nil { return err } @@ -183,7 +183,7 @@ func (repo *Repository) UpdateLanguageStats(commitID string, stats map[string]in // CopyLanguageStat Copy originalRepo language stat information to destRepo (use for forked repo) func CopyLanguageStat(originalRepo, destRepo *Repository) error { - sess := db.DefaultContext().NewSession() + sess := db.NewSession(db.DefaultContext) defer sess.Close() if err := sess.Begin(); err != nil { return err diff --git a/models/repo_list.go b/models/repo_list.go index 686fd27b77d..7179114f467 100644 --- a/models/repo_list.go +++ b/models/repo_list.go @@ -90,7 +90,7 @@ func (repos RepositoryList) loadAttributes(e db.Engine) error { // LoadAttributes loads the attributes for the given RepositoryList func (repos RepositoryList) LoadAttributes() error { - return repos.loadAttributes(db.DefaultContext().Engine()) + return repos.loadAttributes(db.GetEngine(db.DefaultContext)) } // MirrorRepositoryList contains the mirror repositories @@ -130,7 +130,7 @@ func (repos MirrorRepositoryList) loadAttributes(e db.Engine) error { // LoadAttributes loads the attributes for the given MirrorRepositoryList func (repos MirrorRepositoryList) LoadAttributes() error { - return repos.loadAttributes(db.DefaultContext().Engine()) + return repos.loadAttributes(db.GetEngine(db.DefaultContext)) } // SearchRepoOptions holds the search options @@ -410,7 +410,7 @@ func searchRepositoryByCondition(opts *SearchRepoOptions, cond builder.Cond) (*x opts.OrderBy = SearchOrderBy(fmt.Sprintf("CASE WHEN owner_id = %d THEN 0 ELSE owner_id END, %s", opts.PriorityOwnerID, opts.OrderBy)) } - sess := db.DefaultContext().NewSession() + sess := db.NewSession(db.DefaultContext) var count int64 if opts.PageSize > 0 { @@ -520,7 +520,7 @@ func AccessibleRepoIDsQuery(user *User) *builder.Builder { // FindUserAccessibleRepoIDs find all accessible repositories' ID by user's id func FindUserAccessibleRepoIDs(user *User) ([]int64, error) { repoIDs := make([]int64, 0, 10) - if err := db.DefaultContext().Engine(). + if err := db.GetEngine(db.DefaultContext). Table("repository"). Cols("id"). Where(accessibleRepositoryCondition(user)). diff --git a/models/repo_mirror.go b/models/repo_mirror.go index b086b87cf13..35685b32209 100644 --- a/models/repo_mirror.go +++ b/models/repo_mirror.go @@ -95,7 +95,7 @@ func getMirrorByRepoID(e db.Engine, repoID int64) (*Mirror, error) { // GetMirrorByRepoID returns mirror information of a repository. func GetMirrorByRepoID(repoID int64) (*Mirror, error) { - return getMirrorByRepoID(db.DefaultContext().Engine(), repoID) + return getMirrorByRepoID(db.GetEngine(db.DefaultContext), repoID) } func updateMirror(e db.Engine, m *Mirror) error { @@ -105,18 +105,18 @@ func updateMirror(e db.Engine, m *Mirror) error { // UpdateMirror updates the mirror func UpdateMirror(m *Mirror) error { - return updateMirror(db.DefaultContext().Engine(), m) + return updateMirror(db.GetEngine(db.DefaultContext), m) } // DeleteMirrorByRepoID deletes a mirror by repoID func DeleteMirrorByRepoID(repoID int64) error { - _, err := db.DefaultContext().Engine().Delete(&Mirror{RepoID: repoID}) + _, err := db.GetEngine(db.DefaultContext).Delete(&Mirror{RepoID: repoID}) return err } // MirrorsIterate iterates all mirror repositories. func MirrorsIterate(f func(idx int, bean interface{}) error) error { - return db.DefaultContext().Engine(). + return db.GetEngine(db.DefaultContext). Where("next_update_unix<=?", time.Now().Unix()). And("next_update_unix!=0"). Iterate(new(Mirror), f) @@ -124,6 +124,6 @@ func MirrorsIterate(f func(idx int, bean interface{}) error) error { // InsertMirror inserts a mirror to database func InsertMirror(mirror *Mirror) error { - _, err := db.DefaultContext().Engine().Insert(mirror) + _, err := db.GetEngine(db.DefaultContext).Insert(mirror) return err } diff --git a/models/repo_permission.go b/models/repo_permission.go index 4f518e1746f..5ec933aa0fc 100644 --- a/models/repo_permission.go +++ b/models/repo_permission.go @@ -140,7 +140,7 @@ func (p *Permission) ColorFormat(s fmt.State) { // GetUserRepoPermission returns the user permissions to the repository func GetUserRepoPermission(repo *Repository, user *User) (Permission, error) { - return getUserRepoPermission(db.DefaultContext().Engine(), repo, user) + return getUserRepoPermission(db.GetEngine(db.DefaultContext), repo, user) } func getUserRepoPermission(e db.Engine, repo *Repository, user *User) (perm Permission, err error) { @@ -278,7 +278,7 @@ func IsUserRealRepoAdmin(repo *Repository, user *User) (bool, error) { return true, nil } - sess := db.DefaultContext().NewSession() + sess := db.NewSession(db.DefaultContext) defer sess.Close() if err := repo.getOwner(sess); err != nil { @@ -295,7 +295,7 @@ func IsUserRealRepoAdmin(repo *Repository, user *User) (bool, error) { // IsUserRepoAdmin return true if user has admin right of a repo func IsUserRepoAdmin(repo *Repository, user *User) (bool, error) { - return isUserRepoAdmin(db.DefaultContext().Engine(), repo, user) + return isUserRepoAdmin(db.GetEngine(db.DefaultContext), repo, user) } func isUserRepoAdmin(e db.Engine, repo *Repository, user *User) (bool, error) { @@ -330,13 +330,13 @@ func isUserRepoAdmin(e db.Engine, repo *Repository, user *User) (bool, error) { // AccessLevel returns the Access a user has to a repository. Will return NoneAccess if the // user does not have access. func AccessLevel(user *User, repo *Repository) (AccessMode, error) { - return accessLevelUnit(db.DefaultContext().Engine(), user, repo, UnitTypeCode) + return accessLevelUnit(db.GetEngine(db.DefaultContext), user, repo, UnitTypeCode) } // AccessLevelUnit returns the Access a user has to a repository's. Will return NoneAccess if the // user does not have access. func AccessLevelUnit(user *User, repo *Repository, unitType UnitType) (AccessMode, error) { - return accessLevelUnit(db.DefaultContext().Engine(), user, repo, unitType) + return accessLevelUnit(db.GetEngine(db.DefaultContext), user, repo, unitType) } func accessLevelUnit(e db.Engine, user *User, repo *Repository, unitType UnitType) (AccessMode, error) { @@ -354,14 +354,14 @@ func hasAccessUnit(e db.Engine, user *User, repo *Repository, unitType UnitType, // HasAccessUnit returns true if user has testMode to the unit of the repository func HasAccessUnit(user *User, repo *Repository, unitType UnitType, testMode AccessMode) (bool, error) { - return hasAccessUnit(db.DefaultContext().Engine(), user, repo, unitType, testMode) + return hasAccessUnit(db.GetEngine(db.DefaultContext), user, repo, unitType, testMode) } // CanBeAssigned return true if user can be assigned to issue or pull requests in repo // Currently any write access (code, issues or pr's) is assignable, to match assignee list in user interface. // FIXME: user could send PullRequest also could be assigned??? func CanBeAssigned(user *User, repo *Repository, isPull bool) (bool, error) { - return canBeAssigned(db.DefaultContext().Engine(), user, repo, isPull) + return canBeAssigned(db.GetEngine(db.DefaultContext), user, repo, isPull) } func canBeAssigned(e db.Engine, user *User, repo *Repository, _ bool) (bool, error) { @@ -393,7 +393,7 @@ func hasAccess(e db.Engine, userID int64, repo *Repository) (bool, error) { // HasAccess returns true if user has access to repo func HasAccess(userID int64, repo *Repository) (bool, error) { - return hasAccess(db.DefaultContext().Engine(), userID, repo) + return hasAccess(db.GetEngine(db.DefaultContext), userID, repo) } // FilterOutRepoIdsWithoutUnitAccess filter out repos where user has no access to repositories diff --git a/models/repo_permission_test.go b/models/repo_permission_test.go index 625e0dd205b..1fbf1b9f8fa 100644 --- a/models/repo_permission_test.go +++ b/models/repo_permission_test.go @@ -16,7 +16,7 @@ func TestRepoPermissionPublicNonOrgRepo(t *testing.T) { // public non-organization repo repo := db.AssertExistsAndLoadBean(t, &Repository{ID: 4}).(*Repository) - assert.NoError(t, repo.getUnits(db.DefaultContext().Engine())) + assert.NoError(t, repo.getUnits(db.GetEngine(db.DefaultContext))) // plain user user := db.AssertExistsAndLoadBean(t, &User{ID: 2}).(*User) @@ -69,7 +69,7 @@ func TestRepoPermissionPrivateNonOrgRepo(t *testing.T) { // private non-organization repo repo := db.AssertExistsAndLoadBean(t, &Repository{ID: 2}).(*Repository) - assert.NoError(t, repo.getUnits(db.DefaultContext().Engine())) + assert.NoError(t, repo.getUnits(db.GetEngine(db.DefaultContext))) // plain user user := db.AssertExistsAndLoadBean(t, &User{ID: 4}).(*User) @@ -121,7 +121,7 @@ func TestRepoPermissionPublicOrgRepo(t *testing.T) { // public organization repo repo := db.AssertExistsAndLoadBean(t, &Repository{ID: 32}).(*Repository) - assert.NoError(t, repo.getUnits(db.DefaultContext().Engine())) + assert.NoError(t, repo.getUnits(db.GetEngine(db.DefaultContext))) // plain user user := db.AssertExistsAndLoadBean(t, &User{ID: 5}).(*User) @@ -183,7 +183,7 @@ func TestRepoPermissionPrivateOrgRepo(t *testing.T) { // private organization repo repo := db.AssertExistsAndLoadBean(t, &Repository{ID: 24}).(*Repository) - assert.NoError(t, repo.getUnits(db.DefaultContext().Engine())) + assert.NoError(t, repo.getUnits(db.GetEngine(db.DefaultContext))) // plain user user := db.AssertExistsAndLoadBean(t, &User{ID: 5}).(*User) diff --git a/models/repo_pushmirror.go b/models/repo_pushmirror.go index b0e28521622..c6207bae6df 100644 --- a/models/repo_pushmirror.go +++ b/models/repo_pushmirror.go @@ -62,32 +62,32 @@ func (m *PushMirror) GetRemoteName() string { // InsertPushMirror inserts a push-mirror to database func InsertPushMirror(m *PushMirror) error { - _, err := db.DefaultContext().Engine().Insert(m) + _, err := db.GetEngine(db.DefaultContext).Insert(m) return err } // UpdatePushMirror updates the push-mirror func UpdatePushMirror(m *PushMirror) error { - _, err := db.DefaultContext().Engine().ID(m.ID).AllCols().Update(m) + _, err := db.GetEngine(db.DefaultContext).ID(m.ID).AllCols().Update(m) return err } // DeletePushMirrorByID deletes a push-mirrors by ID func DeletePushMirrorByID(ID int64) error { - _, err := db.DefaultContext().Engine().ID(ID).Delete(&PushMirror{}) + _, err := db.GetEngine(db.DefaultContext).ID(ID).Delete(&PushMirror{}) return err } // DeletePushMirrorsByRepoID deletes all push-mirrors by repoID func DeletePushMirrorsByRepoID(repoID int64) error { - _, err := db.DefaultContext().Engine().Delete(&PushMirror{RepoID: repoID}) + _, err := db.GetEngine(db.DefaultContext).Delete(&PushMirror{RepoID: repoID}) return err } // GetPushMirrorByID returns push-mirror information. func GetPushMirrorByID(ID int64) (*PushMirror, error) { m := &PushMirror{} - has, err := db.DefaultContext().Engine().ID(ID).Get(m) + has, err := db.GetEngine(db.DefaultContext).ID(ID).Get(m) if err != nil { return nil, err } else if !has { @@ -99,12 +99,12 @@ func GetPushMirrorByID(ID int64) (*PushMirror, error) { // GetPushMirrorsByRepoID returns push-mirror information of a repository. func GetPushMirrorsByRepoID(repoID int64) ([]*PushMirror, error) { mirrors := make([]*PushMirror, 0, 10) - return mirrors, db.DefaultContext().Engine().Where("repo_id=?", repoID).Find(&mirrors) + return mirrors, db.GetEngine(db.DefaultContext).Where("repo_id=?", repoID).Find(&mirrors) } // PushMirrorsIterate iterates all push-mirror repositories. func PushMirrorsIterate(f func(idx int, bean interface{}) error) error { - return db.DefaultContext().Engine(). + return db.GetEngine(db.DefaultContext). Where("last_update + (`interval` / ?) <= ?", time.Second, time.Now().Unix()). And("`interval` != 0"). Iterate(new(PushMirror), f) diff --git a/models/repo_redirect.go b/models/repo_redirect.go index 95196d2a0f2..18422f9d18e 100644 --- a/models/repo_redirect.go +++ b/models/repo_redirect.go @@ -26,7 +26,7 @@ func init() { func LookupRepoRedirect(ownerID int64, repoName string) (int64, error) { repoName = strings.ToLower(repoName) redirect := &RepoRedirect{OwnerID: ownerID, LowerName: repoName} - if has, err := db.DefaultContext().Engine().Get(redirect); err != nil { + if has, err := db.GetEngine(db.DefaultContext).Get(redirect); err != nil { return 0, err } else if !has { return 0, ErrRepoRedirectNotExist{OwnerID: ownerID, RepoName: repoName} diff --git a/models/repo_redirect_test.go b/models/repo_redirect_test.go index 9e99fdae37d..9400422752c 100644 --- a/models/repo_redirect_test.go +++ b/models/repo_redirect_test.go @@ -27,7 +27,7 @@ func TestNewRepoRedirect(t *testing.T) { assert.NoError(t, db.PrepareTestDatabase()) repo := db.AssertExistsAndLoadBean(t, &Repository{ID: 1}).(*Repository) - assert.NoError(t, newRepoRedirect(db.DefaultContext().Engine(), repo.OwnerID, repo.ID, repo.Name, "newreponame")) + assert.NoError(t, newRepoRedirect(db.GetEngine(db.DefaultContext), repo.OwnerID, repo.ID, repo.Name, "newreponame")) db.AssertExistsAndLoadBean(t, &RepoRedirect{ OwnerID: repo.OwnerID, @@ -46,7 +46,7 @@ func TestNewRepoRedirect2(t *testing.T) { assert.NoError(t, db.PrepareTestDatabase()) repo := db.AssertExistsAndLoadBean(t, &Repository{ID: 1}).(*Repository) - assert.NoError(t, newRepoRedirect(db.DefaultContext().Engine(), repo.OwnerID, repo.ID, repo.Name, "oldrepo1")) + assert.NoError(t, newRepoRedirect(db.GetEngine(db.DefaultContext), repo.OwnerID, repo.ID, repo.Name, "oldrepo1")) db.AssertExistsAndLoadBean(t, &RepoRedirect{ OwnerID: repo.OwnerID, @@ -65,7 +65,7 @@ func TestNewRepoRedirect3(t *testing.T) { assert.NoError(t, db.PrepareTestDatabase()) repo := db.AssertExistsAndLoadBean(t, &Repository{ID: 2}).(*Repository) - assert.NoError(t, newRepoRedirect(db.DefaultContext().Engine(), repo.OwnerID, repo.ID, repo.Name, "newreponame")) + assert.NoError(t, newRepoRedirect(db.GetEngine(db.DefaultContext), repo.OwnerID, repo.ID, repo.Name, "newreponame")) db.AssertExistsAndLoadBean(t, &RepoRedirect{ OwnerID: repo.OwnerID, diff --git a/models/repo_test.go b/models/repo_test.go index 2467b63840b..8073a9cd2f2 100644 --- a/models/repo_test.go +++ b/models/repo_test.go @@ -109,7 +109,7 @@ func TestUpdateRepositoryVisibilityChanged(t *testing.T) { // Check visibility of action has become private act := Action{} - _, err = db.DefaultContext().Engine().ID(3).Get(&act) + _, err = db.GetEngine(db.DefaultContext).ID(3).Get(&act) assert.NoError(t, err) assert.True(t, act.IsPrivate) diff --git a/models/repo_transfer.go b/models/repo_transfer.go index 2ede0fbbe71..e3eb756eb40 100644 --- a/models/repo_transfer.go +++ b/models/repo_transfer.go @@ -98,7 +98,7 @@ func (r *RepoTransfer) CanUserAcceptTransfer(u *User) bool { func GetPendingRepositoryTransfer(repo *Repository) (*RepoTransfer, error) { transfer := new(RepoTransfer) - has, err := db.DefaultContext().Engine().Where("repo_id = ? ", repo.ID).Get(transfer) + has, err := db.GetEngine(db.DefaultContext).Where("repo_id = ? ", repo.ID).Get(transfer) if err != nil { return nil, err } @@ -118,7 +118,7 @@ func deleteRepositoryTransfer(e db.Engine, repoID int64) error { // CancelRepositoryTransfer marks the repository as ready and remove pending transfer entry, // thus cancel the transfer process. func CancelRepositoryTransfer(repo *Repository) error { - sess := db.DefaultContext().NewSession() + sess := db.NewSession(db.DefaultContext) defer sess.Close() if err := sess.Begin(); err != nil { return err @@ -150,7 +150,7 @@ func TestRepositoryReadyForTransfer(status RepositoryStatus) error { // CreatePendingRepositoryTransfer transfer a repo from one owner to a new one. // it marks the repository transfer as "pending" func CreatePendingRepositoryTransfer(doer, newOwner *User, repoID int64, teams []*Team) error { - sess := db.DefaultContext().NewSession() + sess := db.NewSession(db.DefaultContext) defer sess.Close() if err := sess.Begin(); err != nil { return err @@ -232,7 +232,7 @@ func TransferOwnership(doer *User, newOwnerName string, repo *Repository) (err e } }() - sess := db.DefaultContext().NewSession() + sess := db.NewSession(db.DefaultContext) defer sess.Close() if err := sess.Begin(); err != nil { return fmt.Errorf("sess.Begin: %v", err) diff --git a/models/repo_watch.go b/models/repo_watch.go index 635507561e4..d3720fe857a 100644 --- a/models/repo_watch.go +++ b/models/repo_watch.go @@ -60,7 +60,7 @@ func isWatchMode(mode RepoWatchMode) bool { // IsWatching checks if user has watched given repository. func IsWatching(userID, repoID int64) bool { - watch, err := getWatch(db.DefaultContext().Engine(), userID, repoID) + watch, err := getWatch(db.GetEngine(db.DefaultContext), userID, repoID) return err == nil && isWatchMode(watch.Mode) } @@ -107,10 +107,10 @@ func watchRepoMode(e db.Engine, watch Watch, mode RepoWatchMode) (err error) { // WatchRepoMode watch repository in specific mode. func WatchRepoMode(userID, repoID int64, mode RepoWatchMode) (err error) { var watch Watch - if watch, err = getWatch(db.DefaultContext().Engine(), userID, repoID); err != nil { + if watch, err = getWatch(db.GetEngine(db.DefaultContext), userID, repoID); err != nil { return err } - return watchRepoMode(db.DefaultContext().Engine(), watch, mode) + return watchRepoMode(db.GetEngine(db.DefaultContext), watch, mode) } func watchRepo(e db.Engine, userID, repoID int64, doWatch bool) (err error) { @@ -130,7 +130,7 @@ func watchRepo(e db.Engine, userID, repoID int64, doWatch bool) (err error) { // WatchRepo watch or unwatch repository. func WatchRepo(userID, repoID int64, watch bool) (err error) { - return watchRepo(db.DefaultContext().Engine(), userID, repoID, watch) + return watchRepo(db.GetEngine(db.DefaultContext), userID, repoID, watch) } func getWatchers(e db.Engine, repoID int64) ([]*Watch, error) { @@ -145,14 +145,14 @@ func getWatchers(e db.Engine, repoID int64) ([]*Watch, error) { // GetWatchers returns all watchers of given repository. func GetWatchers(repoID int64) ([]*Watch, error) { - return getWatchers(db.DefaultContext().Engine(), repoID) + return getWatchers(db.GetEngine(db.DefaultContext), repoID) } // GetRepoWatchersIDs returns IDs of watchers for a given repo ID // but avoids joining with `user` for performance reasons // User permissions must be verified elsewhere if required func GetRepoWatchersIDs(repoID int64) ([]int64, error) { - return getRepoWatchersIDs(db.DefaultContext().Engine(), repoID) + return getRepoWatchersIDs(db.GetEngine(db.DefaultContext), repoID) } func getRepoWatchersIDs(e db.Engine, repoID int64) ([]int64, error) { @@ -166,7 +166,7 @@ func getRepoWatchersIDs(e db.Engine, repoID int64) ([]int64, error) { // GetWatchers returns range of users watching given repository. func (repo *Repository) GetWatchers(opts ListOptions) ([]*User, error) { - sess := db.DefaultContext().Engine().Where("watch.repo_id=?", repo.ID). + sess := db.GetEngine(db.DefaultContext).Where("watch.repo_id=?", repo.ID). Join("LEFT", "watch", "`user`.id=`watch`.user_id"). And("`watch`.mode<>?", RepoWatchModeDont) if opts.Page > 0 { @@ -284,12 +284,12 @@ func notifyWatchers(e db.Engine, actions ...*Action) error { // NotifyWatchers creates batch of actions for every watcher. func NotifyWatchers(actions ...*Action) error { - return notifyWatchers(db.DefaultContext().Engine(), actions...) + return notifyWatchers(db.GetEngine(db.DefaultContext), actions...) } // NotifyWatchersActions creates batch of actions for every watcher. func NotifyWatchersActions(acts []*Action) error { - sess := db.DefaultContext().NewSession() + sess := db.NewSession(db.DefaultContext) defer sess.Close() if err := sess.Begin(); err != nil { return err @@ -318,5 +318,5 @@ func watchIfAuto(e db.Engine, userID, repoID int64, isWrite bool) error { // WatchIfAuto subscribes to repo if AutoWatchOnChanges is set func WatchIfAuto(userID, repoID int64, isWrite bool) error { - return watchIfAuto(db.DefaultContext().Engine(), userID, repoID, isWrite) + return watchIfAuto(db.GetEngine(db.DefaultContext), userID, repoID, isWrite) } diff --git a/models/review.go b/models/review.go index ed656f49737..3f81c39b2fc 100644 --- a/models/review.go +++ b/models/review.go @@ -95,7 +95,7 @@ func (r *Review) loadCodeComments(e db.Engine) (err error) { // LoadCodeComments loads CodeComments func (r *Review) LoadCodeComments() error { - return r.loadCodeComments(db.DefaultContext().Engine()) + return r.loadCodeComments(db.GetEngine(db.DefaultContext)) } func (r *Review) loadIssue(e db.Engine) (err error) { @@ -125,12 +125,12 @@ func (r *Review) loadReviewerTeam(e db.Engine) (err error) { // LoadReviewer loads reviewer func (r *Review) LoadReviewer() error { - return r.loadReviewer(db.DefaultContext().Engine()) + return r.loadReviewer(db.GetEngine(db.DefaultContext)) } // LoadReviewerTeam loads reviewer team func (r *Review) LoadReviewerTeam() error { - return r.loadReviewerTeam(db.DefaultContext().Engine()) + return r.loadReviewerTeam(db.GetEngine(db.DefaultContext)) } func (r *Review) loadAttributes(e db.Engine) (err error) { @@ -151,7 +151,7 @@ func (r *Review) loadAttributes(e db.Engine) (err error) { // LoadAttributes loads all attributes except CodeComments func (r *Review) LoadAttributes() error { - return r.loadAttributes(db.DefaultContext().Engine()) + return r.loadAttributes(db.GetEngine(db.DefaultContext)) } func getReviewByID(e db.Engine, id int64) (*Review, error) { @@ -167,7 +167,7 @@ func getReviewByID(e db.Engine, id int64) (*Review, error) { // GetReviewByID returns the review by the given ID func GetReviewByID(id int64) (*Review, error) { - return getReviewByID(db.DefaultContext().Engine(), id) + return getReviewByID(db.GetEngine(db.DefaultContext), id) } // FindReviewOptions represent possible filters to find reviews @@ -210,12 +210,12 @@ func findReviews(e db.Engine, opts FindReviewOptions) ([]*Review, error) { // FindReviews returns reviews passing FindReviewOptions func FindReviews(opts FindReviewOptions) ([]*Review, error) { - return findReviews(db.DefaultContext().Engine(), opts) + return findReviews(db.GetEngine(db.DefaultContext), opts) } // CountReviews returns count of reviews passing FindReviewOptions func CountReviews(opts FindReviewOptions) (int64, error) { - return db.DefaultContext().Engine().Where(opts.toCond()).Count(&Review{}) + return db.GetEngine(db.DefaultContext).Where(opts.toCond()).Count(&Review{}) } // CreateReviewOptions represent the options to create a review. Type, Issue and Reviewer are required. @@ -232,7 +232,7 @@ type CreateReviewOptions struct { // IsOfficialReviewer check if at least one of the provided reviewers can make official reviews in issue (counts towards required approvals) func IsOfficialReviewer(issue *Issue, reviewers ...*User) (bool, error) { - return isOfficialReviewer(db.DefaultContext().Engine(), issue, reviewers...) + return isOfficialReviewer(db.GetEngine(db.DefaultContext), issue, reviewers...) } func isOfficialReviewer(e db.Engine, issue *Issue, reviewers ...*User) (bool, error) { @@ -259,7 +259,7 @@ func isOfficialReviewer(e db.Engine, issue *Issue, reviewers ...*User) (bool, er // IsOfficialReviewerTeam check if reviewer in this team can make official reviews in issue (counts towards required approvals) func IsOfficialReviewerTeam(issue *Issue, team *Team) (bool, error) { - return isOfficialReviewerTeam(db.DefaultContext().Engine(), issue, team) + return isOfficialReviewerTeam(db.GetEngine(db.DefaultContext), issue, team) } func isOfficialReviewerTeam(e db.Engine, issue *Issue, team *Team) (bool, error) { @@ -310,7 +310,7 @@ func createReview(e db.Engine, opts CreateReviewOptions) (*Review, error) { // CreateReview creates a new review based on opts func CreateReview(opts CreateReviewOptions) (*Review, error) { - return createReview(db.DefaultContext().Engine(), opts) + return createReview(db.GetEngine(db.DefaultContext), opts) } func getCurrentReview(e db.Engine, reviewer *User, issue *Issue) (*Review, error) { @@ -335,12 +335,12 @@ func getCurrentReview(e db.Engine, reviewer *User, issue *Issue) (*Review, error // ReviewExists returns whether a review exists for a particular line of code in the PR func ReviewExists(issue *Issue, treePath string, line int64) (bool, error) { - return db.DefaultContext().Engine().Cols("id").Exist(&Comment{IssueID: issue.ID, TreePath: treePath, Line: line, Type: CommentTypeCode}) + return db.GetEngine(db.DefaultContext).Cols("id").Exist(&Comment{IssueID: issue.ID, TreePath: treePath, Line: line, Type: CommentTypeCode}) } // GetCurrentReview returns the current pending review of reviewer for given issue func GetCurrentReview(reviewer *User, issue *Issue) (*Review, error) { - return getCurrentReview(db.DefaultContext().Engine(), reviewer, issue) + return getCurrentReview(db.GetEngine(db.DefaultContext), reviewer, issue) } // ContentEmptyErr represents an content empty error @@ -358,7 +358,7 @@ func IsContentEmptyErr(err error) bool { // SubmitReview creates a review out of the existing pending review or creates a new one if no pending review exist func SubmitReview(doer *User, issue *Issue, reviewType ReviewType, content, commitID string, stale bool, attachmentUUIDs []string) (*Review, *Comment, error) { - sess := db.DefaultContext().NewSession() + sess := db.NewSession(db.DefaultContext) defer sess.Close() if err := sess.Begin(); err != nil { return nil, nil, err @@ -470,7 +470,7 @@ func SubmitReview(doer *User, issue *Issue, reviewType ReviewType, content, comm func GetReviewersByIssueID(issueID int64) ([]*Review, error) { reviews := make([]*Review, 0, 10) - sess := db.DefaultContext().NewSession() + sess := db.NewSession(db.DefaultContext) defer sess.Close() if err := sess.Begin(); err != nil { return nil, err @@ -502,7 +502,7 @@ func GetReviewersFromOriginalAuthorsByIssueID(issueID int64) ([]*Review, error) reviews := make([]*Review, 0, 10) // Get latest review of each reviewer, sorted in order they were made - if err := db.DefaultContext().Engine().SQL("SELECT * FROM review WHERE id IN (SELECT max(id) as id FROM review WHERE issue_id = ? AND reviewer_team_id = 0 AND type in (?, ?, ?) AND original_author_id <> 0 GROUP BY issue_id, original_author_id) ORDER BY review.updated_unix ASC", + if err := db.GetEngine(db.DefaultContext).SQL("SELECT * FROM review WHERE id IN (SELECT max(id) as id FROM review WHERE issue_id = ? AND reviewer_team_id = 0 AND type in (?, ?, ?) AND original_author_id <> 0 GROUP BY issue_id, original_author_id) ORDER BY review.updated_unix ASC", issueID, ReviewTypeApprove, ReviewTypeReject, ReviewTypeRequest). Find(&reviews); err != nil { return nil, err @@ -513,7 +513,7 @@ func GetReviewersFromOriginalAuthorsByIssueID(issueID int64) ([]*Review, error) // GetReviewByIssueIDAndUserID get the latest review of reviewer for a pull request func GetReviewByIssueIDAndUserID(issueID, userID int64) (*Review, error) { - return getReviewByIssueIDAndUserID(db.DefaultContext().Engine(), issueID, userID) + return getReviewByIssueIDAndUserID(db.GetEngine(db.DefaultContext), issueID, userID) } func getReviewByIssueIDAndUserID(e db.Engine, issueID, userID int64) (*Review, error) { @@ -535,7 +535,7 @@ func getReviewByIssueIDAndUserID(e db.Engine, issueID, userID int64) (*Review, e // GetTeamReviewerByIssueIDAndTeamID get the latest review requst of reviewer team for a pull request func GetTeamReviewerByIssueIDAndTeamID(issueID, teamID int64) (review *Review, err error) { - return getTeamReviewerByIssueIDAndTeamID(db.DefaultContext().Engine(), issueID, teamID) + return getTeamReviewerByIssueIDAndTeamID(db.GetEngine(db.DefaultContext), issueID, teamID) } func getTeamReviewerByIssueIDAndTeamID(e db.Engine, issueID, teamID int64) (review *Review, err error) { @@ -557,14 +557,14 @@ func getTeamReviewerByIssueIDAndTeamID(e db.Engine, issueID, teamID int64) (revi // MarkReviewsAsStale marks existing reviews as stale func MarkReviewsAsStale(issueID int64) (err error) { - _, err = db.DefaultContext().Engine().Exec("UPDATE `review` SET stale=? WHERE issue_id=?", true, issueID) + _, err = db.GetEngine(db.DefaultContext).Exec("UPDATE `review` SET stale=? WHERE issue_id=?", true, issueID) return } // MarkReviewsAsNotStale marks existing reviews as not stale for a giving commit SHA func MarkReviewsAsNotStale(issueID int64, commitID string) (err error) { - _, err = db.DefaultContext().Engine().Exec("UPDATE `review` SET stale=? WHERE issue_id=? AND commit_id=?", false, issueID, commitID) + _, err = db.GetEngine(db.DefaultContext).Exec("UPDATE `review` SET stale=? WHERE issue_id=? AND commit_id=?", false, issueID, commitID) return } @@ -581,14 +581,14 @@ func DismissReview(review *Review, isDismiss bool) (err error) { return ErrReviewNotExist{} } - _, err = db.DefaultContext().Engine().ID(review.ID).Cols("dismissed").Update(review) + _, err = db.GetEngine(db.DefaultContext).ID(review.ID).Cols("dismissed").Update(review) return } // InsertReviews inserts review and review comments func InsertReviews(reviews []*Review) error { - sess := db.DefaultContext().NewSession() + sess := db.NewSession(db.DefaultContext) defer sess.Close() if err := sess.Begin(); err != nil { @@ -630,7 +630,7 @@ func InsertReviews(reviews []*Review) error { // AddReviewRequest add a review request from one reviewer func AddReviewRequest(issue *Issue, reviewer, doer *User) (*Comment, error) { - sess := db.DefaultContext().NewSession() + sess := db.NewSession(db.DefaultContext) defer sess.Close() if err := sess.Begin(); err != nil { return nil, err @@ -684,7 +684,7 @@ func AddReviewRequest(issue *Issue, reviewer, doer *User) (*Comment, error) { // RemoveReviewRequest remove a review request from one reviewer func RemoveReviewRequest(issue *Issue, reviewer, doer *User) (*Comment, error) { - sess := db.DefaultContext().NewSession() + sess := db.NewSession(db.DefaultContext) defer sess.Close() if err := sess.Begin(); err != nil { return nil, err @@ -737,7 +737,7 @@ func RemoveReviewRequest(issue *Issue, reviewer, doer *User) (*Comment, error) { // AddTeamReviewRequest add a review request from one team func AddTeamReviewRequest(issue *Issue, reviewer *Team, doer *User) (*Comment, error) { - sess := db.DefaultContext().NewSession() + sess := db.NewSession(db.DefaultContext) defer sess.Close() if err := sess.Begin(); err != nil { return nil, err @@ -796,7 +796,7 @@ func AddTeamReviewRequest(issue *Issue, reviewer *Team, doer *User) (*Comment, e // RemoveTeamReviewRequest remove a review request from one team func RemoveTeamReviewRequest(issue *Issue, reviewer *Team, doer *User) (*Comment, error) { - sess := db.DefaultContext().NewSession() + sess := db.NewSession(db.DefaultContext) defer sess.Close() if err := sess.Begin(); err != nil { return nil, err @@ -864,7 +864,7 @@ func MarkConversation(comment *Comment, doer *User, isResolve bool) (err error) return nil } - if _, err = db.DefaultContext().Engine().Exec("UPDATE `comment` SET resolve_doer_id=? WHERE id=?", doer.ID, comment.ID); err != nil { + if _, err = db.GetEngine(db.DefaultContext).Exec("UPDATE `comment` SET resolve_doer_id=? WHERE id=?", doer.ID, comment.ID); err != nil { return err } } else { @@ -872,7 +872,7 @@ func MarkConversation(comment *Comment, doer *User, isResolve bool) (err error) return nil } - if _, err = db.DefaultContext().Engine().Exec("UPDATE `comment` SET resolve_doer_id=? WHERE id=?", 0, comment.ID); err != nil { + if _, err = db.GetEngine(db.DefaultContext).Exec("UPDATE `comment` SET resolve_doer_id=? WHERE id=?", 0, comment.ID); err != nil { return err } } @@ -914,7 +914,7 @@ func CanMarkConversation(issue *Issue, doer *User) (permResult bool, err error) // DeleteReview delete a review and it's code comments func DeleteReview(r *Review) error { - sess := db.DefaultContext().NewSession() + sess := db.NewSession(db.DefaultContext) defer sess.Close() if err := sess.Begin(); err != nil { @@ -968,7 +968,7 @@ func (r *Review) GetCodeCommentsCount() int { conds = conds.And(builder.Eq{"invalidated": false}) } - count, err := db.DefaultContext().Engine().Where(conds).Count(new(Comment)) + count, err := db.GetEngine(db.DefaultContext).Where(conds).Count(new(Comment)) if err != nil { return 0 } @@ -983,7 +983,7 @@ func (r *Review) HTMLURL() string { ReviewID: r.ID, } comment := new(Comment) - has, err := db.DefaultContext().Engine().Where(opts.toConds()).Get(comment) + has, err := db.GetEngine(db.DefaultContext).Where(opts.toConds()).Get(comment) if err != nil || !has { return "" } diff --git a/models/session.go b/models/session.go index 9a0c71fdd97..65fe2bef4f6 100644 --- a/models/session.go +++ b/models/session.go @@ -24,7 +24,7 @@ func init() { // UpdateSession updates the session with provided id func UpdateSession(key string, data []byte) error { - _, err := db.DefaultContext().Engine().ID(key).Update(&Session{ + _, err := db.GetEngine(db.DefaultContext).ID(key).Update(&Session{ Data: data, Expiry: timeutil.TimeStampNow(), }) @@ -36,7 +36,7 @@ func ReadSession(key string) (*Session, error) { session := Session{ Key: key, } - sess := db.DefaultContext().NewSession() + sess := db.NewSession(db.DefaultContext) defer sess.Close() if err := sess.Begin(); err != nil { return nil, err @@ -60,12 +60,12 @@ func ExistSession(key string) (bool, error) { session := Session{ Key: key, } - return db.DefaultContext().Engine().Get(&session) + return db.GetEngine(db.DefaultContext).Get(&session) } // DestroySession destroys a session func DestroySession(key string) error { - _, err := db.DefaultContext().Engine().Delete(&Session{ + _, err := db.GetEngine(db.DefaultContext).Delete(&Session{ Key: key, }) return err @@ -73,7 +73,7 @@ func DestroySession(key string) error { // RegenerateSession regenerates a session from the old id func RegenerateSession(oldKey, newKey string) (*Session, error) { - sess := db.DefaultContext().NewSession() + sess := db.NewSession(db.DefaultContext) defer sess.Close() if err := sess.Begin(); err != nil { return nil, err @@ -117,11 +117,11 @@ func RegenerateSession(oldKey, newKey string) (*Session, error) { // CountSessions returns the number of sessions func CountSessions() (int64, error) { - return db.DefaultContext().Engine().Count(&Session{}) + return db.GetEngine(db.DefaultContext).Count(&Session{}) } // CleanupSessions cleans up expired sessions func CleanupSessions(maxLifetime int64) error { - _, err := db.DefaultContext().Engine().Where("expiry <= ?", timeutil.TimeStampNow().Add(-maxLifetime)).Delete(&Session{}) + _, err := db.GetEngine(db.DefaultContext).Where("expiry <= ?", timeutil.TimeStampNow().Add(-maxLifetime)).Delete(&Session{}) return err } diff --git a/models/ssh_key.go b/models/ssh_key.go index 04be4ce605e..41016537eb6 100644 --- a/models/ssh_key.go +++ b/models/ssh_key.go @@ -95,7 +95,7 @@ func AddPublicKey(ownerID int64, name, content string, loginSourceID int64) (*Pu return nil, err } - sess := db.DefaultContext().NewSession() + sess := db.NewSession(db.DefaultContext) defer sess.Close() if err = sess.Begin(); err != nil { return nil, err @@ -134,7 +134,7 @@ func AddPublicKey(ownerID int64, name, content string, loginSourceID int64) (*Pu // GetPublicKeyByID returns public key by given ID. func GetPublicKeyByID(keyID int64) (*PublicKey, error) { key := new(PublicKey) - has, err := db.DefaultContext().Engine(). + has, err := db.GetEngine(db.DefaultContext). ID(keyID). Get(key) if err != nil { @@ -161,7 +161,7 @@ func searchPublicKeyByContentWithEngine(e db.Engine, content string) (*PublicKey // SearchPublicKeyByContent searches content as prefix (leak e-mail part) // and returns public key found. func SearchPublicKeyByContent(content string) (*PublicKey, error) { - return searchPublicKeyByContentWithEngine(db.DefaultContext().Engine(), content) + return searchPublicKeyByContentWithEngine(db.GetEngine(db.DefaultContext), content) } func searchPublicKeyByContentExactWithEngine(e db.Engine, content string) (*PublicKey, error) { @@ -180,7 +180,7 @@ func searchPublicKeyByContentExactWithEngine(e db.Engine, content string) (*Publ // SearchPublicKeyByContentExact searches content // and returns public key found. func SearchPublicKeyByContentExact(content string) (*PublicKey, error) { - return searchPublicKeyByContentExactWithEngine(db.DefaultContext().Engine(), content) + return searchPublicKeyByContentExactWithEngine(db.GetEngine(db.DefaultContext), content) } // SearchPublicKey returns a list of public keys matching the provided arguments. @@ -193,12 +193,12 @@ func SearchPublicKey(uid int64, fingerprint string) ([]*PublicKey, error) { if fingerprint != "" { cond = cond.And(builder.Eq{"fingerprint": fingerprint}) } - return keys, db.DefaultContext().Engine().Where(cond).Find(&keys) + return keys, db.GetEngine(db.DefaultContext).Where(cond).Find(&keys) } // ListPublicKeys returns a list of public keys belongs to given user. func ListPublicKeys(uid int64, listOptions ListOptions) ([]*PublicKey, error) { - sess := db.DefaultContext().Engine().Where("owner_id = ? AND type != ?", uid, KeyTypePrincipal) + sess := db.GetEngine(db.DefaultContext).Where("owner_id = ? AND type != ?", uid, KeyTypePrincipal) if listOptions.Page != 0 { sess = setSessionPagination(sess, &listOptions) @@ -212,14 +212,14 @@ func ListPublicKeys(uid int64, listOptions ListOptions) ([]*PublicKey, error) { // CountPublicKeys count public keys a user has func CountPublicKeys(userID int64) (int64, error) { - sess := db.DefaultContext().Engine().Where("owner_id = ? AND type != ?", userID, KeyTypePrincipal) + sess := db.GetEngine(db.DefaultContext).Where("owner_id = ? AND type != ?", userID, KeyTypePrincipal) return sess.Count(&PublicKey{}) } // ListPublicKeysBySource returns a list of synchronized public keys for a given user and login source. func ListPublicKeysBySource(uid, loginSourceID int64) ([]*PublicKey, error) { keys := make([]*PublicKey, 0, 5) - return keys, db.DefaultContext().Engine(). + return keys, db.GetEngine(db.DefaultContext). Where("owner_id = ? AND login_source_id = ?", uid, loginSourceID). Find(&keys) } @@ -228,13 +228,13 @@ func ListPublicKeysBySource(uid, loginSourceID int64) ([]*PublicKey, error) { func UpdatePublicKeyUpdated(id int64) error { // Check if key exists before update as affected rows count is unreliable // and will return 0 affected rows if two updates are made at the same time - if cnt, err := db.DefaultContext().Engine().ID(id).Count(&PublicKey{}); err != nil { + if cnt, err := db.GetEngine(db.DefaultContext).ID(id).Count(&PublicKey{}); err != nil { return err } else if cnt != 1 { return ErrKeyNotExist{id} } - _, err := db.DefaultContext().Engine().ID(id).Cols("updated_unix").Update(&PublicKey{ + _, err := db.GetEngine(db.DefaultContext).ID(id).Cols("updated_unix").Update(&PublicKey{ UpdatedUnix: timeutil.TimeStampNow(), }) if err != nil { @@ -333,7 +333,7 @@ func DeletePublicKey(doer *User, id int64) (err error) { return ErrKeyAccessDenied{doer.ID, key.ID, "public"} } - sess := db.DefaultContext().NewSession() + sess := db.NewSession(db.DefaultContext) defer sess.Close() if err = sess.Begin(); err != nil { return err @@ -358,7 +358,7 @@ func DeletePublicKey(doer *User, id int64) (err error) { // deleteKeysMarkedForDeletion returns true if ssh keys needs update func deleteKeysMarkedForDeletion(keys []string) (bool, error) { // Start session - sess := db.DefaultContext().NewSession() + sess := db.NewSession(db.DefaultContext) defer sess.Close() if err := sess.Begin(); err != nil { return false, err diff --git a/models/ssh_key_authorized_keys.go b/models/ssh_key_authorized_keys.go index e490f211804..ed17a12e9a8 100644 --- a/models/ssh_key_authorized_keys.go +++ b/models/ssh_key_authorized_keys.go @@ -115,10 +115,10 @@ func appendAuthorizedKeysToFile(keys ...*PublicKey) error { } // RewriteAllPublicKeys removes any authorized key and rewrite all keys from database again. -// Note: db.DefaultContext().Engine().Iterate does not get latest data after insert/delete, so we have to call this function +// Note: db.GetEngine(db.DefaultContext).Iterate does not get latest data after insert/delete, so we have to call this function // outside any session scope independently. func RewriteAllPublicKeys() error { - return rewriteAllPublicKeys(db.DefaultContext().Engine()) + return rewriteAllPublicKeys(db.GetEngine(db.DefaultContext)) } func rewriteAllPublicKeys(e db.Engine) error { @@ -179,7 +179,7 @@ func rewriteAllPublicKeys(e db.Engine) error { // RegeneratePublicKeys regenerates the authorized_keys file func RegeneratePublicKeys(t io.StringWriter) error { - return regeneratePublicKeys(db.DefaultContext().Engine(), t) + return regeneratePublicKeys(db.GetEngine(db.DefaultContext), t) } func regeneratePublicKeys(e db.Engine, t io.StringWriter) error { diff --git a/models/ssh_key_authorized_principals.go b/models/ssh_key_authorized_principals.go index c5f7b217858..c053b4b6d55 100644 --- a/models/ssh_key_authorized_principals.go +++ b/models/ssh_key_authorized_principals.go @@ -40,10 +40,10 @@ import ( const authorizedPrincipalsFile = "authorized_principals" // RewriteAllPrincipalKeys removes any authorized principal and rewrite all keys from database again. -// Note: db.DefaultContext().Engine().Iterate does not get latest data after insert/delete, so we have to call this function +// Note: db.GetEngine(db.DefaultContext).Iterate does not get latest data after insert/delete, so we have to call this function // outside any session scope independently. func RewriteAllPrincipalKeys() error { - return rewriteAllPrincipalKeys(db.DefaultContext().Engine()) + return rewriteAllPrincipalKeys(db.GetEngine(db.DefaultContext)) } func rewriteAllPrincipalKeys(e db.Engine) error { @@ -102,7 +102,7 @@ func rewriteAllPrincipalKeys(e db.Engine) error { // RegeneratePrincipalKeys regenerates the authorized_principals file func RegeneratePrincipalKeys(t io.StringWriter) error { - return regeneratePrincipalKeys(db.DefaultContext().Engine(), t) + return regeneratePrincipalKeys(db.GetEngine(db.DefaultContext), t) } func regeneratePrincipalKeys(e db.Engine, t io.StringWriter) error { diff --git a/models/ssh_key_deploy.go b/models/ssh_key_deploy.go index 7aa764522ab..3b9a1682807 100644 --- a/models/ssh_key_deploy.go +++ b/models/ssh_key_deploy.go @@ -107,7 +107,7 @@ func addDeployKey(e *xorm.Session, keyID, repoID int64, name, fingerprint string // HasDeployKey returns true if public key is a deploy key of given repository. func HasDeployKey(keyID, repoID int64) bool { - has, _ := db.DefaultContext().Engine(). + has, _ := db.GetEngine(db.DefaultContext). Where("key_id = ? AND repo_id = ?", keyID, repoID). Get(new(DeployKey)) return has @@ -125,7 +125,7 @@ func AddDeployKey(repoID int64, name, content string, readOnly bool) (*DeployKey accessMode = AccessModeWrite } - sess := db.DefaultContext().NewSession() + sess := db.NewSession(db.DefaultContext) defer sess.Close() if err = sess.Begin(); err != nil { return nil, err @@ -164,7 +164,7 @@ func AddDeployKey(repoID int64, name, content string, readOnly bool) (*DeployKey // GetDeployKeyByID returns deploy key by given ID. func GetDeployKeyByID(id int64) (*DeployKey, error) { - return getDeployKeyByID(db.DefaultContext().Engine(), id) + return getDeployKeyByID(db.GetEngine(db.DefaultContext), id) } func getDeployKeyByID(e db.Engine, id int64) (*DeployKey, error) { @@ -180,7 +180,7 @@ func getDeployKeyByID(e db.Engine, id int64) (*DeployKey, error) { // GetDeployKeyByRepo returns deploy key by given public key ID and repository ID. func GetDeployKeyByRepo(keyID, repoID int64) (*DeployKey, error) { - return getDeployKeyByRepo(db.DefaultContext().Engine(), keyID, repoID) + return getDeployKeyByRepo(db.GetEngine(db.DefaultContext), keyID, repoID) } func getDeployKeyByRepo(e db.Engine, keyID, repoID int64) (*DeployKey, error) { @@ -199,19 +199,19 @@ func getDeployKeyByRepo(e db.Engine, keyID, repoID int64) (*DeployKey, error) { // UpdateDeployKeyCols updates deploy key information in the specified columns. func UpdateDeployKeyCols(key *DeployKey, cols ...string) error { - _, err := db.DefaultContext().Engine().ID(key.ID).Cols(cols...).Update(key) + _, err := db.GetEngine(db.DefaultContext).ID(key.ID).Cols(cols...).Update(key) return err } // UpdateDeployKey updates deploy key information. func UpdateDeployKey(key *DeployKey) error { - _, err := db.DefaultContext().Engine().ID(key.ID).AllCols().Update(key) + _, err := db.GetEngine(db.DefaultContext).ID(key.ID).AllCols().Update(key) return err } // DeleteDeployKey deletes deploy key from its repository authorized_keys file if needed. func DeleteDeployKey(doer *User, id int64) error { - sess := db.DefaultContext().NewSession() + sess := db.NewSession(db.DefaultContext) defer sess.Close() if err := sess.Begin(); err != nil { return err @@ -293,7 +293,7 @@ func (opt ListDeployKeysOptions) toCond() builder.Cond { // ListDeployKeys returns a list of deploy keys matching the provided arguments. func ListDeployKeys(opts *ListDeployKeysOptions) ([]*DeployKey, error) { - return listDeployKeys(db.DefaultContext().Engine(), opts) + return listDeployKeys(db.GetEngine(db.DefaultContext), opts) } func listDeployKeys(e db.Engine, opts *ListDeployKeysOptions) ([]*DeployKey, error) { @@ -312,5 +312,5 @@ func listDeployKeys(e db.Engine, opts *ListDeployKeysOptions) ([]*DeployKey, err // CountDeployKeys returns count deploy keys matching the provided arguments. func CountDeployKeys(opts *ListDeployKeysOptions) (int64, error) { - return db.DefaultContext().Engine().Where(opts.toCond()).Count(&DeployKey{}) + return db.GetEngine(db.DefaultContext).Where(opts.toCond()).Count(&DeployKey{}) } diff --git a/models/ssh_key_principals.go b/models/ssh_key_principals.go index 5f95cf74df0..383693e14ed 100644 --- a/models/ssh_key_principals.go +++ b/models/ssh_key_principals.go @@ -24,7 +24,7 @@ import ( // AddPrincipalKey adds new principal to database and authorized_principals file. func AddPrincipalKey(ownerID int64, content string, loginSourceID int64) (*PublicKey, error) { - sess := db.DefaultContext().NewSession() + sess := db.NewSession(db.DefaultContext) defer sess.Close() if err := sess.Begin(); err != nil { return nil, err @@ -113,7 +113,7 @@ func CheckPrincipalKeyString(user *User, content string) (_ string, err error) { // ListPrincipalKeys returns a list of principals belongs to given user. func ListPrincipalKeys(uid int64, listOptions ListOptions) ([]*PublicKey, error) { - sess := db.DefaultContext().Engine().Where("owner_id = ? AND type = ?", uid, KeyTypePrincipal) + sess := db.GetEngine(db.DefaultContext).Where("owner_id = ? AND type = ?", uid, KeyTypePrincipal) if listOptions.Page != 0 { sess = setSessionPagination(sess, &listOptions) diff --git a/models/star.go b/models/star.go index 2d50a002d7e..ad583f19985 100644 --- a/models/star.go +++ b/models/star.go @@ -23,7 +23,7 @@ func init() { // StarRepo or unstar repository. func StarRepo(userID, repoID int64, star bool) error { - sess := db.DefaultContext().NewSession() + sess := db.NewSession(db.DefaultContext) defer sess.Close() if err := sess.Begin(); err != nil { @@ -65,7 +65,7 @@ func StarRepo(userID, repoID int64, star bool) error { // IsStaring checks if user has starred given repository. func IsStaring(userID, repoID int64) bool { - return isStaring(db.DefaultContext().Engine(), userID, repoID) + return isStaring(db.GetEngine(db.DefaultContext), userID, repoID) } func isStaring(e db.Engine, userID, repoID int64) bool { @@ -75,7 +75,7 @@ func isStaring(e db.Engine, userID, repoID int64) bool { // GetStargazers returns the users that starred the repo. func (repo *Repository) GetStargazers(opts ListOptions) ([]*User, error) { - sess := db.DefaultContext().Engine().Where("star.repo_id = ?", repo.ID). + sess := db.GetEngine(db.DefaultContext).Where("star.repo_id = ?", repo.ID). Join("LEFT", "star", "`user`.id = star.uid") if opts.Page > 0 { sess = setSessionPagination(sess, &opts) @@ -93,7 +93,7 @@ func (u *User) GetStarredRepos(private bool, page, pageSize int, orderBy string) if len(orderBy) == 0 { orderBy = "updated_unix DESC" } - sess := db.DefaultContext().Engine(). + sess := db.GetEngine(db.DefaultContext). Join("INNER", "star", "star.repo_id = repository.id"). Where("star.uid = ?", u.ID). OrderBy(orderBy) @@ -113,7 +113,7 @@ func (u *User) GetStarredRepos(private bool, page, pageSize int, orderBy string) return } - if err = repos.loadAttributes(db.DefaultContext().Engine()); err != nil { + if err = repos.loadAttributes(db.GetEngine(db.DefaultContext)); err != nil { return } @@ -122,7 +122,7 @@ func (u *User) GetStarredRepos(private bool, page, pageSize int, orderBy string) // GetStarredRepoCount returns the numbers of repo the user starred. func (u *User) GetStarredRepoCount(private bool) (int64, error) { - sess := db.DefaultContext().Engine(). + sess := db.GetEngine(db.DefaultContext). Join("INNER", "star", "star.repo_id = repository.id"). Where("star.uid = ?", u.ID) diff --git a/models/statistic.go b/models/statistic.go index 715a10e70d1..d192a971f59 100644 --- a/models/statistic.go +++ b/models/statistic.go @@ -23,12 +23,12 @@ type Statistic struct { func GetStatistic() (stats Statistic) { stats.Counter.User = CountUsers() stats.Counter.Org = CountOrganizations() - stats.Counter.PublicKey, _ = db.DefaultContext().Engine().Count(new(PublicKey)) + stats.Counter.PublicKey, _ = db.GetEngine(db.DefaultContext).Count(new(PublicKey)) stats.Counter.Repo = CountRepositories(true) - stats.Counter.Watch, _ = db.DefaultContext().Engine().Count(new(Watch)) - stats.Counter.Star, _ = db.DefaultContext().Engine().Count(new(Star)) - stats.Counter.Action, _ = db.DefaultContext().Engine().Count(new(Action)) - stats.Counter.Access, _ = db.DefaultContext().Engine().Count(new(Access)) + stats.Counter.Watch, _ = db.GetEngine(db.DefaultContext).Count(new(Watch)) + stats.Counter.Star, _ = db.GetEngine(db.DefaultContext).Count(new(Star)) + stats.Counter.Action, _ = db.GetEngine(db.DefaultContext).Count(new(Action)) + stats.Counter.Access, _ = db.GetEngine(db.DefaultContext).Count(new(Access)) type IssueCount struct { Count int64 @@ -36,7 +36,7 @@ func GetStatistic() (stats Statistic) { } issueCounts := []IssueCount{} - _ = db.DefaultContext().Engine().Select("COUNT(*) AS count, is_closed").Table("issue").GroupBy("is_closed").Find(&issueCounts) + _ = db.GetEngine(db.DefaultContext).Select("COUNT(*) AS count, is_closed").Table("issue").GroupBy("is_closed").Find(&issueCounts) for _, c := range issueCounts { if c.IsClosed { stats.Counter.IssueClosed = c.Count @@ -47,17 +47,17 @@ func GetStatistic() (stats Statistic) { stats.Counter.Issue = stats.Counter.IssueClosed + stats.Counter.IssueOpen - stats.Counter.Comment, _ = db.DefaultContext().Engine().Count(new(Comment)) + stats.Counter.Comment, _ = db.GetEngine(db.DefaultContext).Count(new(Comment)) stats.Counter.Oauth = 0 - stats.Counter.Follow, _ = db.DefaultContext().Engine().Count(new(Follow)) - stats.Counter.Mirror, _ = db.DefaultContext().Engine().Count(new(Mirror)) - stats.Counter.Release, _ = db.DefaultContext().Engine().Count(new(Release)) + stats.Counter.Follow, _ = db.GetEngine(db.DefaultContext).Count(new(Follow)) + stats.Counter.Mirror, _ = db.GetEngine(db.DefaultContext).Count(new(Mirror)) + stats.Counter.Release, _ = db.GetEngine(db.DefaultContext).Count(new(Release)) stats.Counter.LoginSource = CountLoginSources() - stats.Counter.Webhook, _ = db.DefaultContext().Engine().Count(new(Webhook)) - stats.Counter.Milestone, _ = db.DefaultContext().Engine().Count(new(Milestone)) - stats.Counter.Label, _ = db.DefaultContext().Engine().Count(new(Label)) - stats.Counter.HookTask, _ = db.DefaultContext().Engine().Count(new(HookTask)) - stats.Counter.Team, _ = db.DefaultContext().Engine().Count(new(Team)) - stats.Counter.Attachment, _ = db.DefaultContext().Engine().Count(new(Attachment)) + stats.Counter.Webhook, _ = db.GetEngine(db.DefaultContext).Count(new(Webhook)) + stats.Counter.Milestone, _ = db.GetEngine(db.DefaultContext).Count(new(Milestone)) + stats.Counter.Label, _ = db.GetEngine(db.DefaultContext).Count(new(Label)) + stats.Counter.HookTask, _ = db.GetEngine(db.DefaultContext).Count(new(HookTask)) + stats.Counter.Team, _ = db.GetEngine(db.DefaultContext).Count(new(Team)) + stats.Counter.Attachment, _ = db.GetEngine(db.DefaultContext).Count(new(Attachment)) return } diff --git a/models/task.go b/models/task.go index a943834b959..7da9307c959 100644 --- a/models/task.go +++ b/models/task.go @@ -49,7 +49,7 @@ type TranslatableMessage struct { // LoadRepo loads repository of the task func (task *Task) LoadRepo() error { - return task.loadRepo(db.DefaultContext().Engine()) + return task.loadRepo(db.GetEngine(db.DefaultContext)) } func (task *Task) loadRepo(e db.Engine) error { @@ -76,7 +76,7 @@ func (task *Task) LoadDoer() error { } var doer User - has, err := db.DefaultContext().Engine().ID(task.DoerID).Get(&doer) + has, err := db.GetEngine(db.DefaultContext).ID(task.DoerID).Get(&doer) if err != nil { return err } else if !has { @@ -96,7 +96,7 @@ func (task *Task) LoadOwner() error { } var owner User - has, err := db.DefaultContext().Engine().ID(task.OwnerID).Get(&owner) + has, err := db.GetEngine(db.DefaultContext).ID(task.OwnerID).Get(&owner) if err != nil { return err } else if !has { @@ -111,7 +111,7 @@ func (task *Task) LoadOwner() error { // UpdateCols updates some columns func (task *Task) UpdateCols(cols ...string) error { - _, err := db.DefaultContext().Engine().ID(task.ID).Cols(cols...).Update(task) + _, err := db.GetEngine(db.DefaultContext).ID(task.ID).Cols(cols...).Update(task) return err } @@ -170,7 +170,7 @@ func GetMigratingTask(repoID int64) (*Task, error) { RepoID: repoID, Type: structs.TaskTypeMigrateRepo, } - has, err := db.DefaultContext().Engine().Get(&task) + has, err := db.GetEngine(db.DefaultContext).Get(&task) if err != nil { return nil, err } else if !has { @@ -186,7 +186,7 @@ func GetMigratingTaskByID(id, doerID int64) (*Task, *migration.MigrateOptions, e DoerID: doerID, Type: structs.TaskTypeMigrateRepo, } - has, err := db.DefaultContext().Engine().Get(&task) + has, err := db.GetEngine(db.DefaultContext).Get(&task) if err != nil { return nil, nil, err } else if !has { @@ -217,13 +217,13 @@ func (opts FindTaskOptions) ToConds() builder.Cond { // FindTasks find all tasks func FindTasks(opts FindTaskOptions) ([]*Task, error) { tasks := make([]*Task, 0, 10) - err := db.DefaultContext().Engine().Where(opts.ToConds()).Find(&tasks) + err := db.GetEngine(db.DefaultContext).Where(opts.ToConds()).Find(&tasks) return tasks, err } // CreateTask creates a task on database func CreateTask(task *Task) error { - return createTask(db.DefaultContext().Engine(), task) + return createTask(db.GetEngine(db.DefaultContext), task) } func createTask(e db.Engine, task *Task) error { @@ -253,7 +253,7 @@ func FinishMigrateTask(task *Task) error { } task.PayloadContent = string(confBytes) - sess := db.DefaultContext().NewSession() + sess := db.NewSession(db.DefaultContext) defer sess.Close() if err := sess.Begin(); err != nil { return err diff --git a/models/token.go b/models/token.go index 4e1e8f1e88a..48ae7954246 100644 --- a/models/token.go +++ b/models/token.go @@ -69,7 +69,7 @@ func NewAccessToken(t *AccessToken) error { t.Token = base.EncodeSha1(gouuid.New().String()) t.TokenHash = hashToken(t.Token, t.TokenSalt) t.TokenLastEight = t.Token[len(t.Token)-8:] - _, err = db.DefaultContext().Engine().Insert(t) + _, err = db.GetEngine(db.DefaultContext).Insert(t) return err } @@ -110,7 +110,7 @@ func GetAccessTokenBySHA(token string) (*AccessToken, error) { TokenLastEight: lastEight, } // Re-get the token from the db in case it has been deleted in the intervening period - has, err := db.DefaultContext().Engine().ID(id).Get(token) + has, err := db.GetEngine(db.DefaultContext).ID(id).Get(token) if err != nil { return nil, err } @@ -121,7 +121,7 @@ func GetAccessTokenBySHA(token string) (*AccessToken, error) { } var tokens []AccessToken - err := db.DefaultContext().Engine().Table(&AccessToken{}).Where("token_last_eight = ?", lastEight).Find(&tokens) + err := db.GetEngine(db.DefaultContext).Table(&AccessToken{}).Where("token_last_eight = ?", lastEight).Find(&tokens) if err != nil { return nil, err } else if len(tokens) == 0 { @@ -142,7 +142,7 @@ func GetAccessTokenBySHA(token string) (*AccessToken, error) { // AccessTokenByNameExists checks if a token name has been used already by a user. func AccessTokenByNameExists(token *AccessToken) (bool, error) { - return db.DefaultContext().Engine().Table("access_token").Where("name = ?", token.Name).And("uid = ?", token.UID).Exist() + return db.GetEngine(db.DefaultContext).Table("access_token").Where("name = ?", token.Name).And("uid = ?", token.UID).Exist() } // ListAccessTokensOptions contain filter options @@ -154,7 +154,7 @@ type ListAccessTokensOptions struct { // ListAccessTokens returns a list of access tokens belongs to given user. func ListAccessTokens(opts ListAccessTokensOptions) ([]*AccessToken, error) { - sess := db.DefaultContext().Engine().Where("uid=?", opts.UserID) + sess := db.GetEngine(db.DefaultContext).Where("uid=?", opts.UserID) if len(opts.Name) != 0 { sess = sess.Where("name=?", opts.Name) @@ -175,13 +175,13 @@ func ListAccessTokens(opts ListAccessTokensOptions) ([]*AccessToken, error) { // UpdateAccessToken updates information of access token. func UpdateAccessToken(t *AccessToken) error { - _, err := db.DefaultContext().Engine().ID(t.ID).AllCols().Update(t) + _, err := db.GetEngine(db.DefaultContext).ID(t.ID).AllCols().Update(t) return err } // CountAccessTokens count access tokens belongs to given user by options func CountAccessTokens(opts ListAccessTokensOptions) (int64, error) { - sess := db.DefaultContext().Engine().Where("uid=?", opts.UserID) + sess := db.GetEngine(db.DefaultContext).Where("uid=?", opts.UserID) if len(opts.Name) != 0 { sess = sess.Where("name=?", opts.Name) } @@ -190,7 +190,7 @@ func CountAccessTokens(opts ListAccessTokensOptions) (int64, error) { // DeleteAccessTokenByID deletes access token by given ID. func DeleteAccessTokenByID(id, userID int64) error { - cnt, err := db.DefaultContext().Engine().ID(id).Delete(&AccessToken{ + cnt, err := db.GetEngine(db.DefaultContext).ID(id).Delete(&AccessToken{ UID: userID, }) if err != nil { diff --git a/models/topic.go b/models/topic.go index 4b219cc0eba..cf563e9b11c 100644 --- a/models/topic.go +++ b/models/topic.go @@ -88,7 +88,7 @@ func SanitizeAndValidateTopics(topics []string) (validTopics, invalidTopics []st // GetTopicByName retrieves topic by name func GetTopicByName(name string) (*Topic, error) { var topic Topic - if has, err := db.DefaultContext().Engine().Where("name = ?", name).Get(&topic); err != nil { + if has, err := db.GetEngine(db.DefaultContext).Where("name = ?", name).Get(&topic); err != nil { return nil, err } else if !has { return nil, ErrTopicNotExist{name} @@ -184,7 +184,7 @@ func (opts *FindTopicOptions) toConds() builder.Cond { // FindTopics retrieves the topics via FindTopicOptions func FindTopics(opts *FindTopicOptions) ([]*Topic, int64, error) { - sess := db.DefaultContext().Engine().Select("topic.*").Where(opts.toConds()) + sess := db.GetEngine(db.DefaultContext).Select("topic.*").Where(opts.toConds()) if opts.RepoID > 0 { sess.Join("INNER", "repo_topic", "repo_topic.topic_id = topic.id") } @@ -198,7 +198,7 @@ func FindTopics(opts *FindTopicOptions) ([]*Topic, int64, error) { // CountTopics counts the number of topics matching the FindTopicOptions func CountTopics(opts *FindTopicOptions) (int64, error) { - sess := db.DefaultContext().Engine().Where(opts.toConds()) + sess := db.GetEngine(db.DefaultContext).Where(opts.toConds()) if opts.RepoID > 0 { sess.Join("INNER", "repo_topic", "repo_topic.topic_id = topic.id") } @@ -207,7 +207,7 @@ func CountTopics(opts *FindTopicOptions) (int64, error) { // GetRepoTopicByName retrieves topic from name for a repo if it exist func GetRepoTopicByName(repoID int64, topicName string) (*Topic, error) { - return getRepoTopicByName(db.DefaultContext().Engine(), repoID, topicName) + return getRepoTopicByName(db.GetEngine(db.DefaultContext), repoID, topicName) } func getRepoTopicByName(e db.Engine, repoID int64, topicName string) (*Topic, error) { @@ -225,7 +225,7 @@ func getRepoTopicByName(e db.Engine, repoID int64, topicName string) (*Topic, er // AddTopic adds a topic name to a repository (if it does not already have it) func AddTopic(repoID int64, topicName string) (*Topic, error) { - sess := db.DefaultContext().NewSession() + sess := db.NewSession(db.DefaultContext) defer sess.Close() if err := sess.Begin(); err != nil { return nil, err @@ -272,7 +272,7 @@ func DeleteTopic(repoID int64, topicName string) (*Topic, error) { return nil, nil } - err = removeTopicFromRepo(db.DefaultContext().Engine(), repoID, topic) + err = removeTopicFromRepo(db.GetEngine(db.DefaultContext), repoID, topic) return topic, err } @@ -286,7 +286,7 @@ func SaveTopics(repoID int64, topicNames ...string) error { return err } - sess := db.DefaultContext().NewSession() + sess := db.NewSession(db.DefaultContext) defer sess.Close() if err := sess.Begin(); err != nil { diff --git a/models/twofactor.go b/models/twofactor.go index f2443e04cec..dd7fde77e21 100644 --- a/models/twofactor.go +++ b/models/twofactor.go @@ -93,13 +93,13 @@ func (t *TwoFactor) ValidateTOTP(passcode string) (bool, error) { // NewTwoFactor creates a new two-factor authentication token. func NewTwoFactor(t *TwoFactor) error { - _, err := db.DefaultContext().Engine().Insert(t) + _, err := db.GetEngine(db.DefaultContext).Insert(t) return err } // UpdateTwoFactor updates a two-factor authentication token. func UpdateTwoFactor(t *TwoFactor) error { - _, err := db.DefaultContext().Engine().ID(t.ID).AllCols().Update(t) + _, err := db.GetEngine(db.DefaultContext).ID(t.ID).AllCols().Update(t) return err } @@ -107,7 +107,7 @@ func UpdateTwoFactor(t *TwoFactor) error { // the user, if any. func GetTwoFactorByUID(uid int64) (*TwoFactor, error) { twofa := &TwoFactor{} - has, err := db.DefaultContext().Engine().Where("uid=?", uid).Get(twofa) + has, err := db.GetEngine(db.DefaultContext).Where("uid=?", uid).Get(twofa) if err != nil { return nil, err } else if !has { @@ -118,7 +118,7 @@ func GetTwoFactorByUID(uid int64) (*TwoFactor, error) { // DeleteTwoFactorByID deletes two-factor authentication token by given ID. func DeleteTwoFactorByID(id, userID int64) error { - cnt, err := db.DefaultContext().Engine().ID(id).Delete(&TwoFactor{ + cnt, err := db.GetEngine(db.DefaultContext).ID(id).Delete(&TwoFactor{ UID: userID, }) if err != nil { diff --git a/models/u2f.go b/models/u2f.go index 66943f8dd2c..17b82956263 100644 --- a/models/u2f.go +++ b/models/u2f.go @@ -45,7 +45,7 @@ func (reg *U2FRegistration) updateCounter(e db.Engine) error { // UpdateCounter will update the database value of counter func (reg *U2FRegistration) UpdateCounter() error { - return reg.updateCounter(db.DefaultContext().Engine()) + return reg.updateCounter(db.GetEngine(db.DefaultContext)) } // U2FRegistrationList is a list of *U2FRegistration @@ -73,7 +73,7 @@ func getU2FRegistrationsByUID(e db.Engine, uid int64) (U2FRegistrationList, erro // GetU2FRegistrationByID returns U2F registration by id func GetU2FRegistrationByID(id int64) (*U2FRegistration, error) { - return getU2FRegistrationByID(db.DefaultContext().Engine(), id) + return getU2FRegistrationByID(db.GetEngine(db.DefaultContext), id) } func getU2FRegistrationByID(e db.Engine, id int64) (*U2FRegistration, error) { @@ -88,7 +88,7 @@ func getU2FRegistrationByID(e db.Engine, id int64) (*U2FRegistration, error) { // GetU2FRegistrationsByUID returns all U2F registrations of the given user func GetU2FRegistrationsByUID(uid int64) (U2FRegistrationList, error) { - return getU2FRegistrationsByUID(db.DefaultContext().Engine(), uid) + return getU2FRegistrationsByUID(db.GetEngine(db.DefaultContext), uid) } func createRegistration(e db.Engine, user *User, name string, reg *u2f.Registration) (*U2FRegistration, error) { @@ -111,12 +111,12 @@ func createRegistration(e db.Engine, user *User, name string, reg *u2f.Registrat // CreateRegistration will create a new U2FRegistration from the given Registration func CreateRegistration(user *User, name string, reg *u2f.Registration) (*U2FRegistration, error) { - return createRegistration(db.DefaultContext().Engine(), user, name, reg) + return createRegistration(db.GetEngine(db.DefaultContext), user, name, reg) } // DeleteRegistration will delete U2FRegistration func DeleteRegistration(reg *U2FRegistration) error { - return deleteRegistration(db.DefaultContext().Engine(), reg) + return deleteRegistration(db.GetEngine(db.DefaultContext), reg) } func deleteRegistration(e db.Engine, reg *U2FRegistration) error { diff --git a/models/update.go b/models/update.go index 0fb73ac8919..0898ab54c12 100644 --- a/models/update.go +++ b/models/update.go @@ -5,6 +5,7 @@ package models import ( + "context" "fmt" "strings" @@ -12,8 +13,8 @@ import ( ) // PushUpdateDeleteTagsContext updates a number of delete tags with context -func PushUpdateDeleteTagsContext(ctx *db.Context, repo *Repository, tags []string) error { - return pushUpdateDeleteTags(ctx.Engine(), repo, tags) +func PushUpdateDeleteTagsContext(ctx context.Context, repo *Repository, tags []string) error { + return pushUpdateDeleteTags(db.GetEngine(ctx), repo, tags) } func pushUpdateDeleteTags(e db.Engine, repo *Repository, tags []string) error { @@ -55,14 +56,14 @@ func PushUpdateDeleteTag(repo *Repository, tagName string) error { return fmt.Errorf("GetRelease: %v", err) } if rel.IsTag { - if _, err = db.DefaultContext().Engine().ID(rel.ID).Delete(new(Release)); err != nil { + if _, err = db.GetEngine(db.DefaultContext).ID(rel.ID).Delete(new(Release)); err != nil { return fmt.Errorf("Delete: %v", err) } } else { rel.IsDraft = true rel.NumCommits = 0 rel.Sha1 = "" - if _, err = db.DefaultContext().Engine().ID(rel.ID).AllCols().Update(rel); err != nil { + if _, err = db.GetEngine(db.DefaultContext).ID(rel.ID).AllCols().Update(rel); err != nil { return fmt.Errorf("Update: %v", err) } } @@ -79,7 +80,7 @@ func SaveOrUpdateTag(repo *Repository, newRel *Release) error { if rel == nil { rel = newRel - if _, err = db.DefaultContext().Engine().Insert(rel); err != nil { + if _, err = db.GetEngine(db.DefaultContext).Insert(rel); err != nil { return fmt.Errorf("InsertOne: %v", err) } } else { @@ -90,7 +91,7 @@ func SaveOrUpdateTag(repo *Repository, newRel *Release) error { if rel.IsTag && newRel.PublisherID > 0 { rel.PublisherID = newRel.PublisherID } - if _, err = db.DefaultContext().Engine().ID(rel.ID).AllCols().Update(rel); err != nil { + if _, err = db.GetEngine(db.DefaultContext).ID(rel.ID).AllCols().Update(rel); err != nil { return fmt.Errorf("Update: %v", err) } } diff --git a/models/upload.go b/models/upload.go index ca88c6a393e..503220db577 100644 --- a/models/upload.go +++ b/models/upload.go @@ -73,7 +73,7 @@ func NewUpload(name string, buf []byte, file multipart.File) (_ *Upload, err err return nil, fmt.Errorf("Copy: %v", err) } - if _, err := db.DefaultContext().Engine().Insert(upload); err != nil { + if _, err := db.GetEngine(db.DefaultContext).Insert(upload); err != nil { return nil, err } @@ -83,7 +83,7 @@ func NewUpload(name string, buf []byte, file multipart.File) (_ *Upload, err err // GetUploadByUUID returns the Upload by UUID func GetUploadByUUID(uuid string) (*Upload, error) { upload := &Upload{} - has, err := db.DefaultContext().Engine().Where("uuid=?", uuid).Get(upload) + has, err := db.GetEngine(db.DefaultContext).Where("uuid=?", uuid).Get(upload) if err != nil { return nil, err } else if !has { @@ -100,7 +100,7 @@ func GetUploadsByUUIDs(uuids []string) ([]*Upload, error) { // Silently drop invalid uuids. uploads := make([]*Upload, 0, len(uuids)) - return uploads, db.DefaultContext().Engine().In("uuid", uuids).Find(&uploads) + return uploads, db.GetEngine(db.DefaultContext).In("uuid", uuids).Find(&uploads) } // DeleteUploads deletes multiple uploads @@ -109,7 +109,7 @@ func DeleteUploads(uploads ...*Upload) (err error) { return nil } - sess := db.DefaultContext().NewSession() + sess := db.NewSession(db.DefaultContext) defer sess.Close() if err = sess.Begin(); err != nil { return err diff --git a/models/user.go b/models/user.go index a4a3d83166a..fc5d417d360 100644 --- a/models/user.go +++ b/models/user.go @@ -236,7 +236,7 @@ func (u *User) GetEmail() string { // GetAllUsers returns a slice of all individual users found in DB. func GetAllUsers() ([]*User, error) { users := make([]*User, 0) - return users, db.DefaultContext().Engine().OrderBy("id").Where("type = ?", UserTypeIndividual).Find(&users) + return users, db.GetEngine(db.DefaultContext).OrderBy("id").Where("type = ?", UserTypeIndividual).Find(&users) } // IsLocal returns true if user login type is LoginPlain. @@ -332,7 +332,7 @@ func (u *User) GenerateEmailActivateCode(email string) string { // GetFollowers returns range of user's followers. func (u *User) GetFollowers(listOptions ListOptions) ([]*User, error) { - sess := db.DefaultContext().Engine(). + sess := db.GetEngine(db.DefaultContext). Where("follow.follow_id=?", u.ID). Join("LEFT", "follow", "`user`.id=follow.user_id") @@ -354,7 +354,7 @@ func (u *User) IsFollowing(followID int64) bool { // GetFollowing returns range of user's following. func (u *User) GetFollowing(listOptions ListOptions) ([]*User, error) { - sess := db.DefaultContext().Engine(). + sess := db.GetEngine(db.DefaultContext). Where("follow.user_id=?", u.ID). Join("LEFT", "follow", "`user`.id=follow.follow_id") @@ -437,7 +437,7 @@ func (u *User) IsPasswordSet() bool { // IsVisibleToUser check if viewer is able to see user profile func (u *User) IsVisibleToUser(viewer *User) bool { - return u.isVisibleToUser(db.DefaultContext().Engine(), viewer) + return u.isVisibleToUser(db.GetEngine(db.DefaultContext), viewer) } func (u *User) isVisibleToUser(e db.Engine, viewer *User) bool { @@ -465,7 +465,7 @@ func (u *User) isVisibleToUser(e db.Engine, viewer *User) bool { } // Now we need to check if they in some organization together - count, err := db.DefaultContext().Engine().Table("team_user"). + count, err := db.GetEngine(db.DefaultContext).Table("team_user"). Where( builder.And( builder.Eq{"uid": viewer.ID}, @@ -508,7 +508,7 @@ func (u *User) IsUserOrgOwner(orgID int64) bool { // HasMemberWithUserID returns true if user with userID is part of the u organisation. func (u *User) HasMemberWithUserID(userID int64) bool { - return u.hasMemberWithUserID(db.DefaultContext().Engine(), userID) + return u.hasMemberWithUserID(db.GetEngine(db.DefaultContext), userID) } func (u *User) hasMemberWithUserID(e db.Engine, userID int64) bool { @@ -538,7 +538,7 @@ func (u *User) getOrganizationCount(e db.Engine) (int64, error) { // GetOrganizationCount returns count of membership of organization of user. func (u *User) GetOrganizationCount() (int64, error) { - return u.getOrganizationCount(db.DefaultContext().Engine()) + return u.getOrganizationCount(db.GetEngine(db.DefaultContext)) } // GetRepositories returns repositories that user owns, including private repositories. @@ -552,7 +552,7 @@ func (u *User) GetRepositories(listOpts ListOptions, names ...string) (err error func (u *User) GetRepositoryIDs(units ...UnitType) ([]int64, error) { var ids []int64 - sess := db.DefaultContext().Engine().Table("repository").Cols("repository.id") + sess := db.GetEngine(db.DefaultContext).Table("repository").Cols("repository.id") if len(units) > 0 { sess = sess.Join("INNER", "repo_unit", "repository.id = repo_unit.repo_id") @@ -567,7 +567,7 @@ func (u *User) GetRepositoryIDs(units ...UnitType) ([]int64, error) { func (u *User) GetActiveRepositoryIDs(units ...UnitType) ([]int64, error) { var ids []int64 - sess := db.DefaultContext().Engine().Table("repository").Cols("repository.id") + sess := db.GetEngine(db.DefaultContext).Table("repository").Cols("repository.id") if len(units) > 0 { sess = sess.Join("INNER", "repo_unit", "repository.id = repo_unit.repo_id") @@ -584,7 +584,7 @@ func (u *User) GetActiveRepositoryIDs(units ...UnitType) ([]int64, error) { func (u *User) GetOrgRepositoryIDs(units ...UnitType) ([]int64, error) { var ids []int64 - if err := db.DefaultContext().Engine().Table("repository"). + if err := db.GetEngine(db.DefaultContext).Table("repository"). Cols("repository.id"). Join("INNER", "team_user", "repository.owner_id = team_user.org_id"). Join("INNER", "team_repo", "(? != ? and repository.is_private != ?) OR (team_user.team_id = team_repo.team_id AND repository.id = team_repo.repo_id)", true, u.IsRestricted, true). @@ -605,7 +605,7 @@ func (u *User) GetOrgRepositoryIDs(units ...UnitType) ([]int64, error) { func (u *User) GetActiveOrgRepositoryIDs(units ...UnitType) ([]int64, error) { var ids []int64 - if err := db.DefaultContext().Engine().Table("repository"). + if err := db.GetEngine(db.DefaultContext).Table("repository"). Cols("repository.id"). Join("INNER", "team_user", "repository.owner_id = team_user.org_id"). Join("INNER", "team_repo", "(? != ? and repository.is_private != ?) OR (team_user.team_id = team_repo.team_id AND repository.id = team_repo.repo_id)", true, u.IsRestricted, true). @@ -743,7 +743,7 @@ func isUserExist(e db.Engine, uid int64, name string) (bool, error) { // If uid is presented, then check will rule out that one, // it is used when update a user name in settings page. func IsUserExist(uid int64, name string) (bool, error) { - return isUserExist(db.DefaultContext().Engine(), uid, name) + return isUserExist(db.GetEngine(db.DefaultContext), uid, name) } // GetUserSalt returns a random user salt token. @@ -879,7 +879,7 @@ func CreateUser(u *User, overwriteDefault ...*CreateUserOverwriteOptions) (err e u.Visibility = overwriteDefault[0].Visibility } - sess := db.DefaultContext().NewSession() + sess := db.NewSession(db.DefaultContext) defer sess.Close() if err = sess.Begin(); err != nil { return err @@ -949,7 +949,7 @@ func countUsers(e db.Engine) int64 { // CountUsers returns number of users. func CountUsers() int64 { - return countUsers(db.DefaultContext().Engine()) + return countUsers(db.GetEngine(db.DefaultContext)) } // get user by verify code @@ -997,7 +997,7 @@ func VerifyActiveEmailCode(code, email string) *EmailAddress { if base.VerifyTimeLimitCode(data, minutes, prefix) { emailAddress := &EmailAddress{UID: user.ID, Email: email} - if has, _ := db.DefaultContext().Engine().Get(emailAddress); has { + if has, _ := db.GetEngine(db.DefaultContext).Get(emailAddress); has { return emailAddress } } @@ -1012,7 +1012,7 @@ func ChangeUserName(u *User, newUserName string) (err error) { return err } - sess := db.DefaultContext().NewSession() + sess := db.NewSession(db.DefaultContext) defer sess.Close() if err = sess.Begin(); err != nil { return err @@ -1086,12 +1086,12 @@ func updateUser(e db.Engine, u *User) error { // UpdateUser updates user's information. func UpdateUser(u *User) error { - return updateUser(db.DefaultContext().Engine(), u) + return updateUser(db.GetEngine(db.DefaultContext), u) } // UpdateUserCols update user according special columns func UpdateUserCols(u *User, cols ...string) error { - return updateUserCols(db.DefaultContext().Engine(), u, cols...) + return updateUserCols(db.GetEngine(db.DefaultContext), u, cols...) } func updateUserCols(e db.Engine, u *User, cols ...string) error { @@ -1105,7 +1105,7 @@ func updateUserCols(e db.Engine, u *User, cols ...string) error { // UpdateUserSetting updates user's settings. func UpdateUserSetting(u *User) (err error) { - sess := db.DefaultContext().NewSession() + sess := db.NewSession(db.DefaultContext) defer sess.Close() if err = sess.Begin(); err != nil { return err @@ -1311,7 +1311,7 @@ func DeleteUser(u *User) (err error) { return fmt.Errorf("%s is an organization not a user", u.Name) } - sess := db.DefaultContext().NewSession() + sess := db.NewSession(db.DefaultContext) defer sess.Close() if err = sess.Begin(); err != nil { return err @@ -1329,13 +1329,13 @@ func DeleteUser(u *User) (err error) { func DeleteInactiveUsers(ctx context.Context, olderThan time.Duration) (err error) { users := make([]*User, 0, 10) if olderThan > 0 { - if err = db.DefaultContext().Engine(). + if err = db.GetEngine(db.DefaultContext). Where("is_active = ? and created_unix < ?", false, time.Now().Add(-olderThan).Unix()). Find(&users); err != nil { return fmt.Errorf("get all inactive users: %v", err) } } else { - if err = db.DefaultContext().Engine(). + if err = db.GetEngine(db.DefaultContext). Where("is_active = ?", false). Find(&users); err != nil { return fmt.Errorf("get all inactive users: %v", err) @@ -1357,7 +1357,7 @@ func DeleteInactiveUsers(ctx context.Context, olderThan time.Duration) (err erro } } - _, err = db.DefaultContext().Engine(). + _, err = db.GetEngine(db.DefaultContext). Where("is_activated = ?", false). Delete(new(EmailAddress)) return err @@ -1381,12 +1381,12 @@ func getUserByID(e db.Engine, id int64) (*User, error) { // GetUserByID returns the user object by given ID if exists. func GetUserByID(id int64) (*User, error) { - return getUserByID(db.DefaultContext().Engine(), id) + return getUserByID(db.GetEngine(db.DefaultContext), id) } // GetUserByName returns user by given name. func GetUserByName(name string) (*User, error) { - return getUserByName(db.DefaultContext().Engine(), name) + return getUserByName(db.GetEngine(db.DefaultContext), name) } func getUserByName(e db.Engine, name string) (*User, error) { @@ -1406,7 +1406,7 @@ func getUserByName(e db.Engine, name string) (*User, error) { // GetUserEmailsByNames returns a list of e-mails corresponds to names of users // that have their email notifications set to enabled or onmention. func GetUserEmailsByNames(names []string) []string { - return getUserEmailsByNames(db.DefaultContext().Engine(), names) + return getUserEmailsByNames(db.GetEngine(db.DefaultContext), names) } func getUserEmailsByNames(e db.Engine, names []string) []string { @@ -1431,7 +1431,7 @@ func GetMaileableUsersByIDs(ids []int64, isMention bool) ([]*User, error) { ous := make([]*User, 0, len(ids)) if isMention { - return ous, db.DefaultContext().Engine().In("id", ids). + return ous, db.GetEngine(db.DefaultContext).In("id", ids). Where("`type` = ?", UserTypeIndividual). And("`prohibit_login` = ?", false). And("`is_active` = ?", true). @@ -1439,7 +1439,7 @@ func GetMaileableUsersByIDs(ids []int64, isMention bool) ([]*User, error) { Find(&ous) } - return ous, db.DefaultContext().Engine().In("id", ids). + return ous, db.GetEngine(db.DefaultContext).In("id", ids). Where("`type` = ?", UserTypeIndividual). And("`prohibit_login` = ?", false). And("`is_active` = ?", true). @@ -1450,7 +1450,7 @@ func GetMaileableUsersByIDs(ids []int64, isMention bool) ([]*User, error) { // GetUserNamesByIDs returns usernames for all resolved users from a list of Ids. func GetUserNamesByIDs(ids []int64) ([]string, error) { unames := make([]string, 0, len(ids)) - err := db.DefaultContext().Engine().In("id", ids). + err := db.GetEngine(db.DefaultContext).In("id", ids). Table("user"). Asc("name"). Cols("name"). @@ -1464,7 +1464,7 @@ func GetUsersByIDs(ids []int64) (UserList, error) { if len(ids) == 0 { return ous, nil } - err := db.DefaultContext().Engine().In("id", ids). + err := db.GetEngine(db.DefaultContext).In("id", ids). Asc("name"). Find(&ous) return ous, err @@ -1490,7 +1490,7 @@ func GetUserIDsByNames(names []string, ignoreNonExistent bool) ([]int64, error) // GetUsersBySource returns a list of Users for a login source func GetUsersBySource(s *LoginSource) ([]*User, error) { var users []*User - err := db.DefaultContext().Engine().Where("login_type = ? AND login_source = ?", s.Type, s.ID).Find(&users) + err := db.GetEngine(db.DefaultContext).Where("login_type = ? AND login_source = ?", s.Type, s.ID).Find(&users) return users, err } @@ -1539,11 +1539,11 @@ func ValidateCommitsWithEmails(oldCommits []*git.Commit) []*UserCommit { // GetUserByEmail returns the user object by given e-mail if exists. func GetUserByEmail(email string) (*User, error) { - return GetUserByEmailContext(db.DefaultContext(), email) + return GetUserByEmailContext(db.DefaultContext, email) } // GetUserByEmailContext returns the user object by given e-mail if exists with db context -func GetUserByEmailContext(ctx *db.Context, email string) (*User, error) { +func GetUserByEmailContext(ctx context.Context, email string) (*User, error) { if len(email) == 0 { return nil, ErrUserNotExist{0, email, 0} } @@ -1551,7 +1551,7 @@ func GetUserByEmailContext(ctx *db.Context, email string) (*User, error) { email = strings.ToLower(email) // First try to find the user by primary email user := &User{Email: email} - has, err := ctx.Engine().Get(user) + has, err := db.GetEngine(ctx).Get(user) if err != nil { return nil, err } @@ -1561,19 +1561,19 @@ func GetUserByEmailContext(ctx *db.Context, email string) (*User, error) { // Otherwise, check in alternative list for activated email addresses emailAddress := &EmailAddress{Email: email, IsActivated: true} - has, err = ctx.Engine().Get(emailAddress) + has, err = db.GetEngine(ctx).Get(emailAddress) if err != nil { return nil, err } if has { - return getUserByID(ctx.Engine(), emailAddress.UID) + return getUserByID(db.GetEngine(ctx), emailAddress.UID) } // Finally, if email address is the protected email address: if strings.HasSuffix(email, fmt.Sprintf("@%s", setting.Service.NoReplyAddress)) { username := strings.TrimSuffix(email, fmt.Sprintf("@%s", setting.Service.NoReplyAddress)) user := &User{} - has, err := ctx.Engine().Where("lower_name=?", username).Get(user) + has, err := db.GetEngine(ctx).Where("lower_name=?", username).Get(user) if err != nil { return nil, err } @@ -1587,7 +1587,7 @@ func GetUserByEmailContext(ctx *db.Context, email string) (*User, error) { // GetUser checks if a user already exists func GetUser(user *User) (bool, error) { - return db.DefaultContext().Engine().Get(user) + return db.GetEngine(db.DefaultContext).Get(user) } // SearchUserOptions contains the options for searching @@ -1664,7 +1664,7 @@ func (opts *SearchUserOptions) toConds() builder.Cond { // it returns results in given range and number of total results. func SearchUsers(opts *SearchUserOptions) (users []*User, _ int64, _ error) { cond := opts.toConds() - count, err := db.DefaultContext().Engine().Where(cond).Count(new(User)) + count, err := db.GetEngine(db.DefaultContext).Where(cond).Count(new(User)) if err != nil { return nil, 0, fmt.Errorf("Count: %v", err) } @@ -1673,7 +1673,7 @@ func SearchUsers(opts *SearchUserOptions) (users []*User, _ int64, _ error) { opts.OrderBy = SearchOrderByAlphabetically } - sess := db.DefaultContext().Engine().Where(cond).OrderBy(opts.OrderBy.String()) + sess := db.GetEngine(db.DefaultContext).Where(cond).OrderBy(opts.OrderBy.String()) if opts.Page != 0 { sess = setSessionPagination(sess, opts) } @@ -1684,7 +1684,7 @@ func SearchUsers(opts *SearchUserOptions) (users []*User, _ int64, _ error) { // GetStarredRepos returns the repos starred by a particular user func GetStarredRepos(userID int64, private bool, listOptions ListOptions) ([]*Repository, error) { - sess := db.DefaultContext().Engine().Where("star.uid=?", userID). + sess := db.GetEngine(db.DefaultContext).Where("star.uid=?", userID). Join("LEFT", "star", "`repository`.id=`star`.repo_id") if !private { sess = sess.And("is_private=?", false) @@ -1703,7 +1703,7 @@ func GetStarredRepos(userID int64, private bool, listOptions ListOptions) ([]*Re // GetWatchedRepos returns the repos watched by a particular user func GetWatchedRepos(userID int64, private bool, listOptions ListOptions) ([]*Repository, int64, error) { - sess := db.DefaultContext().Engine().Where("watch.user_id=?", userID). + sess := db.GetEngine(db.DefaultContext).Where("watch.user_id=?", userID). And("`watch`.mode<>?", RepoWatchModeDont). Join("LEFT", "watch", "`repository`.id=`watch`.repo_id") if !private { @@ -1729,7 +1729,7 @@ func IterateUser(f func(user *User) error) error { batchSize := setting.Database.IterateBufferSize for { users := make([]*User, 0, batchSize) - if err := db.DefaultContext().Engine().Limit(batchSize, start).Find(&users); err != nil { + if err := db.GetEngine(db.DefaultContext).Limit(batchSize, start).Find(&users); err != nil { return err } if len(users) == 0 { diff --git a/models/user_avatar.go b/models/user_avatar.go index 99e53375884..65e59eb326a 100644 --- a/models/user_avatar.go +++ b/models/user_avatar.go @@ -26,7 +26,7 @@ func (u *User) CustomAvatarRelativePath() string { // GenerateRandomAvatar generates a random avatar for user. func (u *User) GenerateRandomAvatar() error { - return u.generateRandomAvatar(db.DefaultContext().Engine()) + return u.generateRandomAvatar(db.GetEngine(db.DefaultContext)) } func (u *User) generateRandomAvatar(e db.Engine) error { @@ -125,7 +125,7 @@ func (u *User) UploadAvatar(data []byte) error { return err } - sess := db.DefaultContext().NewSession() + sess := db.NewSession(db.DefaultContext) defer sess.Close() if err = sess.Begin(); err != nil { return err @@ -165,7 +165,7 @@ func (u *User) DeleteAvatar() error { u.UseCustomAvatar = false u.Avatar = "" - if _, err := db.DefaultContext().Engine().ID(u.ID).Cols("avatar, use_custom_avatar").Update(u); err != nil { + if _, err := db.GetEngine(db.DefaultContext).ID(u.ID).Cols("avatar, use_custom_avatar").Update(u); err != nil { return fmt.Errorf("UpdateUser: %v", err) } return nil diff --git a/models/user_follow.go b/models/user_follow.go index ceaaaf9103d..8832aa2f18d 100644 --- a/models/user_follow.go +++ b/models/user_follow.go @@ -23,7 +23,7 @@ func init() { // IsFollowing returns true if user is following followID. func IsFollowing(userID, followID int64) bool { - has, _ := db.DefaultContext().Engine().Get(&Follow{UserID: userID, FollowID: followID}) + has, _ := db.GetEngine(db.DefaultContext).Get(&Follow{UserID: userID, FollowID: followID}) return has } @@ -33,7 +33,7 @@ func FollowUser(userID, followID int64) (err error) { return nil } - sess := db.DefaultContext().NewSession() + sess := db.NewSession(db.DefaultContext) defer sess.Close() if err = sess.Begin(); err != nil { return err @@ -59,7 +59,7 @@ func UnfollowUser(userID, followID int64) (err error) { return nil } - sess := db.DefaultContext().NewSession() + sess := db.NewSession(db.DefaultContext) defer sess.Close() if err = sess.Begin(); err != nil { return err diff --git a/models/user_heatmap.go b/models/user_heatmap.go index e713612635a..3e94a6f9b70 100644 --- a/models/user_heatmap.go +++ b/models/user_heatmap.go @@ -59,7 +59,7 @@ func getUserHeatmapData(user *User, team *Team, doer *User) ([]*UserHeatmapData, return nil, err } - return hdata, db.DefaultContext().Engine(). + return hdata, db.GetEngine(db.DefaultContext). Select(groupBy+" AS timestamp, count(user_id) as contributions"). Table("action"). Where(cond). diff --git a/models/user_mail.go b/models/user_mail.go index 169399bc714..51d34d26826 100644 --- a/models/user_mail.go +++ b/models/user_mail.go @@ -58,7 +58,7 @@ func ValidateEmail(email string) error { // GetEmailAddresses returns all email addresses belongs to given user. func GetEmailAddresses(uid int64) ([]*EmailAddress, error) { emails := make([]*EmailAddress, 0, 5) - if err := db.DefaultContext().Engine(). + if err := db.GetEngine(db.DefaultContext). Where("uid=?", uid). Asc("id"). Find(&emails); err != nil { @@ -71,7 +71,7 @@ func GetEmailAddresses(uid int64) ([]*EmailAddress, error) { func GetEmailAddressByID(uid, id int64) (*EmailAddress, error) { // User ID is required for security reasons email := &EmailAddress{UID: uid} - if has, err := db.DefaultContext().Engine().ID(id).Get(email); err != nil { + if has, err := db.GetEngine(db.DefaultContext).ID(id).Get(email); err != nil { return nil, err } else if !has { return nil, nil @@ -114,7 +114,7 @@ func isEmailUsed(e db.Engine, email string) (bool, error) { // IsEmailUsed returns true if the email has been used. func IsEmailUsed(email string) (bool, error) { - return isEmailUsed(db.DefaultContext().Engine(), email) + return isEmailUsed(db.GetEngine(db.DefaultContext), email) } func addEmailAddress(e db.Engine, email *EmailAddress) error { @@ -136,7 +136,7 @@ func addEmailAddress(e db.Engine, email *EmailAddress) error { // AddEmailAddress adds an email address to given user. func AddEmailAddress(email *EmailAddress) error { - return addEmailAddress(db.DefaultContext().Engine(), email) + return addEmailAddress(db.GetEngine(db.DefaultContext), email) } // AddEmailAddresses adds an email address to given user. @@ -159,7 +159,7 @@ func AddEmailAddresses(emails []*EmailAddress) error { } } - if _, err := db.DefaultContext().Engine().Insert(emails); err != nil { + if _, err := db.GetEngine(db.DefaultContext).Insert(emails); err != nil { return fmt.Errorf("Insert: %v", err) } @@ -168,7 +168,7 @@ func AddEmailAddresses(emails []*EmailAddress) error { // Activate activates the email address to given user. func (email *EmailAddress) Activate() error { - sess := db.DefaultContext().NewSession() + sess := db.NewSession(db.DefaultContext) defer sess.Close() if err := sess.Begin(); err != nil { return err @@ -206,12 +206,12 @@ func DeleteEmailAddress(email *EmailAddress) (err error) { UID: email.UID, } if email.ID > 0 { - deleted, err = db.DefaultContext().Engine().ID(email.ID).Delete(&address) + deleted, err = db.GetEngine(db.DefaultContext).ID(email.ID).Delete(&address) } else { if email.Email != "" && email.LowerEmail == "" { email.LowerEmail = strings.ToLower(email.Email) } - deleted, err = db.DefaultContext().Engine(). + deleted, err = db.GetEngine(db.DefaultContext). Where("lower_email=?", email.LowerEmail). Delete(&address) } @@ -237,7 +237,7 @@ func DeleteEmailAddresses(emails []*EmailAddress) (err error) { // MakeEmailPrimary sets primary email address of given user. func MakeEmailPrimary(email *EmailAddress) error { - has, err := db.DefaultContext().Engine().Get(email) + has, err := db.GetEngine(db.DefaultContext).Get(email) if err != nil { return err } else if !has { @@ -249,14 +249,14 @@ func MakeEmailPrimary(email *EmailAddress) error { } user := &User{} - has, err = db.DefaultContext().Engine().ID(email.UID).Get(user) + has, err = db.GetEngine(db.DefaultContext).ID(email.UID).Get(user) if err != nil { return err } else if !has { return ErrUserNotExist{email.UID, "", 0} } - sess := db.DefaultContext().NewSession() + sess := db.NewSession(db.DefaultContext) defer sess.Close() if err = sess.Begin(); err != nil { return err @@ -346,7 +346,7 @@ func SearchEmails(opts *SearchEmailOptions) ([]*SearchEmailResult, int64, error) cond = cond.And(builder.Eq{"email_address.is_activated": false}) } - count, err := db.DefaultContext().Engine().Join("INNER", "`user`", "`user`.ID = email_address.uid"). + count, err := db.GetEngine(db.DefaultContext).Join("INNER", "`user`", "`user`.ID = email_address.uid"). Where(cond).Count(new(EmailAddress)) if err != nil { return nil, 0, fmt.Errorf("Count: %v", err) @@ -360,7 +360,7 @@ func SearchEmails(opts *SearchEmailOptions) ([]*SearchEmailResult, int64, error) opts.setDefaultValues() emails := make([]*SearchEmailResult, 0, opts.PageSize) - err = db.DefaultContext().Engine().Table("email_address"). + err = db.GetEngine(db.DefaultContext).Table("email_address"). Select("email_address.*, `user`.name, `user`.full_name"). Join("INNER", "`user`", "`user`.ID = email_address.uid"). Where(cond). @@ -374,7 +374,7 @@ func SearchEmails(opts *SearchEmailOptions) ([]*SearchEmailResult, int64, error) // ActivateUserEmail will change the activated state of an email address, // either primary or secondary (all in the email_address table) func ActivateUserEmail(userID int64, email string, activate bool) (err error) { - sess := db.DefaultContext().NewSession() + sess := db.NewSession(db.DefaultContext) defer sess.Close() if err = sess.Begin(); err != nil { return err diff --git a/models/user_openid.go b/models/user_openid.go index 4844b68c299..17a58536a23 100644 --- a/models/user_openid.go +++ b/models/user_openid.go @@ -30,7 +30,7 @@ func init() { // GetUserOpenIDs returns all openid addresses that belongs to given user. func GetUserOpenIDs(uid int64) ([]*UserOpenID, error) { openids := make([]*UserOpenID, 0, 5) - if err := db.DefaultContext().Engine(). + if err := db.GetEngine(db.DefaultContext). Where("uid=?", uid). Asc("id"). Find(&openids); err != nil { @@ -64,7 +64,7 @@ func addUserOpenID(e db.Engine, openid *UserOpenID) error { // AddUserOpenID adds an pre-verified/normalized OpenID URI to given user. func AddUserOpenID(openid *UserOpenID) error { - return addUserOpenID(db.DefaultContext().Engine(), openid) + return addUserOpenID(db.GetEngine(db.DefaultContext), openid) } // DeleteUserOpenID deletes an openid address of given user. @@ -75,9 +75,9 @@ func DeleteUserOpenID(openid *UserOpenID) (err error) { UID: openid.UID, } if openid.ID > 0 { - deleted, err = db.DefaultContext().Engine().ID(openid.ID).Delete(&address) + deleted, err = db.GetEngine(db.DefaultContext).ID(openid.ID).Delete(&address) } else { - deleted, err = db.DefaultContext().Engine(). + deleted, err = db.GetEngine(db.DefaultContext). Where("openid=?", openid.URI). Delete(&address) } @@ -92,7 +92,7 @@ func DeleteUserOpenID(openid *UserOpenID) (err error) { // ToggleUserOpenIDVisibility toggles visibility of an openid address of given user. func ToggleUserOpenIDVisibility(id int64) (err error) { - _, err = db.DefaultContext().Engine().Exec("update `user_open_id` set `show` = not `show` where `id` = ?", id) + _, err = db.GetEngine(db.DefaultContext).Exec("update `user_open_id` set `show` = not `show` where `id` = ?", id) return err } @@ -111,7 +111,7 @@ func GetUserByOpenID(uri string) (*User, error) { // Otherwise, check in openid table oid := &UserOpenID{} - has, err := db.DefaultContext().Engine().Where("uri=?", uri).Get(oid) + has, err := db.GetEngine(db.DefaultContext).Where("uri=?", uri).Get(oid) if err != nil { return nil, err } diff --git a/models/user_redirect.go b/models/user_redirect.go index 4380eb5984e..fdc730775f7 100644 --- a/models/user_redirect.go +++ b/models/user_redirect.go @@ -25,7 +25,7 @@ func init() { func LookupUserRedirect(userName string) (int64, error) { userName = strings.ToLower(userName) redirect := &UserRedirect{LowerName: userName} - if has, err := db.DefaultContext().Engine().Get(redirect); err != nil { + if has, err := db.GetEngine(db.DefaultContext).Get(redirect); err != nil { return 0, err } else if !has { return 0, ErrUserRedirectNotExist{Name: userName} diff --git a/models/user_redirect_test.go b/models/user_redirect_test.go index 190778cfbcb..346bf98b846 100644 --- a/models/user_redirect_test.go +++ b/models/user_redirect_test.go @@ -27,7 +27,7 @@ func TestNewUserRedirect(t *testing.T) { assert.NoError(t, db.PrepareTestDatabase()) user := db.AssertExistsAndLoadBean(t, &User{ID: 1}).(*User) - assert.NoError(t, newUserRedirect(db.DefaultContext().Engine(), user.ID, user.Name, "newusername")) + assert.NoError(t, newUserRedirect(db.GetEngine(db.DefaultContext), user.ID, user.Name, "newusername")) db.AssertExistsAndLoadBean(t, &UserRedirect{ LowerName: user.LowerName, @@ -44,7 +44,7 @@ func TestNewUserRedirect2(t *testing.T) { assert.NoError(t, db.PrepareTestDatabase()) user := db.AssertExistsAndLoadBean(t, &User{ID: 1}).(*User) - assert.NoError(t, newUserRedirect(db.DefaultContext().Engine(), user.ID, user.Name, "olduser1")) + assert.NoError(t, newUserRedirect(db.GetEngine(db.DefaultContext), user.ID, user.Name, "olduser1")) db.AssertExistsAndLoadBean(t, &UserRedirect{ LowerName: user.LowerName, @@ -61,7 +61,7 @@ func TestNewUserRedirect3(t *testing.T) { assert.NoError(t, db.PrepareTestDatabase()) user := db.AssertExistsAndLoadBean(t, &User{ID: 2}).(*User) - assert.NoError(t, newUserRedirect(db.DefaultContext().Engine(), user.ID, user.Name, "newusername")) + assert.NoError(t, newUserRedirect(db.GetEngine(db.DefaultContext), user.ID, user.Name, "newusername")) db.AssertExistsAndLoadBean(t, &UserRedirect{ LowerName: user.LowerName, diff --git a/models/user_test.go b/models/user_test.go index aadf7e4c5eb..6c616a60a90 100644 --- a/models/user_test.go +++ b/models/user_test.go @@ -160,7 +160,7 @@ func TestDeleteUser(t *testing.T) { user := db.AssertExistsAndLoadBean(t, &User{ID: userID}).(*User) ownedRepos := make([]*Repository, 0, 10) - assert.NoError(t, db.DefaultContext().Engine().Find(&ownedRepos, &Repository{OwnerID: userID})) + assert.NoError(t, db.GetEngine(db.DefaultContext).Find(&ownedRepos, &Repository{OwnerID: userID})) if len(ownedRepos) > 0 { err := DeleteUser(user) assert.Error(t, err) @@ -169,7 +169,7 @@ func TestDeleteUser(t *testing.T) { } orgUsers := make([]*OrgUser, 0, 10) - assert.NoError(t, db.DefaultContext().Engine().Find(&orgUsers, &OrgUser{UID: userID})) + assert.NoError(t, db.GetEngine(db.DefaultContext).Find(&orgUsers, &OrgUser{UID: userID})) for _, orgUser := range orgUsers { if err := RemoveOrgUser(orgUser.OrgID, orgUser.UID); err != nil { assert.True(t, IsErrLastOrgOwner(err)) @@ -281,7 +281,7 @@ func TestGetOrgRepositoryIDs(t *testing.T) { func TestNewGitSig(t *testing.T) { users := make([]*User, 0, 20) - sess := db.DefaultContext().NewSession() + sess := db.NewSession(db.DefaultContext) defer sess.Close() sess.Find(&users) @@ -296,7 +296,7 @@ func TestNewGitSig(t *testing.T) { func TestDisplayName(t *testing.T) { users := make([]*User, 0, 20) - sess := db.DefaultContext().NewSession() + sess := db.NewSession(db.DefaultContext) defer sess.Close() sess.Find(&users) diff --git a/models/userlist.go b/models/userlist.go index 9741c90ccfa..bfa7ea1e2ea 100644 --- a/models/userlist.go +++ b/models/userlist.go @@ -29,7 +29,7 @@ func (users UserList) IsUserOrgOwner(orgID int64) map[int64]bool { for _, user := range users { results[user.ID] = false // Set default to false } - ownerMaps, err := users.loadOrganizationOwners(db.DefaultContext().Engine(), orgID) + ownerMaps, err := users.loadOrganizationOwners(db.GetEngine(db.DefaultContext), orgID) if err == nil { for _, owner := range ownerMaps { results[owner.UID] = true @@ -69,7 +69,7 @@ func (users UserList) GetTwoFaStatus() map[int64]bool { for _, user := range users { results[user.ID] = false // Set default to false } - tokenMaps, err := users.loadTwoFactorStatus(db.DefaultContext().Engine()) + tokenMaps, err := users.loadTwoFactorStatus(db.GetEngine(db.DefaultContext)) if err == nil { for _, token := range tokenMaps { results[token.UID] = true diff --git a/models/webhook.go b/models/webhook.go index fca6eec67e9..034b37263aa 100644 --- a/models/webhook.go +++ b/models/webhook.go @@ -351,7 +351,7 @@ func (w *Webhook) EventsArray() []string { // CreateWebhook creates a new web hook. func CreateWebhook(w *Webhook) error { - return createWebhook(db.DefaultContext().Engine(), w) + return createWebhook(db.GetEngine(db.DefaultContext), w) } func createWebhook(e db.Engine, w *Webhook) error { @@ -363,7 +363,7 @@ func createWebhook(e db.Engine, w *Webhook) error { // getWebhook uses argument bean as query condition, // ID must be specified and do not assign unnecessary fields. func getWebhook(bean *Webhook) (*Webhook, error) { - has, err := db.DefaultContext().Engine().Get(bean) + has, err := db.GetEngine(db.DefaultContext).Get(bean) if err != nil { return nil, err } else if !has { @@ -434,17 +434,17 @@ func listWebhooksByOpts(e db.Engine, opts *ListWebhookOptions) ([]*Webhook, erro // ListWebhooksByOpts return webhooks based on options func ListWebhooksByOpts(opts *ListWebhookOptions) ([]*Webhook, error) { - return listWebhooksByOpts(db.DefaultContext().Engine(), opts) + return listWebhooksByOpts(db.GetEngine(db.DefaultContext), opts) } // CountWebhooksByOpts count webhooks based on options and ignore pagination func CountWebhooksByOpts(opts *ListWebhookOptions) (int64, error) { - return db.DefaultContext().Engine().Where(opts.toCond()).Count(&Webhook{}) + return db.GetEngine(db.DefaultContext).Where(opts.toCond()).Count(&Webhook{}) } // GetDefaultWebhooks returns all admin-default webhooks. func GetDefaultWebhooks() ([]*Webhook, error) { - return getDefaultWebhooks(db.DefaultContext().Engine()) + return getDefaultWebhooks(db.GetEngine(db.DefaultContext)) } func getDefaultWebhooks(e db.Engine) ([]*Webhook, error) { @@ -457,7 +457,7 @@ func getDefaultWebhooks(e db.Engine) ([]*Webhook, error) { // GetSystemOrDefaultWebhook returns admin system or default webhook by given ID. func GetSystemOrDefaultWebhook(id int64) (*Webhook, error) { webhook := &Webhook{ID: id} - has, err := db.DefaultContext().Engine(). + has, err := db.GetEngine(db.DefaultContext). Where("repo_id=? AND org_id=?", 0, 0). Get(webhook) if err != nil { @@ -470,7 +470,7 @@ func GetSystemOrDefaultWebhook(id int64) (*Webhook, error) { // GetSystemWebhooks returns all admin system webhooks. func GetSystemWebhooks() ([]*Webhook, error) { - return getSystemWebhooks(db.DefaultContext().Engine()) + return getSystemWebhooks(db.GetEngine(db.DefaultContext)) } func getSystemWebhooks(e db.Engine) ([]*Webhook, error) { @@ -482,20 +482,20 @@ func getSystemWebhooks(e db.Engine) ([]*Webhook, error) { // UpdateWebhook updates information of webhook. func UpdateWebhook(w *Webhook) error { - _, err := db.DefaultContext().Engine().ID(w.ID).AllCols().Update(w) + _, err := db.GetEngine(db.DefaultContext).ID(w.ID).AllCols().Update(w) return err } // UpdateWebhookLastStatus updates last status of webhook. func UpdateWebhookLastStatus(w *Webhook) error { - _, err := db.DefaultContext().Engine().ID(w.ID).Cols("last_status").Update(w) + _, err := db.GetEngine(db.DefaultContext).ID(w.ID).Cols("last_status").Update(w) return err } // deleteWebhook uses argument bean as query condition, // ID must be specified and do not assign unnecessary fields. func deleteWebhook(bean *Webhook) (err error) { - sess := db.DefaultContext().NewSession() + sess := db.NewSession(db.DefaultContext) defer sess.Close() if err = sess.Begin(); err != nil { return err @@ -530,7 +530,7 @@ func DeleteWebhookByOrgID(orgID, id int64) error { // DeleteDefaultSystemWebhook deletes an admin-configured default or system webhook (where Org and Repo ID both 0) func DeleteDefaultSystemWebhook(id int64) error { - sess := db.DefaultContext().NewSession() + sess := db.NewSession(db.DefaultContext) defer sess.Close() if err := sess.Begin(); err != nil { return err @@ -713,7 +713,7 @@ func (t *HookTask) simpleMarshalJSON(v interface{}) string { // HookTasks returns a list of hook tasks by given conditions. func HookTasks(hookID int64, page int) ([]*HookTask, error) { tasks := make([]*HookTask, 0, setting.Webhook.PagingNum) - return tasks, db.DefaultContext().Engine(). + return tasks, db.GetEngine(db.DefaultContext). Limit(setting.Webhook.PagingNum, (page-1)*setting.Webhook.PagingNum). Where("hook_id=?", hookID). Desc("id"). @@ -723,7 +723,7 @@ func HookTasks(hookID int64, page int) ([]*HookTask, error) { // CreateHookTask creates a new hook task, // it handles conversion from Payload to PayloadContent. func CreateHookTask(t *HookTask) error { - return createHookTask(db.DefaultContext().Engine(), t) + return createHookTask(db.GetEngine(db.DefaultContext), t) } func createHookTask(e db.Engine, t *HookTask) error { @@ -739,14 +739,14 @@ func createHookTask(e db.Engine, t *HookTask) error { // UpdateHookTask updates information of hook task. func UpdateHookTask(t *HookTask) error { - _, err := db.DefaultContext().Engine().ID(t.ID).AllCols().Update(t) + _, err := db.GetEngine(db.DefaultContext).ID(t.ID).AllCols().Update(t) return err } // FindUndeliveredHookTasks represents find the undelivered hook tasks func FindUndeliveredHookTasks() ([]*HookTask, error) { tasks := make([]*HookTask, 0, 10) - if err := db.DefaultContext().Engine().Where("is_delivered=?", false).Find(&tasks); err != nil { + if err := db.GetEngine(db.DefaultContext).Where("is_delivered=?", false).Find(&tasks); err != nil { return nil, err } return tasks, nil @@ -755,7 +755,7 @@ func FindUndeliveredHookTasks() ([]*HookTask, error) { // FindRepoUndeliveredHookTasks represents find the undelivered hook tasks of one repository func FindRepoUndeliveredHookTasks(repoID int64) ([]*HookTask, error) { tasks := make([]*HookTask, 0, 5) - if err := db.DefaultContext().Engine().Where("repo_id=? AND is_delivered=?", repoID, false).Find(&tasks); err != nil { + if err := db.GetEngine(db.DefaultContext).Where("repo_id=? AND is_delivered=?", repoID, false).Find(&tasks); err != nil { return nil, err } return tasks, nil @@ -767,7 +767,7 @@ func CleanupHookTaskTable(ctx context.Context, cleanupType HookTaskCleanupType, if cleanupType == OlderThan { deleteOlderThan := time.Now().Add(-olderThan).UnixNano() - deletes, err := db.DefaultContext().Engine(). + deletes, err := db.GetEngine(db.DefaultContext). Where("is_delivered = ? and delivered < ?", true, deleteOlderThan). Delete(new(HookTask)) if err != nil { @@ -776,7 +776,7 @@ func CleanupHookTaskTable(ctx context.Context, cleanupType HookTaskCleanupType, log.Trace("Deleted %d rows from hook_task", deletes) } else if cleanupType == PerWebhook { hookIDs := make([]int64, 0, 10) - err := db.DefaultContext().Engine().Table("webhook"). + err := db.GetEngine(db.DefaultContext).Table("webhook"). Where("id > 0"). Cols("id"). Find(&hookIDs) @@ -801,7 +801,7 @@ func CleanupHookTaskTable(ctx context.Context, cleanupType HookTaskCleanupType, func deleteDeliveredHookTasksByWebhook(hookID int64, numberDeliveriesToKeep int) error { log.Trace("Deleting hook_task rows for webhook %d, keeping the most recent %d deliveries", hookID, numberDeliveriesToKeep) deliveryDates := make([]int64, 0, 10) - err := db.DefaultContext().Engine().Table("hook_task"). + err := db.GetEngine(db.DefaultContext).Table("hook_task"). Where("hook_task.hook_id = ? AND hook_task.is_delivered = ? AND hook_task.delivered is not null", hookID, true). Cols("hook_task.delivered"). Join("INNER", "webhook", "hook_task.hook_id = webhook.id"). @@ -813,7 +813,7 @@ func deleteDeliveredHookTasksByWebhook(hookID int64, numberDeliveriesToKeep int) } if len(deliveryDates) > 0 { - deletes, err := db.DefaultContext().Engine(). + deletes, err := db.GetEngine(db.DefaultContext). Where("hook_id = ? and is_delivered = ? and delivered <= ?", hookID, true, deliveryDates[0]). Delete(new(HookTask)) if err != nil { diff --git a/modules/doctor/mergebase.go b/modules/doctor/mergebase.go index e792c2b2fdd..c959da8d7f5 100644 --- a/modules/doctor/mergebase.go +++ b/modules/doctor/mergebase.go @@ -18,7 +18,7 @@ import ( func iteratePRs(repo *models.Repository, each func(*models.Repository, *models.PullRequest) error) error { return db.Iterate( - db.DefaultContext(), + db.DefaultContext, new(models.PullRequest), builder.Eq{"base_repo_id": repo.ID}, func(idx int, bean interface{}) error { diff --git a/modules/doctor/misc.go b/modules/doctor/misc.go index 25bc3c3a726..2f748bcb718 100644 --- a/modules/doctor/misc.go +++ b/modules/doctor/misc.go @@ -26,7 +26,7 @@ import ( func iterateRepositories(each func(*models.Repository) error) error { err := db.Iterate( - db.DefaultContext(), + db.DefaultContext, new(models.Repository), builder.Gt{"id": 0}, func(idx int, bean interface{}) error { diff --git a/modules/repository/adopt.go b/modules/repository/adopt.go index 9371822fbcc..daefee9c746 100644 --- a/modules/repository/adopt.go +++ b/modules/repository/adopt.go @@ -5,6 +5,7 @@ package repository import ( + "context" "fmt" "os" "path/filepath" @@ -47,7 +48,7 @@ func AdoptRepository(doer, u *models.User, opts models.CreateRepoOptions) (*mode IsEmpty: !opts.AutoInit, } - if err := db.WithTx(func(ctx *db.Context) error { + if err := db.WithTx(func(ctx context.Context) error { repoPath := models.RepoPath(u.Name, repo.Name) isExist, err := util.IsExist(repoPath) if err != nil { diff --git a/modules/repository/check.go b/modules/repository/check.go index 1b550ad4f08..78e6f8a9013 100644 --- a/modules/repository/check.go +++ b/modules/repository/check.go @@ -24,7 +24,7 @@ func GitFsck(ctx context.Context, timeout time.Duration, args []string) error { log.Trace("Doing: GitFsck") if err := db.Iterate( - db.DefaultContext(), + db.DefaultContext, new(models.Repository), builder.Expr("id>0 AND is_fsck_enabled=?", true), func(idx int, bean interface{}) error { @@ -59,7 +59,7 @@ func GitGcRepos(ctx context.Context, timeout time.Duration, args ...string) erro args = append([]string{"gc"}, args...) if err := db.Iterate( - db.DefaultContext(), + db.DefaultContext, new(models.Repository), builder.Gt{"id": 0}, func(idx int, bean interface{}) error { @@ -94,7 +94,7 @@ func GitGcRepos(ctx context.Context, timeout time.Duration, args ...string) erro } // Now update the size of the repository - if err := repo.UpdateSize(db.DefaultContext()); err != nil { + if err := repo.UpdateSize(db.DefaultContext); err != nil { log.Error("Updating size as part of garbage collection failed for %v. Stdout: %s\nError: %v", repo, stdout, err) desc := fmt.Sprintf("Updating size as part of garbage collection failed for %s. Stdout: %s\nError: %v", repo.RepoPath(), stdout, err) if err = models.CreateRepositoryNotice(desc); err != nil { @@ -116,7 +116,7 @@ func GitGcRepos(ctx context.Context, timeout time.Duration, args ...string) erro func gatherMissingRepoRecords(ctx context.Context) ([]*models.Repository, error) { repos := make([]*models.Repository, 0, 10) if err := db.Iterate( - db.DefaultContext(), + db.DefaultContext, new(models.Repository), builder.Gt{"id": 0}, func(idx int, bean interface{}) error { diff --git a/modules/repository/create.go b/modules/repository/create.go index 80f446e83f0..0e91a73b835 100644 --- a/modules/repository/create.go +++ b/modules/repository/create.go @@ -5,6 +5,7 @@ package repository import ( + "context" "fmt" "strings" @@ -55,7 +56,7 @@ func CreateRepository(doer, u *models.User, opts models.CreateRepoOptions) (*mod var rollbackRepo *models.Repository - if err := db.WithTx(func(ctx *db.Context) error { + if err := db.WithTx(func(ctx context.Context) error { if err := models.CreateRepository(ctx, doer, u, repo, false); err != nil { return err } diff --git a/modules/repository/fork.go b/modules/repository/fork.go index ff69f75b32a..59c07271a64 100644 --- a/modules/repository/fork.go +++ b/modules/repository/fork.go @@ -5,6 +5,7 @@ package repository import ( + "context" "fmt" "strings" "time" @@ -79,7 +80,7 @@ func ForkRepository(doer, owner *models.User, opts models.ForkRepoOptions) (_ *m panic(panicErr) }() - err = db.WithTx(func(ctx *db.Context) error { + err = db.WithTx(func(ctx context.Context) error { if err = models.CreateRepository(ctx, doer, owner, repo, false); err != nil { return err } @@ -123,7 +124,7 @@ func ForkRepository(doer, owner *models.User, opts models.ForkRepoOptions) (_ *m } // even if below operations failed, it could be ignored. And they will be retried - ctx := db.DefaultContext() + ctx := db.DefaultContext if err := repo.UpdateSize(ctx); err != nil { log.Error("Failed to update size for repository: %v", err) } @@ -136,7 +137,7 @@ func ForkRepository(doer, owner *models.User, opts models.ForkRepoOptions) (_ *m // ConvertForkToNormalRepository convert the provided repo from a forked repo to normal repo func ConvertForkToNormalRepository(repo *models.Repository) error { - err := db.WithTx(func(ctx *db.Context) error { + err := db.WithTx(func(ctx context.Context) error { repo, err := models.GetRepositoryByIDCtx(ctx, repo.ID) if err != nil { return err diff --git a/modules/repository/generate.go b/modules/repository/generate.go index 8ab518add50..4fcebc06dc3 100644 --- a/modules/repository/generate.go +++ b/modules/repository/generate.go @@ -5,6 +5,7 @@ package repository import ( + "context" "fmt" "os" "path" @@ -13,7 +14,6 @@ import ( "time" "code.gitea.io/gitea/models" - "code.gitea.io/gitea/models/db" "code.gitea.io/gitea/modules/git" "code.gitea.io/gitea/modules/log" "code.gitea.io/gitea/modules/util" @@ -185,7 +185,7 @@ func generateRepoCommit(repo, templateRepo, generateRepo *models.Repository, tmp return initRepoCommit(tmpDir, repo, repo.Owner, templateRepo.DefaultBranch) } -func generateGitContent(ctx *db.Context, repo, templateRepo, generateRepo *models.Repository) (err error) { +func generateGitContent(ctx context.Context, repo, templateRepo, generateRepo *models.Repository) (err error) { tmpDir, err := os.MkdirTemp(os.TempDir(), "gitea-"+repo.Name) if err != nil { return fmt.Errorf("Failed to create temp dir for repository %s: %v", repo.RepoPath(), err) @@ -223,7 +223,7 @@ func generateGitContent(ctx *db.Context, repo, templateRepo, generateRepo *model } // GenerateGitContent generates git content from a template repository -func GenerateGitContent(ctx *db.Context, templateRepo, generateRepo *models.Repository) error { +func GenerateGitContent(ctx context.Context, templateRepo, generateRepo *models.Repository) error { if err := generateGitContent(ctx, generateRepo, templateRepo, generateRepo); err != nil { return err } @@ -239,7 +239,7 @@ func GenerateGitContent(ctx *db.Context, templateRepo, generateRepo *models.Repo } // GenerateRepository generates a repository from a template -func GenerateRepository(ctx *db.Context, doer, owner *models.User, templateRepo *models.Repository, opts models.GenerateRepoOptions) (_ *models.Repository, err error) { +func GenerateRepository(ctx context.Context, doer, owner *models.User, templateRepo *models.Repository, opts models.GenerateRepoOptions) (_ *models.Repository, err error) { generateRepo := &models.Repository{ OwnerID: owner.ID, Owner: owner, diff --git a/modules/repository/hooks.go b/modules/repository/hooks.go index e219903f75a..6072dda0163 100644 --- a/modules/repository/hooks.go +++ b/modules/repository/hooks.go @@ -221,7 +221,7 @@ func SyncRepositoryHooks(ctx context.Context) error { log.Trace("Doing: SyncRepositoryHooks") if err := db.Iterate( - db.DefaultContext(), + db.DefaultContext, new(models.Repository), builder.Gt{"id": 0}, func(idx int, bean interface{}) error { diff --git a/modules/repository/init.go b/modules/repository/init.go index 2a86e964cac..5a1ff7e98bc 100644 --- a/modules/repository/init.go +++ b/modules/repository/init.go @@ -6,6 +6,7 @@ package repository import ( "bytes" + "context" "fmt" "os" "path/filepath" @@ -13,7 +14,6 @@ import ( "time" "code.gitea.io/gitea/models" - "code.gitea.io/gitea/models/db" "code.gitea.io/gitea/modules/git" "code.gitea.io/gitea/modules/log" "code.gitea.io/gitea/modules/setting" @@ -22,7 +22,7 @@ import ( "github.com/unknwon/com" ) -func prepareRepoCommit(ctx *db.Context, repo *models.Repository, tmpDir, repoPath string, opts models.CreateRepoOptions) error { +func prepareRepoCommit(ctx context.Context, repo *models.Repository, tmpDir, repoPath string, opts models.CreateRepoOptions) error { commitTimeStr := time.Now().Format(time.RFC3339) authorSig := repo.Owner.NewGitSig() @@ -196,7 +196,7 @@ func checkInitRepository(owner, name string) (err error) { return nil } -func adoptRepository(ctx *db.Context, repoPath string, u *models.User, repo *models.Repository, opts models.CreateRepoOptions) (err error) { +func adoptRepository(ctx context.Context, repoPath string, u *models.User, repo *models.Repository, opts models.CreateRepoOptions) (err error) { isExist, err := util.IsExist(repoPath) if err != nil { log.Error("Unable to check if %s exists. Error: %v", repoPath, err) @@ -283,7 +283,7 @@ func adoptRepository(ctx *db.Context, repoPath string, u *models.User, repo *mod } // InitRepository initializes README and .gitignore if needed. -func initRepository(ctx *db.Context, repoPath string, u *models.User, repo *models.Repository, opts models.CreateRepoOptions) (err error) { +func initRepository(ctx context.Context, repoPath string, u *models.User, repo *models.Repository, opts models.CreateRepoOptions) (err error) { if err = checkInitRepository(repo.OwnerName, repo.Name); err != nil { return err } diff --git a/modules/repository/repo.go b/modules/repository/repo.go index b59a80ee2f2..ee970fd711e 100644 --- a/modules/repository/repo.go +++ b/modules/repository/repo.go @@ -133,7 +133,7 @@ func MigrateRepositoryGitData(ctx context.Context, u *models.User, repo *models. } } - if err = repo.UpdateSize(db.DefaultContext()); err != nil { + if err = repo.UpdateSize(db.DefaultContext); err != nil { log.Error("Failed to update size for repository: %v", err) } diff --git a/modules/repository/update.go b/modules/repository/update.go index d9ff12e1ad5..b9a5db2a6a1 100644 --- a/modules/repository/update.go +++ b/modules/repository/update.go @@ -5,6 +5,7 @@ package repository import ( + "context" "fmt" "strings" "time" @@ -17,7 +18,7 @@ import ( // PushUpdateAddDeleteTags updates a number of added and delete tags func PushUpdateAddDeleteTags(repo *models.Repository, gitRepo *git.Repository, addTags, delTags []string) error { - return db.WithTx(func(ctx *db.Context) error { + return db.WithTx(func(ctx context.Context) error { if err := models.PushUpdateDeleteTagsContext(ctx, repo, delTags); err != nil { return err } @@ -26,7 +27,7 @@ func PushUpdateAddDeleteTags(repo *models.Repository, gitRepo *git.Repository, a } // pushUpdateAddTags updates a number of add tags -func pushUpdateAddTags(ctx *db.Context, repo *models.Repository, gitRepo *git.Repository, tags []string) error { +func pushUpdateAddTags(ctx context.Context, repo *models.Repository, gitRepo *git.Repository, tags []string) error { if len(tags) == 0 { return nil } diff --git a/routers/web/org/org_labels.go b/routers/web/org/org_labels.go index 17509c50fe0..13728a31b30 100644 --- a/routers/web/org/org_labels.go +++ b/routers/web/org/org_labels.go @@ -99,7 +99,7 @@ func InitializeLabels(ctx *context.Context) { return } - if err := models.InitializeLabels(db.DefaultContext(), ctx.Org.Organization.ID, form.TemplateName, true); err != nil { + if err := models.InitializeLabels(db.DefaultContext, ctx.Org.Organization.ID, form.TemplateName, true); err != nil { if models.IsErrIssueLabelTemplateLoad(err) { originalErr := err.(models.ErrIssueLabelTemplateLoad).OriginalError ctx.Flash.Error(ctx.Tr("repo.issues.label_templates.fail_to_load_file", form.TemplateName, originalErr)) diff --git a/routers/web/repo/issue_label.go b/routers/web/repo/issue_label.go index daed302dcaa..0ce51144854 100644 --- a/routers/web/repo/issue_label.go +++ b/routers/web/repo/issue_label.go @@ -39,7 +39,7 @@ func InitializeLabels(ctx *context.Context) { return } - if err := models.InitializeLabels(db.DefaultContext(), ctx.Repo.Repository.ID, form.TemplateName, false); err != nil { + if err := models.InitializeLabels(db.DefaultContext, ctx.Repo.Repository.ID, form.TemplateName, false); err != nil { if models.IsErrIssueLabelTemplateLoad(err) { originalErr := err.(models.ErrIssueLabelTemplateLoad).OriginalError ctx.Flash.Error(ctx.Tr("repo.issues.label_templates.fail_to_load_file", form.TemplateName, originalErr)) diff --git a/routers/web/repo/repo.go b/routers/web/repo/repo.go index 46a80524edd..735bf4fe9f0 100644 --- a/routers/web/repo/repo.go +++ b/routers/web/repo/repo.go @@ -343,7 +343,7 @@ func RedirectDownload(ctx *context.Context) { ) tagNames := []string{vTag} curRepo := ctx.Repo.Repository - releases, err := models.GetReleasesByRepoIDAndNames(db.DefaultContext(), curRepo.ID, tagNames) + releases, err := models.GetReleasesByRepoIDAndNames(db.DefaultContext, curRepo.ID, tagNames) if err != nil { if models.IsErrAttachmentNotExist(err) { ctx.Error(http.StatusNotFound) @@ -380,7 +380,7 @@ func Download(ctx *context.Context) { return } - archiver, err := models.GetRepoArchiver(db.DefaultContext(), aReq.RepoID, aReq.Type, aReq.CommitID) + archiver, err := models.GetRepoArchiver(db.DefaultContext, aReq.RepoID, aReq.Type, aReq.CommitID) if err != nil { ctx.ServerError("models.GetRepoArchiver", err) return @@ -410,7 +410,7 @@ func Download(ctx *context.Context) { return } times++ - archiver, err = models.GetRepoArchiver(db.DefaultContext(), aReq.RepoID, aReq.Type, aReq.CommitID) + archiver, err = models.GetRepoArchiver(db.DefaultContext, aReq.RepoID, aReq.Type, aReq.CommitID) if err != nil { ctx.ServerError("archiver_service.StartArchive", err) return @@ -466,7 +466,7 @@ func InitiateDownload(ctx *context.Context) { return } - archiver, err := models.GetRepoArchiver(db.DefaultContext(), aReq.RepoID, aReq.Type, aReq.CommitID) + archiver, err := models.GetRepoArchiver(db.DefaultContext, aReq.RepoID, aReq.Type, aReq.CommitID) if err != nil { ctx.ServerError("archiver_service.StartArchive", err) return diff --git a/services/attachment/attachment.go b/services/attachment/attachment.go index 06f79be01b9..7500a8ac3a6 100644 --- a/services/attachment/attachment.go +++ b/services/attachment/attachment.go @@ -6,6 +6,7 @@ package attachment import ( "bytes" + "context" "fmt" "io" @@ -23,7 +24,7 @@ func NewAttachment(attach *models.Attachment, file io.Reader) (*models.Attachmen return nil, fmt.Errorf("attachment %s should belong to a repository", attach.Name) } - err := db.WithTx(func(ctx *db.Context) error { + err := db.WithTx(func(ctx context.Context) error { attach.UUID = uuid.New().String() size, err := storage.Attachments.Save(attach.RelativePath(), file, -1) if err != nil { diff --git a/services/comments/comments.go b/services/comments/comments.go index 901b82e3801..d65c66aef26 100644 --- a/services/comments/comments.go +++ b/services/comments/comments.go @@ -23,7 +23,7 @@ func CreateIssueComment(doer *models.User, repo *models.Repository, issue *model if err != nil { return nil, err } - mentions, err := issue.FindAndUpdateIssueMentions(db.DefaultContext(), doer, comment.Content) + mentions, err := issue.FindAndUpdateIssueMentions(db.DefaultContext, doer, comment.Content) if err != nil { return nil, err } diff --git a/services/issue/issue.go b/services/issue/issue.go index b2ac24e088e..e3571bd396f 100644 --- a/services/issue/issue.go +++ b/services/issue/issue.go @@ -24,7 +24,7 @@ func NewIssue(repo *models.Repository, issue *models.Issue, labelIDs []int64, uu } } - mentions, err := issue.FindAndUpdateIssueMentions(db.DefaultContext(), issue.Poster, issue.Content) + mentions, err := issue.FindAndUpdateIssueMentions(db.DefaultContext, issue.Poster, issue.Content) if err != nil { return err } diff --git a/services/mirror/mirror_pull.go b/services/mirror/mirror_pull.go index 1c0bf2b5951..c2b413131d1 100644 --- a/services/mirror/mirror_pull.go +++ b/services/mirror/mirror_pull.go @@ -204,7 +204,7 @@ func runSync(ctx context.Context, m *models.Mirror) ([]*mirrorSyncResult, bool) gitRepo.Close() log.Trace("SyncMirrors [repo: %-v]: updating size of repository", m.Repo) - if err := m.Repo.UpdateSize(db.DefaultContext()); err != nil { + if err := m.Repo.UpdateSize(db.DefaultContext); err != nil { log.Error("Failed to update size for mirror repository: %v", err) } diff --git a/services/pull/pull.go b/services/pull/pull.go index d78d9b1bd00..bd5551b6dcc 100644 --- a/services/pull/pull.go +++ b/services/pull/pull.go @@ -59,7 +59,7 @@ func NewPullRequest(repo *models.Repository, pull *models.Issue, labelIDs []int6 return err } - mentions, err := pull.FindAndUpdateIssueMentions(db.DefaultContext(), pull.Poster, pull.Content) + mentions, err := pull.FindAndUpdateIssueMentions(db.DefaultContext, pull.Poster, pull.Content) if err != nil { return err } diff --git a/services/pull/review.go b/services/pull/review.go index ce34cc59dfd..f65314c45d1 100644 --- a/services/pull/review.go +++ b/services/pull/review.go @@ -59,7 +59,7 @@ func CreateCodeComment(doer *models.User, gitRepo *git.Repository, issue *models return nil, err } - mentions, err := issue.FindAndUpdateIssueMentions(db.DefaultContext(), doer, comment.Content) + mentions, err := issue.FindAndUpdateIssueMentions(db.DefaultContext, doer, comment.Content) if err != nil { return nil, err } @@ -246,7 +246,7 @@ func SubmitReview(doer *models.User, gitRepo *git.Repository, issue *models.Issu return nil, nil, err } - ctx := db.DefaultContext() + ctx := db.DefaultContext mentions, err := issue.FindAndUpdateIssueMentions(ctx, doer, comm.Content) if err != nil { return nil, nil, err diff --git a/services/release/release.go b/services/release/release.go index a9181398b59..f6f456e8fa3 100644 --- a/services/release/release.go +++ b/services/release/release.go @@ -123,7 +123,7 @@ func CreateRelease(gitRepo *git.Repository, rel *models.Release, attachmentUUIDs return err } - if err = models.AddReleaseAttachments(db.DefaultContext(), rel.ID, attachmentUUIDs); err != nil { + if err = models.AddReleaseAttachments(db.DefaultContext, rel.ID, attachmentUUIDs); err != nil { return err } @@ -311,7 +311,7 @@ func DeleteReleaseByID(id int64, doer *models.User, delTag bool) error { } else { rel.IsTag = true - if err = models.UpdateRelease(db.DefaultContext(), rel); err != nil { + if err = models.UpdateRelease(db.DefaultContext, rel); err != nil { return fmt.Errorf("Update: %v", err) } } diff --git a/services/repository/generate.go b/services/repository/generate.go index 5a9f6aa6584..fe38723dea3 100644 --- a/services/repository/generate.go +++ b/services/repository/generate.go @@ -5,6 +5,8 @@ package repository import ( + "context" + "code.gitea.io/gitea/models" "code.gitea.io/gitea/models/db" "code.gitea.io/gitea/modules/log" @@ -21,7 +23,7 @@ func GenerateRepository(doer, owner *models.User, templateRepo *models.Repositor } var generateRepo *models.Repository - if err = db.WithTx(func(ctx *db.Context) error { + if err = db.WithTx(func(ctx context.Context) error { generateRepo, err = repo_module.GenerateRepository(ctx, doer, owner, templateRepo, opts) if err != nil { return err diff --git a/services/repository/push.go b/services/repository/push.go index f7590d5787d..4d86667539c 100644 --- a/services/repository/push.go +++ b/services/repository/push.go @@ -83,7 +83,7 @@ func pushUpdates(optsList []*repo_module.PushUpdateOptions) error { } defer gitRepo.Close() - if err = repo.UpdateSize(db.DefaultContext()); err != nil { + if err = repo.UpdateSize(db.DefaultContext); err != nil { log.Error("Failed to update size for repository: %v", err) }