diff options
author | 6543 <6543@obermui.de> | 2022-04-28 13:48:48 +0200 |
---|---|---|
committer | GitHub <noreply@github.com> | 2022-04-28 13:48:48 +0200 |
commit | 06e4687cecaed41500b653e5b8685f48b8b18310 (patch) | |
tree | a98dd6d0139ba5d89c7e08d3c52930d66a77119b /models | |
parent | 332b2ecd214a79b49f3798f4f27fe02b23a17bf8 (diff) | |
download | gitea-06e4687cecaed41500b653e5b8685f48b8b18310.tar.gz gitea-06e4687cecaed41500b653e5b8685f48b8b18310.zip |
more context for models (#19511)
make more usage of context, to have more db transaction in one session
(make diff of #9307 smaller)
Diffstat (limited to 'models')
-rw-r--r-- | models/action.go | 2 | ||||
-rw-r--r-- | models/branches.go | 34 | ||||
-rw-r--r-- | models/branches_test.go | 10 | ||||
-rw-r--r-- | models/commit_status.go | 9 | ||||
-rw-r--r-- | models/issue.go | 20 | ||||
-rw-r--r-- | models/issue_label.go | 21 | ||||
-rw-r--r-- | models/issue_label_test.go | 7 | ||||
-rw-r--r-- | models/issue_xref.go | 2 | ||||
-rw-r--r-- | models/lfs_lock.go | 47 | ||||
-rw-r--r-- | models/organization/org.go | 2 | ||||
-rw-r--r-- | models/organization/team_repo.go | 4 | ||||
-rw-r--r-- | models/pull.go | 39 | ||||
-rw-r--r-- | models/pull_list.go | 11 | ||||
-rw-r--r-- | models/pull_test.go | 4 | ||||
-rw-r--r-- | models/repo.go | 6 | ||||
-rw-r--r-- | models/repo_permission.go | 16 | ||||
-rw-r--r-- | models/repo_permission_test.go | 48 | ||||
-rw-r--r-- | models/review.go | 6 |
18 files changed, 151 insertions, 137 deletions
diff --git a/models/action.go b/models/action.go index 3339d3b87a..5177616497 100644 --- a/models/action.go +++ b/models/action.go @@ -508,7 +508,7 @@ func notifyWatchers(ctx context.Context, actions ...*Action) error { permPR[i] = false continue } - perm, err := getUserRepoPermission(ctx, repo, user) + perm, err := GetUserRepoPermission(ctx, repo, user) if err != nil { permCode[i] = false permIssue[i] = false diff --git a/models/branches.go b/models/branches.go index 8156fd0908..f4ded8588f 100644 --- a/models/branches.go +++ b/models/branches.go @@ -337,43 +337,43 @@ type WhitelistOptions struct { // If ID is 0, it creates a new record. Otherwise, updates existing record. // This function also performs check if whitelist user and team's IDs have been changed // to avoid unnecessary whitelist delete and regenerate. -func UpdateProtectBranch(repo *repo_model.Repository, protectBranch *ProtectedBranch, opts WhitelistOptions) (err error) { - if err = repo.GetOwner(db.DefaultContext); err != nil { +func UpdateProtectBranch(ctx context.Context, repo *repo_model.Repository, protectBranch *ProtectedBranch, opts WhitelistOptions) (err error) { + if err = repo.GetOwner(ctx); err != nil { return fmt.Errorf("GetOwner: %v", err) } - whitelist, err := updateUserWhitelist(repo, protectBranch.WhitelistUserIDs, opts.UserIDs) + whitelist, err := updateUserWhitelist(ctx, repo, protectBranch.WhitelistUserIDs, opts.UserIDs) if err != nil { return err } protectBranch.WhitelistUserIDs = whitelist - whitelist, err = updateUserWhitelist(repo, protectBranch.MergeWhitelistUserIDs, opts.MergeUserIDs) + whitelist, err = updateUserWhitelist(ctx, repo, protectBranch.MergeWhitelistUserIDs, opts.MergeUserIDs) if err != nil { return err } protectBranch.MergeWhitelistUserIDs = whitelist - whitelist, err = updateApprovalWhitelist(repo, protectBranch.ApprovalsWhitelistUserIDs, opts.ApprovalsUserIDs) + whitelist, err = updateApprovalWhitelist(ctx, repo, protectBranch.ApprovalsWhitelistUserIDs, opts.ApprovalsUserIDs) if err != nil { return err } protectBranch.ApprovalsWhitelistUserIDs = whitelist // if the repo is in an organization - whitelist, err = updateTeamWhitelist(repo, protectBranch.WhitelistTeamIDs, opts.TeamIDs) + whitelist, err = updateTeamWhitelist(ctx, repo, protectBranch.WhitelistTeamIDs, opts.TeamIDs) if err != nil { return err } protectBranch.WhitelistTeamIDs = whitelist - whitelist, err = updateTeamWhitelist(repo, protectBranch.MergeWhitelistTeamIDs, opts.MergeTeamIDs) + whitelist, err = updateTeamWhitelist(ctx, repo, protectBranch.MergeWhitelistTeamIDs, opts.MergeTeamIDs) if err != nil { return err } protectBranch.MergeWhitelistTeamIDs = whitelist - whitelist, err = updateTeamWhitelist(repo, protectBranch.ApprovalsWhitelistTeamIDs, opts.ApprovalsTeamIDs) + whitelist, err = updateTeamWhitelist(ctx, repo, protectBranch.ApprovalsWhitelistTeamIDs, opts.ApprovalsTeamIDs) if err != nil { return err } @@ -381,13 +381,13 @@ func UpdateProtectBranch(repo *repo_model.Repository, protectBranch *ProtectedBr // Make sure protectBranch.ID is not 0 for whitelists if protectBranch.ID == 0 { - if _, err = db.GetEngine(db.DefaultContext).Insert(protectBranch); err != nil { + if _, err = db.GetEngine(ctx).Insert(protectBranch); err != nil { return fmt.Errorf("Insert: %v", err) } return nil } - if _, err = db.GetEngine(db.DefaultContext).ID(protectBranch.ID).AllCols().Update(protectBranch); err != nil { + if _, err = db.GetEngine(ctx).ID(protectBranch.ID).AllCols().Update(protectBranch); err != nil { return fmt.Errorf("Update: %v", err) } @@ -416,7 +416,7 @@ func IsProtectedBranch(repoID int64, branchName string) (bool, error) { // updateApprovalWhitelist checks whether the user whitelist changed and returns a whitelist with // the users from newWhitelist which have explicit read or write access to the repo. -func updateApprovalWhitelist(repo *repo_model.Repository, currentWhitelist, newWhitelist []int64) (whitelist []int64, err error) { +func updateApprovalWhitelist(ctx context.Context, repo *repo_model.Repository, currentWhitelist, newWhitelist []int64) (whitelist []int64, err error) { hasUsersChanged := !util.IsSliceInt64Eq(currentWhitelist, newWhitelist) if !hasUsersChanged { return currentWhitelist, nil @@ -424,7 +424,7 @@ func updateApprovalWhitelist(repo *repo_model.Repository, currentWhitelist, newW whitelist = make([]int64, 0, len(newWhitelist)) for _, userID := range newWhitelist { - if reader, err := IsRepoReader(repo, userID); err != nil { + if reader, err := IsRepoReader(ctx, repo, userID); err != nil { return nil, err } else if !reader { continue @@ -437,7 +437,7 @@ func updateApprovalWhitelist(repo *repo_model.Repository, currentWhitelist, newW // updateUserWhitelist checks whether the user whitelist changed and returns a whitelist with // the users from newWhitelist which have write access to the repo. -func updateUserWhitelist(repo *repo_model.Repository, currentWhitelist, newWhitelist []int64) (whitelist []int64, err error) { +func updateUserWhitelist(ctx context.Context, repo *repo_model.Repository, currentWhitelist, newWhitelist []int64) (whitelist []int64, err error) { hasUsersChanged := !util.IsSliceInt64Eq(currentWhitelist, newWhitelist) if !hasUsersChanged { return currentWhitelist, nil @@ -445,11 +445,11 @@ func updateUserWhitelist(repo *repo_model.Repository, currentWhitelist, newWhite whitelist = make([]int64, 0, len(newWhitelist)) for _, userID := range newWhitelist { - user, err := user_model.GetUserByID(userID) + user, err := user_model.GetUserByIDCtx(ctx, userID) if err != nil { return nil, fmt.Errorf("GetUserByID [user_id: %d, repo_id: %d]: %v", userID, repo.ID, err) } - perm, err := GetUserRepoPermission(repo, user) + perm, err := GetUserRepoPermission(ctx, repo, user) if err != nil { return nil, fmt.Errorf("GetUserRepoPermission [user_id: %d, repo_id: %d]: %v", userID, repo.ID, err) } @@ -466,13 +466,13 @@ func updateUserWhitelist(repo *repo_model.Repository, currentWhitelist, newWhite // updateTeamWhitelist checks whether the team whitelist changed and returns a whitelist with // the teams from newWhitelist which have write access to the repo. -func updateTeamWhitelist(repo *repo_model.Repository, currentWhitelist, newWhitelist []int64) (whitelist []int64, err error) { +func updateTeamWhitelist(ctx context.Context, repo *repo_model.Repository, currentWhitelist, newWhitelist []int64) (whitelist []int64, err error) { hasTeamsChanged := !util.IsSliceInt64Eq(currentWhitelist, newWhitelist) if !hasTeamsChanged { return currentWhitelist, nil } - teams, err := organization.GetTeamsWithAccessToRepo(repo.OwnerID, repo.ID, perm.AccessModeRead) + teams, err := organization.GetTeamsWithAccessToRepo(ctx, repo.OwnerID, repo.ID, perm.AccessModeRead) if err != nil { return nil, fmt.Errorf("GetTeamsWithAccessToRepo [org_id: %d, repo_id: %d]: %v", repo.OwnerID, repo.ID, err) } diff --git a/models/branches_test.go b/models/branches_test.go index e1a71853f2..0a0f125cc6 100644 --- a/models/branches_test.go +++ b/models/branches_test.go @@ -7,6 +7,7 @@ package models import ( "testing" + "code.gitea.io/gitea/models/db" repo_model "code.gitea.io/gitea/models/repo" "code.gitea.io/gitea/models/unittest" @@ -99,11 +100,14 @@ func TestRenameBranch(t *testing.T) { repo1 := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1}).(*repo_model.Repository) _isDefault := false - err := UpdateProtectBranch(repo1, &ProtectedBranch{ + ctx, committer, err := db.TxContext() + defer committer.Close() + assert.NoError(t, err) + assert.NoError(t, UpdateProtectBranch(ctx, repo1, &ProtectedBranch{ RepoID: repo1.ID, BranchName: "master", - }, WhitelistOptions{}) - assert.NoError(t, err) + }, WhitelistOptions{})) + assert.NoError(t, committer.Commit()) assert.NoError(t, RenameBranch(repo1, "master", "main", func(isDefault bool) error { _isDefault = isDefault diff --git a/models/commit_status.go b/models/commit_status.go index cd7497eed8..cf2143d30f 100644 --- a/models/commit_status.go +++ b/models/commit_status.go @@ -232,12 +232,13 @@ type CommitStatusIndex struct { // GetLatestCommitStatus returns all statuses with a unique context for a given commit. func GetLatestCommitStatus(repoID int64, sha string, listOptions db.ListOptions) ([]*CommitStatus, int64, error) { - return getLatestCommitStatus(db.GetEngine(db.DefaultContext), repoID, sha, listOptions) + return GetLatestCommitStatusCtx(db.DefaultContext, repoID, sha, listOptions) } -func getLatestCommitStatus(e db.Engine, repoID int64, sha string, listOptions db.ListOptions) ([]*CommitStatus, int64, error) { +// GetLatestCommitStatusCtx returns all statuses with a unique context for a given commit. +func GetLatestCommitStatusCtx(ctx context.Context, repoID int64, sha string, listOptions db.ListOptions) ([]*CommitStatus, int64, error) { ids := make([]int64, 0, 10) - sess := e.Table(&CommitStatus{}). + sess := db.GetEngine(ctx).Table(&CommitStatus{}). Where("repo_id = ?", repoID).And("sha = ?", sha). Select("max( id ) as id"). GroupBy("context_hash").OrderBy("max( id ) desc") @@ -252,7 +253,7 @@ func getLatestCommitStatus(e db.Engine, repoID int64, sha string, listOptions db if len(ids) == 0 { return statuses, count, nil } - return statuses, count, e.In("id", ids).Find(&statuses) + return statuses, count, db.GetEngine(ctx).In("id", ids).Find(&statuses) } // FindRepoRecentCommitStatusContexts returns repository's recent commit status contexts diff --git a/models/issue.go b/models/issue.go index 8bb46bde7e..2a41cbc28e 100644 --- a/models/issue.go +++ b/models/issue.go @@ -162,13 +162,9 @@ func (issue *Issue) GetPullRequest() (pr *PullRequest, err error) { } // LoadLabels loads labels -func (issue *Issue) LoadLabels() error { - return issue.loadLabels(db.GetEngine(db.DefaultContext)) -} - -func (issue *Issue) loadLabels(e db.Engine) (err error) { +func (issue *Issue) LoadLabels(ctx context.Context) (err error) { if issue.Labels == nil { - issue.Labels, err = getLabelsByIssueID(e, issue.ID) + issue.Labels, err = getLabelsByIssueID(db.GetEngine(ctx), issue.ID) if err != nil { return fmt.Errorf("getLabelsByIssueID [%d]: %v", issue.ID, err) } @@ -313,7 +309,7 @@ func (issue *Issue) loadAttributes(ctx context.Context) (err error) { return } - if err = issue.loadLabels(e); err != nil { + if err = issue.LoadLabels(ctx); err != nil { return } @@ -493,7 +489,7 @@ func ClearIssueLabels(issue *Issue, doer *user_model.User) (err error) { return err } - perm, err := getUserRepoPermission(ctx, issue.Repo, doer) + perm, err := GetUserRepoPermission(ctx, issue.Repo, doer) if err != nil { return err } @@ -539,7 +535,7 @@ func ReplaceIssueLabels(issue *Issue, labels []*Label, doer *user_model.User) (e return err } - if err = issue.loadLabels(db.GetEngine(ctx)); err != nil { + if err = issue.LoadLabels(ctx); err != nil { return err } @@ -587,7 +583,7 @@ func ReplaceIssueLabels(issue *Issue, labels []*Label, doer *user_model.User) (e } issue.Labels = nil - if err = issue.loadLabels(db.GetEngine(ctx)); err != nil { + if err = issue.LoadLabels(ctx); err != nil { return err } @@ -2341,9 +2337,9 @@ func ResolveIssueMentionsByVisibility(ctx context.Context, issue *Issue, doer *u continue } // Normal users must have read access to the referencing issue - perm, err := getUserRepoPermission(ctx, issue.Repo, user) + perm, err := GetUserRepoPermission(ctx, issue.Repo, user) if err != nil { - return nil, fmt.Errorf("getUserRepoPermission [%d]: %v", user.ID, err) + return nil, fmt.Errorf("GetUserRepoPermission [%d]: %v", user.ID, err) } if !perm.CanReadIssuesOrPulls(issue.IsPull) { continue diff --git a/models/issue_label.go b/models/issue_label.go index 25e6350bc1..d069153939 100644 --- a/models/issue_label.go +++ b/models/issue_label.go @@ -613,7 +613,6 @@ func NewIssueLabel(issue *Issue, label *Label, doer *user_model.User) (err error return err } defer committer.Close() - sess := db.GetEngine(ctx) if err = issue.LoadRepo(ctx); err != nil { return err @@ -629,7 +628,7 @@ func NewIssueLabel(issue *Issue, label *Label, doer *user_model.User) (err error } issue.Labels = nil - if err = issue.loadLabels(sess); err != nil { + if err = issue.LoadLabels(ctx); err != nil { return err } @@ -670,7 +669,7 @@ func NewIssueLabels(issue *Issue, labels []*Label, doer *user_model.User) (err e } issue.Labels = nil - if err = issue.loadLabels(db.GetEngine(ctx)); err != nil { + if err = issue.LoadLabels(ctx); err != nil { return err } @@ -707,23 +706,13 @@ func deleteIssueLabel(ctx context.Context, issue *Issue, label *Label, doer *use } // DeleteIssueLabel deletes issue-label relation. -func DeleteIssueLabel(issue *Issue, label *Label, doer *user_model.User) (err error) { - ctx, committer, err := db.TxContext() - if err != nil { - return err - } - defer committer.Close() - - if err = deleteIssueLabel(ctx, issue, label, doer); err != nil { +func DeleteIssueLabel(ctx context.Context, issue *Issue, label *Label, doer *user_model.User) error { + if err := deleteIssueLabel(ctx, issue, label, doer); err != nil { return err } issue.Labels = nil - if err = issue.loadLabels(db.GetEngine(ctx)); err != nil { - return err - } - - return committer.Commit() + return issue.LoadLabels(ctx) } func deleteLabelsByRepoID(sess db.Engine, repoID int64) error { diff --git a/models/issue_label_test.go b/models/issue_label_test.go index c9ff1a270f..2dd0cf98e0 100644 --- a/models/issue_label_test.go +++ b/models/issue_label_test.go @@ -369,7 +369,12 @@ func TestDeleteIssueLabel(t *testing.T) { } } - assert.NoError(t, DeleteIssueLabel(issue, label, doer)) + ctx, committer, err := db.TxContext() + defer committer.Close() + assert.NoError(t, err) + assert.NoError(t, DeleteIssueLabel(ctx, issue, label, doer)) + assert.NoError(t, committer.Commit()) + unittest.AssertNotExistsBean(t, &IssueLabel{IssueID: issueID, LabelID: labelID}) unittest.AssertExistsAndLoadBean(t, &Comment{ Type: CommentTypeLabel, diff --git a/models/issue_xref.go b/models/issue_xref.go index 405f1dae22..2647f9c656 100644 --- a/models/issue_xref.go +++ b/models/issue_xref.go @@ -215,7 +215,7 @@ func (issue *Issue) verifyReferencedIssue(stdCtx context.Context, ctx *crossRefe // Check doer permissions; set action to None if the doer can't change the destination if refIssue.RepoID != ctx.OrigIssue.RepoID || ref.Action != references.XRefActionNone { - perm, err := getUserRepoPermission(stdCtx, refIssue.Repo, ctx.Doer) + perm, err := GetUserRepoPermission(stdCtx, refIssue.Repo, ctx.Doer) if err != nil { return nil, references.XRefActionNone, err } diff --git a/models/lfs_lock.go b/models/lfs_lock.go index a77dd24e9f..b5f8e4907f 100644 --- a/models/lfs_lock.go +++ b/models/lfs_lock.go @@ -5,6 +5,7 @@ package models import ( + "context" "fmt" "path" "strings" @@ -42,15 +43,20 @@ func cleanPath(p string) string { // CreateLFSLock creates a new lock. func CreateLFSLock(repo *repo_model.Repository, lock *LFSLock) (*LFSLock, error) { - err := CheckLFSAccessForRepo(lock.OwnerID, repo, perm.AccessModeWrite) + dbCtx, committer, err := db.TxContext() if err != nil { return nil, err } + defer committer.Close() + + if err := CheckLFSAccessForRepo(dbCtx, lock.OwnerID, repo, perm.AccessModeWrite); err != nil { + return nil, err + } lock.Path = cleanPath(lock.Path) lock.RepoID = repo.ID - l, err := GetLFSLock(repo, lock.Path) + l, err := GetLFSLock(dbCtx, repo, lock.Path) if err == nil { return l, ErrLFSLockAlreadyExist{lock.RepoID, lock.Path} } @@ -58,15 +64,18 @@ func CreateLFSLock(repo *repo_model.Repository, lock *LFSLock) (*LFSLock, error) return nil, err } - err = db.Insert(db.DefaultContext, lock) - return lock, err + if err := db.Insert(dbCtx, lock); err != nil { + return nil, err + } + + return lock, committer.Commit() } // GetLFSLock returns release by given path. -func GetLFSLock(repo *repo_model.Repository, path string) (*LFSLock, error) { +func GetLFSLock(ctx context.Context, repo *repo_model.Repository, path string) (*LFSLock, error) { path = cleanPath(path) rel := &LFSLock{RepoID: repo.ID} - has, err := db.GetEngine(db.DefaultContext).Where("lower(path) = ?", strings.ToLower(path)).Get(rel) + has, err := db.GetEngine(ctx).Where("lower(path) = ?", strings.ToLower(path)).Get(rel) if err != nil { return nil, err } @@ -77,9 +86,9 @@ func GetLFSLock(repo *repo_model.Repository, path string) (*LFSLock, error) { } // GetLFSLockByID returns release by given id. -func GetLFSLockByID(id int64) (*LFSLock, error) { +func GetLFSLockByID(ctx context.Context, id int64) (*LFSLock, error) { lock := new(LFSLock) - has, err := db.GetEngine(db.DefaultContext).ID(id).Get(lock) + has, err := db.GetEngine(ctx).ID(id).Get(lock) if err != nil { return nil, err } else if !has { @@ -127,34 +136,42 @@ func CountLFSLockByRepoID(repoID int64) (int64, error) { // DeleteLFSLockByID deletes a lock by given ID. func DeleteLFSLockByID(id int64, repo *repo_model.Repository, u *user_model.User, force bool) (*LFSLock, error) { - lock, err := GetLFSLockByID(id) + dbCtx, committer, err := db.TxContext() if err != nil { return nil, err } + defer committer.Close() - err = CheckLFSAccessForRepo(u.ID, repo, perm.AccessModeWrite) + lock, err := GetLFSLockByID(dbCtx, id) if err != nil { return nil, err } + if err := CheckLFSAccessForRepo(dbCtx, u.ID, repo, perm.AccessModeWrite); err != nil { + return nil, err + } + if !force && u.ID != lock.OwnerID { return nil, fmt.Errorf("user doesn't own lock and force flag is not set") } - _, err = db.GetEngine(db.DefaultContext).ID(id).Delete(new(LFSLock)) - return lock, err + if _, err := db.GetEngine(dbCtx).ID(id).Delete(new(LFSLock)); err != nil { + return nil, err + } + + return lock, committer.Commit() } // CheckLFSAccessForRepo check needed access mode base on action -func CheckLFSAccessForRepo(ownerID int64, repo *repo_model.Repository, mode perm.AccessMode) error { +func CheckLFSAccessForRepo(ctx context.Context, ownerID int64, repo *repo_model.Repository, mode perm.AccessMode) error { if ownerID == 0 { return ErrLFSUnauthorizedAction{repo.ID, "undefined", mode} } - u, err := user_model.GetUserByID(ownerID) + u, err := user_model.GetUserByIDCtx(ctx, ownerID) if err != nil { return err } - perm, err := GetUserRepoPermission(repo, u) + perm, err := GetUserRepoPermission(ctx, repo, u) if err != nil { return err } diff --git a/models/organization/org.go b/models/organization/org.go index 9e71bbe80d..3761335922 100644 --- a/models/organization/org.go +++ b/models/organization/org.go @@ -683,7 +683,7 @@ func (org *Organization) getUserTeamIDs(ctx context.Context, userID int64) ([]in // TeamsWithAccessToRepo returns all teams that have given access level to the repository. func (org *Organization) TeamsWithAccessToRepo(repoID int64, mode perm.AccessMode) ([]*Team, error) { - return GetTeamsWithAccessToRepo(org.ID, repoID, mode) + return GetTeamsWithAccessToRepo(db.DefaultContext, org.ID, repoID, mode) } // GetUserTeamIDs returns of all team IDs of the organization that user is member of. diff --git a/models/organization/team_repo.go b/models/organization/team_repo.go index 657e83aaa5..717d754c40 100644 --- a/models/organization/team_repo.go +++ b/models/organization/team_repo.go @@ -75,9 +75,9 @@ func RemoveTeamRepo(ctx context.Context, 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 perm.AccessMode) ([]*Team, error) { +func GetTeamsWithAccessToRepo(ctx context.Context, orgID, repoID int64, mode perm.AccessMode) ([]*Team, error) { teams := make([]*Team, 0, 5) - return teams, db.GetEngine(db.DefaultContext).Where("team.authorize >= ?", mode). + return teams, db.GetEngine(ctx).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). diff --git a/models/pull.go b/models/pull.go index ac44ebf0be..e04263af9f 100644 --- a/models/pull.go +++ b/models/pull.go @@ -130,7 +130,8 @@ func (pr *PullRequest) LoadAttributes() error { return pr.loadAttributes(db.GetEngine(db.DefaultContext)) } -func (pr *PullRequest) loadHeadRepo(ctx context.Context) (err error) { +// LoadHeadRepoCtx loads the head repository +func (pr *PullRequest) LoadHeadRepoCtx(ctx context.Context) (err error) { if !pr.isHeadRepoLoaded && pr.HeadRepo == nil && pr.HeadRepoID > 0 { if pr.HeadRepoID == pr.BaseRepoID { if pr.BaseRepo != nil { @@ -153,15 +154,16 @@ func (pr *PullRequest) loadHeadRepo(ctx context.Context) (err error) { // LoadHeadRepo loads the head repository func (pr *PullRequest) LoadHeadRepo() error { - return pr.loadHeadRepo(db.DefaultContext) + return pr.LoadHeadRepoCtx(db.DefaultContext) } // LoadBaseRepo loads the target repository func (pr *PullRequest) LoadBaseRepo() error { - return pr.loadBaseRepo(db.DefaultContext) + return pr.LoadBaseRepoCtx(db.DefaultContext) } -func (pr *PullRequest) loadBaseRepo(ctx context.Context) (err error) { +// LoadBaseRepoCtx loads the target repository +func (pr *PullRequest) LoadBaseRepoCtx(ctx context.Context) (err error) { if pr.BaseRepo != nil { return nil } @@ -185,15 +187,16 @@ func (pr *PullRequest) loadBaseRepo(ctx context.Context) (err error) { // LoadIssue loads issue information from database func (pr *PullRequest) LoadIssue() (err error) { - return pr.loadIssue(db.GetEngine(db.DefaultContext)) + return pr.LoadIssueCtx(db.DefaultContext) } -func (pr *PullRequest) loadIssue(e db.Engine) (err error) { +// LoadIssueCtx loads issue information from database +func (pr *PullRequest) LoadIssueCtx(ctx context.Context) (err error) { if pr.Issue != nil { return nil } - pr.Issue, err = getIssueByID(e, pr.IssueID) + pr.Issue, err = getIssueByID(db.GetEngine(ctx), pr.IssueID) if err == nil { pr.Issue.PullRequest = pr } @@ -202,10 +205,11 @@ 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) + return pr.LoadProtectedBranchCtx(db.DefaultContext) } -func (pr *PullRequest) loadProtectedBranch(ctx context.Context) (err error) { +// LoadProtectedBranchCtx loads the protected branch of the base branch +func (pr *PullRequest) LoadProtectedBranchCtx(ctx context.Context) (err error) { if pr.ProtectedBranch == nil { if pr.BaseRepo == nil { if pr.BaseRepoID == 0 { @@ -392,7 +396,7 @@ func (pr *PullRequest) SetMerged() (bool, error) { } pr.Issue = nil - if err := pr.loadIssue(sess); err != nil { + if err := pr.LoadIssueCtx(ctx); err != nil { return false, err } @@ -510,6 +514,11 @@ func GetLatestPullRequestByHeadInfo(repoID int64, branch string) (*PullRequest, // GetPullRequestByIndex returns a pull request by the given index func GetPullRequestByIndex(repoID, index int64) (*PullRequest, error) { + return GetPullRequestByIndexCtx(db.DefaultContext, repoID, index) +} + +// GetPullRequestByIndexCtx returns a pull request by the given index +func GetPullRequestByIndexCtx(ctx context.Context, repoID, index int64) (*PullRequest, error) { if index < 1 { return nil, ErrPullRequestNotExist{} } @@ -518,17 +527,17 @@ func GetPullRequestByIndex(repoID, index int64) (*PullRequest, error) { Index: index, } - has, err := db.GetEngine(db.DefaultContext).Get(pr) + has, err := db.GetEngine(ctx).Get(pr) if err != nil { return nil, err } else if !has { return nil, ErrPullRequestNotExist{0, 0, 0, repoID, "", ""} } - if err = pr.LoadAttributes(); err != nil { + if err = pr.loadAttributes(db.GetEngine(ctx)); err != nil { return nil, err } - if err = pr.LoadIssue(); err != nil { + if err = pr.LoadIssueCtx(ctx); err != nil { return nil, err } @@ -547,8 +556,8 @@ 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.GetEngine(db.DefaultContext), id) +func GetPullRequestByID(ctx context.Context, id int64) (*PullRequest, error) { + return getPullRequestByID(db.GetEngine(ctx), id) } // GetPullRequestByIssueIDWithNoAttributes returns pull request with no attributes loaded by given issue ID. diff --git a/models/pull_list.go b/models/pull_list.go index 9d4d428928..055119a1e5 100644 --- a/models/pull_list.go +++ b/models/pull_list.go @@ -5,6 +5,7 @@ package models import ( + "context" "fmt" "code.gitea.io/gitea/models/db" @@ -158,13 +159,14 @@ func (prs PullRequestList) LoadAttributes() error { return prs.loadAttributes(db.GetEngine(db.DefaultContext)) } -func (prs PullRequestList) invalidateCodeComments(e db.Engine, doer *user_model.User, repo *git.Repository, branch string) error { +// InvalidateCodeComments will lookup the prs for code comments which got invalidated by change +func (prs PullRequestList) InvalidateCodeComments(ctx context.Context, doer *user_model.User, repo *git.Repository, branch string) error { if len(prs) == 0 { return nil } issueIDs := prs.getIssueIDs() var codeComments []*Comment - if err := e. + if err := db.GetEngine(ctx). Where("type = ? and invalidated = ?", CommentTypeCode, false). In("issue_id", issueIDs). Find(&codeComments); err != nil { @@ -177,8 +179,3 @@ func (prs PullRequestList) invalidateCodeComments(e db.Engine, doer *user_model. } return nil } - -// InvalidateCodeComments will lookup the prs for code comments which got invalidated by change -func (prs PullRequestList) InvalidateCodeComments(doer *user_model.User, repo *git.Repository, branch string) error { - return prs.invalidateCodeComments(db.GetEngine(db.DefaultContext), doer, repo, branch) -} diff --git a/models/pull_test.go b/models/pull_test.go index 9098b61161..6194ac0e24 100644 --- a/models/pull_test.go +++ b/models/pull_test.go @@ -159,12 +159,12 @@ func TestGetPullRequestByIndex(t *testing.T) { func TestGetPullRequestByID(t *testing.T) { assert.NoError(t, unittest.PrepareTestDatabase()) - pr, err := GetPullRequestByID(1) + pr, err := GetPullRequestByID(db.DefaultContext, 1) assert.NoError(t, err) assert.Equal(t, int64(1), pr.ID) assert.Equal(t, int64(2), pr.IssueID) - _, err = GetPullRequestByID(9223372036854775807) + _, err = GetPullRequestByID(db.DefaultContext, 9223372036854775807) assert.Error(t, err) assert.True(t, IsErrPullRequestNotExist(err)) } diff --git a/models/repo.go b/models/repo.go index 5073d1ceb9..9c2fce8d3c 100644 --- a/models/repo.go +++ b/models/repo.go @@ -57,9 +57,9 @@ func checkRepoUnitUser(ctx context.Context, repo *repo_model.Repository, user *u if user.IsAdmin { return true } - perm, err := getUserRepoPermission(ctx, repo, user) + perm, err := GetUserRepoPermission(ctx, repo, user) if err != nil { - log.Error("getUserRepoPermission(): %v", err) + log.Error("GetUserRepoPermission(): %v", err) return false } @@ -198,7 +198,7 @@ func GetReviewerTeams(repo *repo_model.Repository) ([]*organization.Team, error) return nil, nil } - teams, err := organization.GetTeamsWithAccessToRepo(repo.OwnerID, repo.ID, perm.AccessModeRead) + teams, err := organization.GetTeamsWithAccessToRepo(db.DefaultContext, repo.OwnerID, repo.ID, perm.AccessModeRead) if err != nil { return nil, err } diff --git a/models/repo_permission.go b/models/repo_permission.go index 3e9ad04482..b4291f2362 100644 --- a/models/repo_permission.go +++ b/models/repo_permission.go @@ -145,11 +145,7 @@ func (p *Permission) ColorFormat(s fmt.State) { } // GetUserRepoPermission returns the user permissions to the repository -func GetUserRepoPermission(repo *repo_model.Repository, user *user_model.User) (Permission, error) { - return getUserRepoPermission(db.DefaultContext, repo, user) -} - -func getUserRepoPermission(ctx context.Context, repo *repo_model.Repository, user *user_model.User) (perm Permission, err error) { +func GetUserRepoPermission(ctx context.Context, repo *repo_model.Repository, user *user_model.User) (perm Permission, err error) { if log.IsTrace() { defer func() { if user == nil { @@ -347,7 +343,7 @@ func AccessLevelUnit(user *user_model.User, repo *repo_model.Repository, unitTyp } func accessLevelUnit(ctx context.Context, user *user_model.User, repo *repo_model.Repository, unitType unit.Type) (perm_model.AccessMode, error) { - perm, err := getUserRepoPermission(ctx, repo, user) + perm, err := GetUserRepoPermission(ctx, repo, user) if err != nil { return perm_model.AccessModeNone, err } @@ -375,7 +371,7 @@ func canBeAssigned(ctx context.Context, user *user_model.User, repo *repo_model. if user.IsOrganization() { return false, fmt.Errorf("Organization can't be added as assignee [user_id: %d, repo_id: %d]", user.ID, repo.ID) } - perm, err := getUserRepoPermission(ctx, repo, user) + perm, err := GetUserRepoPermission(ctx, repo, user) if err != nil { return false, err } @@ -391,7 +387,7 @@ func hasAccess(ctx context.Context, userID int64, repo *repo_model.Repository) ( return false, err } } - perm, err := getUserRepoPermission(ctx, repo, user) + perm, err := GetUserRepoPermission(ctx, repo, user) if err != nil { return false, err } @@ -414,9 +410,9 @@ func GetRepoWriters(repo *repo_model.Repository) (_ []*user_model.User, err erro } // IsRepoReader returns true if user has explicit read access or higher to the repository. -func IsRepoReader(repo *repo_model.Repository, userID int64) (bool, error) { +func IsRepoReader(ctx context.Context, repo *repo_model.Repository, userID int64) (bool, error) { if repo.OwnerID == userID { return true, nil } - return db.GetEngine(db.DefaultContext).Where("repo_id = ? AND user_id = ? AND mode >= ?", repo.ID, userID, perm_model.AccessModeRead).Get(&Access{}) + return db.GetEngine(ctx).Where("repo_id = ? AND user_id = ? AND mode >= ?", repo.ID, userID, perm_model.AccessModeRead).Get(&Access{}) } diff --git a/models/repo_permission_test.go b/models/repo_permission_test.go index c103a9363f..7e22437f99 100644 --- a/models/repo_permission_test.go +++ b/models/repo_permission_test.go @@ -27,7 +27,7 @@ func TestRepoPermissionPublicNonOrgRepo(t *testing.T) { // plain user user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2}).(*user_model.User) - perm, err := GetUserRepoPermission(repo, user) + perm, err := GetUserRepoPermission(db.DefaultContext, repo, user) assert.NoError(t, err) for _, unit := range repo.Units { assert.True(t, perm.CanRead(unit.Type)) @@ -36,7 +36,7 @@ func TestRepoPermissionPublicNonOrgRepo(t *testing.T) { // change to collaborator assert.NoError(t, AddCollaborator(repo, user)) - perm, err = GetUserRepoPermission(repo, user) + perm, err = GetUserRepoPermission(db.DefaultContext, repo, user) assert.NoError(t, err) for _, unit := range repo.Units { assert.True(t, perm.CanRead(unit.Type)) @@ -45,7 +45,7 @@ func TestRepoPermissionPublicNonOrgRepo(t *testing.T) { // collaborator collaborator := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 4}).(*user_model.User) - perm, err = GetUserRepoPermission(repo, collaborator) + perm, err = GetUserRepoPermission(db.DefaultContext, repo, collaborator) assert.NoError(t, err) for _, unit := range repo.Units { assert.True(t, perm.CanRead(unit.Type)) @@ -54,7 +54,7 @@ func TestRepoPermissionPublicNonOrgRepo(t *testing.T) { // owner owner := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 5}).(*user_model.User) - perm, err = GetUserRepoPermission(repo, owner) + perm, err = GetUserRepoPermission(db.DefaultContext, repo, owner) assert.NoError(t, err) for _, unit := range repo.Units { assert.True(t, perm.CanRead(unit.Type)) @@ -63,7 +63,7 @@ func TestRepoPermissionPublicNonOrgRepo(t *testing.T) { // admin admin := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 1}).(*user_model.User) - perm, err = GetUserRepoPermission(repo, admin) + perm, err = GetUserRepoPermission(db.DefaultContext, repo, admin) assert.NoError(t, err) for _, unit := range repo.Units { assert.True(t, perm.CanRead(unit.Type)) @@ -80,7 +80,7 @@ func TestRepoPermissionPrivateNonOrgRepo(t *testing.T) { // plain user user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 4}).(*user_model.User) - perm, err := GetUserRepoPermission(repo, user) + perm, err := GetUserRepoPermission(db.DefaultContext, repo, user) assert.NoError(t, err) for _, unit := range repo.Units { assert.False(t, perm.CanRead(unit.Type)) @@ -89,7 +89,7 @@ func TestRepoPermissionPrivateNonOrgRepo(t *testing.T) { // change to collaborator to default write access assert.NoError(t, AddCollaborator(repo, user)) - perm, err = GetUserRepoPermission(repo, user) + perm, err = GetUserRepoPermission(db.DefaultContext, repo, user) assert.NoError(t, err) for _, unit := range repo.Units { assert.True(t, perm.CanRead(unit.Type)) @@ -97,7 +97,7 @@ func TestRepoPermissionPrivateNonOrgRepo(t *testing.T) { } assert.NoError(t, ChangeCollaborationAccessMode(repo, user.ID, perm_model.AccessModeRead)) - perm, err = GetUserRepoPermission(repo, user) + perm, err = GetUserRepoPermission(db.DefaultContext, repo, user) assert.NoError(t, err) for _, unit := range repo.Units { assert.True(t, perm.CanRead(unit.Type)) @@ -106,7 +106,7 @@ func TestRepoPermissionPrivateNonOrgRepo(t *testing.T) { // owner owner := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2}).(*user_model.User) - perm, err = GetUserRepoPermission(repo, owner) + perm, err = GetUserRepoPermission(db.DefaultContext, repo, owner) assert.NoError(t, err) for _, unit := range repo.Units { assert.True(t, perm.CanRead(unit.Type)) @@ -115,7 +115,7 @@ func TestRepoPermissionPrivateNonOrgRepo(t *testing.T) { // admin admin := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 1}).(*user_model.User) - perm, err = GetUserRepoPermission(repo, admin) + perm, err = GetUserRepoPermission(db.DefaultContext, repo, admin) assert.NoError(t, err) for _, unit := range repo.Units { assert.True(t, perm.CanRead(unit.Type)) @@ -132,7 +132,7 @@ func TestRepoPermissionPublicOrgRepo(t *testing.T) { // plain user user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 5}).(*user_model.User) - perm, err := GetUserRepoPermission(repo, user) + perm, err := GetUserRepoPermission(db.DefaultContext, repo, user) assert.NoError(t, err) for _, unit := range repo.Units { assert.True(t, perm.CanRead(unit.Type)) @@ -141,7 +141,7 @@ func TestRepoPermissionPublicOrgRepo(t *testing.T) { // change to collaborator to default write access assert.NoError(t, AddCollaborator(repo, user)) - perm, err = GetUserRepoPermission(repo, user) + perm, err = GetUserRepoPermission(db.DefaultContext, repo, user) assert.NoError(t, err) for _, unit := range repo.Units { assert.True(t, perm.CanRead(unit.Type)) @@ -149,7 +149,7 @@ func TestRepoPermissionPublicOrgRepo(t *testing.T) { } assert.NoError(t, ChangeCollaborationAccessMode(repo, user.ID, perm_model.AccessModeRead)) - perm, err = GetUserRepoPermission(repo, user) + perm, err = GetUserRepoPermission(db.DefaultContext, repo, user) assert.NoError(t, err) for _, unit := range repo.Units { assert.True(t, perm.CanRead(unit.Type)) @@ -158,7 +158,7 @@ func TestRepoPermissionPublicOrgRepo(t *testing.T) { // org member team owner owner := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2}).(*user_model.User) - perm, err = GetUserRepoPermission(repo, owner) + perm, err = GetUserRepoPermission(db.DefaultContext, repo, owner) assert.NoError(t, err) for _, unit := range repo.Units { assert.True(t, perm.CanRead(unit.Type)) @@ -167,7 +167,7 @@ func TestRepoPermissionPublicOrgRepo(t *testing.T) { // org member team tester member := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 15}).(*user_model.User) - perm, err = GetUserRepoPermission(repo, member) + perm, err = GetUserRepoPermission(db.DefaultContext, repo, member) assert.NoError(t, err) for _, unit := range repo.Units { assert.True(t, perm.CanRead(unit.Type)) @@ -177,7 +177,7 @@ func TestRepoPermissionPublicOrgRepo(t *testing.T) { // admin admin := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 1}).(*user_model.User) - perm, err = GetUserRepoPermission(repo, admin) + perm, err = GetUserRepoPermission(db.DefaultContext, repo, admin) assert.NoError(t, err) for _, unit := range repo.Units { assert.True(t, perm.CanRead(unit.Type)) @@ -194,7 +194,7 @@ func TestRepoPermissionPrivateOrgRepo(t *testing.T) { // plain user user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 5}).(*user_model.User) - perm, err := GetUserRepoPermission(repo, user) + perm, err := GetUserRepoPermission(db.DefaultContext, repo, user) assert.NoError(t, err) for _, unit := range repo.Units { assert.False(t, perm.CanRead(unit.Type)) @@ -203,7 +203,7 @@ func TestRepoPermissionPrivateOrgRepo(t *testing.T) { // change to collaborator to default write access assert.NoError(t, AddCollaborator(repo, user)) - perm, err = GetUserRepoPermission(repo, user) + perm, err = GetUserRepoPermission(db.DefaultContext, repo, user) assert.NoError(t, err) for _, unit := range repo.Units { assert.True(t, perm.CanRead(unit.Type)) @@ -211,7 +211,7 @@ func TestRepoPermissionPrivateOrgRepo(t *testing.T) { } assert.NoError(t, ChangeCollaborationAccessMode(repo, user.ID, perm_model.AccessModeRead)) - perm, err = GetUserRepoPermission(repo, user) + perm, err = GetUserRepoPermission(db.DefaultContext, repo, user) assert.NoError(t, err) for _, unit := range repo.Units { assert.True(t, perm.CanRead(unit.Type)) @@ -220,7 +220,7 @@ func TestRepoPermissionPrivateOrgRepo(t *testing.T) { // org member team owner owner := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 15}).(*user_model.User) - perm, err = GetUserRepoPermission(repo, owner) + perm, err = GetUserRepoPermission(db.DefaultContext, repo, owner) assert.NoError(t, err) for _, unit := range repo.Units { assert.True(t, perm.CanRead(unit.Type)) @@ -231,7 +231,7 @@ func TestRepoPermissionPrivateOrgRepo(t *testing.T) { team := unittest.AssertExistsAndLoadBean(t, &organization.Team{ID: 5}).(*organization.Team) err = organization.UpdateTeamUnits(team, nil) assert.NoError(t, err) - perm, err = GetUserRepoPermission(repo, owner) + perm, err = GetUserRepoPermission(db.DefaultContext, repo, owner) assert.NoError(t, err) for _, unit := range repo.Units { assert.True(t, perm.CanRead(unit.Type)) @@ -240,7 +240,7 @@ func TestRepoPermissionPrivateOrgRepo(t *testing.T) { // org member team tester tester := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2}).(*user_model.User) - perm, err = GetUserRepoPermission(repo, tester) + perm, err = GetUserRepoPermission(db.DefaultContext, repo, tester) assert.NoError(t, err) assert.True(t, perm.CanWrite(unit.TypeIssues)) assert.False(t, perm.CanWrite(unit.TypeCode)) @@ -248,7 +248,7 @@ func TestRepoPermissionPrivateOrgRepo(t *testing.T) { // org member team reviewer reviewer := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 20}).(*user_model.User) - perm, err = GetUserRepoPermission(repo, reviewer) + perm, err = GetUserRepoPermission(db.DefaultContext, repo, reviewer) assert.NoError(t, err) assert.False(t, perm.CanRead(unit.TypeIssues)) assert.False(t, perm.CanWrite(unit.TypeCode)) @@ -256,7 +256,7 @@ func TestRepoPermissionPrivateOrgRepo(t *testing.T) { // admin admin := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 1}).(*user_model.User) - perm, err = GetUserRepoPermission(repo, admin) + perm, err = GetUserRepoPermission(db.DefaultContext, repo, admin) assert.NoError(t, err) for _, unit := range repo.Units { assert.True(t, perm.CanRead(unit.Type)) diff --git a/models/review.go b/models/review.go index 51818bc722..a9e29a10e0 100644 --- a/models/review.go +++ b/models/review.go @@ -238,7 +238,7 @@ func isOfficialReviewer(ctx context.Context, issue *Issue, reviewers ...*user_mo if err != nil { return false, err } - if err = pr.loadProtectedBranch(ctx); err != nil { + if err = pr.LoadProtectedBranchCtx(ctx); err != nil { return false, err } if pr.ProtectedBranch == nil { @@ -265,7 +265,7 @@ func isOfficialReviewerTeam(ctx context.Context, issue *Issue, team *organizatio if err != nil { return false, err } - if err = pr.loadProtectedBranch(ctx); err != nil { + if err = pr.LoadProtectedBranchCtx(ctx); err != nil { return false, err } if pr.ProtectedBranch == nil { @@ -891,7 +891,7 @@ func CanMarkConversation(issue *Issue, doer *user_model.User) (permResult bool, return false, err } - p, err := GetUserRepoPermission(issue.Repo, doer) + p, err := GetUserRepoPermission(db.DefaultContext, issue.Repo, doer) if err != nil { return false, err } |