Move almost all functions' parameter db.Engine to context.Context (#19748)

* Move almost all functions' parameter db.Engine to context.Context
* remove some unnecessary wrap functions
tokarchuk/v1.17
Lunny Xiao 3 years ago committed by GitHub
parent d81e31ad78
commit fd7d83ace6
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
  1. 6
      cmd/admin.go
  2. 6
      integrations/api_issue_tracked_time_test.go
  3. 2
      integrations/api_repo_test.go
  4. 4
      integrations/auth_ldap_test.go
  5. 3
      integrations/git_test.go
  6. 2
      integrations/mirror_pull_test.go
  7. 3
      integrations/pull_merge_test.go
  8. 3
      integrations/pull_update_test.go
  9. 12
      models/action.go
  10. 21
      models/action_list.go
  11. 8
      models/asymkey/gpg_key.go
  12. 17
      models/asymkey/gpg_key_add.go
  13. 36
      models/asymkey/ssh_key.go
  14. 11
      models/asymkey/ssh_key_authorized_keys.go
  15. 18
      models/asymkey/ssh_key_authorized_principals.go
  16. 29
      models/asymkey/ssh_key_deploy.go
  17. 5
      models/asymkey/ssh_key_fingerprint.go
  18. 16
      models/asymkey/ssh_key_principals.go
  19. 134
      models/auth/oauth2.go
  20. 33
      models/auth/oauth2_test.go
  21. 10
      models/branches.go
  22. 25
      models/commit_status.go
  23. 2
      models/consistency.go
  24. 5
      models/db/index.go
  25. 145
      models/issue.go
  26. 70
      models/issue_assignees.go
  27. 11
      models/issue_assignees_test.go
  28. 61
      models/issue_comment.go
  29. 55
      models/issue_comment_list.go
  30. 9
      models/issue_dependency.go
  31. 124
      models/issue_label.go
  32. 54
      models/issue_label_test.go
  33. 73
      models/issue_list.go
  34. 26
      models/issue_project.go
  35. 15
      models/issue_stopwatch.go
  36. 5
      models/issue_stopwatch_test.go
  37. 16
      models/issue_test.go
  38. 51
      models/issue_tracked_time.go
  39. 15
      models/issue_tracked_time_test.go
  40. 43
      models/issue_watch.go
  41. 14
      models/issue_watch_test.go
  42. 25
      models/issue_xref.go
  43. 2
      models/issue_xref_test.go
  44. 13
      models/issues/content_history.go
  45. 21
      models/issues/content_history_test.go
  46. 26
      models/issues/milestone.go
  47. 4
      models/issues/milestone_test.go
  48. 108
      models/notification.go
  49. 7
      models/notification_test.go
  50. 6
      models/org.go
  51. 12
      models/org_team.go
  52. 65
      models/organization/org.go
  53. 39
      models/organization/org_test.go
  54. 4
      models/organization/org_user_test.go
  55. 31
      models/organization/team.go
  56. 10
      models/organization/team_test.go
  57. 17
      models/perm/access/access.go
  58. 18
      models/perm/access/repo_permission.go
  59. 41
      models/project/board.go
  60. 8
      models/project/issue.go
  61. 45
      models/project/project.go
  62. 13
      models/project/project_test.go
  63. 74
      models/pull.go
  64. 6
      models/pull_list.go
  65. 10
      models/pull_test.go
  66. 24
      models/release.go
  67. 57
      models/repo.go
  68. 66
      models/repo/attachment.go
  69. 16
      models/repo/attachment_test.go
  70. 17
      models/repo/avatar.go
  71. 11
      models/repo/collaboration.go
  72. 10
      models/repo/fork.go
  73. 26
      models/repo/language_stats.go
  74. 44
      models/repo/mirror.go
  75. 17
      models/repo/pushmirror.go
  76. 82
      models/repo/repo.go
  77. 28
      models/repo/repo_indexer.go
  78. 3
      models/repo/repo_list.go
  79. 19
      models/repo/repo_test.go
  80. 5
      models/repo/repo_unit.go
  81. 12
      models/repo/star.go
  82. 4
      models/repo/star_test.go
  83. 34
      models/repo/topic.go
  84. 13
      models/repo/update.go
  85. 37
      models/repo/user_repo.go
  86. 17
      models/repo/watch.go
  87. 14
      models/repo/watch_test.go
  88. 8
      models/repo_collaboration.go
  89. 4
      models/repo_generate.go
  90. 20
      models/repo_list.go
  91. 6
      models/repo_test.go
  92. 18
      models/repo_transfer.go
  93. 150
      models/review.go
  94. 12
      models/review_test.go
  95. 4
      models/statistic.go
  96. 14
      models/task.go
  97. 8
      models/user.go
  98. 9
      models/user/avatar.go
  99. 27
      models/user/email_address.go
  100. 4
      models/user/email_address_test.go
  101. Some files were not shown because too many files have changed in this diff Show More

@ -490,7 +490,7 @@ func runChangePassword(c *cli.Context) error {
return errors.New("The password you chose is on a list of stolen passwords previously exposed in public data breaches. Please try again with a different password.\nFor more details, see https://haveibeenpwned.com/Passwords") return errors.New("The password you chose is on a list of stolen passwords previously exposed in public data breaches. Please try again with a different password.\nFor more details, see https://haveibeenpwned.com/Passwords")
} }
uname := c.String("username") uname := c.String("username")
user, err := user_model.GetUserByName(uname) user, err := user_model.GetUserByName(ctx, uname)
if err != nil { if err != nil {
return err return err
} }
@ -659,7 +659,7 @@ func runDeleteUser(c *cli.Context) error {
if c.IsSet("email") { if c.IsSet("email") {
user, err = user_model.GetUserByEmail(c.String("email")) user, err = user_model.GetUserByEmail(c.String("email"))
} else if c.IsSet("username") { } else if c.IsSet("username") {
user, err = user_model.GetUserByName(c.String("username")) user, err = user_model.GetUserByName(ctx, c.String("username"))
} else { } else {
user, err = user_model.GetUserByID(c.Int64("id")) user, err = user_model.GetUserByID(c.Int64("id"))
} }
@ -689,7 +689,7 @@ func runGenerateAccessToken(c *cli.Context) error {
return err return err
} }
user, err := user_model.GetUserByName(c.String("username")) user, err := user_model.GetUserByName(ctx, c.String("username"))
if err != nil { if err != nil {
return err return err
} }

@ -33,7 +33,7 @@ func TestAPIGetTrackedTimes(t *testing.T) {
resp := session.MakeRequest(t, req, http.StatusOK) resp := session.MakeRequest(t, req, http.StatusOK)
var apiTimes api.TrackedTimeList var apiTimes api.TrackedTimeList
DecodeJSON(t, resp, &apiTimes) DecodeJSON(t, resp, &apiTimes)
expect, err := models.GetTrackedTimes(&models.FindTrackedTimesOptions{IssueID: issue2.ID}) expect, err := models.GetTrackedTimes(db.DefaultContext, &models.FindTrackedTimesOptions{IssueID: issue2.ID})
assert.NoError(t, err) assert.NoError(t, err)
assert.Len(t, apiTimes, 3) assert.Len(t, apiTimes, 3)
@ -83,7 +83,7 @@ func TestAPIDeleteTrackedTime(t *testing.T) {
session.MakeRequest(t, req, http.StatusNotFound) session.MakeRequest(t, req, http.StatusNotFound)
// Reset time of user 2 on issue 2 // Reset time of user 2 on issue 2
trackedSeconds, err := models.GetTrackedSeconds(models.FindTrackedTimesOptions{IssueID: 2, UserID: 2}) trackedSeconds, err := models.GetTrackedSeconds(db.DefaultContext, models.FindTrackedTimesOptions{IssueID: 2, UserID: 2})
assert.NoError(t, err) assert.NoError(t, err)
assert.Equal(t, int64(3661), trackedSeconds) assert.Equal(t, int64(3661), trackedSeconds)
@ -91,7 +91,7 @@ func TestAPIDeleteTrackedTime(t *testing.T) {
session.MakeRequest(t, req, http.StatusNoContent) session.MakeRequest(t, req, http.StatusNoContent)
session.MakeRequest(t, req, http.StatusNotFound) session.MakeRequest(t, req, http.StatusNotFound)
trackedSeconds, err = models.GetTrackedSeconds(models.FindTrackedTimesOptions{IssueID: 2, UserID: 2}) trackedSeconds, err = models.GetTrackedSeconds(db.DefaultContext, models.FindTrackedTimesOptions{IssueID: 2, UserID: 2})
assert.NoError(t, err) assert.NoError(t, err)
assert.Equal(t, int64(0), trackedSeconds) assert.Equal(t, int64(0), trackedSeconds)
} }

@ -388,7 +388,7 @@ func testAPIRepoMigrateConflict(t *testing.T, u *url.URL) {
defer util.RemoveAll(dstPath) defer util.RemoveAll(dstPath)
t.Run("CreateRepo", doAPICreateRepository(httpContext, false)) t.Run("CreateRepo", doAPICreateRepository(httpContext, false))
user, err := user_model.GetUserByName(httpContext.Username) user, err := user_model.GetUserByName(db.DefaultContext, httpContext.Username)
assert.NoError(t, err) assert.NoError(t, err)
userID := user.ID userID := user.ID

@ -321,7 +321,7 @@ func TestLDAPGroupTeamSyncAddMember(t *testing.T) {
addAuthSourceLDAP(t, "", "on", `{"cn=ship_crew,ou=people,dc=planetexpress,dc=com":{"org26": ["team11"]},"cn=admin_staff,ou=people,dc=planetexpress,dc=com": {"non-existent": ["non-existent"]}}`) addAuthSourceLDAP(t, "", "on", `{"cn=ship_crew,ou=people,dc=planetexpress,dc=com":{"org26": ["team11"]},"cn=admin_staff,ou=people,dc=planetexpress,dc=com": {"non-existent": ["non-existent"]}}`)
org, err := organization.GetOrgByName("org26") org, err := organization.GetOrgByName("org26")
assert.NoError(t, err) assert.NoError(t, err)
team, err := organization.GetTeam(org.ID, "team11") team, err := organization.GetTeam(db.DefaultContext, org.ID, "team11")
assert.NoError(t, err) assert.NoError(t, err)
auth.SyncExternalUsers(context.Background(), true) auth.SyncExternalUsers(context.Background(), true)
for _, gitLDAPUser := range gitLDAPUsers { for _, gitLDAPUser := range gitLDAPUsers {
@ -366,7 +366,7 @@ func TestLDAPGroupTeamSyncRemoveMember(t *testing.T) {
addAuthSourceLDAP(t, "", "on", `{"cn=dispatch,ou=people,dc=planetexpress,dc=com": {"org26": ["team11"]}}`) addAuthSourceLDAP(t, "", "on", `{"cn=dispatch,ou=people,dc=planetexpress,dc=com": {"org26": ["team11"]}}`)
org, err := organization.GetOrgByName("org26") org, err := organization.GetOrgByName("org26")
assert.NoError(t, err) assert.NoError(t, err)
team, err := organization.GetTeam(org.ID, "team11") team, err := organization.GetTeam(db.DefaultContext, org.ID, "team11")
assert.NoError(t, err) assert.NoError(t, err)
loginUserWithPassword(t, gitLDAPUsers[0].UserName, gitLDAPUsers[0].Password) loginUserWithPassword(t, gitLDAPUsers[0].UserName, gitLDAPUsers[0].Password)
user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ user := unittest.AssertExistsAndLoadBean(t, &user_model.User{

@ -18,6 +18,7 @@ import (
"time" "time"
"code.gitea.io/gitea/models" "code.gitea.io/gitea/models"
"code.gitea.io/gitea/models/db"
"code.gitea.io/gitea/models/perm" "code.gitea.io/gitea/models/perm"
repo_model "code.gitea.io/gitea/models/repo" repo_model "code.gitea.io/gitea/models/repo"
"code.gitea.io/gitea/models/unittest" "code.gitea.io/gitea/models/unittest"
@ -438,7 +439,7 @@ func doProtectBranch(ctx APITestContext, branch, userToWhitelist, unprotectedFil
}) })
ctx.Session.MakeRequest(t, req, http.StatusSeeOther) ctx.Session.MakeRequest(t, req, http.StatusSeeOther)
} else { } else {
user, err := user_model.GetUserByName(userToWhitelist) user, err := user_model.GetUserByName(db.DefaultContext, userToWhitelist)
assert.NoError(t, err) assert.NoError(t, err)
// Change branch to protected // Change branch to protected
req := NewRequestWithValues(t, "POST", fmt.Sprintf("/%s/%s/settings/branches/%s", url.PathEscape(ctx.Username), url.PathEscape(ctx.Reponame), url.PathEscape(branch)), map[string]string{ req := NewRequestWithValues(t, "POST", fmt.Sprintf("/%s/%s/settings/branches/%s", url.PathEscape(ctx.Username), url.PathEscape(ctx.Reponame), url.PathEscape(branch)), map[string]string{

@ -75,7 +75,7 @@ func TestMirrorPull(t *testing.T) {
IsTag: true, IsTag: true,
}, nil, "")) }, nil, ""))
_, err = repo_model.GetMirrorByRepoID(mirror.ID) _, err = repo_model.GetMirrorByRepoID(ctx, mirror.ID)
assert.NoError(t, err) assert.NoError(t, err)
ok := mirror_service.SyncPullMirror(ctx, mirror.ID) ok := mirror_service.SyncPullMirror(ctx, mirror.ID)

@ -18,6 +18,7 @@ import (
"time" "time"
"code.gitea.io/gitea/models" "code.gitea.io/gitea/models"
"code.gitea.io/gitea/models/db"
repo_model "code.gitea.io/gitea/models/repo" repo_model "code.gitea.io/gitea/models/repo"
"code.gitea.io/gitea/models/unittest" "code.gitea.io/gitea/models/unittest"
user_model "code.gitea.io/gitea/models/user" user_model "code.gitea.io/gitea/models/user"
@ -407,7 +408,7 @@ func TestConflictChecking(t *testing.T) {
assert.NoError(t, err) assert.NoError(t, err)
issue := unittest.AssertExistsAndLoadBean(t, &models.Issue{Title: "PR with conflict!"}).(*models.Issue) issue := unittest.AssertExistsAndLoadBean(t, &models.Issue{Title: "PR with conflict!"}).(*models.Issue)
conflictingPR, err := models.GetPullRequestByIssueID(issue.ID) conflictingPR, err := models.GetPullRequestByIssueID(db.DefaultContext, issue.ID)
assert.NoError(t, err) assert.NoError(t, err)
// Ensure conflictedFiles is populated. // Ensure conflictedFiles is populated.

@ -11,6 +11,7 @@ import (
"time" "time"
"code.gitea.io/gitea/models" "code.gitea.io/gitea/models"
"code.gitea.io/gitea/models/db"
"code.gitea.io/gitea/models/unittest" "code.gitea.io/gitea/models/unittest"
user_model "code.gitea.io/gitea/models/user" user_model "code.gitea.io/gitea/models/user"
"code.gitea.io/gitea/modules/git" "code.gitea.io/gitea/modules/git"
@ -165,7 +166,7 @@ func createOutdatedPR(t *testing.T, actor, forkOrg *user_model.User) *models.Pul
assert.NoError(t, err) assert.NoError(t, err)
issue := unittest.AssertExistsAndLoadBean(t, &models.Issue{Title: "Test Pull -to-update-"}).(*models.Issue) issue := unittest.AssertExistsAndLoadBean(t, &models.Issue{Title: "Test Pull -to-update-"}).(*models.Issue)
pr, err := models.GetPullRequestByIssueID(issue.ID) pr, err := models.GetPullRequestByIssueID(db.DefaultContext, issue.ID)
assert.NoError(t, err) assert.NoError(t, err)
return pr return pr

@ -222,9 +222,8 @@ func (a *Action) getCommentLink(ctx context.Context) string {
if a == nil { if a == nil {
return "#" return "#"
} }
e := db.GetEngine(ctx)
if a.Comment == nil && a.CommentID != 0 { if a.Comment == nil && a.CommentID != 0 {
a.Comment, _ = getCommentByID(e, a.CommentID) a.Comment, _ = GetCommentByID(ctx, a.CommentID)
} }
if a.Comment != nil { if a.Comment != nil {
return a.Comment.HTMLURL() return a.Comment.HTMLURL()
@ -239,7 +238,7 @@ func (a *Action) getCommentLink(ctx context.Context) string {
return "#" return "#"
} }
issue, err := getIssueByID(e, issueID) issue, err := getIssueByID(ctx, issueID)
if err != nil { if err != nil {
return "#" return "#"
} }
@ -340,8 +339,7 @@ func GetFeeds(ctx context.Context, opts GetFeedsOptions) (ActionList, error) {
return nil, err return nil, err
} }
e := db.GetEngine(ctx) sess := db.GetEngine(ctx).Where(cond).
sess := e.Where(cond).
Select("`action`.*"). // this line will avoid select other joined table's columns Select("`action`.*"). // this line will avoid select other joined table's columns
Join("INNER", "repository", "`repository`.id = `action`.repo_id") Join("INNER", "repository", "`repository`.id = `action`.repo_id")
@ -354,7 +352,7 @@ func GetFeeds(ctx context.Context, opts GetFeedsOptions) (ActionList, error) {
return nil, fmt.Errorf("Find: %v", err) return nil, fmt.Errorf("Find: %v", err)
} }
if err := ActionList(actions).loadAttributes(e); err != nil { if err := ActionList(actions).loadAttributes(ctx); err != nil {
return nil, fmt.Errorf("LoadAttributes: %v", err) return nil, fmt.Errorf("LoadAttributes: %v", err)
} }
@ -504,7 +502,7 @@ func notifyWatchers(ctx context.Context, actions ...*Action) error {
permIssue = make([]bool, len(watchers)) permIssue = make([]bool, len(watchers))
permPR = make([]bool, len(watchers)) permPR = make([]bool, len(watchers))
for i, watcher := range watchers { for i, watcher := range watchers {
user, err := user_model.GetUserByIDEngine(e, watcher.UserID) user, err := user_model.GetUserByIDCtx(ctx, watcher.UserID)
if err != nil { if err != nil {
permCode[i] = false permCode[i] = false
permIssue[i] = false permIssue[i] = false

@ -5,6 +5,7 @@
package models package models
import ( import (
"context"
"fmt" "fmt"
"code.gitea.io/gitea/models/db" "code.gitea.io/gitea/models/db"
@ -26,14 +27,14 @@ func (actions ActionList) getUserIDs() []int64 {
return container.KeysInt64(userIDs) return container.KeysInt64(userIDs)
} }
func (actions ActionList) loadUsers(e db.Engine) (map[int64]*user_model.User, error) { func (actions ActionList) loadUsers(ctx context.Context) (map[int64]*user_model.User, error) {
if len(actions) == 0 { if len(actions) == 0 {
return nil, nil return nil, nil
} }
userIDs := actions.getUserIDs() userIDs := actions.getUserIDs()
userMaps := make(map[int64]*user_model.User, len(userIDs)) userMaps := make(map[int64]*user_model.User, len(userIDs))
err := e. err := db.GetEngine(ctx).
In("id", userIDs). In("id", userIDs).
Find(&userMaps) Find(&userMaps)
if err != nil { if err != nil {
@ -56,14 +57,14 @@ func (actions ActionList) getRepoIDs() []int64 {
return container.KeysInt64(repoIDs) return container.KeysInt64(repoIDs)
} }
func (actions ActionList) loadRepositories(e db.Engine) error { func (actions ActionList) loadRepositories(ctx context.Context) error {
if len(actions) == 0 { if len(actions) == 0 {
return nil return nil
} }
repoIDs := actions.getRepoIDs() repoIDs := actions.getRepoIDs()
repoMaps := make(map[int64]*repo_model.Repository, len(repoIDs)) repoMaps := make(map[int64]*repo_model.Repository, len(repoIDs))
err := e.In("id", repoIDs).Find(&repoMaps) err := db.GetEngine(ctx).In("id", repoIDs).Find(&repoMaps)
if err != nil { if err != nil {
return fmt.Errorf("find repository: %v", err) return fmt.Errorf("find repository: %v", err)
} }
@ -74,7 +75,7 @@ func (actions ActionList) loadRepositories(e db.Engine) error {
return nil return nil
} }
func (actions ActionList) loadRepoOwner(e db.Engine, userMap map[int64]*user_model.User) (err error) { func (actions ActionList) loadRepoOwner(ctx context.Context, userMap map[int64]*user_model.User) (err error) {
if userMap == nil { if userMap == nil {
userMap = make(map[int64]*user_model.User) userMap = make(map[int64]*user_model.User)
} }
@ -85,7 +86,7 @@ func (actions ActionList) loadRepoOwner(e db.Engine, userMap map[int64]*user_mod
} }
repoOwner, ok := userMap[action.Repo.OwnerID] repoOwner, ok := userMap[action.Repo.OwnerID]
if !ok { if !ok {
repoOwner, err = user_model.GetUserByID(action.Repo.OwnerID) repoOwner, err = user_model.GetUserByIDCtx(ctx, action.Repo.OwnerID)
if err != nil { if err != nil {
if user_model.IsErrUserNotExist(err) { if user_model.IsErrUserNotExist(err) {
continue continue
@ -101,15 +102,15 @@ func (actions ActionList) loadRepoOwner(e db.Engine, userMap map[int64]*user_mod
} }
// loadAttributes loads all attributes // loadAttributes loads all attributes
func (actions ActionList) loadAttributes(e db.Engine) error { func (actions ActionList) loadAttributes(ctx context.Context) error {
userMap, err := actions.loadUsers(e) userMap, err := actions.loadUsers(ctx)
if err != nil { if err != nil {
return err return err
} }
if err := actions.loadRepositories(e); err != nil { if err := actions.loadRepositories(ctx); err != nil {
return err return err
} }
return actions.loadRepoOwner(e, userMap) return actions.loadRepoOwner(ctx, userMap)
} }

@ -198,16 +198,16 @@ func parseGPGKey(ownerID int64, e *openpgp.Entity, verified bool) (*GPGKey, erro
} }
// deleteGPGKey does the actual key deletion // deleteGPGKey does the actual key deletion
func deleteGPGKey(e db.Engine, keyID string) (int64, error) { func deleteGPGKey(ctx context.Context, keyID string) (int64, error) {
if keyID == "" { if keyID == "" {
return 0, fmt.Errorf("empty KeyId forbidden") // Should never happen but just to be sure return 0, fmt.Errorf("empty KeyId forbidden") // Should never happen but just to be sure
} }
// Delete imported key // Delete imported key
n, err := e.Where("key_id=?", keyID).Delete(new(GPGKeyImport)) n, err := db.GetEngine(ctx).Where("key_id=?", keyID).Delete(new(GPGKeyImport))
if err != nil { if err != nil {
return n, err return n, err
} }
return e.Where("key_id=?", keyID).Or("primary_key_id=?", keyID).Delete(new(GPGKey)) return db.GetEngine(ctx).Where("key_id=?", keyID).Or("primary_key_id=?", keyID).Delete(new(GPGKey))
} }
// DeleteGPGKey deletes GPG key information in database. // DeleteGPGKey deletes GPG key information in database.
@ -231,7 +231,7 @@ func DeleteGPGKey(doer *user_model.User, id int64) (err error) {
} }
defer committer.Close() defer committer.Close()
if _, err = deleteGPGKey(db.GetEngine(ctx), key.KeyID); err != nil { if _, err = deleteGPGKey(ctx, key.KeyID); err != nil {
return err return err
} }

@ -5,6 +5,7 @@
package asymkey package asymkey
import ( import (
"context"
"strings" "strings"
"code.gitea.io/gitea/models/db" "code.gitea.io/gitea/models/db"
@ -29,21 +30,21 @@ import (
// This file contains functions relating to adding GPG Keys // This file contains functions relating to adding GPG Keys
// addGPGKey add key, import and subkeys to database // addGPGKey add key, import and subkeys to database
func addGPGKey(e db.Engine, key *GPGKey, content string) (err error) { func addGPGKey(ctx context.Context, key *GPGKey, content string) (err error) {
// Add GPGKeyImport // Add GPGKeyImport
if _, err = e.Insert(GPGKeyImport{ if err = db.Insert(ctx, &GPGKeyImport{
KeyID: key.KeyID, KeyID: key.KeyID,
Content: content, Content: content,
}); err != nil { }); err != nil {
return err return err
} }
// Save GPG primary key. // Save GPG primary key.
if _, err = e.Insert(key); err != nil { if err = db.Insert(ctx, key); err != nil {
return err return err
} }
// Save GPG subs key. // Save GPG subs key.
for _, subkey := range key.SubsKey { for _, subkey := range key.SubsKey {
if err := addGPGSubKey(e, subkey); err != nil { if err := addGPGSubKey(ctx, subkey); err != nil {
return err return err
} }
} }
@ -51,14 +52,14 @@ func addGPGKey(e db.Engine, key *GPGKey, content string) (err error) {
} }
// addGPGSubKey add subkeys to database // addGPGSubKey add subkeys to database
func addGPGSubKey(e db.Engine, key *GPGKey) (err error) { func addGPGSubKey(ctx context.Context, key *GPGKey) (err error) {
// Save GPG primary key. // Save GPG primary key.
if _, err = e.Insert(key); err != nil { if err = db.Insert(ctx, key); err != nil {
return err return err
} }
// Save GPG subs key. // Save GPG subs key.
for _, subkey := range key.SubsKey { for _, subkey := range key.SubsKey {
if err := addGPGSubKey(e, subkey); err != nil { if err := addGPGSubKey(ctx, subkey); err != nil {
return err return err
} }
} }
@ -158,7 +159,7 @@ func AddGPGKey(ownerID int64, content, token, signature string) ([]*GPGKey, erro
return nil, err return nil, err
} }
if err = addGPGKey(db.GetEngine(ctx), key, content); err != nil { if err = addGPGKey(ctx, key, content); err != nil {
return nil, err return nil, err
} }
keys = append(keys, key) keys = append(keys, key)

@ -75,7 +75,7 @@ func (key *PublicKey) AuthorizedString() string {
return AuthorizedStringForKey(key) return AuthorizedStringForKey(key)
} }
func addKey(e db.Engine, key *PublicKey) (err error) { func addKey(ctx context.Context, key *PublicKey) (err error) {
if len(key.Fingerprint) == 0 { if len(key.Fingerprint) == 0 {
key.Fingerprint, err = calcFingerprint(key.Content) key.Fingerprint, err = calcFingerprint(key.Content)
if err != nil { if err != nil {
@ -84,7 +84,7 @@ func addKey(e db.Engine, key *PublicKey) (err error) {
} }
// Save SSH key. // Save SSH key.
if _, err = e.Insert(key); err != nil { if err = db.Insert(ctx, key); err != nil {
return err return err
} }
@ -105,14 +105,13 @@ func AddPublicKey(ownerID int64, name, content string, authSourceID int64) (*Pub
return nil, err return nil, err
} }
defer committer.Close() defer committer.Close()
sess := db.GetEngine(ctx)
if err := checkKeyFingerprint(sess, fingerprint); err != nil { if err := checkKeyFingerprint(ctx, fingerprint); err != nil {
return nil, err return nil, err
} }
// Key name of same user cannot be duplicated. // Key name of same user cannot be duplicated.
has, err := sess. has, err := db.GetEngine(ctx).
Where("owner_id = ? AND name = ?", ownerID, name). Where("owner_id = ? AND name = ?", ownerID, name).
Get(new(PublicKey)) Get(new(PublicKey))
if err != nil { if err != nil {
@ -130,7 +129,7 @@ func AddPublicKey(ownerID int64, name, content string, authSourceID int64) (*Pub
Type: KeyTypeUser, Type: KeyTypeUser,
LoginSourceID: authSourceID, LoginSourceID: authSourceID,
} }
if err = addKey(sess, key); err != nil { if err = addKey(ctx, key); err != nil {
return nil, fmt.Errorf("addKey: %v", err) return nil, fmt.Errorf("addKey: %v", err)
} }
@ -151,9 +150,11 @@ func GetPublicKeyByID(keyID int64) (*PublicKey, error) {
return key, nil return key, nil
} }
func searchPublicKeyByContentWithEngine(e db.Engine, content string) (*PublicKey, error) { // SearchPublicKeyByContent searches content as prefix (leak e-mail part)
// and returns public key found.
func SearchPublicKeyByContent(ctx context.Context, content string) (*PublicKey, error) {
key := new(PublicKey) key := new(PublicKey)
has, err := e. has, err := db.GetEngine(ctx).
Where("content like ?", content+"%"). Where("content like ?", content+"%").
Get(key) Get(key)
if err != nil { if err != nil {
@ -164,15 +165,11 @@ func searchPublicKeyByContentWithEngine(e db.Engine, content string) (*PublicKey
return key, nil return key, nil
} }
// SearchPublicKeyByContent searches content as prefix (leak e-mail part) // SearchPublicKeyByContentExact searches content
// and returns public key found. // and returns public key found.
func SearchPublicKeyByContent(content string) (*PublicKey, error) { func SearchPublicKeyByContentExact(ctx context.Context, content string) (*PublicKey, error) {
return searchPublicKeyByContentWithEngine(db.GetEngine(db.DefaultContext), content)
}
func searchPublicKeyByContentExactWithEngine(e db.Engine, content string) (*PublicKey, error) {
key := new(PublicKey) key := new(PublicKey)
has, err := e. has, err := db.GetEngine(ctx).
Where("content = ?", content). Where("content = ?", content).
Get(key) Get(key)
if err != nil { if err != nil {
@ -183,12 +180,6 @@ func searchPublicKeyByContentExactWithEngine(e db.Engine, content string) (*Publ
return key, nil return key, nil
} }
// SearchPublicKeyByContentExact searches content
// and returns public key found.
func SearchPublicKeyByContentExact(content string) (*PublicKey, error) {
return searchPublicKeyByContentExactWithEngine(db.GetEngine(db.DefaultContext), content)
}
// SearchPublicKey returns a list of public keys matching the provided arguments. // SearchPublicKey returns a list of public keys matching the provided arguments.
func SearchPublicKey(uid int64, fingerprint string) ([]*PublicKey, error) { func SearchPublicKey(uid int64, fingerprint string) ([]*PublicKey, error) {
keys := make([]*PublicKey, 0, 5) keys := make([]*PublicKey, 0, 5)
@ -335,12 +326,11 @@ func deleteKeysMarkedForDeletion(keys []string) (bool, error) {
return false, err return false, err
} }
defer committer.Close() defer committer.Close()
sess := db.GetEngine(ctx)
// Delete keys marked for deletion // Delete keys marked for deletion
var sshKeysNeedUpdate bool var sshKeysNeedUpdate bool
for _, KeyToDelete := range keys { for _, KeyToDelete := range keys {
key, err := searchPublicKeyByContentWithEngine(sess, KeyToDelete) key, err := SearchPublicKeyByContent(ctx, KeyToDelete)
if err != nil { if err != nil {
log.Error("SearchPublicKeyByContent: %v", err) log.Error("SearchPublicKeyByContent: %v", err)
continue continue

@ -6,6 +6,7 @@ package asymkey
import ( import (
"bufio" "bufio"
"context"
"fmt" "fmt"
"io" "io"
"os" "os"
@ -165,7 +166,7 @@ func RewriteAllPublicKeys() error {
} }
} }
if err := RegeneratePublicKeys(t); err != nil { if err := RegeneratePublicKeys(db.DefaultContext, t); err != nil {
return err return err
} }
@ -174,12 +175,8 @@ func RewriteAllPublicKeys() error {
} }
// RegeneratePublicKeys regenerates the authorized_keys file // RegeneratePublicKeys regenerates the authorized_keys file
func RegeneratePublicKeys(t io.StringWriter) error { func RegeneratePublicKeys(ctx context.Context, t io.StringWriter) error {
return regeneratePublicKeys(db.GetEngine(db.DefaultContext), t) if err := db.GetEngine(ctx).Where("type != ?", KeyTypePrincipal).Iterate(new(PublicKey), func(idx int, bean interface{}) (err error) {
}
func regeneratePublicKeys(e db.Engine, t io.StringWriter) error {
if err := e.Where("type != ?", KeyTypePrincipal).Iterate(new(PublicKey), func(idx int, bean interface{}) (err error) {
_, err = t.WriteString((bean.(*PublicKey)).AuthorizedString()) _, err = t.WriteString((bean.(*PublicKey)).AuthorizedString())
return err return err
}); err != nil { }); err != nil {

@ -6,6 +6,7 @@ package asymkey
import ( import (
"bufio" "bufio"
"context"
"fmt" "fmt"
"io" "io"
"os" "os"
@ -42,11 +43,7 @@ const authorizedPrincipalsFile = "authorized_principals"
// RewriteAllPrincipalKeys removes any authorized principal and rewrite all keys from database again. // RewriteAllPrincipalKeys removes any authorized principal and rewrite all keys from database again.
// Note: db.GetEngine(db.DefaultContext).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. // outside any session scope independently.
func RewriteAllPrincipalKeys() error { func RewriteAllPrincipalKeys(ctx context.Context) error {
return rewriteAllPrincipalKeys(db.GetEngine(db.DefaultContext))
}
func rewriteAllPrincipalKeys(e db.Engine) error {
// Don't rewrite key if internal server // Don't rewrite key if internal server
if setting.SSH.StartBuiltinServer || !setting.SSH.CreateAuthorizedPrincipalsFile { if setting.SSH.StartBuiltinServer || !setting.SSH.CreateAuthorizedPrincipalsFile {
return nil return nil
@ -92,7 +89,7 @@ func rewriteAllPrincipalKeys(e db.Engine) error {
} }
} }
if err := regeneratePrincipalKeys(e, t); err != nil { if err := regeneratePrincipalKeys(ctx, t); err != nil {
return err return err
} }
@ -100,13 +97,8 @@ func rewriteAllPrincipalKeys(e db.Engine) error {
return util.Rename(tmpPath, fPath) return util.Rename(tmpPath, fPath)
} }
// RegeneratePrincipalKeys regenerates the authorized_principals file func regeneratePrincipalKeys(ctx context.Context, t io.StringWriter) error {
func RegeneratePrincipalKeys(t io.StringWriter) error { if err := db.GetEngine(ctx).Where("type = ?", KeyTypePrincipal).Iterate(new(PublicKey), func(idx int, bean interface{}) (err error) {
return regeneratePrincipalKeys(db.GetEngine(db.DefaultContext), t)
}
func regeneratePrincipalKeys(e db.Engine, t io.StringWriter) error {
if err := e.Where("type = ?", KeyTypePrincipal).Iterate(new(PublicKey), func(idx int, bean interface{}) (err error) {
_, err = t.WriteString((bean.(*PublicKey)).AuthorizedString()) _, err = t.WriteString((bean.(*PublicKey)).AuthorizedString())
return err return err
}); err != nil { }); err != nil {

@ -67,9 +67,9 @@ func init() {
db.RegisterModel(new(DeployKey)) db.RegisterModel(new(DeployKey))
} }
func checkDeployKey(e db.Engine, keyID, repoID int64, name string) error { func checkDeployKey(ctx context.Context, keyID, repoID int64, name string) error {
// Note: We want error detail, not just true or false here. // Note: We want error detail, not just true or false here.
has, err := e. has, err := db.GetEngine(ctx).
Where("key_id = ? AND repo_id = ?", keyID, repoID). Where("key_id = ? AND repo_id = ?", keyID, repoID).
Get(new(DeployKey)) Get(new(DeployKey))
if err != nil { if err != nil {
@ -78,7 +78,7 @@ func checkDeployKey(e db.Engine, keyID, repoID int64, name string) error {
return ErrDeployKeyAlreadyExist{keyID, repoID} return ErrDeployKeyAlreadyExist{keyID, repoID}
} }
has, err = e. has, err = db.GetEngine(ctx).
Where("repo_id = ? AND name = ?", repoID, name). Where("repo_id = ? AND name = ?", repoID, name).
Get(new(DeployKey)) Get(new(DeployKey))
if err != nil { if err != nil {
@ -91,8 +91,8 @@ func checkDeployKey(e db.Engine, keyID, repoID int64, name string) error {
} }
// addDeployKey adds new key-repo relation. // addDeployKey adds new key-repo relation.
func addDeployKey(e db.Engine, keyID, repoID int64, name, fingerprint string, mode perm.AccessMode) (*DeployKey, error) { func addDeployKey(ctx context.Context, keyID, repoID int64, name, fingerprint string, mode perm.AccessMode) (*DeployKey, error) {
if err := checkDeployKey(e, keyID, repoID, name); err != nil { if err := checkDeployKey(ctx, keyID, repoID, name); err != nil {
return nil, err return nil, err
} }
@ -103,8 +103,7 @@ func addDeployKey(e db.Engine, keyID, repoID int64, name, fingerprint string, mo
Fingerprint: fingerprint, Fingerprint: fingerprint,
Mode: mode, Mode: mode,
} }
_, err := e.Insert(key) return key, db.Insert(ctx, key)
return key, err
} }
// HasDeployKey returns true if public key is a deploy key of given repository. // HasDeployKey returns true if public key is a deploy key of given repository.
@ -133,12 +132,10 @@ func AddDeployKey(repoID int64, name, content string, readOnly bool) (*DeployKey
} }
defer committer.Close() defer committer.Close()
sess := db.GetEngine(ctx)
pkey := &PublicKey{ pkey := &PublicKey{
Fingerprint: fingerprint, Fingerprint: fingerprint,
} }
has, err := sess.Get(pkey) has, err := db.GetByBean(ctx, pkey)
if err != nil { if err != nil {
return nil, err return nil, err
} }
@ -153,12 +150,12 @@ func AddDeployKey(repoID int64, name, content string, readOnly bool) (*DeployKey
pkey.Type = KeyTypeDeploy pkey.Type = KeyTypeDeploy
pkey.Content = content pkey.Content = content
pkey.Name = name pkey.Name = name
if err = addKey(sess, pkey); err != nil { if err = addKey(ctx, pkey); err != nil {
return nil, fmt.Errorf("addKey: %v", err) return nil, fmt.Errorf("addKey: %v", err)
} }
} }
key, err := addDeployKey(sess, pkey.ID, repoID, name, pkey.Fingerprint, accessMode) key, err := addDeployKey(ctx, pkey.ID, repoID, name, pkey.Fingerprint, accessMode)
if err != nil { if err != nil {
return nil, err return nil, err
} }
@ -179,16 +176,12 @@ func GetDeployKeyByID(ctx context.Context, id int64) (*DeployKey, error) {
} }
// GetDeployKeyByRepo returns deploy key by given public key ID and repository ID. // GetDeployKeyByRepo returns deploy key by given public key ID and repository ID.
func GetDeployKeyByRepo(keyID, repoID int64) (*DeployKey, error) { func GetDeployKeyByRepo(ctx context.Context, keyID, repoID int64) (*DeployKey, error) {
return getDeployKeyByRepo(db.GetEngine(db.DefaultContext), keyID, repoID)
}
func getDeployKeyByRepo(e db.Engine, keyID, repoID int64) (*DeployKey, error) {
key := &DeployKey{ key := &DeployKey{
KeyID: keyID, KeyID: keyID,
RepoID: repoID, RepoID: repoID,
} }
has, err := e.Get(key) has, err := db.GetByBean(ctx, key)
if err != nil { if err != nil {
return nil, err return nil, err
} else if !has { } else if !has {

@ -5,6 +5,7 @@
package asymkey package asymkey
import ( import (
"context"
"errors" "errors"
"fmt" "fmt"
"strings" "strings"
@ -31,8 +32,8 @@ import (
// checkKeyFingerprint only checks if key fingerprint has been used as public key, // checkKeyFingerprint only checks if key fingerprint has been used as public key,
// it is OK to use same key as deploy key for multiple repositories/users. // it is OK to use same key as deploy key for multiple repositories/users.
func checkKeyFingerprint(e db.Engine, fingerprint string) error { func checkKeyFingerprint(ctx context.Context, fingerprint string) error {
has, err := e.Get(&PublicKey{ has, err := db.GetByBean(ctx, &PublicKey{
Fingerprint: fingerprint, Fingerprint: fingerprint,
}) })
if err != nil { if err != nil {

@ -31,10 +31,9 @@ func AddPrincipalKey(ownerID int64, content string, authSourceID int64) (*Public
return nil, err return nil, err
} }
defer committer.Close() defer committer.Close()
sess := db.GetEngine(ctx)
// Principals cannot be duplicated. // Principals cannot be duplicated.
has, err := sess. has, err := db.GetEngine(ctx).
Where("content = ? AND type = ?", content, KeyTypePrincipal). Where("content = ? AND type = ?", content, KeyTypePrincipal).
Get(new(PublicKey)) Get(new(PublicKey))
if err != nil { if err != nil {
@ -51,7 +50,7 @@ func AddPrincipalKey(ownerID int64, content string, authSourceID int64) (*Public
Type: KeyTypePrincipal, Type: KeyTypePrincipal,
LoginSourceID: authSourceID, LoginSourceID: authSourceID,
} }
if err = addPrincipalKey(sess, key); err != nil { if err = db.Insert(ctx, key); err != nil {
return nil, fmt.Errorf("addKey: %v", err) return nil, fmt.Errorf("addKey: %v", err)
} }
@ -61,16 +60,7 @@ func AddPrincipalKey(ownerID int64, content string, authSourceID int64) (*Public
committer.Close() committer.Close()
return key, RewriteAllPrincipalKeys() return key, RewriteAllPrincipalKeys(db.DefaultContext)
}
func addPrincipalKey(e db.Engine, key *PublicKey) (err error) {
// Save Key representing a principal.
if _, err = e.Insert(key); err != nil {
return err
}
return nil
} }
// CheckPrincipalKeyString strips spaces and returns an error if the given principal contains newlines // CheckPrincipalKeyString strips spaces and returns an error if the given principal contains newlines

@ -92,13 +92,9 @@ func (app *OAuth2Application) ValidateClientSecret(secret []byte) bool {
} }
// GetGrantByUserID returns a OAuth2Grant by its user and application ID // GetGrantByUserID returns a OAuth2Grant by its user and application ID
func (app *OAuth2Application) GetGrantByUserID(userID int64) (*OAuth2Grant, error) { func (app *OAuth2Application) GetGrantByUserID(ctx context.Context, userID int64) (grant *OAuth2Grant, err error) {
return app.getGrantByUserID(db.GetEngine(db.DefaultContext), userID)
}
func (app *OAuth2Application) getGrantByUserID(e db.Engine, userID int64) (grant *OAuth2Grant, err error) {
grant = new(OAuth2Grant) grant = new(OAuth2Grant)
if has, err := e.Where("user_id = ? AND application_id = ?", userID, app.ID).Get(grant); err != nil { if has, err := db.GetEngine(ctx).Where("user_id = ? AND application_id = ?", userID, app.ID).Get(grant); err != nil {
return nil, err return nil, err
} else if !has { } else if !has {
return nil, nil return nil, nil
@ -107,17 +103,13 @@ func (app *OAuth2Application) getGrantByUserID(e db.Engine, userID int64) (grant
} }
// CreateGrant generates a grant for an user // CreateGrant generates a grant for an user
func (app *OAuth2Application) CreateGrant(userID int64, scope string) (*OAuth2Grant, error) { func (app *OAuth2Application) CreateGrant(ctx context.Context, userID int64, scope string) (*OAuth2Grant, error) {
return app.createGrant(db.GetEngine(db.DefaultContext), userID, scope)
}
func (app *OAuth2Application) createGrant(e db.Engine, userID int64, scope string) (*OAuth2Grant, error) {
grant := &OAuth2Grant{ grant := &OAuth2Grant{
ApplicationID: app.ID, ApplicationID: app.ID,
UserID: userID, UserID: userID,
Scope: scope, Scope: scope,
} }
_, err := e.Insert(grant) err := db.Insert(ctx, grant)
if err != nil { if err != nil {
return nil, err return nil, err
} }
@ -125,13 +117,9 @@ 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. // GetOAuth2ApplicationByClientID returns the oauth2 application with the given client_id. Returns an error if not found.
func GetOAuth2ApplicationByClientID(clientID string) (app *OAuth2Application, err error) { func GetOAuth2ApplicationByClientID(ctx context.Context, clientID string) (app *OAuth2Application, err error) {
return getOAuth2ApplicationByClientID(db.GetEngine(db.DefaultContext), clientID)
}
func getOAuth2ApplicationByClientID(e db.Engine, clientID string) (app *OAuth2Application, err error) {
app = new(OAuth2Application) app = new(OAuth2Application)
has, err := e.Where("client_id = ?", clientID).Get(app) has, err := db.GetEngine(ctx).Where("client_id = ?", clientID).Get(app)
if !has { if !has {
return nil, ErrOAuthClientIDInvalid{ClientID: clientID} return nil, ErrOAuthClientIDInvalid{ClientID: clientID}
} }
@ -139,13 +127,9 @@ func getOAuth2ApplicationByClientID(e db.Engine, clientID string) (app *OAuth2Ap
} }
// GetOAuth2ApplicationByID returns the oauth2 application with the given id. Returns an error if not found. // GetOAuth2ApplicationByID returns the oauth2 application with the given id. Returns an error if not found.
func GetOAuth2ApplicationByID(id int64) (app *OAuth2Application, err error) { func GetOAuth2ApplicationByID(ctx context.Context, id int64) (app *OAuth2Application, err error) {
return getOAuth2ApplicationByID(db.GetEngine(db.DefaultContext), id)
}
func getOAuth2ApplicationByID(e db.Engine, id int64) (app *OAuth2Application, err error) {
app = new(OAuth2Application) app = new(OAuth2Application)
has, err := e.ID(id).Get(app) has, err := db.GetEngine(ctx).ID(id).Get(app)
if err != nil { if err != nil {
return nil, err return nil, err
} }
@ -156,13 +140,9 @@ func getOAuth2ApplicationByID(e db.Engine, id int64) (app *OAuth2Application, er
} }
// GetOAuth2ApplicationsByUserID returns all oauth2 applications owned by the user // GetOAuth2ApplicationsByUserID returns all oauth2 applications owned by the user
func GetOAuth2ApplicationsByUserID(userID int64) (apps []*OAuth2Application, err error) { func GetOAuth2ApplicationsByUserID(ctx context.Context, userID int64) (apps []*OAuth2Application, err error) {
return getOAuth2ApplicationsByUserID(db.GetEngine(db.DefaultContext), userID)
}
func getOAuth2ApplicationsByUserID(e db.Engine, userID int64) (apps []*OAuth2Application, err error) {
apps = make([]*OAuth2Application, 0) apps = make([]*OAuth2Application, 0)
err = e.Where("uid = ?", userID).Find(&apps) err = db.GetEngine(ctx).Where("uid = ?", userID).Find(&apps)
return return
} }
@ -174,11 +154,7 @@ type CreateOAuth2ApplicationOptions struct {
} }
// CreateOAuth2Application inserts a new oauth2 application // CreateOAuth2Application inserts a new oauth2 application
func CreateOAuth2Application(opts CreateOAuth2ApplicationOptions) (*OAuth2Application, error) { func CreateOAuth2Application(ctx context.Context, opts CreateOAuth2ApplicationOptions) (*OAuth2Application, error) {
return createOAuth2Application(db.GetEngine(db.DefaultContext), opts)
}
func createOAuth2Application(e db.Engine, opts CreateOAuth2ApplicationOptions) (*OAuth2Application, error) {
clientID := uuid.New().String() clientID := uuid.New().String()
app := &OAuth2Application{ app := &OAuth2Application{
UID: opts.UserID, UID: opts.UserID,
@ -186,7 +162,7 @@ func createOAuth2Application(e db.Engine, opts CreateOAuth2ApplicationOptions) (
ClientID: clientID, ClientID: clientID,
RedirectURIs: opts.RedirectURIs, RedirectURIs: opts.RedirectURIs,
} }
if _, err := e.Insert(app); err != nil { if err := db.Insert(ctx, app); err != nil {
return nil, err return nil, err
} }
return app, nil return app, nil
@ -207,9 +183,8 @@ func UpdateOAuth2Application(opts UpdateOAuth2ApplicationOptions) (*OAuth2Applic
return nil, err return nil, err
} }
defer committer.Close() defer committer.Close()
sess := db.GetEngine(ctx)
app, err := getOAuth2ApplicationByID(sess, opts.ID) app, err := GetOAuth2ApplicationByID(ctx, opts.ID)
if err != nil { if err != nil {
return nil, err return nil, err
} }
@ -220,7 +195,7 @@ func UpdateOAuth2Application(opts UpdateOAuth2ApplicationOptions) (*OAuth2Applic
app.Name = opts.Name app.Name = opts.Name
app.RedirectURIs = opts.RedirectURIs app.RedirectURIs = opts.RedirectURIs
if err = updateOAuth2Application(sess, app); err != nil { if err = updateOAuth2Application(ctx, app); err != nil {
return nil, err return nil, err
} }
app.ClientSecret = "" app.ClientSecret = ""
@ -228,14 +203,15 @@ func UpdateOAuth2Application(opts UpdateOAuth2ApplicationOptions) (*OAuth2Applic
return app, committer.Commit() return app, committer.Commit()
} }
func updateOAuth2Application(e db.Engine, app *OAuth2Application) error { func updateOAuth2Application(ctx context.Context, app *OAuth2Application) error {
if _, err := e.ID(app.ID).Update(app); err != nil { if _, err := db.GetEngine(ctx).ID(app.ID).Update(app); err != nil {
return err return err
} }
return nil return nil
} }
func deleteOAuth2Application(sess db.Engine, id, userid int64) error { func deleteOAuth2Application(ctx context.Context, id, userid int64) error {
sess := db.GetEngine(ctx)
if deleted, err := sess.Delete(&OAuth2Application{ID: id, UID: userid}); err != nil { if deleted, err := sess.Delete(&OAuth2Application{ID: id, UID: userid}); err != nil {
return err return err
} else if deleted == 0 { } else if deleted == 0 {
@ -269,7 +245,7 @@ func DeleteOAuth2Application(id, userid int64) error {
return err return err
} }
defer committer.Close() defer committer.Close()
if err := deleteOAuth2Application(db.GetEngine(ctx), id, userid); err != nil { if err := deleteOAuth2Application(ctx, id, userid); err != nil {
return err return err
} }
return committer.Commit() return committer.Commit()
@ -328,21 +304,13 @@ func (code *OAuth2AuthorizationCode) GenerateRedirectURI(state string) (redirect
} }
// Invalidate deletes the auth code from the database to invalidate this code // Invalidate deletes the auth code from the database to invalidate this code
func (code *OAuth2AuthorizationCode) Invalidate() error { func (code *OAuth2AuthorizationCode) Invalidate(ctx context.Context) error {
return code.invalidate(db.GetEngine(db.DefaultContext)) _, err := db.GetEngine(ctx).ID(code.ID).NoAutoCondition().Delete(code)
}
func (code *OAuth2AuthorizationCode) invalidate(e db.Engine) error {
_, err := e.Delete(code)
return err return err
} }
// ValidateCodeChallenge validates the given verifier against the saved code challenge. This is part of the PKCE implementation. // ValidateCodeChallenge validates the given verifier against the saved code challenge. This is part of the PKCE implementation.
func (code *OAuth2AuthorizationCode) ValidateCodeChallenge(verifier string) bool { func (code *OAuth2AuthorizationCode) ValidateCodeChallenge(verifier string) bool {
return code.validateCodeChallenge(verifier)
}
func (code *OAuth2AuthorizationCode) validateCodeChallenge(verifier string) bool {
switch code.CodeChallengeMethod { switch code.CodeChallengeMethod {
case "S256": case "S256":
// base64url(SHA256(verifier)) see https://tools.ietf.org/html/rfc7636#section-4.6 // base64url(SHA256(verifier)) see https://tools.ietf.org/html/rfc7636#section-4.6
@ -360,19 +328,15 @@ func (code *OAuth2AuthorizationCode) validateCodeChallenge(verifier string) bool
} }
// GetOAuth2AuthorizationByCode returns an authorization by its code // GetOAuth2AuthorizationByCode returns an authorization by its code
func GetOAuth2AuthorizationByCode(code string) (*OAuth2AuthorizationCode, error) { func GetOAuth2AuthorizationByCode(ctx context.Context, code string) (auth *OAuth2AuthorizationCode, err error) {
return getOAuth2AuthorizationByCode(db.GetEngine(db.DefaultContext), code)
}
func getOAuth2AuthorizationByCode(e db.Engine, code string) (auth *OAuth2AuthorizationCode, err error) {
auth = new(OAuth2AuthorizationCode) auth = new(OAuth2AuthorizationCode)
if has, err := e.Where("code = ?", code).Get(auth); err != nil { if has, err := db.GetEngine(ctx).Where("code = ?", code).Get(auth); err != nil {
return nil, err return nil, err
} else if !has { } else if !has {
return nil, nil return nil, nil
} }
auth.Grant = new(OAuth2Grant) auth.Grant = new(OAuth2Grant)
if has, err := e.ID(auth.GrantID).Get(auth.Grant); err != nil { if has, err := db.GetEngine(ctx).ID(auth.GrantID).Get(auth.Grant); err != nil {
return nil, err return nil, err
} else if !has { } else if !has {
return nil, nil return nil, nil
@ -401,11 +365,7 @@ func (grant *OAuth2Grant) TableName() string {
} }
// GenerateNewAuthorizationCode generates a new authorization code for a grant and saves it to the database // 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) { func (grant *OAuth2Grant) GenerateNewAuthorizationCode(ctx context.Context, redirectURI, codeChallenge, codeChallengeMethod string) (code *OAuth2AuthorizationCode, err error) {
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) {
rBytes, err := util.CryptoRandomBytes(32) rBytes, err := util.CryptoRandomBytes(32)
if err != nil { if err != nil {
return &OAuth2AuthorizationCode{}, err return &OAuth2AuthorizationCode{}, err
@ -422,23 +382,19 @@ func (grant *OAuth2Grant) generateNewAuthorizationCode(e db.Engine, redirectURI,
CodeChallenge: codeChallenge, CodeChallenge: codeChallenge,
CodeChallengeMethod: codeChallengeMethod, CodeChallengeMethod: codeChallengeMethod,
} }
if _, err := e.Insert(code); err != nil { if err := db.Insert(ctx, code); err != nil {
return nil, err return nil, err
} }
return code, nil return code, nil
} }
// IncreaseCounter increases the counter and updates the grant // IncreaseCounter increases the counter and updates the grant
func (grant *OAuth2Grant) IncreaseCounter() error { func (grant *OAuth2Grant) IncreaseCounter(ctx context.Context) error {
return grant.increaseCount(db.GetEngine(db.DefaultContext)) _, err := db.GetEngine(ctx).ID(grant.ID).Incr("counter").Update(new(OAuth2Grant))
}
func (grant *OAuth2Grant) increaseCount(e db.Engine) error {
_, err := e.ID(grant.ID).Incr("counter").Update(new(OAuth2Grant))
if err != nil { if err != nil {
return err return err
} }
updatedGrant, err := getOAuth2GrantByID(e, grant.ID) updatedGrant, err := GetOAuth2GrantByID(ctx, grant.ID)
if err != nil { if err != nil {
return err return err
} }
@ -457,13 +413,9 @@ func (grant *OAuth2Grant) ScopeContains(scope string) bool {
} }
// SetNonce updates the current nonce value of a grant // SetNonce updates the current nonce value of a grant
func (grant *OAuth2Grant) SetNonce(nonce string) error { func (grant *OAuth2Grant) SetNonce(ctx context.Context, nonce string) error {
return grant.setNonce(db.GetEngine(db.DefaultContext), nonce)
}
func (grant *OAuth2Grant) setNonce(e db.Engine, nonce string) error {
grant.Nonce = nonce grant.Nonce = nonce
_, err := e.ID(grant.ID).Cols("nonce").Update(grant) _, err := db.GetEngine(ctx).ID(grant.ID).Cols("nonce").Update(grant)
if err != nil { if err != nil {
return err return err
} }
@ -471,13 +423,9 @@ func (grant *OAuth2Grant) setNonce(e db.Engine, nonce string) error {
} }
// GetOAuth2GrantByID returns the grant with the given ID // GetOAuth2GrantByID returns the grant with the given ID
func GetOAuth2GrantByID(id int64) (*OAuth2Grant, error) { func GetOAuth2GrantByID(ctx context.Context, id int64) (grant *OAuth2Grant, err error) {
return getOAuth2GrantByID(db.GetEngine(db.DefaultContext), id)
}
func getOAuth2GrantByID(e db.Engine, id int64) (grant *OAuth2Grant, err error) {
grant = new(OAuth2Grant) grant = new(OAuth2Grant)
if has, err := e.ID(id).Get(grant); err != nil { if has, err := db.GetEngine(ctx).ID(id).Get(grant); err != nil {
return nil, err return nil, err
} else if !has { } else if !has {
return nil, nil return nil, nil
@ -486,18 +434,14 @@ func getOAuth2GrantByID(e db.Engine, id int64) (grant *OAuth2Grant, err error) {
} }
// GetOAuth2GrantsByUserID lists all grants of a certain user // GetOAuth2GrantsByUserID lists all grants of a certain user
func GetOAuth2GrantsByUserID(uid int64) ([]*OAuth2Grant, error) { func GetOAuth2GrantsByUserID(ctx context.Context, uid int64) ([]*OAuth2Grant, error) {
return getOAuth2GrantsByUserID(db.GetEngine(db.DefaultContext), uid)
}
func getOAuth2GrantsByUserID(e db.Engine, uid int64) ([]*OAuth2Grant, error) {
type joinedOAuth2Grant struct { type joinedOAuth2Grant struct {
Grant *OAuth2Grant `xorm:"extends"` Grant *OAuth2Grant `xorm:"extends"`
Application *OAuth2Application `xorm:"extends"` Application *OAuth2Application `xorm:"extends"`
} }
var results *xorm.Rows var results *xorm.Rows
var err error var err error
if results, err = e. if results, err = db.GetEngine(ctx).
Table("oauth2_grant"). Table("oauth2_grant").
Where("user_id = ?", uid). Where("user_id = ?", uid).
Join("INNER", "oauth2_application", "application_id = oauth2_application.id"). Join("INNER", "oauth2_application", "application_id = oauth2_application.id").
@ -518,12 +462,8 @@ func getOAuth2GrantsByUserID(e db.Engine, uid int64) ([]*OAuth2Grant, error) {
} }
// RevokeOAuth2Grant deletes the grant with grantID and userID // RevokeOAuth2Grant deletes the grant with grantID and userID
func RevokeOAuth2Grant(grantID, userID int64) error { func RevokeOAuth2Grant(ctx context.Context, grantID, userID int64) error {
return revokeOAuth2Grant(db.GetEngine(db.DefaultContext), grantID, userID) _, err := db.DeleteByBean(ctx, &OAuth2Grant{ID: grantID, UserID: userID})
}
func revokeOAuth2Grant(e db.Engine, grantID, userID int64) error {
_, err := e.Delete(&OAuth2Grant{ID: grantID, UserID: userID})
return err return err
} }

@ -7,6 +7,7 @@ package auth
import ( import (
"testing" "testing"
"code.gitea.io/gitea/models/db"
"code.gitea.io/gitea/models/unittest" "code.gitea.io/gitea/models/unittest"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
@ -52,18 +53,18 @@ func TestOAuth2Application_ValidateClientSecret(t *testing.T) {
func TestGetOAuth2ApplicationByClientID(t *testing.T) { func TestGetOAuth2ApplicationByClientID(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase()) assert.NoError(t, unittest.PrepareTestDatabase())
app, err := GetOAuth2ApplicationByClientID("da7da3ba-9a13-4167-856f-3899de0b0138") app, err := GetOAuth2ApplicationByClientID(db.DefaultContext, "da7da3ba-9a13-4167-856f-3899de0b0138")
assert.NoError(t, err) assert.NoError(t, err)
assert.Equal(t, "da7da3ba-9a13-4167-856f-3899de0b0138", app.ClientID) assert.Equal(t, "da7da3ba-9a13-4167-856f-3899de0b0138", app.ClientID)
app, err = GetOAuth2ApplicationByClientID("invalid client id") app, err = GetOAuth2ApplicationByClientID(db.DefaultContext, "invalid client id")
assert.Error(t, err) assert.Error(t, err)
assert.Nil(t, app) assert.Nil(t, app)
} }
func TestCreateOAuth2Application(t *testing.T) { func TestCreateOAuth2Application(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase()) assert.NoError(t, unittest.PrepareTestDatabase())
app, err := CreateOAuth2Application(CreateOAuth2ApplicationOptions{Name: "newapp", UserID: 1}) app, err := CreateOAuth2Application(db.DefaultContext, CreateOAuth2ApplicationOptions{Name: "newapp", UserID: 1})
assert.NoError(t, err) assert.NoError(t, err)
assert.Equal(t, "newapp", app.Name) assert.Equal(t, "newapp", app.Name)
assert.Len(t, app.ClientID, 36) assert.Len(t, app.ClientID, 36)
@ -77,11 +78,11 @@ func TestOAuth2Application_TableName(t *testing.T) {
func TestOAuth2Application_GetGrantByUserID(t *testing.T) { func TestOAuth2Application_GetGrantByUserID(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase()) assert.NoError(t, unittest.PrepareTestDatabase())
app := unittest.AssertExistsAndLoadBean(t, &OAuth2Application{ID: 1}).(*OAuth2Application) app := unittest.AssertExistsAndLoadBean(t, &OAuth2Application{ID: 1}).(*OAuth2Application)
grant, err := app.GetGrantByUserID(1) grant, err := app.GetGrantByUserID(db.DefaultContext, 1)
assert.NoError(t, err) assert.NoError(t, err)
assert.Equal(t, int64(1), grant.UserID) assert.Equal(t, int64(1), grant.UserID)
grant, err = app.GetGrantByUserID(34923458) grant, err = app.GetGrantByUserID(db.DefaultContext, 34923458)
assert.NoError(t, err) assert.NoError(t, err)
assert.Nil(t, grant) assert.Nil(t, grant)
} }
@ -89,7 +90,7 @@ func TestOAuth2Application_GetGrantByUserID(t *testing.T) {
func TestOAuth2Application_CreateGrant(t *testing.T) { func TestOAuth2Application_CreateGrant(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase()) assert.NoError(t, unittest.PrepareTestDatabase())
app := unittest.AssertExistsAndLoadBean(t, &OAuth2Application{ID: 1}).(*OAuth2Application) app := unittest.AssertExistsAndLoadBean(t, &OAuth2Application{ID: 1}).(*OAuth2Application)
grant, err := app.CreateGrant(2, "") grant, err := app.CreateGrant(db.DefaultContext, 2, "")
assert.NoError(t, err) assert.NoError(t, err)
assert.NotNil(t, grant) assert.NotNil(t, grant)
assert.Equal(t, int64(2), grant.UserID) assert.Equal(t, int64(2), grant.UserID)
@ -101,11 +102,11 @@ func TestOAuth2Application_CreateGrant(t *testing.T) {
func TestGetOAuth2GrantByID(t *testing.T) { func TestGetOAuth2GrantByID(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase()) assert.NoError(t, unittest.PrepareTestDatabase())
grant, err := GetOAuth2GrantByID(1) grant, err := GetOAuth2GrantByID(db.DefaultContext, 1)
assert.NoError(t, err) assert.NoError(t, err)
assert.Equal(t, int64(1), grant.ID) assert.Equal(t, int64(1), grant.ID)
grant, err = GetOAuth2GrantByID(34923458) grant, err = GetOAuth2GrantByID(db.DefaultContext, 34923458)
assert.NoError(t, err) assert.NoError(t, err)
assert.Nil(t, grant) assert.Nil(t, grant)
} }
@ -113,7 +114,7 @@ func TestGetOAuth2GrantByID(t *testing.T) {
func TestOAuth2Grant_IncreaseCounter(t *testing.T) { func TestOAuth2Grant_IncreaseCounter(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase()) assert.NoError(t, unittest.PrepareTestDatabase())
grant := unittest.AssertExistsAndLoadBean(t, &OAuth2Grant{ID: 1, Counter: 1}).(*OAuth2Grant) grant := unittest.AssertExistsAndLoadBean(t, &OAuth2Grant{ID: 1, Counter: 1}).(*OAuth2Grant)
assert.NoError(t, grant.IncreaseCounter()) assert.NoError(t, grant.IncreaseCounter(db.DefaultContext))
assert.Equal(t, int64(2), grant.Counter) assert.Equal(t, int64(2), grant.Counter)
unittest.AssertExistsAndLoadBean(t, &OAuth2Grant{ID: 1, Counter: 2}) unittest.AssertExistsAndLoadBean(t, &OAuth2Grant{ID: 1, Counter: 2})
} }
@ -130,7 +131,7 @@ func TestOAuth2Grant_ScopeContains(t *testing.T) {
func TestOAuth2Grant_GenerateNewAuthorizationCode(t *testing.T) { func TestOAuth2Grant_GenerateNewAuthorizationCode(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase()) assert.NoError(t, unittest.PrepareTestDatabase())
grant := unittest.AssertExistsAndLoadBean(t, &OAuth2Grant{ID: 1}).(*OAuth2Grant) grant := unittest.AssertExistsAndLoadBean(t, &OAuth2Grant{ID: 1}).(*OAuth2Grant)
code, err := grant.GenerateNewAuthorizationCode("https://example2.com/callback", "CjvyTLSdR47G5zYenDA-eDWW4lRrO8yvjcWwbD_deOg", "S256") code, err := grant.GenerateNewAuthorizationCode(db.DefaultContext, "https://example2.com/callback", "CjvyTLSdR47G5zYenDA-eDWW4lRrO8yvjcWwbD_deOg", "S256")
assert.NoError(t, err) assert.NoError(t, err)
assert.NotNil(t, code) assert.NotNil(t, code)
assert.True(t, len(code.Code) > 32) // secret length > 32 assert.True(t, len(code.Code) > 32) // secret length > 32
@ -142,20 +143,20 @@ func TestOAuth2Grant_TableName(t *testing.T) {
func TestGetOAuth2GrantsByUserID(t *testing.T) { func TestGetOAuth2GrantsByUserID(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase()) assert.NoError(t, unittest.PrepareTestDatabase())
result, err := GetOAuth2GrantsByUserID(1) result, err := GetOAuth2GrantsByUserID(db.DefaultContext, 1)
assert.NoError(t, err) assert.NoError(t, err)
assert.Len(t, result, 1) assert.Len(t, result, 1)
assert.Equal(t, int64(1), result[0].ID) assert.Equal(t, int64(1), result[0].ID)
assert.Equal(t, result[0].ApplicationID, result[0].Application.ID) assert.Equal(t, result[0].ApplicationID, result[0].Application.ID)
result, err = GetOAuth2GrantsByUserID(34134) result, err = GetOAuth2GrantsByUserID(db.DefaultContext, 34134)
assert.NoError(t, err) assert.NoError(t, err)
assert.Empty(t, result) assert.Empty(t, result)
} }
func TestRevokeOAuth2Grant(t *testing.T) { func TestRevokeOAuth2Grant(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase()) assert.NoError(t, unittest.PrepareTestDatabase())
assert.NoError(t, RevokeOAuth2Grant(1, 1)) assert.NoError(t, RevokeOAuth2Grant(db.DefaultContext, 1, 1))
unittest.AssertNotExistsBean(t, &OAuth2Grant{ID: 1, UserID: 1}) unittest.AssertNotExistsBean(t, &OAuth2Grant{ID: 1, UserID: 1})
} }
@ -163,13 +164,13 @@ func TestRevokeOAuth2Grant(t *testing.T) {
func TestGetOAuth2AuthorizationByCode(t *testing.T) { func TestGetOAuth2AuthorizationByCode(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase()) assert.NoError(t, unittest.PrepareTestDatabase())
code, err := GetOAuth2AuthorizationByCode("authcode") code, err := GetOAuth2AuthorizationByCode(db.DefaultContext, "authcode")
assert.NoError(t, err) assert.NoError(t, err)
assert.NotNil(t, code) assert.NotNil(t, code)
assert.Equal(t, "authcode", code.Code) assert.Equal(t, "authcode", code.Code)
assert.Equal(t, int64(1), code.ID) assert.Equal(t, int64(1), code.ID)
code, err = GetOAuth2AuthorizationByCode("does not exist") code, err = GetOAuth2AuthorizationByCode(db.DefaultContext, "does not exist")
assert.NoError(t, err) assert.NoError(t, err)
assert.Nil(t, code) assert.Nil(t, code)
} }
@ -224,7 +225,7 @@ func TestOAuth2AuthorizationCode_GenerateRedirectURI(t *testing.T) {
func TestOAuth2AuthorizationCode_Invalidate(t *testing.T) { func TestOAuth2AuthorizationCode_Invalidate(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase()) assert.NoError(t, unittest.PrepareTestDatabase())
code := unittest.AssertExistsAndLoadBean(t, &OAuth2AuthorizationCode{Code: "authcode"}).(*OAuth2AuthorizationCode) code := unittest.AssertExistsAndLoadBean(t, &OAuth2AuthorizationCode{Code: "authcode"}).(*OAuth2AuthorizationCode)
assert.NoError(t, code.Invalidate()) assert.NoError(t, code.Invalidate(db.DefaultContext))
unittest.AssertNotExistsBean(t, &OAuth2AuthorizationCode{Code: "authcode"}) unittest.AssertNotExistsBean(t, &OAuth2AuthorizationCode{Code: "authcode"})
} }

@ -306,13 +306,9 @@ func (protectBranch *ProtectedBranch) IsUnprotectedFile(patterns []glob.Glob, pa
} }
// GetProtectedBranchBy getting protected branch by ID/Name // GetProtectedBranchBy getting protected branch by ID/Name
func GetProtectedBranchBy(repoID int64, branchName string) (*ProtectedBranch, error) { func GetProtectedBranchBy(ctx context.Context, repoID int64, branchName string) (*ProtectedBranch, error) {
return getProtectedBranchBy(db.GetEngine(db.DefaultContext), repoID, branchName)
}
func getProtectedBranchBy(e db.Engine, repoID int64, branchName string) (*ProtectedBranch, error) {
rel := &ProtectedBranch{RepoID: repoID, BranchName: branchName} rel := &ProtectedBranch{RepoID: repoID, BranchName: branchName}
has, err := e.Get(rel) has, err := db.GetByBean(ctx, rel)
if err != nil { if err != nil {
return nil, err return nil, err
} }
@ -632,7 +628,7 @@ func RenameBranch(repo *repo_model.Repository, from, to string, gitAction func(i
} }
// 2. Update protected branch if needed // 2. Update protected branch if needed
protectedBranch, err := getProtectedBranchBy(sess, repo.ID, from) protectedBranch, err := GetProtectedBranchBy(ctx, repo.ID, from)
if err != nil { if err != nil {
return err return err
} }

@ -49,21 +49,21 @@ func init() {
} }
// upsertCommitStatusIndex the function will not return until it acquires the lock or receives an error. // upsertCommitStatusIndex the function will not return until it acquires the lock or receives an error.
func upsertCommitStatusIndex(e db.Engine, repoID int64, sha string) (err error) { func upsertCommitStatusIndex(ctx context.Context, repoID int64, sha string) (err error) {
// An atomic UPSERT operation (INSERT/UPDATE) is the only operation // An atomic UPSERT operation (INSERT/UPDATE) is the only operation
// that ensures that the key is actually locked. // that ensures that the key is actually locked.
switch { switch {
case setting.Database.UseSQLite3 || setting.Database.UsePostgreSQL: case setting.Database.UseSQLite3 || setting.Database.UsePostgreSQL:
_, err = e.Exec("INSERT INTO `commit_status_index` (repo_id, sha, max_index) "+ _, err = db.Exec(ctx, "INSERT INTO `commit_status_index` (repo_id, sha, max_index) "+
"VALUES (?,?,1) ON CONFLICT (repo_id,sha) DO UPDATE SET max_index = `commit_status_index`.max_index+1", "VALUES (?,?,1) ON CONFLICT (repo_id,sha) DO UPDATE SET max_index = `commit_status_index`.max_index+1",
repoID, sha) repoID, sha)
case setting.Database.UseMySQL: case setting.Database.UseMySQL:
_, err = e.Exec("INSERT INTO `commit_status_index` (repo_id, sha, max_index) "+ _, err = db.Exec(ctx, "INSERT INTO `commit_status_index` (repo_id, sha, max_index) "+
"VALUES (?,?,1) ON DUPLICATE KEY UPDATE max_index = max_index+1", "VALUES (?,?,1) ON DUPLICATE KEY UPDATE max_index = max_index+1",
repoID, sha) repoID, sha)
case setting.Database.UseMSSQL: case setting.Database.UseMSSQL:
// https://weblogs.sqlteam.com/dang/2009/01/31/upsert-race-condition-with-merge/ // https://weblogs.sqlteam.com/dang/2009/01/31/upsert-race-condition-with-merge/
_, err = e.Exec("MERGE `commit_status_index` WITH (HOLDLOCK) as target "+ _, err = db.Exec(ctx, "MERGE `commit_status_index` WITH (HOLDLOCK) as target "+
"USING (SELECT ? AS repo_id, ? AS sha) AS src "+ "USING (SELECT ? AS repo_id, ? AS sha) AS src "+
"ON src.repo_id = target.repo_id AND src.sha = target.sha "+ "ON src.repo_id = target.repo_id AND src.sha = target.sha "+
"WHEN MATCHED THEN UPDATE SET target.max_index = target.max_index+1 "+ "WHEN MATCHED THEN UPDATE SET target.max_index = target.max_index+1 "+
@ -100,17 +100,17 @@ func getNextCommitStatusIndex(repoID int64, sha string) (int64, error) {
defer commiter.Close() defer commiter.Close()
var preIdx int64 var preIdx int64
_, err = ctx.Engine().SQL("SELECT max_index FROM `commit_status_index` WHERE repo_id = ? AND sha = ?", repoID, sha).Get(&preIdx) _, err = db.GetEngine(ctx).SQL("SELECT max_index FROM `commit_status_index` WHERE repo_id = ? AND sha = ?", repoID, sha).Get(&preIdx)
if err != nil { if err != nil {
return 0, err return 0, err
} }
if err := upsertCommitStatusIndex(ctx.Engine(), repoID, sha); err != nil { if err := upsertCommitStatusIndex(ctx, repoID, sha); err != nil {
return 0, err return 0, err
} }
var curIdx int64 var curIdx int64
has, err := ctx.Engine().SQL("SELECT max_index FROM `commit_status_index` WHERE repo_id = ? AND sha = ? AND max_index=?", repoID, sha, preIdx+1).Get(&curIdx) has, err := db.GetEngine(ctx).SQL("SELECT max_index FROM `commit_status_index` WHERE repo_id = ? AND sha = ? AND max_index=?", repoID, sha, preIdx+1).Get(&curIdx)
if err != nil { if err != nil {
return 0, err return 0, err
} }
@ -131,7 +131,7 @@ func (status *CommitStatus) loadAttributes(ctx context.Context) (err error) {
} }
} }
if status.Creator == nil && status.CreatorID > 0 { if status.Creator == nil && status.CreatorID > 0 {
status.Creator, err = user_model.GetUserByIDEngine(db.GetEngine(ctx), status.CreatorID) status.Creator, err = user_model.GetUserByIDCtx(ctx, status.CreatorID)
if err != nil { if err != nil {
return fmt.Errorf("getUserByID [%d]: %v", status.CreatorID, err) return fmt.Errorf("getUserByID [%d]: %v", status.CreatorID, err)
} }
@ -231,12 +231,7 @@ type CommitStatusIndex struct {
} }
// GetLatestCommitStatus returns all statuses with a unique context for a given commit. // GetLatestCommitStatus returns all statuses with a unique context for a given commit.
func GetLatestCommitStatus(repoID int64, sha string, listOptions db.ListOptions) ([]*CommitStatus, int64, error) { func GetLatestCommitStatus(ctx context.Context, repoID int64, sha string, listOptions db.ListOptions) ([]*CommitStatus, int64, error) {
return GetLatestCommitStatusCtx(db.DefaultContext, repoID, sha, listOptions)
}
// 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) ids := make([]int64, 0, 10)
sess := db.GetEngine(ctx).Table(&CommitStatus{}). sess := db.GetEngine(ctx).Table(&CommitStatus{}).
Where("repo_id = ?", repoID).And("sha = ?", sha). Where("repo_id = ?", repoID).And("sha = ?", sha).
@ -341,7 +336,7 @@ func ParseCommitsWithStatus(oldCommits []*asymkey_model.SignCommit, repo *repo_m
commit := &SignCommitWithStatuses{ commit := &SignCommitWithStatuses{
SignCommit: c, SignCommit: c,
} }
statuses, _, err := GetLatestCommitStatus(repo.ID, commit.ID.String(), db.ListOptions{}) statuses, _, err := GetLatestCommitStatus(db.DefaultContext, repo.ID, commit.ID.String(), db.ListOptions{})
if err != nil { if err != nil {
log.Error("GetLatestCommitStatus: %v", err) log.Error("GetLatestCommitStatus: %v", err)
} else { } else {

@ -117,7 +117,7 @@ func DeleteOrphanedIssues() error {
var attachmentPaths []string var attachmentPaths []string
for i := range ids { for i := range ids {
paths, err := deleteIssuesByRepoID(db.GetEngine(ctx), ids[i]) paths, err := deleteIssuesByRepoID(ctx, ids[i])
if err != nil { if err != nil {
return err return err
} }

@ -5,6 +5,7 @@
package db package db
import ( import (
"context"
"errors" "errors"
"fmt" "fmt"
@ -74,8 +75,8 @@ func GetNextResourceIndex(tableName string, groupID int64) (int64, error) {
} }
// DeleteResouceIndex delete resource index // DeleteResouceIndex delete resource index
func DeleteResouceIndex(e Engine, tableName string, groupID int64) error { func DeleteResouceIndex(ctx context.Context, tableName string, groupID int64) error {
_, err := e.Exec(fmt.Sprintf("DELETE FROM %s WHERE group_id=?", tableName), groupID) _, err := Exec(ctx, fmt.Sprintf("DELETE FROM %s WHERE group_id=?", tableName), groupID)
return err return err
} }

@ -107,9 +107,9 @@ func init() {
db.RegisterModel(new(IssueIndex)) db.RegisterModel(new(IssueIndex))
} }
func (issue *Issue) loadTotalTimes(e db.Engine) (err error) { func (issue *Issue) loadTotalTimes(ctx context.Context) (err error) {
opts := FindTrackedTimesOptions{IssueID: issue.ID} opts := FindTrackedTimesOptions{IssueID: issue.ID}
issue.TotalTrackedTime, err = opts.toSession(e).SumInt(&TrackedTime{}, "time") issue.TotalTrackedTime, err = opts.toSession(db.GetEngine(ctx)).SumInt(&TrackedTime{}, "time")
if err != nil { if err != nil {
return err return err
} }
@ -154,7 +154,7 @@ func (issue *Issue) GetPullRequest() (pr *PullRequest, err error) {
return nil, fmt.Errorf("Issue is not a pull request") return nil, fmt.Errorf("Issue is not a pull request")
} }
pr, err = getPullRequestByIssueID(db.GetEngine(db.DefaultContext), issue.ID) pr, err = GetPullRequestByIssueID(db.DefaultContext, issue.ID)
if err != nil { if err != nil {
return nil, err return nil, err
} }
@ -165,7 +165,7 @@ func (issue *Issue) GetPullRequest() (pr *PullRequest, err error) {
// LoadLabels loads labels // LoadLabels loads labels
func (issue *Issue) LoadLabels(ctx context.Context) (err error) { func (issue *Issue) LoadLabels(ctx context.Context) (err error) {
if issue.Labels == nil { if issue.Labels == nil {
issue.Labels, err = getLabelsByIssueID(db.GetEngine(ctx), issue.ID) issue.Labels, err = GetLabelsByIssueID(ctx, issue.ID)
if err != nil { if err != nil {
return fmt.Errorf("getLabelsByIssueID [%d]: %v", issue.ID, err) return fmt.Errorf("getLabelsByIssueID [%d]: %v", issue.ID, err)
} }
@ -175,12 +175,12 @@ func (issue *Issue) LoadLabels(ctx context.Context) (err error) {
// LoadPoster loads poster // LoadPoster loads poster
func (issue *Issue) LoadPoster() error { func (issue *Issue) LoadPoster() error {
return issue.loadPoster(db.GetEngine(db.DefaultContext)) return issue.loadPoster(db.DefaultContext)
} }
func (issue *Issue) loadPoster(e db.Engine) (err error) { func (issue *Issue) loadPoster(ctx context.Context) (err error) {
if issue.Poster == nil { if issue.Poster == nil {
issue.Poster, err = user_model.GetUserByIDEngine(e, issue.PosterID) issue.Poster, err = user_model.GetUserByIDCtx(ctx, issue.PosterID)
if err != nil { if err != nil {
issue.PosterID = -1 issue.PosterID = -1
issue.Poster = user_model.NewGhostUser() issue.Poster = user_model.NewGhostUser()
@ -194,9 +194,9 @@ func (issue *Issue) loadPoster(e db.Engine) (err error) {
return return
} }
func (issue *Issue) loadPullRequest(e db.Engine) (err error) { func (issue *Issue) loadPullRequest(ctx context.Context) (err error) {
if issue.IsPull && issue.PullRequest == nil { if issue.IsPull && issue.PullRequest == nil {
issue.PullRequest, err = getPullRequestByIssueID(e, issue.ID) issue.PullRequest, err = GetPullRequestByIssueID(ctx, issue.ID)
if err != nil { if err != nil {
if IsErrPullRequestNotExist(err) { if IsErrPullRequestNotExist(err) {
return err return err
@ -210,23 +210,23 @@ func (issue *Issue) loadPullRequest(e db.Engine) (err error) {
// LoadPullRequest loads pull request info // LoadPullRequest loads pull request info
func (issue *Issue) LoadPullRequest() error { func (issue *Issue) LoadPullRequest() error {
return issue.loadPullRequest(db.GetEngine(db.DefaultContext)) return issue.loadPullRequest(db.DefaultContext)
} }
func (issue *Issue) loadComments(e db.Engine) (err error) { func (issue *Issue) loadComments(ctx context.Context) (err error) {
return issue.loadCommentsByType(e, CommentTypeUnknown) return issue.loadCommentsByType(ctx, CommentTypeUnknown)
} }
// LoadDiscussComments loads discuss comments // LoadDiscussComments loads discuss comments
func (issue *Issue) LoadDiscussComments() error { func (issue *Issue) LoadDiscussComments() error {
return issue.loadCommentsByType(db.GetEngine(db.DefaultContext), CommentTypeComment) return issue.loadCommentsByType(db.DefaultContext, CommentTypeComment)
} }
func (issue *Issue) loadCommentsByType(e db.Engine, tp CommentType) (err error) { func (issue *Issue) loadCommentsByType(ctx context.Context, tp CommentType) (err error) {
if issue.Comments != nil { if issue.Comments != nil {
return nil return nil
} }
issue.Comments, err = findComments(e, &FindCommentsOptions{ issue.Comments, err = FindComments(ctx, &FindCommentsOptions{
IssueID: issue.ID, IssueID: issue.ID,
Type: tp, Type: tp,
}) })
@ -301,12 +301,11 @@ func (issue *Issue) loadMilestone(ctx context.Context) (err error) {
} }
func (issue *Issue) loadAttributes(ctx context.Context) (err error) { func (issue *Issue) loadAttributes(ctx context.Context) (err error) {
e := db.GetEngine(ctx)
if err = issue.LoadRepo(ctx); err != nil { if err = issue.LoadRepo(ctx); err != nil {
return return
} }
if err = issue.loadPoster(e); err != nil { if err = issue.loadPoster(ctx); err != nil {
return return
} }
@ -318,27 +317,27 @@ func (issue *Issue) loadAttributes(ctx context.Context) (err error) {
return return
} }
if err = issue.loadProject(e); err != nil { if err = issue.loadProject(ctx); err != nil {
return return
} }
if err = issue.loadAssignees(e); err != nil { if err = issue.LoadAssignees(ctx); err != nil {
return return
} }
if err = issue.loadPullRequest(e); err != nil && !IsErrPullRequestNotExist(err) { if err = issue.loadPullRequest(ctx); err != nil && !IsErrPullRequestNotExist(err) {
// It is possible pull request is not yet created. // It is possible pull request is not yet created.
return err return err
} }
if issue.Attachments == nil { if issue.Attachments == nil {
issue.Attachments, err = repo_model.GetAttachmentsByIssueIDCtx(ctx, issue.ID) issue.Attachments, err = repo_model.GetAttachmentsByIssueID(ctx, issue.ID)
if err != nil { if err != nil {
return fmt.Errorf("getAttachmentsByIssueID [%d]: %v", issue.ID, err) return fmt.Errorf("getAttachmentsByIssueID [%d]: %v", issue.ID, err)
} }
} }
if err = issue.loadComments(e); err != nil { if err = issue.loadComments(ctx); err != nil {
return err return err
} }
@ -346,7 +345,7 @@ func (issue *Issue) loadAttributes(ctx context.Context) (err error) {
return err return err
} }
if issue.isTimetrackerEnabled(ctx) { if issue.isTimetrackerEnabled(ctx) {
if err = issue.loadTotalTimes(e); err != nil { if err = issue.loadTotalTimes(ctx); err != nil {
return err return err
} }
} }
@ -449,12 +448,12 @@ func (issue *Issue) IsPoster(uid int64) bool {
return issue.OriginalAuthorID == 0 && issue.PosterID == uid return issue.OriginalAuthorID == 0 && issue.PosterID == uid
} }
func (issue *Issue) getLabels(e db.Engine) (err error) { func (issue *Issue) getLabels(ctx context.Context) (err error) {
if len(issue.Labels) > 0 { if len(issue.Labels) > 0 {
return nil return nil
} }
issue.Labels, err = getLabelsByIssueID(e, issue.ID) issue.Labels, err = GetLabelsByIssueID(ctx, issue.ID)
if err != nil { if err != nil {
return fmt.Errorf("getLabelsByIssueID: %v", err) return fmt.Errorf("getLabelsByIssueID: %v", err)
} }
@ -462,7 +461,7 @@ func (issue *Issue) getLabels(e db.Engine) (err error) {
} }
func clearIssueLabels(ctx context.Context, issue *Issue, doer *user_model.User) (err error) { func clearIssueLabels(ctx context.Context, issue *Issue, doer *user_model.User) (err error) {
if err = issue.getLabels(db.GetEngine(ctx)); err != nil { if err = issue.getLabels(ctx); err != nil {
return fmt.Errorf("getLabels: %v", err) return fmt.Errorf("getLabels: %v", err)
} }
@ -486,7 +485,7 @@ func ClearIssueLabels(issue *Issue, doer *user_model.User) (err error) {
if err := issue.LoadRepo(ctx); err != nil { if err := issue.LoadRepo(ctx); err != nil {
return err return err
} else if err = issue.loadPullRequest(db.GetEngine(ctx)); err != nil { } else if err = issue.loadPullRequest(ctx); err != nil {
return err return err
} }
@ -597,7 +596,7 @@ func (issue *Issue) ReadBy(ctx context.Context, userID int64) error {
return err return err
} }
return setIssueNotificationStatusReadIfUnread(db.GetEngine(db.DefaultContext), userID, issue.ID) return setIssueNotificationStatusReadIfUnread(ctx, userID, issue.ID)
} }
// UpdateIssueCols updates cols of issue // UpdateIssueCols updates cols of issue
@ -610,7 +609,7 @@ func UpdateIssueCols(ctx context.Context, issue *Issue, cols ...string) error {
func changeIssueStatus(ctx context.Context, issue *Issue, doer *user_model.User, isClosed, isMergePull bool) (*Comment, error) { func changeIssueStatus(ctx context.Context, issue *Issue, doer *user_model.User, isClosed, isMergePull bool) (*Comment, error) {
// Reload the issue // Reload the issue
currentIssue, err := getIssueByID(db.GetEngine(ctx), issue.ID) currentIssue, err := getIssueByID(ctx, issue.ID)
if err != nil { if err != nil {
return nil, err return nil, err
} }
@ -632,7 +631,6 @@ func changeIssueStatus(ctx context.Context, issue *Issue, doer *user_model.User,
} }
func doChangeIssueStatus(ctx context.Context, issue *Issue, doer *user_model.User, isMergePull bool) (*Comment, error) { func doChangeIssueStatus(ctx context.Context, issue *Issue, doer *user_model.User, isMergePull bool) (*Comment, error) {
e := db.GetEngine(ctx)
// Check for open dependencies // Check for open dependencies
if issue.IsClosed && issue.Repo.IsDependenciesEnabledCtx(ctx) { if issue.IsClosed && issue.Repo.IsDependenciesEnabledCtx(ctx) {
// only check if dependencies are enabled and we're about to close an issue, otherwise reopening an issue would fail when there are unsatisfied dependencies // only check if dependencies are enabled and we're about to close an issue, otherwise reopening an issue would fail when there are unsatisfied dependencies
@ -657,11 +655,11 @@ func doChangeIssueStatus(ctx context.Context, issue *Issue, doer *user_model.Use
} }
// Update issue count of labels // Update issue count of labels
if err := issue.getLabels(e); err != nil { if err := issue.getLabels(ctx); err != nil {
return nil, err return nil, err
} }
for idx := range issue.Labels { for idx := range issue.Labels {
if err := updateLabelCols(e, issue.Labels[idx], "num_issues", "num_closed_issue"); err != nil { if err := updateLabelCols(ctx, issue.Labels[idx], "num_issues", "num_closed_issue"); err != nil {
return nil, err return nil, err
} }
} }
@ -698,7 +696,7 @@ func ChangeIssueStatus(ctx context.Context, issue *Issue, doer *user_model.User,
if err := issue.LoadRepo(ctx); err != nil { if err := issue.LoadRepo(ctx); err != nil {
return nil, err return nil, err
} }
if err := issue.loadPoster(db.GetEngine(ctx)); err != nil { if err := issue.loadPoster(ctx); err != nil {
return nil, err return nil, err
} }
@ -774,7 +772,7 @@ func ChangeIssueRef(issue *Issue, doer *user_model.User, oldRef string) (err err
// AddDeletePRBranchComment adds delete branch comment for pull request issue // AddDeletePRBranchComment adds delete branch comment for pull request issue
func AddDeletePRBranchComment(ctx context.Context, doer *user_model.User, repo *repo_model.Repository, issueID int64, branchName string) error { func AddDeletePRBranchComment(ctx context.Context, doer *user_model.User, repo *repo_model.Repository, issueID int64, branchName string) error {
issue, err := getIssueByID(db.GetEngine(ctx), issueID) issue, err := getIssueByID(ctx, issueID)
if err != nil { if err != nil {
return err return err
} }
@ -802,7 +800,7 @@ func UpdateIssueAttachments(issueID int64, uuids []string) (err error) {
} }
for i := 0; i < len(attachments); i++ { for i := 0; i < len(attachments); i++ {
attachments[i].IssueID = issueID attachments[i].IssueID = issueID
if err := repo_model.UpdateAttachmentCtx(ctx, attachments[i]); err != nil { if err := repo_model.UpdateAttachment(ctx, attachments[i]); err != nil {
return fmt.Errorf("update attachment [id: %d]: %v", attachments[i].ID, err) return fmt.Errorf("update attachment [id: %d]: %v", attachments[i].ID, err)
} }
} }
@ -822,7 +820,7 @@ func ChangeIssueContent(issue *Issue, doer *user_model.User, content string) (er
return fmt.Errorf("HasIssueContentHistory: %v", err) return fmt.Errorf("HasIssueContentHistory: %v", err)
} }
if !hasContentHistory { if !hasContentHistory {
if err = issues_model.SaveIssueContentHistory(db.GetEngine(ctx), issue.PosterID, issue.ID, 0, if err = issues_model.SaveIssueContentHistory(ctx, issue.PosterID, issue.ID, 0,
issue.CreatedUnix, issue.Content, true); err != nil { issue.CreatedUnix, issue.Content, true); err != nil {
return fmt.Errorf("SaveIssueContentHistory: %v", err) return fmt.Errorf("SaveIssueContentHistory: %v", err)
} }
@ -834,7 +832,7 @@ func ChangeIssueContent(issue *Issue, doer *user_model.User, content string) (er
return fmt.Errorf("UpdateIssueCols: %v", err) return fmt.Errorf("UpdateIssueCols: %v", err)
} }
if err = issues_model.SaveIssueContentHistory(db.GetEngine(ctx), doer.ID, issue.ID, 0, if err = issues_model.SaveIssueContentHistory(ctx, doer.ID, issue.ID, 0,
timeutil.TimeStampNow(), issue.Content, false); err != nil { timeutil.TimeStampNow(), issue.Content, false); err != nil {
return fmt.Errorf("SaveIssueContentHistory: %v", err) return fmt.Errorf("SaveIssueContentHistory: %v", err)
} }
@ -973,7 +971,7 @@ func newIssue(ctx context.Context, doer *user_model.User, opts NewIssueOptions)
return fmt.Errorf("find all labels [label_ids: %v]: %v", opts.LabelIDs, err) return fmt.Errorf("find all labels [label_ids: %v]: %v", opts.LabelIDs, err)
} }
if err = opts.Issue.loadPoster(e); err != nil { if err = opts.Issue.loadPoster(ctx); err != nil {
return err return err
} }
@ -1119,9 +1117,9 @@ func GetIssueWithAttrsByIndex(repoID, index int64) (*Issue, error) {
return issue, issue.LoadAttributes() return issue, issue.LoadAttributes()
} }
func getIssueByID(e db.Engine, id int64) (*Issue, error) { func getIssueByID(ctx context.Context, id int64) (*Issue, error) {
issue := new(Issue) issue := new(Issue)
has, err := e.ID(id).Get(issue) has, err := db.GetEngine(ctx).ID(id).Get(issue)
if err != nil { if err != nil {
return nil, err return nil, err
} else if !has { } else if !has {
@ -1132,7 +1130,7 @@ func getIssueByID(e db.Engine, id int64) (*Issue, error) {
// GetIssueWithAttrsByID returns an issue with attributes by given ID. // GetIssueWithAttrsByID returns an issue with attributes by given ID.
func GetIssueWithAttrsByID(id int64) (*Issue, error) { func GetIssueWithAttrsByID(id int64) (*Issue, error) {
issue, err := getIssueByID(db.GetEngine(db.DefaultContext), id) issue, err := getIssueByID(db.DefaultContext, id)
if err != nil { if err != nil {
return nil, err return nil, err
} }
@ -1141,30 +1139,22 @@ func GetIssueWithAttrsByID(id int64) (*Issue, error) {
// GetIssueByID returns an issue by given ID. // GetIssueByID returns an issue by given ID.
func GetIssueByID(id int64) (*Issue, error) { func GetIssueByID(id int64) (*Issue, error) {
return getIssueByID(db.GetEngine(db.DefaultContext), id) return getIssueByID(db.DefaultContext, id)
} }
func getIssuesByIDs(e db.Engine, issueIDs []int64) ([]*Issue, error) { // GetIssuesByIDs return issues with the given IDs.
func GetIssuesByIDs(ctx context.Context, issueIDs []int64) ([]*Issue, error) {
issues := make([]*Issue, 0, 10) issues := make([]*Issue, 0, 10)
return issues, e.In("id", issueIDs).Find(&issues) return issues, db.GetEngine(ctx).In("id", issueIDs).Find(&issues)
} }
func getIssueIDsByRepoID(e db.Engine, repoID int64) ([]int64, error) { // GetIssueIDsByRepoID returns all issue ids by repo id
func GetIssueIDsByRepoID(ctx context.Context, repoID int64) ([]int64, error) {
ids := make([]int64, 0, 10) ids := make([]int64, 0, 10)
err := e.Table("issue").Cols("id").Where("repo_id = ?", repoID).Find(&ids) err := db.GetEngine(ctx).Table("issue").Cols("id").Where("repo_id = ?", repoID).Find(&ids)
return ids, err return ids, err
} }
// GetIssueIDsByRepoID returns all issue ids by repo id
func GetIssueIDsByRepoID(repoID int64) ([]int64, error) {
return getIssueIDsByRepoID(db.GetEngine(db.DefaultContext), repoID)
}
// GetIssuesByIDs return issues with the given IDs.
func GetIssuesByIDs(issueIDs []int64) ([]*Issue, error) {
return getIssuesByIDs(db.GetEngine(db.DefaultContext), issueIDs)
}
// IssuesOptions represents options of an issue. // IssuesOptions represents options of an issue.
type IssuesOptions struct { type IssuesOptions struct {
db.ListOptions db.ListOptions
@ -1502,7 +1492,7 @@ func GetParticipantsIDsByIssueID(issueID int64) ([]int64, error) {
// IsUserParticipantsOfIssue return true if user is participants of an issue // IsUserParticipantsOfIssue return true if user is participants of an issue
func IsUserParticipantsOfIssue(user *user_model.User, issue *Issue) bool { func IsUserParticipantsOfIssue(user *user_model.User, issue *Issue) bool {
userIDs, err := issue.getParticipantIDsByIssue(db.GetEngine(db.DefaultContext)) userIDs, err := issue.getParticipantIDsByIssue(db.DefaultContext)
if err != nil { if err != nil {
log.Error(err.Error()) log.Error(err.Error())
return false return false
@ -1912,19 +1902,18 @@ func UpdateIssueByAPI(issue *Issue, doer *user_model.User) (statusChangeComment
return nil, false, err return nil, false, err
} }
defer committer.Close() defer committer.Close()
sess := db.GetEngine(ctx)
if err := issue.LoadRepo(ctx); err != nil { if err := issue.LoadRepo(ctx); err != nil {
return nil, false, fmt.Errorf("loadRepo: %v", err) return nil, false, fmt.Errorf("loadRepo: %v", err)
} }
// Reload the issue // Reload the issue
currentIssue, err := getIssueByID(sess, issue.ID) currentIssue, err := getIssueByID(ctx, issue.ID)
if err != nil { if err != nil {
return nil, false, err return nil, false, err
} }
if _, err := sess.ID(issue.ID).Cols( if _, err := db.GetEngine(ctx).ID(issue.ID).Cols(
"name", "content", "milestone_id", "priority", "name", "content", "milestone_id", "priority",
"deadline_unix", "updated_unix", "is_locked"). "deadline_unix", "updated_unix", "is_locked").
Update(issue); err != nil { Update(issue); err != nil {
@ -2000,7 +1989,8 @@ func DeleteIssue(issue *Issue) error {
return committer.Commit() return committer.Commit()
} }
func deleteInIssue(e db.Engine, issueID int64, beans ...interface{}) error { func deleteInIssue(ctx context.Context, issueID int64, beans ...interface{}) error {
e := db.GetEngine(ctx)
for _, bean := range beans { for _, bean := range beans {
if _, err := e.In("issue_id", issueID).Delete(bean); err != nil { if _, err := e.In("issue_id", issueID).Delete(bean); err != nil {
return err return err
@ -2061,7 +2051,7 @@ func deleteIssue(ctx context.Context, issue *Issue) error {
} }
// delete all database data still assigned to this issue // delete all database data still assigned to this issue
if err := deleteInIssue(e, issue.ID, if err := deleteInIssue(ctx, issue.ID,
&issues_model.ContentHistory{}, &issues_model.ContentHistory{},
&Comment{}, &Comment{},
&IssueLabel{}, &IssueLabel{},
@ -2105,12 +2095,12 @@ type DependencyInfo struct {
} }
// getParticipantIDsByIssue returns all userIDs who are participated in comments of an issue and issue author // getParticipantIDsByIssue returns all userIDs who are participated in comments of an issue and issue author
func (issue *Issue) getParticipantIDsByIssue(e db.Engine) ([]int64, error) { func (issue *Issue) getParticipantIDsByIssue(ctx context.Context) ([]int64, error) {
if issue == nil { if issue == nil {
return nil, nil return nil, nil
} }
userIDs := make([]int64, 0, 5) userIDs := make([]int64, 0, 5)
if err := e.Table("comment").Cols("poster_id"). if err := db.GetEngine(ctx).Table("comment").Cols("poster_id").
Where("`comment`.issue_id = ?", issue.ID). Where("`comment`.issue_id = ?", issue.ID).
And("`comment`.type in (?,?,?)", CommentTypeComment, CommentTypeCode, CommentTypeReview). And("`comment`.type in (?,?,?)", CommentTypeComment, CommentTypeCode, CommentTypeReview).
And("`user`.is_active = ?", true). And("`user`.is_active = ?", true).
@ -2126,9 +2116,9 @@ func (issue *Issue) getParticipantIDsByIssue(e db.Engine) ([]int64, error) {
return userIDs, nil return userIDs, nil
} }
// Get Blocked By Dependencies, aka all issues this issue is blocked by. // BlockedByDependencies finds all Dependencies an issue is blocked by
func (issue *Issue) getBlockedByDependencies(e db.Engine) (issueDeps []*DependencyInfo, err error) { func (issue *Issue) BlockedByDependencies(ctx context.Context) (issueDeps []*DependencyInfo, err error) {
err = e. err = db.GetEngine(ctx).
Table("issue"). Table("issue").
Join("INNER", "repository", "repository.id = issue.repo_id"). Join("INNER", "repository", "repository.id = issue.repo_id").
Join("INNER", "issue_dependency", "issue_dependency.dependency_id = issue.id"). Join("INNER", "issue_dependency", "issue_dependency.dependency_id = issue.id").
@ -2144,9 +2134,9 @@ func (issue *Issue) getBlockedByDependencies(e db.Engine) (issueDeps []*Dependen
return issueDeps, err return issueDeps, err
} }
// Get Blocking Dependencies, aka all issues this issue blocks. // BlockingDependencies returns all blocking dependencies, aka all other issues a given issue blocks
func (issue *Issue) getBlockingDependencies(e db.Engine) (issueDeps []*DependencyInfo, err error) { func (issue *Issue) BlockingDependencies(ctx context.Context) (issueDeps []*DependencyInfo, err error) {
err = e. err = db.GetEngine(ctx).
Table("issue"). Table("issue").
Join("INNER", "repository", "repository.id = issue.repo_id"). Join("INNER", "repository", "repository.id = issue.repo_id").
Join("INNER", "issue_dependency", "issue_dependency.issue_id = issue.id"). Join("INNER", "issue_dependency", "issue_dependency.issue_id = issue.id").
@ -2162,16 +2152,6 @@ func (issue *Issue) getBlockingDependencies(e db.Engine) (issueDeps []*Dependenc
return issueDeps, err return issueDeps, err
} }
// BlockedByDependencies finds all Dependencies an issue is blocked by
func (issue *Issue) BlockedByDependencies() ([]*DependencyInfo, error) {
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.GetEngine(db.DefaultContext))
}
func updateIssueClosedNum(ctx context.Context, issue *Issue) (err error) { func updateIssueClosedNum(ctx context.Context, issue *Issue) (err error) {
if issue.IsPull { if issue.IsPull {
err = repoStatsCorrectNumClosed(ctx, issue.RepoID, true, "num_closed_pulls") err = repoStatsCorrectNumClosed(ctx, issue.RepoID, true, "num_closed_pulls")
@ -2354,9 +2334,10 @@ func UpdateReactionsMigrationsByType(gitServiceType api.GitServiceType, original
return err return err
} }
func deleteIssuesByRepoID(sess db.Engine, repoID int64) (attachmentPaths []string, err error) { func deleteIssuesByRepoID(ctx context.Context, repoID int64) (attachmentPaths []string, err error) {
deleteCond := builder.Select("id").From("issue").Where(builder.Eq{"issue.repo_id": repoID}) deleteCond := builder.Select("id").From("issue").Where(builder.Eq{"issue.repo_id": repoID})
sess := db.GetEngine(ctx)
// Delete content histories // Delete content histories
if _, err = sess.In("issue_id", deleteCond). if _, err = sess.In("issue_id", deleteCond).
Delete(&issues_model.ContentHistory{}); err != nil { Delete(&issues_model.ContentHistory{}); err != nil {
@ -2431,7 +2412,7 @@ func deleteIssuesByRepoID(sess db.Engine, repoID int64) (attachmentPaths []strin
return return
} }
if _, err = sess.Delete(&Issue{RepoID: repoID}); err != nil { if _, err = db.DeleteByBean(ctx, &Issue{RepoID: repoID}); err != nil {
return return
} }

@ -25,20 +25,15 @@ func init() {
} }
// LoadAssignees load assignees of this issue. // LoadAssignees load assignees of this issue.
func (issue *Issue) LoadAssignees() error { func (issue *Issue) LoadAssignees(ctx context.Context) (err error) {
return issue.loadAssignees(db.GetEngine(db.DefaultContext))
}
// This loads all assignees of an issue
func (issue *Issue) loadAssignees(e db.Engine) (err error) {
// Reset maybe preexisting assignees // Reset maybe preexisting assignees
issue.Assignees = []*user_model.User{} issue.Assignees = []*user_model.User{}
issue.Assignee = nil
err = e.Table("`user`"). err = db.GetEngine(ctx).Table("`user`").
Join("INNER", "issue_assignees", "assignee_id = `user`.id"). Join("INNER", "issue_assignees", "assignee_id = `user`.id").
Where("issue_assignees.issue_id = ?", issue.ID). Where("issue_assignees.issue_id = ?", issue.ID).
Find(&issue.Assignees) Find(&issue.Assignees)
if err != nil { if err != nil {
return err return err
} }
@ -47,7 +42,6 @@ func (issue *Issue) loadAssignees(e db.Engine) (err error) {
if len(issue.Assignees) > 0 { if len(issue.Assignees) > 0 {
issue.Assignee = issue.Assignees[0] issue.Assignee = issue.Assignees[0]
} }
return return
} }
@ -63,33 +57,9 @@ func GetAssigneeIDsByIssue(issueID int64) ([]int64, error) {
Find(&userIDs) Find(&userIDs)
} }
// GetAssigneesByIssue returns everyone assigned to that issue
func GetAssigneesByIssue(issue *Issue) (assignees []*user_model.User, err error) {
return getAssigneesByIssue(db.GetEngine(db.DefaultContext), issue)
}
func getAssigneesByIssue(e db.Engine, issue *Issue) (assignees []*user_model.User, err error) {
err = issue.loadAssignees(e)
if err != nil {
return assignees, err
}
return issue.Assignees, nil
}
// IsUserAssignedToIssue returns true when the user is assigned to the issue // IsUserAssignedToIssue returns true when the user is assigned to the issue
func IsUserAssignedToIssue(issue *Issue, user *user_model.User) (isAssigned bool, err error) { func IsUserAssignedToIssue(ctx context.Context, issue *Issue, user *user_model.User) (isAssigned bool, err error) {
return isUserAssignedToIssue(db.GetEngine(db.DefaultContext), issue, user) return db.GetByBean(ctx, &IssueAssignees{IssueID: issue.ID, AssigneeID: user.ID})
}
func isUserAssignedToIssue(e db.Engine, issue *Issue, user *user_model.User) (isAssigned bool, err error) {
return e.Get(&IssueAssignees{IssueID: issue.ID, AssigneeID: user.ID})
}
// ClearAssigneeByUserID deletes all assignments of an user
func clearAssigneeByUserID(sess db.Engine, userID int64) (err error) {
_, err = sess.Delete(&IssueAssignees{AssigneeID: userID})
return
} }
// ToggleIssueAssignee changes a user between assigned and not assigned for this issue, and make issue comment for it. // ToggleIssueAssignee changes a user between assigned and not assigned for this issue, and make issue comment for it.
@ -113,8 +83,7 @@ func ToggleIssueAssignee(issue *Issue, doer *user_model.User, assigneeID int64)
} }
func toggleIssueAssignee(ctx context.Context, issue *Issue, doer *user_model.User, assigneeID int64, isCreate bool) (removed bool, comment *Comment, err error) { func toggleIssueAssignee(ctx context.Context, issue *Issue, doer *user_model.User, assigneeID int64, isCreate bool) (removed bool, comment *Comment, err error) {
sess := db.GetEngine(ctx) removed, err = toggleUserAssignee(ctx, issue, assigneeID)
removed, err = toggleUserAssignee(sess, issue, assigneeID)
if err != nil { if err != nil {
return false, nil, fmt.Errorf("UpdateIssueUserByAssignee: %v", err) return false, nil, fmt.Errorf("UpdateIssueUserByAssignee: %v", err)
} }
@ -147,39 +116,38 @@ func toggleIssueAssignee(ctx context.Context, issue *Issue, doer *user_model.Use
} }
// toggles user assignee state in database // toggles user assignee state in database
func toggleUserAssignee(e db.Engine, issue *Issue, assigneeID int64) (removed bool, err error) { func toggleUserAssignee(ctx context.Context, issue *Issue, assigneeID int64) (removed bool, err error) {
// Check if the user exists // Check if the user exists
assignee, err := user_model.GetUserByIDEngine(e, assigneeID) assignee, err := user_model.GetUserByIDCtx(ctx, assigneeID)
if err != nil { if err != nil {
return false, err return false, err
} }
// Check if the submitted user is already assigned, if yes delete him otherwise add him // Check if the submitted user is already assigned, if yes delete him otherwise add him
var i int found := false
for i = 0; i < len(issue.Assignees); i++ { i := 0
for ; i < len(issue.Assignees); i++ {
if issue.Assignees[i].ID == assigneeID { if issue.Assignees[i].ID == assigneeID {
found = true
break break
} }
} }
assigneeIn := IssueAssignees{AssigneeID: assigneeID, IssueID: issue.ID} assigneeIn := IssueAssignees{AssigneeID: assigneeID, IssueID: issue.ID}
if found {
toBeDeleted := i < len(issue.Assignees) issue.Assignees = append(issue.Assignees[:i], issue.Assignees[i+1:]...)
if toBeDeleted { _, err = db.DeleteByBean(ctx, &assigneeIn)
issue.Assignees = append(issue.Assignees[:i], issue.Assignees[i:]...)
_, err = e.Delete(assigneeIn)
if err != nil { if err != nil {
return toBeDeleted, err return found, err
} }
} else { } else {
issue.Assignees = append(issue.Assignees, assignee) issue.Assignees = append(issue.Assignees, assignee)
_, err = e.Insert(assigneeIn) if err = db.Insert(ctx, &assigneeIn); err != nil {
if err != nil { return found, err
return toBeDeleted, err
} }
} }
return toBeDeleted, nil return found, nil
} }
// MakeIDsFromAPIAssigneesToAdd returns an array with all assignee IDs // MakeIDsFromAPIAssigneesToAdd returns an array with all assignee IDs

@ -7,6 +7,7 @@ package models
import ( import (
"testing" "testing"
"code.gitea.io/gitea/models/db"
"code.gitea.io/gitea/models/unittest" "code.gitea.io/gitea/models/unittest"
user_model "code.gitea.io/gitea/models/user" user_model "code.gitea.io/gitea/models/user"
@ -37,28 +38,28 @@ func TestUpdateAssignee(t *testing.T) {
assert.NoError(t, err) assert.NoError(t, err)
// Check if he got removed // Check if he got removed
isAssigned, err := IsUserAssignedToIssue(issue, user1) isAssigned, err := IsUserAssignedToIssue(db.DefaultContext, issue, user1)
assert.NoError(t, err) assert.NoError(t, err)
assert.False(t, isAssigned) assert.False(t, isAssigned)
// Check if they're all there // Check if they're all there
assignees, err := GetAssigneesByIssue(issue) err = issue.LoadAssignees(db.DefaultContext)
assert.NoError(t, err) assert.NoError(t, err)
var expectedAssignees []*user_model.User var expectedAssignees []*user_model.User
expectedAssignees = append(expectedAssignees, user2, user3) expectedAssignees = append(expectedAssignees, user2, user3)
for in, assignee := range assignees { for in, assignee := range issue.Assignees {
assert.Equal(t, assignee.ID, expectedAssignees[in].ID) assert.Equal(t, assignee.ID, expectedAssignees[in].ID)
} }
// Check if the user is assigned // Check if the user is assigned
isAssigned, err = IsUserAssignedToIssue(issue, user2) isAssigned, err = IsUserAssignedToIssue(db.DefaultContext, issue, user2)
assert.NoError(t, err) assert.NoError(t, err)
assert.True(t, isAssigned) assert.True(t, isAssigned)
// This user should not be assigned // This user should not be assigned
isAssigned, err = IsUserAssignedToIssue(issue, &user_model.User{ID: 4}) isAssigned, err = IsUserAssignedToIssue(db.DefaultContext, issue, &user_model.User{ID: 4})
assert.NoError(t, err) assert.NoError(t, err)
assert.False(t, isAssigned) assert.False(t, isAssigned)
} }

@ -298,7 +298,7 @@ func (c *Comment) LoadIssueCtx(ctx context.Context) (err error) {
if c.Issue != nil { if c.Issue != nil {
return nil return nil
} }
c.Issue, err = getIssueByID(db.GetEngine(ctx), c.IssueID) c.Issue, err = getIssueByID(ctx, c.IssueID)
return return
} }
@ -329,12 +329,12 @@ func (c *Comment) AfterLoad(session *xorm.Session) {
} }
} }
func (c *Comment) loadPoster(e db.Engine) (err error) { func (c *Comment) loadPoster(ctx context.Context) (err error) {
if c.PosterID <= 0 || c.Poster != nil { if c.PosterID <= 0 || c.Poster != nil {
return nil return nil
} }
c.Poster, err = user_model.GetUserByIDEngine(e, c.PosterID) c.Poster, err = user_model.GetUserByIDCtx(ctx, c.PosterID)
if err != nil { if err != nil {
if user_model.IsErrUserNotExist(err) { if user_model.IsErrUserNotExist(err) {
c.PosterID = -1 c.PosterID = -1
@ -525,7 +525,7 @@ func (c *Comment) LoadMilestone() error {
// LoadPoster loads comment poster // LoadPoster loads comment poster
func (c *Comment) LoadPoster() error { func (c *Comment) LoadPoster() error {
return c.loadPoster(db.GetEngine(db.DefaultContext)) return c.loadPoster(db.DefaultContext)
} }
// LoadAttachments loads attachments (it never returns error, the error during `GetAttachmentsByCommentIDCtx` is ignored) // LoadAttachments loads attachments (it never returns error, the error during `GetAttachmentsByCommentIDCtx` is ignored)
@ -535,7 +535,7 @@ func (c *Comment) LoadAttachments() error {
} }
var err error var err error
c.Attachments, err = repo_model.GetAttachmentsByCommentIDCtx(db.DefaultContext, c.ID) c.Attachments, err = repo_model.GetAttachmentsByCommentID(db.DefaultContext, c.ID)
if err != nil { if err != nil {
log.Error("getAttachmentsByCommentID[%d]: %v", c.ID, err) log.Error("getAttachmentsByCommentID[%d]: %v", c.ID, err)
} }
@ -557,7 +557,7 @@ func (c *Comment) UpdateAttachments(uuids []string) error {
for i := 0; i < len(attachments); i++ { for i := 0; i < len(attachments); i++ {
attachments[i].IssueID = c.IssueID attachments[i].IssueID = c.IssueID
attachments[i].CommentID = c.ID attachments[i].CommentID = c.ID
if err := repo_model.UpdateAttachmentCtx(ctx, attachments[i]); err != nil { if err := repo_model.UpdateAttachment(ctx, attachments[i]); err != nil {
return fmt.Errorf("update attachment [id: %d]: %v", attachments[i].ID, err) return fmt.Errorf("update attachment [id: %d]: %v", attachments[i].ID, err)
} }
} }
@ -590,7 +590,7 @@ func (c *Comment) LoadAssigneeUserAndTeam() error {
} }
if c.Issue.Repo.Owner.IsOrganization() { if c.Issue.Repo.Owner.IsOrganization() {
c.AssigneeTeam, err = organization.GetTeamByID(c.AssigneeTeamID) c.AssigneeTeam, err = organization.GetTeamByID(db.DefaultContext, c.AssigneeTeamID)
if err != nil && !organization.IsErrTeamNotExist(err) { if err != nil && !organization.IsErrTeamNotExist(err) {
return err return err
} }
@ -624,7 +624,7 @@ func (c *Comment) LoadDepIssueDetails() (err error) {
if c.DependentIssueID <= 0 || c.DependentIssue != nil { if c.DependentIssueID <= 0 || c.DependentIssue != nil {
return nil return nil
} }
c.DependentIssue, err = getIssueByID(db.GetEngine(db.DefaultContext), c.DependentIssueID) c.DependentIssue, err = getIssueByID(db.DefaultContext, c.DependentIssueID)
return err return err
} }
@ -661,9 +661,9 @@ func (c *Comment) LoadReactions(repo *repo_model.Repository) error {
return c.loadReactions(db.DefaultContext, repo) return c.loadReactions(db.DefaultContext, repo)
} }
func (c *Comment) loadReview(e db.Engine) (err error) { func (c *Comment) loadReview(ctx context.Context) (err error) {
if c.Review == nil { if c.Review == nil {
if c.Review, err = getReviewByID(e, c.ReviewID); err != nil { if c.Review, err = GetReviewByID(ctx, c.ReviewID); err != nil {
return err return err
} }
} }
@ -673,7 +673,7 @@ func (c *Comment) loadReview(e db.Engine) (err error) {
// LoadReview loads the associated review // LoadReview loads the associated review
func (c *Comment) LoadReview() error { func (c *Comment) LoadReview() error {
return c.loadReview(db.GetEngine(db.DefaultContext)) return c.loadReview(db.DefaultContext)
} }
var notEnoughLines = regexp.MustCompile(`fatal: file .* has only \d+ lines?`) var notEnoughLines = regexp.MustCompile(`fatal: file .* has only \d+ lines?`)
@ -830,13 +830,12 @@ func CreateCommentCtx(ctx context.Context, opts *CreateCommentOptions) (_ *Comme
} }
func updateCommentInfos(ctx context.Context, opts *CreateCommentOptions, comment *Comment) (err error) { func updateCommentInfos(ctx context.Context, opts *CreateCommentOptions, comment *Comment) (err error) {
e := db.GetEngine(ctx)
// Check comment type. // Check comment type.
switch opts.Type { switch opts.Type {
case CommentTypeCode: case CommentTypeCode:
if comment.ReviewID != 0 { if comment.ReviewID != 0 {
if comment.Review == nil { if comment.Review == nil {
if err := comment.loadReview(e); err != nil { if err := comment.loadReview(ctx); err != nil {
return err return err
} }
} }
@ -846,7 +845,7 @@ func updateCommentInfos(ctx context.Context, opts *CreateCommentOptions, comment
} }
fallthrough fallthrough
case CommentTypeComment: case CommentTypeComment:
if _, err = e.Exec("UPDATE `issue` SET num_comments=num_comments+1 WHERE id=?", opts.Issue.ID); err != nil { if _, err = db.Exec(ctx, "UPDATE `issue` SET num_comments=num_comments+1 WHERE id=?", opts.Issue.ID); err != nil {
return err return err
} }
fallthrough fallthrough
@ -861,7 +860,7 @@ func updateCommentInfos(ctx context.Context, opts *CreateCommentOptions, comment
attachments[i].IssueID = opts.Issue.ID attachments[i].IssueID = opts.Issue.ID
attachments[i].CommentID = comment.ID attachments[i].CommentID = comment.ID
// No assign value could be 0, so ignore AllCols(). // No assign value could be 0, so ignore AllCols().
if _, err = e.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) return fmt.Errorf("update attachment [%d]: %v", attachments[i].ID, err)
} }
} }
@ -1031,13 +1030,9 @@ func CreateRefComment(doer *user_model.User, repo *repo_model.Repository, issue
} }
// GetCommentByID returns the comment by given ID. // GetCommentByID returns the comment by given ID.
func GetCommentByID(id int64) (*Comment, error) { func GetCommentByID(ctx context.Context, id int64) (*Comment, error) {
return getCommentByID(db.GetEngine(db.DefaultContext), id)
}
func getCommentByID(e db.Engine, id int64) (*Comment, error) {
c := new(Comment) c := new(Comment)
has, err := e.ID(id).Get(c) has, err := db.GetEngine(ctx).ID(id).Get(c)
if err != nil { if err != nil {
return nil, err return nil, err
} else if !has { } else if !has {
@ -1088,9 +1083,10 @@ func (opts *FindCommentsOptions) toConds() builder.Cond {
return cond return cond
} }
func findComments(e db.Engine, opts *FindCommentsOptions) ([]*Comment, error) { // FindComments returns all comments according options
func FindComments(ctx context.Context, opts *FindCommentsOptions) ([]*Comment, error) {
comments := make([]*Comment, 0, 10) comments := make([]*Comment, 0, 10)
sess := e.Where(opts.toConds()) sess := db.GetEngine(ctx).Where(opts.toConds())
if opts.RepoID > 0 { if opts.RepoID > 0 {
sess.Join("INNER", "issue", "issue.id = comment.issue_id") sess.Join("INNER", "issue", "issue.id = comment.issue_id")
} }
@ -1107,11 +1103,6 @@ func findComments(e db.Engine, opts *FindCommentsOptions) ([]*Comment, error) {
Find(&comments) Find(&comments)
} }
// FindComments returns all comments according options
func FindComments(opts *FindCommentsOptions) ([]*Comment, error) {
return findComments(db.GetEngine(db.DefaultContext), opts)
}
// CountComments count all comments according options by ignoring pagination // CountComments count all comments according options by ignoring pagination
func CountComments(opts *FindCommentsOptions) (int64, error) { func CountComments(opts *FindCommentsOptions) (int64, error) {
sess := db.GetEngine(db.DefaultContext).Where(opts.toConds()) sess := db.GetEngine(db.DefaultContext).Where(opts.toConds())
@ -1167,7 +1158,7 @@ func deleteComment(ctx context.Context, comment *Comment) error {
return err return err
} }
if _, err := e.Delete(&issues_model.ContentHistory{ if _, err := db.DeleteByBean(ctx, &issues_model.ContentHistory{
CommentID: comment.ID, CommentID: comment.ID,
}); err != nil { }); err != nil {
return err return err
@ -1182,7 +1173,7 @@ func deleteComment(ctx context.Context, comment *Comment) error {
return err return err
} }
if err := comment.neuterCrossReferences(e); err != nil { if err := comment.neuterCrossReferences(ctx); err != nil {
return err return err
} }
@ -1192,7 +1183,8 @@ func deleteComment(ctx context.Context, comment *Comment) error {
// CodeComments represents comments on code by using this structure: FILENAME -> LINE (+ == proposed; - == previous) -> COMMENTS // CodeComments represents comments on code by using this structure: FILENAME -> LINE (+ == proposed; - == previous) -> COMMENTS
type CodeComments map[string]map[int64][]*Comment type CodeComments map[string]map[int64][]*Comment
func fetchCodeComments(ctx context.Context, issue *Issue, currentUser *user_model.User) (CodeComments, error) { // FetchCodeComments will return a 2d-map: ["Path"]["Line"] = Comments at line
func FetchCodeComments(ctx context.Context, issue *Issue, currentUser *user_model.User) (CodeComments, error) {
return fetchCodeCommentsByReview(ctx, issue, currentUser, nil) return fetchCodeCommentsByReview(ctx, issue, currentUser, nil)
} }
@ -1242,7 +1234,7 @@ func findCodeComments(ctx context.Context, opts FindCommentsOptions, issue *Issu
return nil, err return nil, err
} }
if err := CommentList(comments).loadPosters(e); err != nil { if err := CommentList(comments).loadPosters(ctx); err != nil {
return nil, err return nil, err
} }
@ -1302,11 +1294,6 @@ func FetchCodeCommentsByLine(ctx context.Context, issue *Issue, currentUser *use
return findCodeComments(ctx, opts, issue, currentUser, nil) return findCodeComments(ctx, opts, issue, currentUser, nil)
} }
// FetchCodeComments will return a 2d-map: ["Path"]["Line"] = Comments at line
func FetchCodeComments(ctx context.Context, issue *Issue, currentUser *user_model.User) (CodeComments, error) {
return fetchCodeComments(ctx, issue, currentUser)
}
// UpdateCommentsMigrationsByType updates comments' migrations information via given git service type and original id and poster id // 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 { func UpdateCommentsMigrationsByType(tp structs.GitServiceType, originalAuthorID string, posterID int64) error {
_, err := db.GetEngine(db.DefaultContext).Table("comment"). _, err := db.GetEngine(db.DefaultContext).Table("comment").

@ -27,7 +27,7 @@ func (comments CommentList) getPosterIDs() []int64 {
return container.KeysInt64(posterIDs) return container.KeysInt64(posterIDs)
} }
func (comments CommentList) loadPosters(e db.Engine) error { func (comments CommentList) loadPosters(ctx context.Context) error {
if len(comments) == 0 { if len(comments) == 0 {
return nil return nil
} }
@ -40,7 +40,7 @@ func (comments CommentList) loadPosters(e db.Engine) error {
if left < limit { if left < limit {
limit = left limit = left
} }
err := e. err := db.GetEngine(ctx).
In("id", posterIDs[:limit]). In("id", posterIDs[:limit]).
Find(&posterMaps) Find(&posterMaps)
if err != nil { if err != nil {
@ -80,7 +80,7 @@ func (comments CommentList) getLabelIDs() []int64 {
return container.KeysInt64(ids) return container.KeysInt64(ids)
} }
func (comments CommentList) loadLabels(e db.Engine) error { func (comments CommentList) loadLabels(ctx context.Context) error {
if len(comments) == 0 { if len(comments) == 0 {
return nil return nil
} }
@ -93,7 +93,7 @@ func (comments CommentList) loadLabels(e db.Engine) error {
if left < limit { if left < limit {
limit = left limit = left
} }
rows, err := e. rows, err := db.GetEngine(ctx).
In("id", labelIDs[:limit]). In("id", labelIDs[:limit]).
Rows(new(Label)) Rows(new(Label))
if err != nil { if err != nil {
@ -130,7 +130,7 @@ func (comments CommentList) getMilestoneIDs() []int64 {
return container.KeysInt64(ids) return container.KeysInt64(ids)
} }
func (comments CommentList) loadMilestones(e db.Engine) error { func (comments CommentList) loadMilestones(ctx context.Context) error {
if len(comments) == 0 { if len(comments) == 0 {
return nil return nil
} }
@ -147,7 +147,7 @@ func (comments CommentList) loadMilestones(e db.Engine) error {
if left < limit { if left < limit {
limit = left limit = left
} }
err := e. err := db.GetEngine(ctx).
In("id", milestoneIDs[:limit]). In("id", milestoneIDs[:limit]).
Find(&milestoneMaps) Find(&milestoneMaps)
if err != nil { if err != nil {
@ -173,7 +173,7 @@ func (comments CommentList) getOldMilestoneIDs() []int64 {
return container.KeysInt64(ids) return container.KeysInt64(ids)
} }
func (comments CommentList) loadOldMilestones(e db.Engine) error { func (comments CommentList) loadOldMilestones(ctx context.Context) error {
if len(comments) == 0 { if len(comments) == 0 {
return nil return nil
} }
@ -190,7 +190,7 @@ func (comments CommentList) loadOldMilestones(e db.Engine) error {
if left < limit { if left < limit {
limit = left limit = left
} }
err := e. err := db.GetEngine(ctx).
In("id", milestoneIDs[:limit]). In("id", milestoneIDs[:limit]).
Find(&milestoneMaps) Find(&milestoneMaps)
if err != nil { if err != nil {
@ -216,7 +216,7 @@ func (comments CommentList) getAssigneeIDs() []int64 {
return container.KeysInt64(ids) return container.KeysInt64(ids)
} }
func (comments CommentList) loadAssignees(e db.Engine) error { func (comments CommentList) loadAssignees(ctx context.Context) error {
if len(comments) == 0 { if len(comments) == 0 {
return nil return nil
} }
@ -229,7 +229,7 @@ func (comments CommentList) loadAssignees(e db.Engine) error {
if left < limit { if left < limit {
limit = left limit = left
} }
rows, err := e. rows, err := db.GetEngine(ctx).
In("id", assigneeIDs[:limit]). In("id", assigneeIDs[:limit]).
Rows(new(user_model.User)) Rows(new(user_model.User))
if err != nil { if err != nil {
@ -290,7 +290,7 @@ func (comments CommentList) Issues() IssueList {
return issueList return issueList
} }
func (comments CommentList) loadIssues(e db.Engine) error { func (comments CommentList) loadIssues(ctx context.Context) error {
if len(comments) == 0 { if len(comments) == 0 {
return nil return nil
} }
@ -303,7 +303,7 @@ func (comments CommentList) loadIssues(e db.Engine) error {
if left < limit { if left < limit {
limit = left limit = left
} }
rows, err := e. rows, err := db.GetEngine(ctx).
In("id", issueIDs[:limit]). In("id", issueIDs[:limit]).
Rows(new(Issue)) Rows(new(Issue))
if err != nil { if err != nil {
@ -397,7 +397,7 @@ func (comments CommentList) loadDependentIssues(ctx context.Context) error {
return nil return nil
} }
func (comments CommentList) loadAttachments(e db.Engine) (err error) { func (comments CommentList) loadAttachments(ctx context.Context) (err error) {
if len(comments) == 0 { if len(comments) == 0 {
return nil return nil
} }
@ -410,7 +410,7 @@ func (comments CommentList) loadAttachments(e db.Engine) (err error) {
if left < limit { if left < limit {
limit = left limit = left
} }
rows, err := e.Table("attachment"). rows, err := db.GetEngine(ctx).Table("attachment").
Join("INNER", "comment", "comment.id = attachment.comment_id"). Join("INNER", "comment", "comment.id = attachment.comment_id").
In("comment.id", commentsIDs[:limit]). In("comment.id", commentsIDs[:limit]).
Rows(new(repo_model.Attachment)) Rows(new(repo_model.Attachment))
@ -449,7 +449,7 @@ func (comments CommentList) getReviewIDs() []int64 {
return container.KeysInt64(ids) return container.KeysInt64(ids)
} }
func (comments CommentList) loadReviews(e db.Engine) error { func (comments CommentList) loadReviews(ctx context.Context) error {
if len(comments) == 0 { if len(comments) == 0 {
return nil return nil
} }
@ -462,7 +462,7 @@ func (comments CommentList) loadReviews(e db.Engine) error {
if left < limit { if left < limit {
limit = left limit = left
} }
rows, err := e. rows, err := db.GetEngine(ctx).
In("id", reviewIDs[:limit]). In("id", reviewIDs[:limit]).
Rows(new(Review)) Rows(new(Review))
if err != nil { if err != nil {
@ -493,36 +493,35 @@ func (comments CommentList) loadReviews(e db.Engine) error {
// loadAttributes loads all attributes // loadAttributes loads all attributes
func (comments CommentList) loadAttributes(ctx context.Context) (err error) { func (comments CommentList) loadAttributes(ctx context.Context) (err error) {
e := db.GetEngine(ctx) if err = comments.loadPosters(ctx); err != nil {
if err = comments.loadPosters(e); err != nil {
return return
} }
if err = comments.loadLabels(e); err != nil { if err = comments.loadLabels(ctx); err != nil {
return return
} }
if err = comments.loadMilestones(e); err != nil { if err = comments.loadMilestones(ctx); err != nil {
return return
} }
if err = comments.loadOldMilestones(e); err != nil { if err = comments.loadOldMilestones(ctx); err != nil {
return return
} }
if err = comments.loadAssignees(e); err != nil { if err = comments.loadAssignees(ctx); err != nil {
return return
} }
if err = comments.loadAttachments(e); err != nil { if err = comments.loadAttachments(ctx); err != nil {
return return
} }
if err = comments.loadReviews(e); err != nil { if err = comments.loadReviews(ctx); err != nil {
return return
} }
if err = comments.loadIssues(e); err != nil { if err = comments.loadIssues(ctx); err != nil {
return return
} }
@ -541,15 +540,15 @@ func (comments CommentList) LoadAttributes() error {
// LoadAttachments loads attachments // LoadAttachments loads attachments
func (comments CommentList) LoadAttachments() error { func (comments CommentList) LoadAttachments() error {
return comments.loadAttachments(db.GetEngine(db.DefaultContext)) return comments.loadAttachments(db.DefaultContext)
} }
// LoadPosters loads posters // LoadPosters loads posters
func (comments CommentList) LoadPosters() error { func (comments CommentList) LoadPosters() error {
return comments.loadPosters(db.GetEngine(db.DefaultContext)) return comments.loadPosters(db.DefaultContext)
} }
// LoadIssues loads issues of comments // LoadIssues loads issues of comments
func (comments CommentList) LoadIssues() error { func (comments CommentList) LoadIssues() error {
return comments.loadIssues(db.GetEngine(db.DefaultContext)) return comments.loadIssues(db.DefaultContext)
} }

@ -42,10 +42,9 @@ func CreateIssueDependency(user *user_model.User, issue, dep *Issue) error {
return err return err
} }
defer committer.Close() defer committer.Close()
sess := db.GetEngine(ctx)
// Check if it aleready exists // Check if it aleready exists
exists, err := issueDepExists(sess, issue.ID, dep.ID) exists, err := issueDepExists(ctx, issue.ID, dep.ID)
if err != nil { if err != nil {
return err return err
} }
@ -53,7 +52,7 @@ func CreateIssueDependency(user *user_model.User, issue, dep *Issue) error {
return ErrDependencyExists{issue.ID, dep.ID} return ErrDependencyExists{issue.ID, dep.ID}
} }
// And if it would be circular // And if it would be circular
circular, err := issueDepExists(sess, dep.ID, issue.ID) circular, err := issueDepExists(ctx, dep.ID, issue.ID)
if err != nil { if err != nil {
return err return err
} }
@ -114,8 +113,8 @@ func RemoveIssueDependency(user *user_model.User, issue, dep *Issue, depType Dep
} }
// Check if the dependency already exists // Check if the dependency already exists
func issueDepExists(e db.Engine, issueID, depID int64) (bool, error) { func issueDepExists(ctx context.Context, issueID, depID int64) (bool, error) {
return e.Where("(issue_id = ? AND dependency_id = ?)", issueID, depID).Exist(&IssueDependency{}) return db.GetEngine(ctx).Where("(issue_id = ? AND dependency_id = ?)", issueID, depID).Exist(&IssueDependency{})
} }
// IssueNoDependenciesLeft checks if issue can be closed // IssueNoDependenciesLeft checks if issue can be closed

@ -193,12 +193,12 @@ func UpdateLabel(l *Label) error {
if !LabelColorPattern.MatchString(l.Color) { if !LabelColorPattern.MatchString(l.Color) {
return fmt.Errorf("bad color code: %s", l.Color) return fmt.Errorf("bad color code: %s", l.Color)
} }
return updateLabelCols(db.GetEngine(db.DefaultContext), l, "name", "description", "color") return updateLabelCols(db.DefaultContext, l, "name", "description", "color")
} }
// DeleteLabel delete a label // DeleteLabel delete a label
func DeleteLabel(id, labelID int64) error { func DeleteLabel(id, labelID int64) error {
label, err := GetLabelByID(labelID) label, err := GetLabelByID(db.DefaultContext, labelID)
if err != nil { if err != nil {
if IsErrLabelNotExist(err) { if IsErrLabelNotExist(err) {
return nil return nil
@ -237,14 +237,14 @@ func DeleteLabel(id, labelID int64) error {
return committer.Commit() return committer.Commit()
} }
// getLabelByID returns a label by label id // GetLabelByID returns a label by given ID.
func getLabelByID(e db.Engine, labelID int64) (*Label, error) { func GetLabelByID(ctx context.Context, labelID int64) (*Label, error) {
if labelID <= 0 { if labelID <= 0 {
return nil, ErrLabelNotExist{labelID} return nil, ErrLabelNotExist{labelID}
} }
l := &Label{} l := &Label{}
has, err := e.ID(labelID).Get(l) has, err := db.GetEngine(ctx).ID(labelID).Get(l)
if err != nil { if err != nil {
return nil, err return nil, err
} else if !has { } else if !has {
@ -253,11 +253,6 @@ func getLabelByID(e db.Engine, labelID int64) (*Label, error) {
return l, nil return l, nil
} }
// GetLabelByID returns a label by given ID.
func GetLabelByID(id int64) (*Label, error) {
return getLabelByID(db.GetEngine(db.DefaultContext), id)
}
// GetLabelsByIDs returns a list of labels by IDs // GetLabelsByIDs returns a list of labels by IDs
func GetLabelsByIDs(labelIDs []int64) ([]*Label, error) { func GetLabelsByIDs(labelIDs []int64) ([]*Label, error) {
labels := make([]*Label, 0, len(labelIDs)) labels := make([]*Label, 0, len(labelIDs))
@ -275,8 +270,8 @@ func GetLabelsByIDs(labelIDs []int64) ([]*Label, error) {
// |____|_ /\___ > __/ \____/____ >__||__| \____/|__| / ____| // |____|_ /\___ > __/ \____/____ >__||__| \____/|__| / ____|
// \/ \/|__| \/ \/ // \/ \/|__| \/ \/
// getLabelInRepoByName returns a label by Name in given repository. // GetLabelInRepoByName returns a label by name in given repository.
func getLabelInRepoByName(e db.Engine, repoID int64, labelName string) (*Label, error) { func GetLabelInRepoByName(ctx context.Context, repoID int64, labelName string) (*Label, error) {
if len(labelName) == 0 || repoID <= 0 { if len(labelName) == 0 || repoID <= 0 {
return nil, ErrRepoLabelNotExist{0, repoID} return nil, ErrRepoLabelNotExist{0, repoID}
} }
@ -285,7 +280,7 @@ func getLabelInRepoByName(e db.Engine, repoID int64, labelName string) (*Label,
Name: labelName, Name: labelName,
RepoID: repoID, RepoID: repoID,
} }
has, err := e.Get(l) has, err := db.GetByBean(ctx, l)
if err != nil { if err != nil {
return nil, err return nil, err
} else if !has { } else if !has {
@ -294,8 +289,8 @@ func getLabelInRepoByName(e db.Engine, repoID int64, labelName string) (*Label,
return l, nil return l, nil
} }
// getLabelInRepoByID returns a label by ID in given repository. // GetLabelInRepoByID returns a label by ID in given repository.
func getLabelInRepoByID(e db.Engine, repoID, labelID int64) (*Label, error) { func GetLabelInRepoByID(ctx context.Context, repoID, labelID int64) (*Label, error) {
if labelID <= 0 || repoID <= 0 { if labelID <= 0 || repoID <= 0 {
return nil, ErrRepoLabelNotExist{labelID, repoID} return nil, ErrRepoLabelNotExist{labelID, repoID}
} }
@ -304,7 +299,7 @@ func getLabelInRepoByID(e db.Engine, repoID, labelID int64) (*Label, error) {
ID: labelID, ID: labelID,
RepoID: repoID, RepoID: repoID,
} }
has, err := e.Get(l) has, err := db.GetByBean(ctx, l)
if err != nil { if err != nil {
return nil, err return nil, err
} else if !has { } else if !has {
@ -313,11 +308,6 @@ func getLabelInRepoByID(e db.Engine, repoID, labelID int64) (*Label, error) {
return l, nil return l, nil
} }
// GetLabelInRepoByName returns a label by name in given repository.
func GetLabelInRepoByName(repoID int64, labelName string) (*Label, error) {
return getLabelInRepoByName(db.GetEngine(db.DefaultContext), repoID, labelName)
}
// GetLabelIDsInRepoByNames returns a list of labelIDs by names in a given // GetLabelIDsInRepoByNames returns a list of labelIDs by names in a given
// repository. // repository.
// it silently ignores label names that do not belong to the repository. // it silently ignores label names that do not belong to the repository.
@ -342,11 +332,6 @@ func BuildLabelNamesIssueIDsCondition(labelNames []string) *builder.Builder {
GroupBy("issue_label.issue_id") GroupBy("issue_label.issue_id")
} }
// GetLabelInRepoByID returns a label by ID in given repository.
func GetLabelInRepoByID(repoID, labelID int64) (*Label, error) {
return getLabelInRepoByID(db.GetEngine(db.DefaultContext), repoID, labelID)
}
// GetLabelsInRepoByIDs returns a list of labels by IDs in given repository, // GetLabelsInRepoByIDs returns a list of labels by IDs in given repository,
// it silently ignores label IDs that do not belong to the repository. // it silently ignores label IDs that do not belong to the repository.
func GetLabelsInRepoByIDs(repoID int64, labelIDs []int64) ([]*Label, error) { func GetLabelsInRepoByIDs(repoID int64, labelIDs []int64) ([]*Label, error) {
@ -358,12 +343,13 @@ func GetLabelsInRepoByIDs(repoID int64, labelIDs []int64) ([]*Label, error) {
Find(&labels) Find(&labels)
} }
func getLabelsByRepoID(e db.Engine, repoID int64, sortType string, listOptions db.ListOptions) ([]*Label, error) { // GetLabelsByRepoID returns all labels that belong to given repository by ID.
func GetLabelsByRepoID(ctx context.Context, repoID int64, sortType string, listOptions db.ListOptions) ([]*Label, error) {
if repoID <= 0 { if repoID <= 0 {
return nil, ErrRepoLabelNotExist{0, repoID} return nil, ErrRepoLabelNotExist{0, repoID}
} }
labels := make([]*Label, 0, 10) labels := make([]*Label, 0, 10)
sess := e.Where("repo_id = ?", repoID) sess := db.GetEngine(ctx).Where("repo_id = ?", repoID)
switch sortType { switch sortType {
case "reversealphabetically": case "reversealphabetically":
@ -383,11 +369,6 @@ func getLabelsByRepoID(e db.Engine, repoID int64, sortType string, listOptions d
return labels, sess.Find(&labels) return labels, sess.Find(&labels)
} }
// GetLabelsByRepoID returns all labels that belong to given repository by ID.
func GetLabelsByRepoID(repoID int64, sortType string, listOptions db.ListOptions) ([]*Label, error) {
return getLabelsByRepoID(db.GetEngine(db.DefaultContext), repoID, sortType, listOptions)
}
// CountLabelsByRepoID count number of all labels that belong to given repository by ID. // CountLabelsByRepoID count number of all labels that belong to given repository by ID.
func CountLabelsByRepoID(repoID int64) (int64, error) { func CountLabelsByRepoID(repoID int64) (int64, error) {
return db.GetEngine(db.DefaultContext).Where("repo_id = ?", repoID).Count(&Label{}) return db.GetEngine(db.DefaultContext).Where("repo_id = ?", repoID).Count(&Label{})
@ -400,8 +381,8 @@ func CountLabelsByRepoID(repoID int64) (int64, error) {
// \_______ /__| \___ / // \_______ /__| \___ /
// \/ /_____/ // \/ /_____/
// getLabelInOrgByName returns a label by Name in given organization // GetLabelInOrgByName returns a label by name in given organization.
func getLabelInOrgByName(e db.Engine, orgID int64, labelName string) (*Label, error) { func GetLabelInOrgByName(ctx context.Context, orgID int64, labelName string) (*Label, error) {
if len(labelName) == 0 || orgID <= 0 { if len(labelName) == 0 || orgID <= 0 {
return nil, ErrOrgLabelNotExist{0, orgID} return nil, ErrOrgLabelNotExist{0, orgID}
} }
@ -410,7 +391,7 @@ func getLabelInOrgByName(e db.Engine, orgID int64, labelName string) (*Label, er
Name: labelName, Name: labelName,
OrgID: orgID, OrgID: orgID,
} }
has, err := e.Get(l) has, err := db.GetByBean(ctx, l)
if err != nil { if err != nil {
return nil, err return nil, err
} else if !has { } else if !has {
@ -419,8 +400,8 @@ func getLabelInOrgByName(e db.Engine, orgID int64, labelName string) (*Label, er
return l, nil return l, nil
} }
// getLabelInOrgByID returns a label by ID in given organization. // GetLabelInOrgByID returns a label by ID in given organization.
func getLabelInOrgByID(e db.Engine, orgID, labelID int64) (*Label, error) { func GetLabelInOrgByID(ctx context.Context, orgID, labelID int64) (*Label, error) {
if labelID <= 0 || orgID <= 0 { if labelID <= 0 || orgID <= 0 {
return nil, ErrOrgLabelNotExist{labelID, orgID} return nil, ErrOrgLabelNotExist{labelID, orgID}
} }
@ -429,7 +410,7 @@ func getLabelInOrgByID(e db.Engine, orgID, labelID int64) (*Label, error) {
ID: labelID, ID: labelID,
OrgID: orgID, OrgID: orgID,
} }
has, err := e.Get(l) has, err := db.GetByBean(ctx, l)
if err != nil { if err != nil {
return nil, err return nil, err
} else if !has { } else if !has {
@ -438,11 +419,6 @@ func getLabelInOrgByID(e db.Engine, orgID, labelID int64) (*Label, error) {
return l, nil return l, nil
} }
// GetLabelInOrgByName returns a label by name in given organization.
func GetLabelInOrgByName(orgID int64, labelName string) (*Label, error) {
return getLabelInOrgByName(db.GetEngine(db.DefaultContext), orgID, labelName)
}
// GetLabelIDsInOrgByNames returns a list of labelIDs by names in a given // GetLabelIDsInOrgByNames returns a list of labelIDs by names in a given
// organization. // organization.
func GetLabelIDsInOrgByNames(orgID int64, labelNames []string) ([]int64, error) { func GetLabelIDsInOrgByNames(orgID int64, labelNames []string) ([]int64, error) {
@ -459,11 +435,6 @@ func GetLabelIDsInOrgByNames(orgID int64, labelNames []string) ([]int64, error)
Find(&labelIDs) Find(&labelIDs)
} }
// GetLabelInOrgByID returns a label by ID in given organization.
func GetLabelInOrgByID(orgID, labelID int64) (*Label, error) {
return getLabelInOrgByID(db.GetEngine(db.DefaultContext), orgID, labelID)
}
// GetLabelsInOrgByIDs returns a list of labels by IDs in given organization, // GetLabelsInOrgByIDs returns a list of labels by IDs in given organization,
// it silently ignores label IDs that do not belong to the organization. // it silently ignores label IDs that do not belong to the organization.
func GetLabelsInOrgByIDs(orgID int64, labelIDs []int64) ([]*Label, error) { func GetLabelsInOrgByIDs(orgID int64, labelIDs []int64) ([]*Label, error) {
@ -475,12 +446,13 @@ func GetLabelsInOrgByIDs(orgID int64, labelIDs []int64) ([]*Label, error) {
Find(&labels) Find(&labels)
} }
func getLabelsByOrgID(e db.Engine, orgID int64, sortType string, listOptions db.ListOptions) ([]*Label, error) { // GetLabelsByOrgID returns all labels that belong to given organization by ID.
func GetLabelsByOrgID(ctx context.Context, orgID int64, sortType string, listOptions db.ListOptions) ([]*Label, error) {
if orgID <= 0 { if orgID <= 0 {
return nil, ErrOrgLabelNotExist{0, orgID} return nil, ErrOrgLabelNotExist{0, orgID}
} }
labels := make([]*Label, 0, 10) labels := make([]*Label, 0, 10)
sess := e.Where("org_id = ?", orgID) sess := db.GetEngine(ctx).Where("org_id = ?", orgID)
switch sortType { switch sortType {
case "reversealphabetically": case "reversealphabetically":
@ -500,11 +472,6 @@ func getLabelsByOrgID(e db.Engine, orgID int64, sortType string, listOptions db.
return labels, sess.Find(&labels) return labels, sess.Find(&labels)
} }
// GetLabelsByOrgID returns all labels that belong to given organization by ID.
func GetLabelsByOrgID(orgID int64, sortType string, listOptions db.ListOptions) ([]*Label, error) {
return getLabelsByOrgID(db.GetEngine(db.DefaultContext), orgID, sortType, listOptions)
}
// CountLabelsByOrgID count all labels that belong to given organization by ID. // CountLabelsByOrgID count all labels that belong to given organization by ID.
func CountLabelsByOrgID(orgID int64) (int64, error) { func CountLabelsByOrgID(orgID int64) (int64, error) {
return db.GetEngine(db.DefaultContext).Where("org_id = ?", orgID).Count(&Label{}) return db.GetEngine(db.DefaultContext).Where("org_id = ?", orgID).Count(&Label{})
@ -517,21 +484,17 @@ func CountLabelsByOrgID(orgID int64) (int64, error) {
// |___/____ >____ >____/ \___ | // |___/____ >____ >____/ \___ |
// \/ \/ \/ // \/ \/ \/
func getLabelsByIssueID(e db.Engine, issueID int64) ([]*Label, error) { // GetLabelsByIssueID returns all labels that belong to given issue by ID.
func GetLabelsByIssueID(ctx context.Context, issueID int64) ([]*Label, error) {
var labels []*Label var labels []*Label
return labels, e.Where("issue_label.issue_id = ?", issueID). return labels, db.GetEngine(ctx).Where("issue_label.issue_id = ?", issueID).
Join("LEFT", "issue_label", "issue_label.label_id = label.id"). Join("LEFT", "issue_label", "issue_label.label_id = label.id").
Asc("label.name"). Asc("label.name").
Find(&labels) Find(&labels)
} }
// GetLabelsByIssueID returns all labels that belong to given issue by ID. func updateLabelCols(ctx context.Context, l *Label, cols ...string) error {
func GetLabelsByIssueID(issueID int64) ([]*Label, error) { _, err := db.GetEngine(ctx).ID(l.ID).
return getLabelsByIssueID(db.GetEngine(db.DefaultContext), issueID)
}
func updateLabelCols(e db.Engine, l *Label, cols ...string) error {
_, err := e.ID(l.ID).
SetExpr("num_issues", SetExpr("num_issues",
builder.Select("count(*)").From("issue_label"). builder.Select("count(*)").From("issue_label").
Where(builder.Eq{"label_id": l.ID}), Where(builder.Eq{"label_id": l.ID}),
@ -562,21 +525,16 @@ type IssueLabel struct {
LabelID int64 `xorm:"UNIQUE(s)"` LabelID int64 `xorm:"UNIQUE(s)"`
} }
func hasIssueLabel(e db.Engine, issueID, labelID int64) bool {
has, _ := e.Where("issue_id = ? AND label_id = ?", issueID, labelID).Get(new(IssueLabel))
return has
}
// HasIssueLabel returns true if issue has been labeled. // HasIssueLabel returns true if issue has been labeled.
func HasIssueLabel(issueID, labelID int64) bool { func HasIssueLabel(ctx context.Context, issueID, labelID int64) bool {
return hasIssueLabel(db.GetEngine(db.DefaultContext), issueID, labelID) has, _ := db.GetEngine(ctx).Where("issue_id = ? AND label_id = ?", issueID, labelID).Get(new(IssueLabel))
return has
} }
// newIssueLabel this function creates a new label it does not check if the label is valid for the issue // newIssueLabel this function creates a new label it does not check if the label is valid for the issue
// YOU MUST CHECK THIS BEFORE THIS FUNCTION // YOU MUST CHECK THIS BEFORE THIS FUNCTION
func newIssueLabel(ctx context.Context, issue *Issue, label *Label, doer *user_model.User) (err error) { func newIssueLabel(ctx context.Context, issue *Issue, label *Label, doer *user_model.User) (err error) {
e := db.GetEngine(ctx) if err = db.Insert(ctx, &IssueLabel{
if _, err = e.Insert(&IssueLabel{
IssueID: issue.ID, IssueID: issue.ID,
LabelID: label.ID, LabelID: label.ID,
}); err != nil { }); err != nil {
@ -599,12 +557,12 @@ func newIssueLabel(ctx context.Context, issue *Issue, label *Label, doer *user_m
return err return err
} }
return updateLabelCols(e, label, "num_issues", "num_closed_issue") return updateLabelCols(ctx, label, "num_issues", "num_closed_issue")
} }
// NewIssueLabel creates a new issue-label relation. // NewIssueLabel creates a new issue-label relation.
func NewIssueLabel(issue *Issue, label *Label, doer *user_model.User) (err error) { func NewIssueLabel(issue *Issue, label *Label, doer *user_model.User) (err error) {
if HasIssueLabel(issue.ID, label.ID) { if HasIssueLabel(db.DefaultContext, issue.ID, label.ID) {
return nil return nil
} }
@ -637,13 +595,12 @@ func NewIssueLabel(issue *Issue, label *Label, doer *user_model.User) (err error
// newIssueLabels add labels to an issue. It will check if the labels are valid for the issue // newIssueLabels add labels to an issue. It will check if the labels are valid for the issue
func newIssueLabels(ctx context.Context, issue *Issue, labels []*Label, doer *user_model.User) (err error) { func newIssueLabels(ctx context.Context, issue *Issue, labels []*Label, doer *user_model.User) (err error) {
e := db.GetEngine(ctx)
if err = issue.LoadRepo(ctx); err != nil { if err = issue.LoadRepo(ctx); err != nil {
return err return err
} }
for _, label := range labels { for _, label := range labels {
// Don't add already present labels and invalid labels // Don't add already present labels and invalid labels
if hasIssueLabel(e, issue.ID, label.ID) || if HasIssueLabel(ctx, issue.ID, label.ID) ||
(label.RepoID != issue.RepoID && label.OrgID != issue.Repo.OwnerID) { (label.RepoID != issue.RepoID && label.OrgID != issue.Repo.OwnerID) {
continue continue
} }
@ -677,8 +634,7 @@ func NewIssueLabels(issue *Issue, labels []*Label, doer *user_model.User) (err e
} }
func deleteIssueLabel(ctx context.Context, issue *Issue, label *Label, doer *user_model.User) (err error) { func deleteIssueLabel(ctx context.Context, issue *Issue, label *Label, doer *user_model.User) (err error) {
e := db.GetEngine(ctx) if count, err := db.DeleteByBean(ctx, &IssueLabel{
if count, err := e.Delete(&IssueLabel{
IssueID: issue.ID, IssueID: issue.ID,
LabelID: label.ID, LabelID: label.ID,
}); err != nil { }); err != nil {
@ -702,7 +658,7 @@ func deleteIssueLabel(ctx context.Context, issue *Issue, label *Label, doer *use
return err return err
} }
return updateLabelCols(e, label, "num_issues", "num_closed_issue") return updateLabelCols(ctx, label, "num_issues", "num_closed_issue")
} }
// DeleteIssueLabel deletes issue-label relation. // DeleteIssueLabel deletes issue-label relation.
@ -715,14 +671,14 @@ func DeleteIssueLabel(ctx context.Context, issue *Issue, label *Label, doer *use
return issue.LoadLabels(ctx) return issue.LoadLabels(ctx)
} }
func deleteLabelsByRepoID(sess db.Engine, repoID int64) error { func deleteLabelsByRepoID(ctx context.Context, repoID int64) error {
deleteCond := builder.Select("id").From("label").Where(builder.Eq{"label.repo_id": repoID}) deleteCond := builder.Select("id").From("label").Where(builder.Eq{"label.repo_id": repoID})
if _, err := sess.In("label_id", deleteCond). if _, err := db.GetEngine(ctx).In("label_id", deleteCond).
Delete(&IssueLabel{}); err != nil { Delete(&IssueLabel{}); err != nil {
return err return err
} }
_, err := sess.Delete(&Label{RepoID: repoID}) _, err := db.DeleteByBean(ctx, &Label{RepoID: repoID})
return err return err
} }

@ -59,25 +59,25 @@ func TestNewLabels(t *testing.T) {
func TestGetLabelByID(t *testing.T) { func TestGetLabelByID(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase()) assert.NoError(t, unittest.PrepareTestDatabase())
label, err := GetLabelByID(1) label, err := GetLabelByID(db.DefaultContext, 1)
assert.NoError(t, err) assert.NoError(t, err)
assert.EqualValues(t, 1, label.ID) assert.EqualValues(t, 1, label.ID)
_, err = GetLabelByID(unittest.NonexistentID) _, err = GetLabelByID(db.DefaultContext, unittest.NonexistentID)
assert.True(t, IsErrLabelNotExist(err)) assert.True(t, IsErrLabelNotExist(err))
} }
func TestGetLabelInRepoByName(t *testing.T) { func TestGetLabelInRepoByName(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase()) assert.NoError(t, unittest.PrepareTestDatabase())
label, err := GetLabelInRepoByName(1, "label1") label, err := GetLabelInRepoByName(db.DefaultContext, 1, "label1")
assert.NoError(t, err) assert.NoError(t, err)
assert.EqualValues(t, 1, label.ID) assert.EqualValues(t, 1, label.ID)
assert.Equal(t, "label1", label.Name) assert.Equal(t, "label1", label.Name)
_, err = GetLabelInRepoByName(1, "") _, err = GetLabelInRepoByName(db.DefaultContext, 1, "")
assert.True(t, IsErrRepoLabelNotExist(err)) assert.True(t, IsErrRepoLabelNotExist(err))
_, err = GetLabelInRepoByName(unittest.NonexistentID, "nonexistent") _, err = GetLabelInRepoByName(db.DefaultContext, unittest.NonexistentID, "nonexistent")
assert.True(t, IsErrRepoLabelNotExist(err)) assert.True(t, IsErrRepoLabelNotExist(err))
} }
@ -107,14 +107,14 @@ func TestGetLabelInRepoByNamesDiscardsNonExistentLabels(t *testing.T) {
func TestGetLabelInRepoByID(t *testing.T) { func TestGetLabelInRepoByID(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase()) assert.NoError(t, unittest.PrepareTestDatabase())
label, err := GetLabelInRepoByID(1, 1) label, err := GetLabelInRepoByID(db.DefaultContext, 1, 1)
assert.NoError(t, err) assert.NoError(t, err)
assert.EqualValues(t, 1, label.ID) assert.EqualValues(t, 1, label.ID)
_, err = GetLabelInRepoByID(1, -1) _, err = GetLabelInRepoByID(db.DefaultContext, 1, -1)
assert.True(t, IsErrRepoLabelNotExist(err)) assert.True(t, IsErrRepoLabelNotExist(err))
_, err = GetLabelInRepoByID(unittest.NonexistentID, unittest.NonexistentID) _, err = GetLabelInRepoByID(db.DefaultContext, unittest.NonexistentID, unittest.NonexistentID)
assert.True(t, IsErrRepoLabelNotExist(err)) assert.True(t, IsErrRepoLabelNotExist(err))
} }
@ -131,7 +131,7 @@ func TestGetLabelsInRepoByIDs(t *testing.T) {
func TestGetLabelsByRepoID(t *testing.T) { func TestGetLabelsByRepoID(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase()) assert.NoError(t, unittest.PrepareTestDatabase())
testSuccess := func(repoID int64, sortType string, expectedIssueIDs []int64) { testSuccess := func(repoID int64, sortType string, expectedIssueIDs []int64) {
labels, err := GetLabelsByRepoID(repoID, sortType, db.ListOptions{}) labels, err := GetLabelsByRepoID(db.DefaultContext, repoID, sortType, db.ListOptions{})
assert.NoError(t, err) assert.NoError(t, err)
assert.Len(t, labels, len(expectedIssueIDs)) assert.Len(t, labels, len(expectedIssueIDs))
for i, label := range labels { for i, label := range labels {
@ -148,21 +148,21 @@ func TestGetLabelsByRepoID(t *testing.T) {
func TestGetLabelInOrgByName(t *testing.T) { func TestGetLabelInOrgByName(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase()) assert.NoError(t, unittest.PrepareTestDatabase())
label, err := GetLabelInOrgByName(3, "orglabel3") label, err := GetLabelInOrgByName(db.DefaultContext, 3, "orglabel3")
assert.NoError(t, err) assert.NoError(t, err)
assert.EqualValues(t, 3, label.ID) assert.EqualValues(t, 3, label.ID)
assert.Equal(t, "orglabel3", label.Name) assert.Equal(t, "orglabel3", label.Name)
_, err = GetLabelInOrgByName(3, "") _, err = GetLabelInOrgByName(db.DefaultContext, 3, "")
assert.True(t, IsErrOrgLabelNotExist(err)) assert.True(t, IsErrOrgLabelNotExist(err))
_, err = GetLabelInOrgByName(0, "orglabel3") _, err = GetLabelInOrgByName(db.DefaultContext, 0, "orglabel3")
assert.True(t, IsErrOrgLabelNotExist(err)) assert.True(t, IsErrOrgLabelNotExist(err))
_, err = GetLabelInOrgByName(-1, "orglabel3") _, err = GetLabelInOrgByName(db.DefaultContext, -1, "orglabel3")
assert.True(t, IsErrOrgLabelNotExist(err)) assert.True(t, IsErrOrgLabelNotExist(err))
_, err = GetLabelInOrgByName(unittest.NonexistentID, "nonexistent") _, err = GetLabelInOrgByName(db.DefaultContext, unittest.NonexistentID, "nonexistent")
assert.True(t, IsErrOrgLabelNotExist(err)) assert.True(t, IsErrOrgLabelNotExist(err))
} }
@ -192,20 +192,20 @@ func TestGetLabelInOrgByNamesDiscardsNonExistentLabels(t *testing.T) {
func TestGetLabelInOrgByID(t *testing.T) { func TestGetLabelInOrgByID(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase()) assert.NoError(t, unittest.PrepareTestDatabase())
label, err := GetLabelInOrgByID(3, 3) label, err := GetLabelInOrgByID(db.DefaultContext, 3, 3)
assert.NoError(t, err) assert.NoError(t, err)
assert.EqualValues(t, 3, label.ID) assert.EqualValues(t, 3, label.ID)
_, err = GetLabelInOrgByID(3, -1) _, err = GetLabelInOrgByID(db.DefaultContext, 3, -1)
assert.True(t, IsErrOrgLabelNotExist(err)) assert.True(t, IsErrOrgLabelNotExist(err))
_, err = GetLabelInOrgByID(0, 3) _, err = GetLabelInOrgByID(db.DefaultContext, 0, 3)
assert.True(t, IsErrOrgLabelNotExist(err)) assert.True(t, IsErrOrgLabelNotExist(err))
_, err = GetLabelInOrgByID(-1, 3) _, err = GetLabelInOrgByID(db.DefaultContext, -1, 3)
assert.True(t, IsErrOrgLabelNotExist(err)) assert.True(t, IsErrOrgLabelNotExist(err))
_, err = GetLabelInOrgByID(unittest.NonexistentID, unittest.NonexistentID) _, err = GetLabelInOrgByID(db.DefaultContext, unittest.NonexistentID, unittest.NonexistentID)
assert.True(t, IsErrOrgLabelNotExist(err)) assert.True(t, IsErrOrgLabelNotExist(err))
} }
@ -222,7 +222,7 @@ func TestGetLabelsInOrgByIDs(t *testing.T) {
func TestGetLabelsByOrgID(t *testing.T) { func TestGetLabelsByOrgID(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase()) assert.NoError(t, unittest.PrepareTestDatabase())
testSuccess := func(orgID int64, sortType string, expectedIssueIDs []int64) { testSuccess := func(orgID int64, sortType string, expectedIssueIDs []int64) {
labels, err := GetLabelsByOrgID(orgID, sortType, db.ListOptions{}) labels, err := GetLabelsByOrgID(db.DefaultContext, orgID, sortType, db.ListOptions{})
assert.NoError(t, err) assert.NoError(t, err)
assert.Len(t, labels, len(expectedIssueIDs)) assert.Len(t, labels, len(expectedIssueIDs))
for i, label := range labels { for i, label := range labels {
@ -235,10 +235,10 @@ func TestGetLabelsByOrgID(t *testing.T) {
testSuccess(3, "default", []int64{3, 4}) testSuccess(3, "default", []int64{3, 4})
var err error var err error
_, err = GetLabelsByOrgID(0, "leastissues", db.ListOptions{}) _, err = GetLabelsByOrgID(db.DefaultContext, 0, "leastissues", db.ListOptions{})
assert.True(t, IsErrOrgLabelNotExist(err)) assert.True(t, IsErrOrgLabelNotExist(err))
_, err = GetLabelsByOrgID(-1, "leastissues", db.ListOptions{}) _, err = GetLabelsByOrgID(db.DefaultContext, -1, "leastissues", db.ListOptions{})
assert.True(t, IsErrOrgLabelNotExist(err)) assert.True(t, IsErrOrgLabelNotExist(err))
} }
@ -246,13 +246,13 @@ func TestGetLabelsByOrgID(t *testing.T) {
func TestGetLabelsByIssueID(t *testing.T) { func TestGetLabelsByIssueID(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase()) assert.NoError(t, unittest.PrepareTestDatabase())
labels, err := GetLabelsByIssueID(1) labels, err := GetLabelsByIssueID(db.DefaultContext, 1)
assert.NoError(t, err) assert.NoError(t, err)
if assert.Len(t, labels, 1) { if assert.Len(t, labels, 1) {
assert.EqualValues(t, 1, labels[0].ID) assert.EqualValues(t, 1, labels[0].ID)
} }
labels, err = GetLabelsByIssueID(unittest.NonexistentID) labels, err = GetLabelsByIssueID(db.DefaultContext, unittest.NonexistentID)
assert.NoError(t, err) assert.NoError(t, err)
assert.Len(t, labels, 0) assert.Len(t, labels, 0)
} }
@ -293,9 +293,9 @@ func TestDeleteLabel(t *testing.T) {
func TestHasIssueLabel(t *testing.T) { func TestHasIssueLabel(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase()) assert.NoError(t, unittest.PrepareTestDatabase())
assert.True(t, HasIssueLabel(1, 1)) assert.True(t, HasIssueLabel(db.DefaultContext, 1, 1))
assert.False(t, HasIssueLabel(1, 2)) assert.False(t, HasIssueLabel(db.DefaultContext, 1, 2))
assert.False(t, HasIssueLabel(unittest.NonexistentID, unittest.NonexistentID)) assert.False(t, HasIssueLabel(db.DefaultContext, unittest.NonexistentID, unittest.NonexistentID))
} }
func TestNewIssueLabel(t *testing.T) { func TestNewIssueLabel(t *testing.T) {

@ -5,6 +5,7 @@
package models package models
import ( import (
"context"
"fmt" "fmt"
"code.gitea.io/gitea/models/db" "code.gitea.io/gitea/models/db"
@ -37,7 +38,7 @@ func (issues IssueList) getRepoIDs() []int64 {
return container.KeysInt64(repoIDs) return container.KeysInt64(repoIDs)
} }
func (issues IssueList) loadRepositories(e db.Engine) ([]*repo_model.Repository, error) { func (issues IssueList) loadRepositories(ctx context.Context) ([]*repo_model.Repository, error) {
if len(issues) == 0 { if len(issues) == 0 {
return nil, nil return nil, nil
} }
@ -50,7 +51,7 @@ func (issues IssueList) loadRepositories(e db.Engine) ([]*repo_model.Repository,
if left < limit { if left < limit {
limit = left limit = left
} }
err := e. err := db.GetEngine(ctx).
In("id", repoIDs[:limit]). In("id", repoIDs[:limit]).
Find(&repoMaps) Find(&repoMaps)
if err != nil { if err != nil {
@ -75,7 +76,7 @@ func (issues IssueList) loadRepositories(e db.Engine) ([]*repo_model.Repository,
// LoadRepositories loads issues' all repositories // LoadRepositories loads issues' all repositories
func (issues IssueList) LoadRepositories() ([]*repo_model.Repository, error) { func (issues IssueList) LoadRepositories() ([]*repo_model.Repository, error) {
return issues.loadRepositories(db.GetEngine(db.DefaultContext)) return issues.loadRepositories(db.DefaultContext)
} }
func (issues IssueList) getPosterIDs() []int64 { func (issues IssueList) getPosterIDs() []int64 {
@ -88,7 +89,7 @@ func (issues IssueList) getPosterIDs() []int64 {
return container.KeysInt64(posterIDs) return container.KeysInt64(posterIDs)
} }
func (issues IssueList) loadPosters(e db.Engine) error { func (issues IssueList) loadPosters(ctx context.Context) error {
if len(issues) == 0 { if len(issues) == 0 {
return nil return nil
} }
@ -101,7 +102,7 @@ func (issues IssueList) loadPosters(e db.Engine) error {
if left < limit { if left < limit {
limit = left limit = left
} }
err := e. err := db.GetEngine(ctx).
In("id", posterIDs[:limit]). In("id", posterIDs[:limit]).
Find(&posterMaps) Find(&posterMaps)
if err != nil { if err != nil {
@ -131,7 +132,7 @@ func (issues IssueList) getIssueIDs() []int64 {
return ids return ids
} }
func (issues IssueList) loadLabels(e db.Engine) error { func (issues IssueList) loadLabels(ctx context.Context) error {
if len(issues) == 0 { if len(issues) == 0 {
return nil return nil
} }
@ -149,7 +150,7 @@ func (issues IssueList) loadLabels(e db.Engine) error {
if left < limit { if left < limit {
limit = left limit = left
} }
rows, err := e.Table("label"). rows, err := db.GetEngine(ctx).Table("label").
Join("LEFT", "issue_label", "issue_label.label_id = label.id"). Join("LEFT", "issue_label", "issue_label.label_id = label.id").
In("issue_label.issue_id", issueIDs[:limit]). In("issue_label.issue_id", issueIDs[:limit]).
Asc("label.name"). Asc("label.name").
@ -194,7 +195,7 @@ func (issues IssueList) getMilestoneIDs() []int64 {
return container.KeysInt64(ids) return container.KeysInt64(ids)
} }
func (issues IssueList) loadMilestones(e db.Engine) error { func (issues IssueList) loadMilestones(ctx context.Context) error {
milestoneIDs := issues.getMilestoneIDs() milestoneIDs := issues.getMilestoneIDs()
if len(milestoneIDs) == 0 { if len(milestoneIDs) == 0 {
return nil return nil
@ -207,7 +208,7 @@ func (issues IssueList) loadMilestones(e db.Engine) error {
if left < limit { if left < limit {
limit = left limit = left
} }
err := e. err := db.GetEngine(ctx).
In("id", milestoneIDs[:limit]). In("id", milestoneIDs[:limit]).
Find(&milestoneMaps) Find(&milestoneMaps)
if err != nil { if err != nil {
@ -223,7 +224,7 @@ func (issues IssueList) loadMilestones(e db.Engine) error {
return nil return nil
} }
func (issues IssueList) loadAssignees(e db.Engine) error { func (issues IssueList) loadAssignees(ctx context.Context) error {
if len(issues) == 0 { if len(issues) == 0 {
return nil return nil
} }
@ -241,7 +242,7 @@ func (issues IssueList) loadAssignees(e db.Engine) error {
if left < limit { if left < limit {
limit = left limit = left
} }
rows, err := e.Table("issue_assignees"). rows, err := db.GetEngine(ctx).Table("issue_assignees").
Join("INNER", "`user`", "`user`.id = `issue_assignees`.assignee_id"). Join("INNER", "`user`", "`user`.id = `issue_assignees`.assignee_id").
In("`issue_assignees`.issue_id", issueIDs[:limit]). In("`issue_assignees`.issue_id", issueIDs[:limit]).
Rows(new(AssigneeIssue)) Rows(new(AssigneeIssue))
@ -284,7 +285,7 @@ func (issues IssueList) getPullIssueIDs() []int64 {
return ids return ids
} }
func (issues IssueList) loadPullRequests(e db.Engine) error { func (issues IssueList) loadPullRequests(ctx context.Context) error {
issuesIDs := issues.getPullIssueIDs() issuesIDs := issues.getPullIssueIDs()
if len(issuesIDs) == 0 { if len(issuesIDs) == 0 {
return nil return nil
@ -297,7 +298,7 @@ func (issues IssueList) loadPullRequests(e db.Engine) error {
if left < limit { if left < limit {
limit = left limit = left
} }
rows, err := e. rows, err := db.GetEngine(ctx).
In("issue_id", issuesIDs[:limit]). In("issue_id", issuesIDs[:limit]).
Rows(new(PullRequest)) Rows(new(PullRequest))
if err != nil { if err != nil {
@ -328,7 +329,7 @@ func (issues IssueList) loadPullRequests(e db.Engine) error {
return nil return nil
} }
func (issues IssueList) loadAttachments(e db.Engine) (err error) { func (issues IssueList) loadAttachments(ctx context.Context) (err error) {
if len(issues) == 0 { if len(issues) == 0 {
return nil return nil
} }
@ -341,7 +342,7 @@ func (issues IssueList) loadAttachments(e db.Engine) (err error) {
if left < limit { if left < limit {
limit = left limit = left
} }
rows, err := e.Table("attachment"). rows, err := db.GetEngine(ctx).Table("attachment").
Join("INNER", "issue", "issue.id = attachment.issue_id"). Join("INNER", "issue", "issue.id = attachment.issue_id").
In("issue.id", issuesIDs[:limit]). In("issue.id", issuesIDs[:limit]).
Rows(new(repo_model.Attachment)) Rows(new(repo_model.Attachment))
@ -373,7 +374,7 @@ func (issues IssueList) loadAttachments(e db.Engine) (err error) {
return nil return nil
} }
func (issues IssueList) loadComments(e db.Engine, cond builder.Cond) (err error) { func (issues IssueList) loadComments(ctx context.Context, cond builder.Cond) (err error) {
if len(issues) == 0 { if len(issues) == 0 {
return nil return nil
} }
@ -386,7 +387,7 @@ func (issues IssueList) loadComments(e db.Engine, cond builder.Cond) (err error)
if left < limit { if left < limit {
limit = left limit = left
} }
rows, err := e.Table("comment"). rows, err := db.GetEngine(ctx).Table("comment").
Join("INNER", "issue", "issue.id = comment.issue_id"). Join("INNER", "issue", "issue.id = comment.issue_id").
In("issue.id", issuesIDs[:limit]). In("issue.id", issuesIDs[:limit]).
Where(cond). Where(cond).
@ -419,7 +420,7 @@ func (issues IssueList) loadComments(e db.Engine, cond builder.Cond) (err error)
return nil return nil
} }
func (issues IssueList) loadTotalTrackedTimes(e db.Engine) (err error) { func (issues IssueList) loadTotalTrackedTimes(ctx context.Context) (err error) {
type totalTimesByIssue struct { type totalTimesByIssue struct {
IssueID int64 IssueID int64
Time int64 Time int64
@ -444,7 +445,7 @@ func (issues IssueList) loadTotalTrackedTimes(e db.Engine) (err error) {
} }
// select issue_id, sum(time) from tracked_time where issue_id in (<issue ids in current page>) group by issue_id // select issue_id, sum(time) from tracked_time where issue_id in (<issue ids in current page>) group by issue_id
rows, err := e.Table("tracked_time"). rows, err := db.GetEngine(ctx).Table("tracked_time").
Where("deleted = ?", false). Where("deleted = ?", false).
Select("issue_id, sum(time) as time"). Select("issue_id, sum(time) as time").
In("issue_id", ids[:limit]). In("issue_id", ids[:limit]).
@ -479,32 +480,32 @@ func (issues IssueList) loadTotalTrackedTimes(e db.Engine) (err error) {
} }
// loadAttributes loads all attributes, expect for attachments and comments // loadAttributes loads all attributes, expect for attachments and comments
func (issues IssueList) loadAttributes(e db.Engine) error { func (issues IssueList) loadAttributes(ctx context.Context) error {
if _, err := issues.loadRepositories(e); err != nil { if _, err := issues.loadRepositories(ctx); err != nil {
return fmt.Errorf("issue.loadAttributes: loadRepositories: %v", err) return fmt.Errorf("issue.loadAttributes: loadRepositories: %v", err)
} }
if err := issues.loadPosters(e); err != nil { if err := issues.loadPosters(ctx); err != nil {
return fmt.Errorf("issue.loadAttributes: loadPosters: %v", err) return fmt.Errorf("issue.loadAttributes: loadPosters: %v", err)
} }
if err := issues.loadLabels(e); err != nil { if err := issues.loadLabels(ctx); err != nil {
return fmt.Errorf("issue.loadAttributes: loadLabels: %v", err) return fmt.Errorf("issue.loadAttributes: loadLabels: %v", err)
} }
if err := issues.loadMilestones(e); err != nil { if err := issues.loadMilestones(ctx); err != nil {
return fmt.Errorf("issue.loadAttributes: loadMilestones: %v", err) return fmt.Errorf("issue.loadAttributes: loadMilestones: %v", err)
} }
if err := issues.loadAssignees(e); err != nil { if err := issues.loadAssignees(ctx); err != nil {
return fmt.Errorf("issue.loadAttributes: loadAssignees: %v", err) return fmt.Errorf("issue.loadAttributes: loadAssignees: %v", err)
} }
if err := issues.loadPullRequests(e); err != nil { if err := issues.loadPullRequests(ctx); err != nil {
return fmt.Errorf("issue.loadAttributes: loadPullRequests: %v", err) return fmt.Errorf("issue.loadAttributes: loadPullRequests: %v", err)
} }
if err := issues.loadTotalTrackedTimes(e); err != nil { if err := issues.loadTotalTrackedTimes(ctx); err != nil {
return fmt.Errorf("issue.loadAttributes: loadTotalTrackedTimes: %v", err) return fmt.Errorf("issue.loadAttributes: loadTotalTrackedTimes: %v", err)
} }
@ -514,42 +515,38 @@ func (issues IssueList) loadAttributes(e db.Engine) error {
// LoadAttributes loads attributes of the issues, except for attachments and // LoadAttributes loads attributes of the issues, except for attachments and
// comments // comments
func (issues IssueList) LoadAttributes() error { func (issues IssueList) LoadAttributes() error {
return issues.loadAttributes(db.GetEngine(db.DefaultContext)) return issues.loadAttributes(db.DefaultContext)
} }
// LoadAttachments loads attachments // LoadAttachments loads attachments
func (issues IssueList) LoadAttachments() error { func (issues IssueList) LoadAttachments() error {
return issues.loadAttachments(db.GetEngine(db.DefaultContext)) return issues.loadAttachments(db.DefaultContext)
} }
// LoadComments loads comments // LoadComments loads comments
func (issues IssueList) LoadComments() error { func (issues IssueList) LoadComments() error {
return issues.loadComments(db.GetEngine(db.DefaultContext), builder.NewCond()) return issues.loadComments(db.DefaultContext, builder.NewCond())
} }
// LoadDiscussComments loads discuss comments // LoadDiscussComments loads discuss comments
func (issues IssueList) LoadDiscussComments() error { func (issues IssueList) LoadDiscussComments() error {
return issues.loadComments(db.GetEngine(db.DefaultContext), builder.Eq{"comment.type": CommentTypeComment}) return issues.loadComments(db.DefaultContext, builder.Eq{"comment.type": CommentTypeComment})
} }
// LoadPullRequests loads pull requests // LoadPullRequests loads pull requests
func (issues IssueList) LoadPullRequests() error { func (issues IssueList) LoadPullRequests() error {
return issues.loadPullRequests(db.GetEngine(db.DefaultContext)) return issues.loadPullRequests(db.DefaultContext)
} }
// GetApprovalCounts returns a map of issue ID to slice of approval counts // 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 // FIXME: only returns official counts due to double counting of non-official approvals
func (issues IssueList) GetApprovalCounts() (map[int64][]*ReviewCount, error) { func (issues IssueList) GetApprovalCounts(ctx context.Context) (map[int64][]*ReviewCount, error) {
return issues.getApprovalCounts(db.GetEngine(db.DefaultContext))
}
func (issues IssueList) getApprovalCounts(e db.Engine) (map[int64][]*ReviewCount, error) {
rCounts := make([]*ReviewCount, 0, 2*len(issues)) rCounts := make([]*ReviewCount, 0, 2*len(issues))
ids := make([]int64, len(issues)) ids := make([]int64, len(issues))
for i, issue := range issues { for i, issue := range issues {
ids[i] = issue.ID ids[i] = issue.ID
} }
sess := e.In("issue_id", ids) sess := db.GetEngine(ctx).In("issue_id", ids)
err := sess.Select("issue_id, type, count(id) as `count`"). err := sess.Select("issue_id, type, count(id) as `count`").
Where("official = ? AND dismissed = ?", true, false). Where("official = ? AND dismissed = ?", true, false).
GroupBy("issue_id, type"). GroupBy("issue_id, type").

@ -15,13 +15,13 @@ import (
// LoadProject load the project the issue was assigned to // LoadProject load the project the issue was assigned to
func (i *Issue) LoadProject() (err error) { func (i *Issue) LoadProject() (err error) {
return i.loadProject(db.GetEngine(db.DefaultContext)) return i.loadProject(db.DefaultContext)
} }
func (i *Issue) loadProject(e db.Engine) (err error) { func (i *Issue) loadProject(ctx context.Context) (err error) {
if i.Project == nil { if i.Project == nil {
var p project_model.Project var p project_model.Project
if _, err = e.Table("project"). if _, err = db.GetEngine(ctx).Table("project").
Join("INNER", "project_issue", "project.id=project_issue.project_id"). Join("INNER", "project_issue", "project.id=project_issue.project_id").
Where("project_issue.issue_id = ?", i.ID). Where("project_issue.issue_id = ?", i.ID).
Get(&p); err != nil { Get(&p); err != nil {
@ -34,12 +34,12 @@ func (i *Issue) loadProject(e db.Engine) (err error) {
// ProjectID return project id if issue was assigned to one // ProjectID return project id if issue was assigned to one
func (i *Issue) ProjectID() int64 { func (i *Issue) ProjectID() int64 {
return i.projectID(db.GetEngine(db.DefaultContext)) return i.projectID(db.DefaultContext)
} }
func (i *Issue) projectID(e db.Engine) int64 { func (i *Issue) projectID(ctx context.Context) int64 {
var ip project_model.ProjectIssue var ip project_model.ProjectIssue
has, err := e.Where("issue_id=?", i.ID).Get(&ip) has, err := db.GetEngine(ctx).Where("issue_id=?", i.ID).Get(&ip)
if err != nil || !has { if err != nil || !has {
return 0 return 0
} }
@ -48,12 +48,12 @@ func (i *Issue) projectID(e db.Engine) int64 {
// ProjectBoardID return project board id if issue was assigned to one // ProjectBoardID return project board id if issue was assigned to one
func (i *Issue) ProjectBoardID() int64 { func (i *Issue) ProjectBoardID() int64 {
return i.projectBoardID(db.GetEngine(db.DefaultContext)) return i.projectBoardID(db.DefaultContext)
} }
func (i *Issue) projectBoardID(e db.Engine) int64 { func (i *Issue) projectBoardID(ctx context.Context) int64 {
var ip project_model.ProjectIssue var ip project_model.ProjectIssue
has, err := e.Where("issue_id=?", i.ID).Get(&ip) has, err := db.GetEngine(ctx).Where("issue_id=?", i.ID).Get(&ip)
if err != nil || !has { if err != nil || !has {
return 0 return 0
} }
@ -122,10 +122,9 @@ func ChangeProjectAssign(issue *Issue, doer *user_model.User, newProjectID int64
} }
func addUpdateIssueProject(ctx context.Context, issue *Issue, doer *user_model.User, newProjectID int64) error { func addUpdateIssueProject(ctx context.Context, issue *Issue, doer *user_model.User, newProjectID int64) error {
e := db.GetEngine(ctx) oldProjectID := issue.projectID(ctx)
oldProjectID := issue.projectID(e)
if _, err := e.Where("project_issue.issue_id=?", issue.ID).Delete(&project_model.ProjectIssue{}); err != nil { if _, err := db.GetEngine(ctx).Where("project_issue.issue_id=?", issue.ID).Delete(&project_model.ProjectIssue{}); err != nil {
return err return err
} }
@ -146,11 +145,10 @@ func addUpdateIssueProject(ctx context.Context, issue *Issue, doer *user_model.U
} }
} }
_, err := e.Insert(&project_model.ProjectIssue{ return db.Insert(ctx, &project_model.ProjectIssue{
IssueID: issue.ID, IssueID: issue.ID,
ProjectID: newProjectID, ProjectID: newProjectID,
}) })
return err
} }
// MoveIssueAcrossProjectBoards move a card from one board to another // MoveIssueAcrossProjectBoards move a card from one board to another

@ -125,13 +125,9 @@ func StopwatchExists(userID, issueID int64) bool {
} }
// HasUserStopwatch returns true if the user has a stopwatch // HasUserStopwatch returns true if the user has a stopwatch
func HasUserStopwatch(userID int64) (exists bool, sw *Stopwatch, err error) { func HasUserStopwatch(ctx context.Context, userID int64) (exists bool, sw *Stopwatch, err error) {
return hasUserStopwatch(db.GetEngine(db.DefaultContext), userID)
}
func hasUserStopwatch(e db.Engine, userID int64) (exists bool, sw *Stopwatch, err error) {
sw = new(Stopwatch) sw = new(Stopwatch)
exists, err = e. exists, err = db.GetEngine(ctx).
Where("user_id = ?", userID). Where("user_id = ?", userID).
Get(sw) Get(sw)
return return
@ -203,24 +199,23 @@ func FinishIssueStopwatch(ctx context.Context, user *user_model.User, issue *Iss
}); err != nil { }); err != nil {
return err return err
} }
_, err = db.GetEngine(ctx).Delete(sw) _, err = db.DeleteByBean(ctx, sw)
return err return err
} }
// CreateIssueStopwatch creates a stopwatch if not exist, otherwise return an error // CreateIssueStopwatch creates a stopwatch if not exist, otherwise return an error
func CreateIssueStopwatch(ctx context.Context, user *user_model.User, issue *Issue) error { func CreateIssueStopwatch(ctx context.Context, user *user_model.User, issue *Issue) error {
e := db.GetEngine(ctx)
if err := issue.LoadRepo(ctx); err != nil { if err := issue.LoadRepo(ctx); err != nil {
return err return err
} }
// if another stopwatch is running: stop it // if another stopwatch is running: stop it
exists, sw, err := hasUserStopwatch(e, user.ID) exists, sw, err := HasUserStopwatch(ctx, user.ID)
if err != nil { if err != nil {
return err return err
} }
if exists { if exists {
issue, err := getIssueByID(e, sw.IssueID) issue, err := getIssueByID(ctx, sw.IssueID)
if err != nil { if err != nil {
return err return err
} }

@ -7,6 +7,7 @@ package models
import ( import (
"testing" "testing"
"code.gitea.io/gitea/models/db"
"code.gitea.io/gitea/models/unittest" "code.gitea.io/gitea/models/unittest"
user_model "code.gitea.io/gitea/models/user" user_model "code.gitea.io/gitea/models/user"
"code.gitea.io/gitea/modules/timeutil" "code.gitea.io/gitea/modules/timeutil"
@ -44,12 +45,12 @@ func TestStopwatchExists(t *testing.T) {
func TestHasUserStopwatch(t *testing.T) { func TestHasUserStopwatch(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase()) assert.NoError(t, unittest.PrepareTestDatabase())
exists, sw, err := HasUserStopwatch(1) exists, sw, err := HasUserStopwatch(db.DefaultContext, 1)
assert.NoError(t, err) assert.NoError(t, err)
assert.True(t, exists) assert.True(t, exists)
assert.Equal(t, int64(1), sw.ID) assert.Equal(t, int64(1), sw.ID)
exists, _, err = HasUserStopwatch(3) exists, _, err = HasUserStopwatch(db.DefaultContext, 3)
assert.NoError(t, err) assert.NoError(t, err)
assert.False(t, exists) assert.False(t, exists)
} }

@ -52,7 +52,7 @@ func TestIssue_ReplaceLabels(t *testing.T) {
func Test_GetIssueIDsByRepoID(t *testing.T) { func Test_GetIssueIDsByRepoID(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase()) assert.NoError(t, unittest.PrepareTestDatabase())
ids, err := GetIssueIDsByRepoID(1) ids, err := GetIssueIDsByRepoID(db.DefaultContext, 1)
assert.NoError(t, err) assert.NoError(t, err)
assert.Len(t, ids, 5) assert.Len(t, ids, 5)
} }
@ -69,7 +69,7 @@ func TestIssueAPIURL(t *testing.T) {
func TestGetIssuesByIDs(t *testing.T) { func TestGetIssuesByIDs(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase()) assert.NoError(t, unittest.PrepareTestDatabase())
testSuccess := func(expectedIssueIDs, nonExistentIssueIDs []int64) { testSuccess := func(expectedIssueIDs, nonExistentIssueIDs []int64) {
issues, err := GetIssuesByIDs(append(expectedIssueIDs, nonExistentIssueIDs...)) issues, err := GetIssuesByIDs(db.DefaultContext, append(expectedIssueIDs, nonExistentIssueIDs...))
assert.NoError(t, err) assert.NoError(t, err)
actualIssueIDs := make([]int64, len(issues)) actualIssueIDs := make([]int64, len(issues))
for i, issue := range issues { for i, issue := range issues {
@ -87,7 +87,7 @@ func TestGetParticipantIDsByIssue(t *testing.T) {
checkParticipants := func(issueID int64, userIDs []int) { checkParticipants := func(issueID int64, userIDs []int) {
issue, err := GetIssueByID(issueID) issue, err := GetIssueByID(issueID)
assert.NoError(t, err) assert.NoError(t, err)
participants, err := issue.getParticipantIDsByIssue(db.GetEngine(db.DefaultContext)) participants, err := issue.getParticipantIDsByIssue(db.DefaultContext)
if assert.NoError(t, err) { if assert.NoError(t, err) {
participantsIDs := make([]int, len(participants)) participantsIDs := make([]int, len(participants))
for i, uid := range participants { for i, uid := range participants {
@ -317,7 +317,7 @@ func TestIssue_loadTotalTimes(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase()) assert.NoError(t, unittest.PrepareTestDatabase())
ms, err := GetIssueByID(2) ms, err := GetIssueByID(2)
assert.NoError(t, err) assert.NoError(t, err)
assert.NoError(t, ms.loadTotalTimes(db.GetEngine(db.DefaultContext))) assert.NoError(t, ms.loadTotalTimes(db.DefaultContext))
assert.Equal(t, int64(3682), ms.TotalTrackedTime) assert.Equal(t, int64(3682), ms.TotalTrackedTime)
} }
@ -419,7 +419,7 @@ func TestIssue_InsertIssue(t *testing.T) {
func TestIssue_DeleteIssue(t *testing.T) { func TestIssue_DeleteIssue(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase()) assert.NoError(t, unittest.PrepareTestDatabase())
issueIDs, err := GetIssueIDsByRepoID(1) issueIDs, err := GetIssueIDsByRepoID(db.DefaultContext, 1)
assert.NoError(t, err) assert.NoError(t, err)
assert.EqualValues(t, 5, len(issueIDs)) assert.EqualValues(t, 5, len(issueIDs))
@ -430,12 +430,12 @@ func TestIssue_DeleteIssue(t *testing.T) {
err = DeleteIssue(issue) err = DeleteIssue(issue)
assert.NoError(t, err) assert.NoError(t, err)
issueIDs, err = GetIssueIDsByRepoID(1) issueIDs, err = GetIssueIDsByRepoID(db.DefaultContext, 1)
assert.NoError(t, err) assert.NoError(t, err)
assert.EqualValues(t, 4, len(issueIDs)) assert.EqualValues(t, 4, len(issueIDs))
// check attachment removal // check attachment removal
attachments, err := repo_model.GetAttachmentsByIssueID(4) attachments, err := repo_model.GetAttachmentsByIssueID(db.DefaultContext, 4)
assert.NoError(t, err) assert.NoError(t, err)
issue, err = GetIssueByID(4) issue, err = GetIssueByID(4)
assert.NoError(t, err) assert.NoError(t, err)
@ -443,7 +443,7 @@ func TestIssue_DeleteIssue(t *testing.T) {
assert.NoError(t, err) assert.NoError(t, err)
assert.EqualValues(t, 2, len(attachments)) assert.EqualValues(t, 2, len(attachments))
for i := range attachments { for i := range attachments {
attachment, err := repo_model.GetAttachmentByUUID(attachments[i].UUID) attachment, err := repo_model.GetAttachmentByUUID(db.DefaultContext, attachments[i].UUID)
assert.Error(t, err) assert.Error(t, err)
assert.True(t, repo_model.IsErrAttachmentNotExist(err)) assert.True(t, repo_model.IsErrAttachmentNotExist(err))
assert.Nil(t, attachment) assert.Nil(t, attachment)

@ -47,9 +47,8 @@ func (t *TrackedTime) LoadAttributes() (err error) {
} }
func (t *TrackedTime) loadAttributes(ctx context.Context) (err error) { func (t *TrackedTime) loadAttributes(ctx context.Context) (err error) {
e := db.GetEngine(ctx)
if t.Issue == nil { if t.Issue == nil {
t.Issue, err = getIssueByID(e, t.IssueID) t.Issue, err = getIssueByID(ctx, t.IssueID)
if err != nil { if err != nil {
return return
} }
@ -59,7 +58,7 @@ func (t *TrackedTime) loadAttributes(ctx context.Context) (err error) {
} }
} }
if t.User == nil { if t.User == nil {
t.User, err = user_model.GetUserByIDEngine(e, t.UserID) t.User, err = user_model.GetUserByIDCtx(ctx, t.UserID)
if err != nil { if err != nil {
return return
} }
@ -128,14 +127,10 @@ func (opts *FindTrackedTimesOptions) toSession(e db.Engine) db.Engine {
return sess return sess
} }
func getTrackedTimes(e db.Engine, options *FindTrackedTimesOptions) (trackedTimes TrackedTimeList, err error) {
err = options.toSession(e).Find(&trackedTimes)
return
}
// GetTrackedTimes returns all tracked times that fit to the given options. // GetTrackedTimes returns all tracked times that fit to the given options.
func GetTrackedTimes(opts *FindTrackedTimesOptions) (TrackedTimeList, error) { func GetTrackedTimes(ctx context.Context, options *FindTrackedTimesOptions) (trackedTimes TrackedTimeList, err error) {
return getTrackedTimes(db.GetEngine(db.DefaultContext), opts) err = options.toSession(db.GetEngine(ctx)).Find(&trackedTimes)
return
} }
// CountTrackedTimes returns count of tracked times that fit to the given options. // CountTrackedTimes returns count of tracked times that fit to the given options.
@ -147,13 +142,9 @@ func CountTrackedTimes(opts *FindTrackedTimesOptions) (int64, error) {
return sess.Count(&TrackedTime{}) return sess.Count(&TrackedTime{})
} }
func getTrackedSeconds(e db.Engine, opts FindTrackedTimesOptions) (trackedSeconds int64, err error) {
return opts.toSession(e).SumInt(&TrackedTime{}, "time")
}
// GetTrackedSeconds return sum of seconds // GetTrackedSeconds return sum of seconds
func GetTrackedSeconds(opts FindTrackedTimesOptions) (int64, error) { func GetTrackedSeconds(ctx context.Context, opts FindTrackedTimesOptions) (trackedSeconds int64, err error) {
return getTrackedSeconds(db.GetEngine(db.DefaultContext), opts) return opts.toSession(db.GetEngine(ctx)).SumInt(&TrackedTime{}, "time")
} }
// AddTime will add the given time (in seconds) to the issue // AddTime will add the given time (in seconds) to the issue
@ -163,9 +154,8 @@ func AddTime(user *user_model.User, issue *Issue, amount int64, created time.Tim
return nil, err return nil, err
} }
defer committer.Close() defer committer.Close()
sess := db.GetEngine(ctx)
t, err := addTime(sess, user, issue, amount, created) t, err := addTime(ctx, user, issue, amount, created)
if err != nil { if err != nil {
return nil, err return nil, err
} }
@ -188,7 +178,7 @@ func AddTime(user *user_model.User, issue *Issue, amount int64, created time.Tim
return t, committer.Commit() return t, committer.Commit()
} }
func addTime(e db.Engine, user *user_model.User, issue *Issue, amount int64, created time.Time) (*TrackedTime, error) { func addTime(ctx context.Context, user *user_model.User, issue *Issue, amount int64, created time.Time) (*TrackedTime, error) {
if created.IsZero() { if created.IsZero() {
created = time.Now() created = time.Now()
} }
@ -198,16 +188,12 @@ func addTime(e db.Engine, user *user_model.User, issue *Issue, amount int64, cre
Time: amount, Time: amount,
Created: created, Created: created,
} }
if _, err := e.Insert(tt); err != nil { return tt, db.Insert(ctx, tt)
return nil, err
}
return tt, nil
} }
// TotalTimes returns the spent time for each user by an issue // TotalTimes returns the spent time for each user by an issue
func TotalTimes(options *FindTrackedTimesOptions) (map[*user_model.User]string, error) { func TotalTimes(options *FindTrackedTimesOptions) (map[*user_model.User]string, error) {
trackedTimes, err := GetTrackedTimes(options) trackedTimes, err := GetTrackedTimes(db.DefaultContext, options)
if err != nil { if err != nil {
return nil, err return nil, err
} }
@ -239,14 +225,13 @@ func DeleteIssueUserTimes(issue *Issue, user *user_model.User) error {
return err return err
} }
defer committer.Close() defer committer.Close()
sess := db.GetEngine(ctx)
opts := FindTrackedTimesOptions{ opts := FindTrackedTimesOptions{
IssueID: issue.ID, IssueID: issue.ID,
UserID: user.ID, UserID: user.ID,
} }
removedTime, err := deleteTimes(sess, opts) removedTime, err := deleteTimes(ctx, opts)
if err != nil { if err != nil {
return err return err
} }
@ -282,7 +267,7 @@ func DeleteTime(t *TrackedTime) error {
return err return err
} }
if err := deleteTime(db.GetEngine(ctx), t); err != nil { if err := deleteTime(ctx, t); err != nil {
return err return err
} }
@ -299,22 +284,22 @@ func DeleteTime(t *TrackedTime) error {
return committer.Commit() return committer.Commit()
} }
func deleteTimes(e db.Engine, opts FindTrackedTimesOptions) (removedTime int64, err error) { func deleteTimes(ctx context.Context, opts FindTrackedTimesOptions) (removedTime int64, err error) {
removedTime, err = getTrackedSeconds(e, opts) removedTime, err = GetTrackedSeconds(ctx, opts)
if err != nil || removedTime == 0 { if err != nil || removedTime == 0 {
return return
} }
_, err = opts.toSession(e).Table("tracked_time").Cols("deleted").Update(&TrackedTime{Deleted: true}) _, err = opts.toSession(db.GetEngine(ctx)).Table("tracked_time").Cols("deleted").Update(&TrackedTime{Deleted: true})
return return
} }
func deleteTime(e db.Engine, t *TrackedTime) error { func deleteTime(ctx context.Context, t *TrackedTime) error {
if t.Deleted { if t.Deleted {
return db.ErrNotExist{ID: t.ID} return db.ErrNotExist{ID: t.ID}
} }
t.Deleted = true t.Deleted = true
_, err := e.ID(t.ID).Cols("deleted").Update(t) _, err := db.GetEngine(ctx).ID(t.ID).Cols("deleted").Update(t)
return err return err
} }

@ -8,6 +8,7 @@ import (
"testing" "testing"
"time" "time"
"code.gitea.io/gitea/models/db"
"code.gitea.io/gitea/models/unittest" "code.gitea.io/gitea/models/unittest"
user_model "code.gitea.io/gitea/models/user" user_model "code.gitea.io/gitea/models/user"
@ -41,27 +42,27 @@ func TestGetTrackedTimes(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase()) assert.NoError(t, unittest.PrepareTestDatabase())
// by Issue // by Issue
times, err := GetTrackedTimes(&FindTrackedTimesOptions{IssueID: 1}) times, err := GetTrackedTimes(db.DefaultContext, &FindTrackedTimesOptions{IssueID: 1})
assert.NoError(t, err) assert.NoError(t, err)
assert.Len(t, times, 1) assert.Len(t, times, 1)
assert.Equal(t, int64(400), times[0].Time) assert.Equal(t, int64(400), times[0].Time)
times, err = GetTrackedTimes(&FindTrackedTimesOptions{IssueID: -1}) times, err = GetTrackedTimes(db.DefaultContext, &FindTrackedTimesOptions{IssueID: -1})
assert.NoError(t, err) assert.NoError(t, err)
assert.Len(t, times, 0) assert.Len(t, times, 0)
// by User // by User
times, err = GetTrackedTimes(&FindTrackedTimesOptions{UserID: 1}) times, err = GetTrackedTimes(db.DefaultContext, &FindTrackedTimesOptions{UserID: 1})
assert.NoError(t, err) assert.NoError(t, err)
assert.Len(t, times, 3) assert.Len(t, times, 3)
assert.Equal(t, int64(400), times[0].Time) assert.Equal(t, int64(400), times[0].Time)
times, err = GetTrackedTimes(&FindTrackedTimesOptions{UserID: 3}) times, err = GetTrackedTimes(db.DefaultContext, &FindTrackedTimesOptions{UserID: 3})
assert.NoError(t, err) assert.NoError(t, err)
assert.Len(t, times, 0) assert.Len(t, times, 0)
// by Repo // by Repo
times, err = GetTrackedTimes(&FindTrackedTimesOptions{RepositoryID: 2}) times, err = GetTrackedTimes(db.DefaultContext, &FindTrackedTimesOptions{RepositoryID: 2})
assert.NoError(t, err) assert.NoError(t, err)
assert.Len(t, times, 3) assert.Len(t, times, 3)
assert.Equal(t, int64(1), times[0].Time) assert.Equal(t, int64(1), times[0].Time)
@ -69,11 +70,11 @@ func TestGetTrackedTimes(t *testing.T) {
assert.NoError(t, err) assert.NoError(t, err)
assert.Equal(t, issue.RepoID, int64(2)) assert.Equal(t, issue.RepoID, int64(2))
times, err = GetTrackedTimes(&FindTrackedTimesOptions{RepositoryID: 1}) times, err = GetTrackedTimes(db.DefaultContext, &FindTrackedTimesOptions{RepositoryID: 1})
assert.NoError(t, err) assert.NoError(t, err)
assert.Len(t, times, 5) assert.Len(t, times, 5)
times, err = GetTrackedTimes(&FindTrackedTimesOptions{RepositoryID: 10}) times, err = GetTrackedTimes(db.DefaultContext, &FindTrackedTimesOptions{RepositoryID: 10})
assert.NoError(t, err) assert.NoError(t, err)
assert.Len(t, times, 0) assert.Len(t, times, 0)
} }

@ -5,6 +5,8 @@
package models package models
import ( import (
"context"
"code.gitea.io/gitea/models/db" "code.gitea.io/gitea/models/db"
repo_model "code.gitea.io/gitea/models/repo" repo_model "code.gitea.io/gitea/models/repo"
user_model "code.gitea.io/gitea/models/user" user_model "code.gitea.io/gitea/models/user"
@ -30,7 +32,7 @@ type IssueWatchList []*IssueWatch
// CreateOrUpdateIssueWatch set watching for a user and issue // CreateOrUpdateIssueWatch set watching for a user and issue
func CreateOrUpdateIssueWatch(userID, issueID int64, isWatching bool) error { func CreateOrUpdateIssueWatch(userID, issueID int64, isWatching bool) error {
iw, exists, err := getIssueWatch(db.GetEngine(db.DefaultContext), userID, issueID) iw, exists, err := GetIssueWatch(db.DefaultContext, userID, issueID)
if err != nil { if err != nil {
return err return err
} }
@ -57,14 +59,9 @@ func CreateOrUpdateIssueWatch(userID, issueID int64, isWatching bool) error {
// GetIssueWatch returns all IssueWatch objects from db by user and issue // GetIssueWatch returns all IssueWatch objects from db by user and issue
// the current Web-UI need iw object for watchers AND explicit non-watchers // the current Web-UI need iw object for watchers AND explicit non-watchers
func GetIssueWatch(userID, issueID int64) (iw *IssueWatch, exists bool, err error) { func GetIssueWatch(ctx context.Context, userID, issueID int64) (iw *IssueWatch, exists bool, err error) {
return getIssueWatch(db.GetEngine(db.DefaultContext), userID, issueID)
}
// Return watcher AND explicit non-watcher if entry in db exist
func getIssueWatch(e db.Engine, userID, issueID int64) (iw *IssueWatch, exists bool, err error) {
iw = new(IssueWatch) iw = new(IssueWatch)
exists, err = e. exists, err = db.GetEngine(ctx).
Where("user_id = ?", userID). Where("user_id = ?", userID).
And("issue_id = ?", issueID). And("issue_id = ?", issueID).
Get(iw) Get(iw)
@ -74,7 +71,7 @@ func getIssueWatch(e db.Engine, userID, issueID int64) (iw *IssueWatch, exists b
// CheckIssueWatch check if an user is watching an issue // CheckIssueWatch check if an user is watching an issue
// it takes participants and repo watch into account // it takes participants and repo watch into account
func CheckIssueWatch(user *user_model.User, issue *Issue) (bool, error) { func CheckIssueWatch(user *user_model.User, issue *Issue) (bool, error) {
iw, exist, err := getIssueWatch(db.GetEngine(db.DefaultContext), user.ID, issue.ID) iw, exist, err := GetIssueWatch(db.DefaultContext, user.ID, issue.ID)
if err != nil { if err != nil {
return false, err return false, err
} }
@ -91,13 +88,9 @@ func CheckIssueWatch(user *user_model.User, issue *Issue) (bool, error) {
// GetIssueWatchersIDs returns IDs of subscribers or explicit unsubscribers to a given issue id // GetIssueWatchersIDs returns IDs of subscribers or explicit unsubscribers to a given issue id
// but avoids joining with `user` for performance reasons // but avoids joining with `user` for performance reasons
// User permissions must be verified elsewhere if required // User permissions must be verified elsewhere if required
func GetIssueWatchersIDs(issueID int64, watching bool) ([]int64, error) { func GetIssueWatchersIDs(ctx context.Context, issueID int64, watching bool) ([]int64, error) {
return getIssueWatchersIDs(db.GetEngine(db.DefaultContext), issueID, watching)
}
func getIssueWatchersIDs(e db.Engine, issueID int64, watching bool) ([]int64, error) {
ids := make([]int64, 0, 64) ids := make([]int64, 0, 64)
return ids, e.Table("issue_watch"). return ids, db.GetEngine(ctx).Table("issue_watch").
Where("issue_id=?", issueID). Where("issue_id=?", issueID).
And("is_watching = ?", watching). And("is_watching = ?", watching).
Select("user_id"). Select("user_id").
@ -105,12 +98,8 @@ func getIssueWatchersIDs(e db.Engine, issueID int64, watching bool) ([]int64, er
} }
// GetIssueWatchers returns watchers/unwatchers of a given issue // GetIssueWatchers returns watchers/unwatchers of a given issue
func GetIssueWatchers(issueID int64, listOptions db.ListOptions) (IssueWatchList, error) { func GetIssueWatchers(ctx context.Context, issueID int64, listOptions db.ListOptions) (IssueWatchList, error) {
return getIssueWatchers(db.GetEngine(db.DefaultContext), issueID, listOptions) sess := db.GetEngine(ctx).
}
func getIssueWatchers(e db.Engine, issueID int64, listOptions db.ListOptions) (IssueWatchList, error) {
sess := e.
Where("`issue_watch`.issue_id = ?", issueID). Where("`issue_watch`.issue_id = ?", issueID).
And("`issue_watch`.is_watching = ?", true). And("`issue_watch`.is_watching = ?", true).
And("`user`.is_active = ?", true). And("`user`.is_active = ?", true).
@ -127,12 +116,8 @@ func getIssueWatchers(e db.Engine, issueID int64, listOptions db.ListOptions) (I
} }
// CountIssueWatchers count watchers/unwatchers of a given issue // CountIssueWatchers count watchers/unwatchers of a given issue
func CountIssueWatchers(issueID int64) (int64, error) { func CountIssueWatchers(ctx context.Context, issueID int64) (int64, error) {
return countIssueWatchers(db.GetEngine(db.DefaultContext), issueID) return db.GetEngine(ctx).
}
func countIssueWatchers(e db.Engine, issueID int64) (int64, error) {
return e.
Where("`issue_watch`.issue_id = ?", issueID). Where("`issue_watch`.issue_id = ?", issueID).
And("`issue_watch`.is_watching = ?", true). And("`issue_watch`.is_watching = ?", true).
And("`user`.is_active = ?", true). And("`user`.is_active = ?", true).
@ -140,8 +125,8 @@ func countIssueWatchers(e db.Engine, issueID int64) (int64, error) {
Join("INNER", "`user`", "`user`.id = `issue_watch`.user_id").Count(new(IssueWatch)) Join("INNER", "`user`", "`user`.id = `issue_watch`.user_id").Count(new(IssueWatch))
} }
func removeIssueWatchersByRepoID(e db.Engine, userID, repoID int64) error { func removeIssueWatchersByRepoID(ctx context.Context, userID, repoID int64) error {
_, err := e. _, err := db.GetEngine(ctx).
Join("INNER", "issue", "`issue`.id = `issue_watch`.issue_id AND `issue`.repo_id = ?", repoID). Join("INNER", "issue", "`issue`.id = `issue_watch`.issue_id AND `issue`.repo_id = ?", repoID).
Where("`issue_watch`.user_id = ?", userID). Where("`issue_watch`.user_id = ?", userID).
Delete(new(IssueWatch)) Delete(new(IssueWatch))

@ -28,16 +28,16 @@ func TestCreateOrUpdateIssueWatch(t *testing.T) {
func TestGetIssueWatch(t *testing.T) { func TestGetIssueWatch(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase()) assert.NoError(t, unittest.PrepareTestDatabase())
_, exists, err := GetIssueWatch(9, 1) _, exists, err := GetIssueWatch(db.DefaultContext, 9, 1)
assert.True(t, exists) assert.True(t, exists)
assert.NoError(t, err) assert.NoError(t, err)
iw, exists, err := GetIssueWatch(2, 2) iw, exists, err := GetIssueWatch(db.DefaultContext, 2, 2)
assert.True(t, exists) assert.True(t, exists)
assert.NoError(t, err) assert.NoError(t, err)
assert.False(t, iw.IsWatching) assert.False(t, iw.IsWatching)
_, exists, err = GetIssueWatch(3, 1) _, exists, err = GetIssueWatch(db.DefaultContext, 3, 1)
assert.False(t, exists) assert.False(t, exists)
assert.NoError(t, err) assert.NoError(t, err)
} }
@ -45,22 +45,22 @@ func TestGetIssueWatch(t *testing.T) {
func TestGetIssueWatchers(t *testing.T) { func TestGetIssueWatchers(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase()) assert.NoError(t, unittest.PrepareTestDatabase())
iws, err := GetIssueWatchers(1, db.ListOptions{}) iws, err := GetIssueWatchers(db.DefaultContext, 1, db.ListOptions{})
assert.NoError(t, err) assert.NoError(t, err)
// Watcher is inactive, thus 0 // Watcher is inactive, thus 0
assert.Len(t, iws, 0) assert.Len(t, iws, 0)
iws, err = GetIssueWatchers(2, db.ListOptions{}) iws, err = GetIssueWatchers(db.DefaultContext, 2, db.ListOptions{})
assert.NoError(t, err) assert.NoError(t, err)
// Watcher is explicit not watching // Watcher is explicit not watching
assert.Len(t, iws, 0) assert.Len(t, iws, 0)
iws, err = GetIssueWatchers(5, db.ListOptions{}) iws, err = GetIssueWatchers(db.DefaultContext, 5, db.ListOptions{})
assert.NoError(t, err) assert.NoError(t, err)
// Issue has no Watchers // Issue has no Watchers
assert.Len(t, iws, 0) assert.Len(t, iws, 0)
iws, err = GetIssueWatchers(7, db.ListOptions{}) iws, err = GetIssueWatchers(db.DefaultContext, 7, db.ListOptions{})
assert.NoError(t, err) assert.NoError(t, err)
// Issue has one watcher // Issue has one watcher
assert.Len(t, iws, 1) assert.Len(t, iws, 1)

@ -30,16 +30,16 @@ type crossReferencesContext struct {
RemoveOld bool RemoveOld bool
} }
func findOldCrossReferences(e db.Engine, issueID, commentID int64) ([]*Comment, error) { func findOldCrossReferences(ctx context.Context, issueID, commentID int64) ([]*Comment, error) {
active := make([]*Comment, 0, 10) active := make([]*Comment, 0, 10)
return active, e.Where("`ref_action` IN (?, ?, ?)", references.XRefActionNone, references.XRefActionCloses, references.XRefActionReopens). return active, db.GetEngine(ctx).Where("`ref_action` IN (?, ?, ?)", references.XRefActionNone, references.XRefActionCloses, references.XRefActionReopens).
And("`ref_issue_id` = ?", issueID). And("`ref_issue_id` = ?", issueID).
And("`ref_comment_id` = ?", commentID). And("`ref_comment_id` = ?", commentID).
Find(&active) Find(&active)
} }
func neuterCrossReferences(e db.Engine, issueID, commentID int64) error { func neuterCrossReferences(ctx context.Context, issueID, commentID int64) error {
active, err := findOldCrossReferences(e, issueID, commentID) active, err := findOldCrossReferences(ctx, issueID, commentID)
if err != nil { if err != nil {
return err return err
} }
@ -47,11 +47,11 @@ func neuterCrossReferences(e db.Engine, issueID, commentID int64) error {
for i, c := range active { for i, c := range active {
ids[i] = c.ID ids[i] = c.ID
} }
return neuterCrossReferencesIds(e, ids) return neuterCrossReferencesIds(ctx, ids)
} }
func neuterCrossReferencesIds(e db.Engine, ids []int64) error { func neuterCrossReferencesIds(ctx context.Context, ids []int64) error {
_, err := e.In("id", ids).Cols("`ref_action`").Update(&Comment{RefAction: references.XRefActionNeutered}) _, err := db.GetEngine(ctx).In("id", ids).Cols("`ref_action`").Update(&Comment{RefAction: references.XRefActionNeutered})
return err return err
} }
@ -80,7 +80,6 @@ func (issue *Issue) addCrossReferences(stdCtx context.Context, doer *user_model.
} }
func (issue *Issue) createCrossReferences(stdCtx context.Context, ctx *crossReferencesContext, plaincontent, mdcontent string) error { func (issue *Issue) createCrossReferences(stdCtx context.Context, ctx *crossReferencesContext, plaincontent, mdcontent string) error {
e := db.GetEngine(stdCtx)
xreflist, err := ctx.OrigIssue.getCrossReferences(stdCtx, ctx, plaincontent, mdcontent) xreflist, err := ctx.OrigIssue.getCrossReferences(stdCtx, ctx, plaincontent, mdcontent)
if err != nil { if err != nil {
return err return err
@ -90,7 +89,7 @@ func (issue *Issue) createCrossReferences(stdCtx context.Context, ctx *crossRefe
if ctx.OrigComment != nil { if ctx.OrigComment != nil {
commentID = ctx.OrigComment.ID commentID = ctx.OrigComment.ID
} }
active, err := findOldCrossReferences(e, ctx.OrigIssue.ID, commentID) active, err := findOldCrossReferences(stdCtx, ctx.OrigIssue.ID, commentID)
if err != nil { if err != nil {
return err return err
} }
@ -109,7 +108,7 @@ func (issue *Issue) createCrossReferences(stdCtx context.Context, ctx *crossRefe
} }
} }
if len(ids) > 0 { if len(ids) > 0 {
if err = neuterCrossReferencesIds(e, ids); err != nil { if err = neuterCrossReferencesIds(stdCtx, ids); err != nil {
return err return err
} }
} }
@ -263,8 +262,8 @@ func (comment *Comment) addCrossReferences(stdCtx context.Context, doer *user_mo
return comment.Issue.createCrossReferences(stdCtx, ctx, "", comment.Content) return comment.Issue.createCrossReferences(stdCtx, ctx, "", comment.Content)
} }
func (comment *Comment) neuterCrossReferences(e db.Engine) error { func (comment *Comment) neuterCrossReferences(ctx context.Context) error {
return neuterCrossReferences(e, comment.IssueID, comment.ID) return neuterCrossReferences(ctx, comment.IssueID, comment.ID)
} }
// LoadRefComment loads comment that created this reference from database // LoadRefComment loads comment that created this reference from database
@ -272,7 +271,7 @@ func (comment *Comment) LoadRefComment() (err error) {
if comment.RefComment != nil { if comment.RefComment != nil {
return nil return nil
} }
comment.RefComment, err = GetCommentByID(comment.RefCommentID) comment.RefComment, err = GetCommentByID(db.DefaultContext, comment.RefCommentID)
return return
} }

@ -150,7 +150,7 @@ func testCreateIssue(t *testing.T, repo, doer int64, title, content string, ispu
Issue: i, Issue: i,
}) })
assert.NoError(t, err) assert.NoError(t, err)
i, err = getIssueByID(db.GetEngine(ctx), i.ID) i, err = getIssueByID(ctx, i.ID)
assert.NoError(t, err) assert.NoError(t, err)
assert.NoError(t, i.addCrossReferences(ctx, d, false)) assert.NoError(t, i.addCrossReferences(ctx, d, false))
assert.NoError(t, committer.Commit()) assert.NoError(t, committer.Commit())

@ -38,7 +38,7 @@ func init() {
} }
// SaveIssueContentHistory save history // SaveIssueContentHistory save history
func SaveIssueContentHistory(e db.Engine, posterID, issueID, commentID int64, editTime timeutil.TimeStamp, contentText string, isFirstCreated bool) error { func SaveIssueContentHistory(ctx context.Context, posterID, issueID, commentID int64, editTime timeutil.TimeStamp, contentText string, isFirstCreated bool) error {
ch := &ContentHistory{ ch := &ContentHistory{
PosterID: posterID, PosterID: posterID,
IssueID: issueID, IssueID: issueID,
@ -47,27 +47,26 @@ func SaveIssueContentHistory(e db.Engine, posterID, issueID, commentID int64, ed
EditedUnix: editTime, EditedUnix: editTime,
IsFirstCreated: isFirstCreated, IsFirstCreated: isFirstCreated,
} }
_, err := e.Insert(ch) if err := db.Insert(ctx, ch); err != nil {
if err != nil {
log.Error("can not save issue content history. err=%v", err) log.Error("can not save issue content history. err=%v", err)
return err return err
} }
// We only keep at most 20 history revisions now. It is enough in most cases. // We only keep at most 20 history revisions now. It is enough in most cases.
// If there is a special requirement to keep more, we can consider introducing a new setting option then, but not now. // If there is a special requirement to keep more, we can consider introducing a new setting option then, but not now.
keepLimitedContentHistory(e, issueID, commentID, 20) keepLimitedContentHistory(ctx, issueID, commentID, 20)
return nil return nil
} }
// keepLimitedContentHistory keeps at most `limit` history revisions, it will hard delete out-dated revisions, sorting by revision interval // keepLimitedContentHistory keeps at most `limit` history revisions, it will hard delete out-dated revisions, sorting by revision interval
// we can ignore all errors in this function, so we just log them // we can ignore all errors in this function, so we just log them
func keepLimitedContentHistory(e db.Engine, issueID, commentID int64, limit int) { func keepLimitedContentHistory(ctx context.Context, issueID, commentID int64, limit int) {
type IDEditTime struct { type IDEditTime struct {
ID int64 ID int64
EditedUnix timeutil.TimeStamp EditedUnix timeutil.TimeStamp
} }
var res []*IDEditTime var res []*IDEditTime
err := e.Select("id, edited_unix").Table("issue_content_history"). err := db.GetEngine(ctx).Select("id, edited_unix").Table("issue_content_history").
Where(builder.Eq{"issue_id": issueID, "comment_id": commentID}). Where(builder.Eq{"issue_id": issueID, "comment_id": commentID}).
OrderBy("edited_unix ASC"). OrderBy("edited_unix ASC").
Find(&res) Find(&res)
@ -96,7 +95,7 @@ func keepLimitedContentHistory(e db.Engine, issueID, commentID int64, limit int)
} }
// hard delete the found one // hard delete the found one
_, err = e.Delete(&ContentHistory{ID: res[indexToDelete].ID}) _, err = db.GetEngine(ctx).Delete(&ContentHistory{ID: res[indexToDelete].ID})
if err != nil { if err != nil {
log.Error("can not delete out-dated content history, err=%v", err) log.Error("can not delete out-dated content history, err=%v", err)
break break

@ -18,18 +18,17 @@ func TestContentHistory(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase()) assert.NoError(t, unittest.PrepareTestDatabase())
dbCtx := db.DefaultContext dbCtx := db.DefaultContext
dbEngine := db.GetEngine(dbCtx)
timeStampNow := timeutil.TimeStampNow() timeStampNow := timeutil.TimeStampNow()
_ = SaveIssueContentHistory(dbEngine, 1, 10, 0, timeStampNow, "i-a", true) _ = SaveIssueContentHistory(dbCtx, 1, 10, 0, timeStampNow, "i-a", true)
_ = SaveIssueContentHistory(dbEngine, 1, 10, 0, timeStampNow.Add(2), "i-b", false) _ = SaveIssueContentHistory(dbCtx, 1, 10, 0, timeStampNow.Add(2), "i-b", false)
_ = SaveIssueContentHistory(dbEngine, 1, 10, 0, timeStampNow.Add(7), "i-c", false) _ = SaveIssueContentHistory(dbCtx, 1, 10, 0, timeStampNow.Add(7), "i-c", false)
_ = SaveIssueContentHistory(dbEngine, 1, 10, 100, timeStampNow, "c-a", true) _ = SaveIssueContentHistory(dbCtx, 1, 10, 100, timeStampNow, "c-a", true)
_ = SaveIssueContentHistory(dbEngine, 1, 10, 100, timeStampNow.Add(5), "c-b", false) _ = SaveIssueContentHistory(dbCtx, 1, 10, 100, timeStampNow.Add(5), "c-b", false)
_ = SaveIssueContentHistory(dbEngine, 1, 10, 100, timeStampNow.Add(20), "c-c", false) _ = SaveIssueContentHistory(dbCtx, 1, 10, 100, timeStampNow.Add(20), "c-c", false)
_ = SaveIssueContentHistory(dbEngine, 1, 10, 100, timeStampNow.Add(50), "c-d", false) _ = SaveIssueContentHistory(dbCtx, 1, 10, 100, timeStampNow.Add(50), "c-d", false)
_ = SaveIssueContentHistory(dbEngine, 1, 10, 100, timeStampNow.Add(51), "c-e", false) _ = SaveIssueContentHistory(dbCtx, 1, 10, 100, timeStampNow.Add(51), "c-e", false)
h1, _ := GetIssueContentHistoryByID(dbCtx, 1) h1, _ := GetIssueContentHistoryByID(dbCtx, 1)
assert.EqualValues(t, 1, h1.ID) assert.EqualValues(t, 1, h1.ID)
@ -47,7 +46,7 @@ func TestContentHistory(t *testing.T) {
Name string Name string
FullName string FullName string
} }
_ = dbEngine.Sync2(&User{}) _ = db.GetEngine(dbCtx).Sync2(&User{})
list1, _ := FetchIssueContentHistoryList(dbCtx, 10, 0) list1, _ := FetchIssueContentHistoryList(dbCtx, 10, 0)
assert.Len(t, list1, 3) assert.Len(t, list1, 3)
@ -70,7 +69,7 @@ func TestContentHistory(t *testing.T) {
assert.EqualValues(t, 4, h6Prev.ID) assert.EqualValues(t, 4, h6Prev.ID)
// only keep 3 history revisions for comment_id=100, the first and the last should never be deleted // only keep 3 history revisions for comment_id=100, the first and the last should never be deleted
keepLimitedContentHistory(dbEngine, 10, 100, 3) keepLimitedContentHistory(dbCtx, 10, 100, 3)
list1, _ = FetchIssueContentHistoryList(dbCtx, 10, 0) list1, _ = FetchIssueContentHistoryList(dbCtx, 10, 0)
assert.Len(t, list1, 3) assert.Len(t, list1, 3)
list2, _ = FetchIssueContentHistoryList(dbCtx, 10, 100) list2, _ = FetchIssueContentHistoryList(dbCtx, 10, 100)

@ -292,11 +292,11 @@ func DeleteMilestoneByRepoID(repoID, id int64) error {
return err return err
} }
numMilestones, err := countRepoMilestones(sess, repo.ID) numMilestones, err := countRepoMilestones(ctx, repo.ID)
if err != nil { if err != nil {
return err return err
} }
numClosedMilestones, err := countRepoClosedMilestones(sess, repo.ID) numClosedMilestones, err := countRepoClosedMilestones(ctx, repo.ID)
if err != nil { if err != nil {
return err return err
} }
@ -503,21 +503,21 @@ func GetMilestonesStatsByRepoCondAndKw(repoCond builder.Cond, keyword string) (*
return stats, nil return stats, nil
} }
func countRepoMilestones(e db.Engine, repoID int64) (int64, error) { func countRepoMilestones(ctx context.Context, repoID int64) (int64, error) {
return e. return db.GetEngine(ctx).
Where("repo_id=?", repoID). Where("repo_id=?", repoID).
Count(new(Milestone)) Count(new(Milestone))
} }
func countRepoClosedMilestones(e db.Engine, repoID int64) (int64, error) { func countRepoClosedMilestones(ctx context.Context, repoID int64) (int64, error) {
return e. return db.GetEngine(ctx).
Where("repo_id=? AND is_closed=?", repoID, true). Where("repo_id=? AND is_closed=?", repoID, true).
Count(new(Milestone)) Count(new(Milestone))
} }
// CountRepoClosedMilestones returns number of closed milestones in given repository. // CountRepoClosedMilestones returns number of closed milestones in given repository.
func CountRepoClosedMilestones(repoID int64) (int64, error) { func CountRepoClosedMilestones(repoID int64) (int64, error) {
return countRepoClosedMilestones(db.GetEngine(db.DefaultContext), repoID) return countRepoClosedMilestones(db.DefaultContext, repoID)
} }
// CountMilestonesByRepoCond map from repo conditions to number of milestones matching the options` // CountMilestonesByRepoCond map from repo conditions to number of milestones matching the options`
@ -590,7 +590,7 @@ func updateRepoMilestoneNum(ctx context.Context, repoID int64) error {
// |_||_| \__,_|\___|_|\_\___|\__,_| |_| |_|_| |_| |_|\___||___/ // |_||_| \__,_|\___|_|\_\___|\__,_| |_| |_|_| |_| |_|\___||___/
// //
func (milestones MilestoneList) loadTotalTrackedTimes(e db.Engine) error { func (milestones MilestoneList) loadTotalTrackedTimes(ctx context.Context) error {
type totalTimesByMilestone struct { type totalTimesByMilestone struct {
MilestoneID int64 MilestoneID int64
Time int64 Time int64
@ -601,7 +601,7 @@ func (milestones MilestoneList) loadTotalTrackedTimes(e db.Engine) error {
trackedTimes := make(map[int64]int64, len(milestones)) trackedTimes := make(map[int64]int64, len(milestones))
// Get total tracked time by milestone_id // Get total tracked time by milestone_id
rows, err := e.Table("issue"). rows, err := db.GetEngine(ctx).Table("issue").
Join("INNER", "milestone", "issue.milestone_id = milestone.id"). Join("INNER", "milestone", "issue.milestone_id = milestone.id").
Join("LEFT", "tracked_time", "tracked_time.issue_id = issue.id"). Join("LEFT", "tracked_time", "tracked_time.issue_id = issue.id").
Where("tracked_time.deleted = ?", false). Where("tracked_time.deleted = ?", false).
@ -630,13 +630,13 @@ func (milestones MilestoneList) loadTotalTrackedTimes(e db.Engine) error {
return nil return nil
} }
func (m *Milestone) loadTotalTrackedTime(e db.Engine) error { func (m *Milestone) loadTotalTrackedTime(ctx context.Context) error {
type totalTimesByMilestone struct { type totalTimesByMilestone struct {
MilestoneID int64 MilestoneID int64
Time int64 Time int64
} }
totalTime := &totalTimesByMilestone{MilestoneID: m.ID} totalTime := &totalTimesByMilestone{MilestoneID: m.ID}
has, err := e.Table("issue"). has, err := db.GetEngine(ctx).Table("issue").
Join("INNER", "milestone", "issue.milestone_id = milestone.id"). Join("INNER", "milestone", "issue.milestone_id = milestone.id").
Join("LEFT", "tracked_time", "tracked_time.issue_id = issue.id"). Join("LEFT", "tracked_time", "tracked_time.issue_id = issue.id").
Where("tracked_time.deleted = ?", false). Where("tracked_time.deleted = ?", false).
@ -655,10 +655,10 @@ func (m *Milestone) loadTotalTrackedTime(e db.Engine) error {
// LoadTotalTrackedTimes loads for every milestone in the list the TotalTrackedTime by a batch request // LoadTotalTrackedTimes loads for every milestone in the list the TotalTrackedTime by a batch request
func (milestones MilestoneList) LoadTotalTrackedTimes() error { func (milestones MilestoneList) LoadTotalTrackedTimes() error {
return milestones.loadTotalTrackedTimes(db.GetEngine(db.DefaultContext)) return milestones.loadTotalTrackedTimes(db.DefaultContext)
} }
// LoadTotalTrackedTime loads the tracked time for the milestone // LoadTotalTrackedTime loads the tracked time for the milestone
func (m *Milestone) LoadTotalTrackedTime() error { func (m *Milestone) LoadTotalTrackedTime() error {
return m.loadTotalTrackedTime(db.GetEngine(db.DefaultContext)) return m.loadTotalTrackedTime(db.DefaultContext)
} }

@ -149,7 +149,7 @@ func TestCountRepoMilestones(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase()) assert.NoError(t, unittest.PrepareTestDatabase())
test := func(repoID int64) { test := func(repoID int64) {
repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: repoID}).(*repo_model.Repository) repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: repoID}).(*repo_model.Repository)
count, err := countRepoMilestones(db.GetEngine(db.DefaultContext), repoID) count, err := countRepoMilestones(db.DefaultContext, repoID)
assert.NoError(t, err) assert.NoError(t, err)
assert.EqualValues(t, repo.NumMilestones, count) assert.EqualValues(t, repo.NumMilestones, count)
} }
@ -157,7 +157,7 @@ func TestCountRepoMilestones(t *testing.T) {
test(2) test(2)
test(3) test(3)
count, err := countRepoMilestones(db.GetEngine(db.DefaultContext), unittest.NonexistentID) count, err := countRepoMilestones(db.DefaultContext, unittest.NonexistentID)
assert.NoError(t, err) assert.NoError(t, err)
assert.EqualValues(t, 0, count) assert.EqualValues(t, 0, count)
} }

@ -119,22 +119,18 @@ func (opts *FindNotificationOptions) ToCond() builder.Cond {
} }
// ToSession will convert the given options to a xorm Session by using the conditions from ToCond and joining with issue table if required // ToSession will convert the given options to a xorm Session by using the conditions from ToCond and joining with issue table if required
func (opts *FindNotificationOptions) ToSession(e db.Engine) *xorm.Session { func (opts *FindNotificationOptions) ToSession(ctx context.Context) *xorm.Session {
sess := e.Where(opts.ToCond()) sess := db.GetEngine(ctx).Where(opts.ToCond())
if opts.Page != 0 { if opts.Page != 0 {
sess = db.SetSessionPagination(sess, opts) sess = db.SetSessionPagination(sess, opts)
} }
return sess return sess
} }
func getNotifications(e db.Engine, options *FindNotificationOptions) (nl NotificationList, err error) {
err = options.ToSession(e).OrderBy("notification.updated_unix DESC").Find(&nl)
return
}
// GetNotifications returns all notifications that fit to the given options. // GetNotifications returns all notifications that fit to the given options.
func GetNotifications(opts *FindNotificationOptions) (NotificationList, error) { func GetNotifications(ctx context.Context, options *FindNotificationOptions) (nl NotificationList, err error) {
return getNotifications(db.GetEngine(db.DefaultContext), opts) err = options.ToSession(ctx).OrderBy("notification.updated_unix DESC").Find(&nl)
return
} }
// CountNotifications count all notifications that fit to the given options and ignore pagination. // CountNotifications count all notifications that fit to the given options and ignore pagination.
@ -201,15 +197,14 @@ func CreateOrUpdateIssueNotifications(issueID, commentID, notificationAuthorID,
} }
func createOrUpdateIssueNotifications(ctx context.Context, issueID, commentID, notificationAuthorID, receiverID int64) error { func createOrUpdateIssueNotifications(ctx context.Context, issueID, commentID, notificationAuthorID, receiverID int64) error {
e := db.GetEngine(ctx)
// init // init
var toNotify map[int64]struct{} var toNotify map[int64]struct{}
notifications, err := getNotificationsByIssueID(e, issueID) notifications, err := getNotificationsByIssueID(ctx, issueID)
if err != nil { if err != nil {
return err return err
} }
issue, err := getIssueByID(e, issueID) issue, err := getIssueByID(ctx, issueID)
if err != nil { if err != nil {
return err return err
} }
@ -219,7 +214,7 @@ func createOrUpdateIssueNotifications(ctx context.Context, issueID, commentID, n
toNotify[receiverID] = struct{}{} toNotify[receiverID] = struct{}{}
} else { } else {
toNotify = make(map[int64]struct{}, 32) toNotify = make(map[int64]struct{}, 32)
issueWatches, err := getIssueWatchersIDs(e, issueID, true) issueWatches, err := GetIssueWatchersIDs(ctx, issueID, true)
if err != nil { if err != nil {
return err return err
} }
@ -235,7 +230,7 @@ func createOrUpdateIssueNotifications(ctx context.Context, issueID, commentID, n
toNotify[id] = struct{}{} toNotify[id] = struct{}{}
} }
} }
issueParticipants, err := issue.getParticipantIDsByIssue(e) issueParticipants, err := issue.getParticipantIDsByIssue(ctx)
if err != nil { if err != nil {
return err return err
} }
@ -246,7 +241,7 @@ func createOrUpdateIssueNotifications(ctx context.Context, issueID, commentID, n
// dont notify user who cause notification // dont notify user who cause notification
delete(toNotify, notificationAuthorID) delete(toNotify, notificationAuthorID)
// explicit unwatch on issue // explicit unwatch on issue
issueUnWatches, err := getIssueWatchersIDs(e, issueID, false) issueUnWatches, err := GetIssueWatchersIDs(ctx, issueID, false)
if err != nil { if err != nil {
return err return err
} }
@ -263,7 +258,7 @@ func createOrUpdateIssueNotifications(ctx context.Context, issueID, commentID, n
// notify // notify
for userID := range toNotify { for userID := range toNotify {
issue.Repo.Units = nil issue.Repo.Units = nil
user, err := user_model.GetUserByIDEngine(e, userID) user, err := user_model.GetUserByIDCtx(ctx, userID)
if err != nil { if err != nil {
if user_model.IsErrUserNotExist(err) { if user_model.IsErrUserNotExist(err) {
continue continue
@ -279,20 +274,20 @@ func createOrUpdateIssueNotifications(ctx context.Context, issueID, commentID, n
} }
if notificationExists(notifications, issue.ID, userID) { if notificationExists(notifications, issue.ID, userID) {
if err = updateIssueNotification(e, userID, issue.ID, commentID, notificationAuthorID); err != nil { if err = updateIssueNotification(ctx, userID, issue.ID, commentID, notificationAuthorID); err != nil {
return err return err
} }
continue continue
} }
if err = createIssueNotification(e, userID, issue, commentID, notificationAuthorID); err != nil { if err = createIssueNotification(ctx, userID, issue, commentID, notificationAuthorID); err != nil {
return err return err
} }
} }
return nil return nil
} }
func getNotificationsByIssueID(e db.Engine, issueID int64) (notifications []*Notification, err error) { func getNotificationsByIssueID(ctx context.Context, issueID int64) (notifications []*Notification, err error) {
err = e. err = db.GetEngine(ctx).
Where("issue_id = ?", issueID). Where("issue_id = ?", issueID).
Find(&notifications) Find(&notifications)
return return
@ -308,7 +303,7 @@ func notificationExists(notifications []*Notification, issueID, userID int64) bo
return false return false
} }
func createIssueNotification(e db.Engine, userID int64, issue *Issue, commentID, updatedByID int64) error { func createIssueNotification(ctx context.Context, userID int64, issue *Issue, commentID, updatedByID int64) error {
notification := &Notification{ notification := &Notification{
UserID: userID, UserID: userID,
RepoID: issue.RepoID, RepoID: issue.RepoID,
@ -324,12 +319,11 @@ func createIssueNotification(e db.Engine, userID int64, issue *Issue, commentID,
notification.Source = NotificationSourceIssue notification.Source = NotificationSourceIssue
} }
_, err := e.Insert(notification) return db.Insert(ctx, notification)
return err
} }
func updateIssueNotification(e db.Engine, userID, issueID, commentID, updatedByID int64) error { func updateIssueNotification(ctx context.Context, userID, issueID, commentID, updatedByID int64) error {
notification, err := getIssueNotification(e, userID, issueID) notification, err := getIssueNotification(ctx, userID, issueID)
if err != nil { if err != nil {
return err return err
} }
@ -346,13 +340,13 @@ func updateIssueNotification(e db.Engine, userID, issueID, commentID, updatedByI
cols = []string{"update_by"} cols = []string{"update_by"}
} }
_, err = e.ID(notification.ID).Cols(cols...).Update(notification) _, err = db.GetEngine(ctx).ID(notification.ID).Cols(cols...).Update(notification)
return err return err
} }
func getIssueNotification(e db.Engine, userID, issueID int64) (*Notification, error) { func getIssueNotification(ctx context.Context, userID, issueID int64) (*Notification, error) {
notification := new(Notification) notification := new(Notification)
_, err := e. _, err := db.GetEngine(ctx).
Where("user_id = ?", userID). Where("user_id = ?", userID).
And("issue_id = ?", issueID). And("issue_id = ?", issueID).
Get(notification) Get(notification)
@ -360,16 +354,12 @@ func getIssueNotification(e db.Engine, userID, issueID int64) (*Notification, er
} }
// NotificationsForUser returns notifications for a given user and status // NotificationsForUser returns notifications for a given user and status
func NotificationsForUser(user *user_model.User, statuses []NotificationStatus, page, perPage int) (NotificationList, error) { func NotificationsForUser(ctx context.Context, user *user_model.User, statuses []NotificationStatus, page, perPage int) (notifications NotificationList, err error) {
return notificationsForUser(db.GetEngine(db.DefaultContext), user, statuses, page, perPage)
}
func notificationsForUser(e db.Engine, user *user_model.User, statuses []NotificationStatus, page, perPage int) (notifications []*Notification, err error) {
if len(statuses) == 0 { if len(statuses) == 0 {
return return
} }
sess := e. sess := db.GetEngine(ctx).
Where("user_id = ?", user.ID). Where("user_id = ?", user.ID).
In("status", statuses). In("status", statuses).
OrderBy("updated_unix DESC") OrderBy("updated_unix DESC")
@ -383,12 +373,8 @@ func notificationsForUser(e db.Engine, user *user_model.User, statuses []Notific
} }
// CountUnread count unread notifications for a user // CountUnread count unread notifications for a user
func CountUnread(user *user_model.User) int64 { func CountUnread(ctx context.Context, userID int64) int64 {
return countUnread(db.GetEngine(db.DefaultContext), user.ID) exist, err := db.GetEngine(ctx).Where("user_id = ?", userID).And("status = ?", NotificationStatusUnread).Count(new(Notification))
}
func countUnread(e db.Engine, userID int64) int64 {
exist, err := e.Where("user_id = ?", userID).And("status = ?", NotificationStatusUnread).Count(new(Notification))
if err != nil { if err != nil {
log.Error("countUnread", err) log.Error("countUnread", err)
return 0 return 0
@ -402,17 +388,16 @@ func (n *Notification) LoadAttributes() (err error) {
} }
func (n *Notification) loadAttributes(ctx context.Context) (err error) { func (n *Notification) loadAttributes(ctx context.Context) (err error) {
e := db.GetEngine(ctx)
if err = n.loadRepo(ctx); err != nil { if err = n.loadRepo(ctx); err != nil {
return return
} }
if err = n.loadIssue(ctx); err != nil { if err = n.loadIssue(ctx); err != nil {
return return
} }
if err = n.loadUser(e); err != nil { if err = n.loadUser(ctx); err != nil {
return return
} }
if err = n.loadComment(e); err != nil { if err = n.loadComment(ctx); err != nil {
return return
} }
return return
@ -430,7 +415,7 @@ func (n *Notification) loadRepo(ctx context.Context) (err error) {
func (n *Notification) loadIssue(ctx context.Context) (err error) { func (n *Notification) loadIssue(ctx context.Context) (err error) {
if n.Issue == nil && n.IssueID != 0 { if n.Issue == nil && n.IssueID != 0 {
n.Issue, err = getIssueByID(db.GetEngine(ctx), n.IssueID) n.Issue, err = getIssueByID(ctx, n.IssueID)
if err != nil { if err != nil {
return fmt.Errorf("getIssueByID [%d]: %v", n.IssueID, err) return fmt.Errorf("getIssueByID [%d]: %v", n.IssueID, err)
} }
@ -439,9 +424,9 @@ func (n *Notification) loadIssue(ctx context.Context) (err error) {
return nil return nil
} }
func (n *Notification) loadComment(e db.Engine) (err error) { func (n *Notification) loadComment(ctx context.Context) (err error) {
if n.Comment == nil && n.CommentID != 0 { if n.Comment == nil && n.CommentID != 0 {
n.Comment, err = getCommentByID(e, n.CommentID) n.Comment, err = GetCommentByID(ctx, n.CommentID)
if err != nil { if err != nil {
if IsErrCommentNotExist(err) { if IsErrCommentNotExist(err) {
return ErrCommentNotExist{ return ErrCommentNotExist{
@ -455,9 +440,9 @@ func (n *Notification) loadComment(e db.Engine) (err error) {
return nil return nil
} }
func (n *Notification) loadUser(e db.Engine) (err error) { func (n *Notification) loadUser(ctx context.Context) (err error) {
if n.User == nil { if n.User == nil {
n.User, err = user_model.GetUserByIDEngine(e, n.UserID) n.User, err = user_model.GetUserByIDCtx(ctx, n.UserID)
if err != nil { if err != nil {
return fmt.Errorf("getUserByID [%d]: %v", n.UserID, err) return fmt.Errorf("getUserByID [%d]: %v", n.UserID, err)
} }
@ -739,12 +724,8 @@ func (nl NotificationList) LoadComments() ([]int, error) {
} }
// GetNotificationCount returns the notification count for user // GetNotificationCount returns the notification count for user
func GetNotificationCount(user *user_model.User, status NotificationStatus) (int64, error) { func GetNotificationCount(ctx context.Context, user *user_model.User, status NotificationStatus) (count int64, err error) {
return getNotificationCount(db.GetEngine(db.DefaultContext), user, status) count, err = db.GetEngine(ctx).
}
func getNotificationCount(e db.Engine, user *user_model.User, status NotificationStatus) (count int64, err error) {
count, err = e.
Where("user_id = ?", user.ID). Where("user_id = ?", user.ID).
And("status = ?", status). And("status = ?", status).
Count(&Notification{}) Count(&Notification{})
@ -766,8 +747,8 @@ func GetUIDsAndNotificationCounts(since, until timeutil.TimeStamp) ([]UserIDCoun
return res, db.GetEngine(db.DefaultContext).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 { func setIssueNotificationStatusReadIfUnread(ctx context.Context, userID, issueID int64) error {
notification, err := getIssueNotification(e, userID, issueID) notification, err := getIssueNotification(ctx, userID, issueID)
// ignore if not exists // ignore if not exists
if err != nil { if err != nil {
return nil return nil
@ -779,12 +760,13 @@ func setIssueNotificationStatusReadIfUnread(e db.Engine, userID, issueID int64)
notification.Status = NotificationStatusRead notification.Status = NotificationStatusRead
_, err = e.ID(notification.ID).Update(notification) _, err = db.GetEngine(ctx).ID(notification.ID).Update(notification)
return err return err
} }
func setRepoNotificationStatusReadIfUnread(e db.Engine, userID, repoID int64) error { // SetRepoReadBy sets repo to be visited by given user.
_, err := e.Where(builder.Eq{ func SetRepoReadBy(ctx context.Context, userID, repoID int64) error {
_, err := db.GetEngine(ctx).Where(builder.Eq{
"user_id": userID, "user_id": userID,
"status": NotificationStatusUnread, "status": NotificationStatusUnread,
"source": NotificationSourceRepository, "source": NotificationSourceRepository,
@ -795,7 +777,7 @@ func setRepoNotificationStatusReadIfUnread(e db.Engine, userID, repoID int64) er
// SetNotificationStatus change the notification status // SetNotificationStatus change the notification status
func SetNotificationStatus(notificationID int64, user *user_model.User, status NotificationStatus) (*Notification, error) { func SetNotificationStatus(notificationID int64, user *user_model.User, status NotificationStatus) (*Notification, error) {
notification, err := getNotificationByID(db.GetEngine(db.DefaultContext), notificationID) notification, err := getNotificationByID(db.DefaultContext, notificationID)
if err != nil { if err != nil {
return notification, err return notification, err
} }
@ -812,12 +794,12 @@ func SetNotificationStatus(notificationID int64, user *user_model.User, status N
// GetNotificationByID return notification by ID // GetNotificationByID return notification by ID
func GetNotificationByID(notificationID int64) (*Notification, error) { func GetNotificationByID(notificationID int64) (*Notification, error) {
return getNotificationByID(db.GetEngine(db.DefaultContext), notificationID) return getNotificationByID(db.DefaultContext, notificationID)
} }
func getNotificationByID(e db.Engine, notificationID int64) (*Notification, error) { func getNotificationByID(ctx context.Context, notificationID int64) (*Notification, error) {
notification := new(Notification) notification := new(Notification)
ok, err := e. ok, err := db.GetEngine(ctx).
Where("id = ?", notificationID). Where("id = ?", notificationID).
Get(notification) Get(notification)
if err != nil { if err != nil {

@ -7,6 +7,7 @@ package models
import ( import (
"testing" "testing"
"code.gitea.io/gitea/models/db"
"code.gitea.io/gitea/models/unittest" "code.gitea.io/gitea/models/unittest"
user_model "code.gitea.io/gitea/models/user" user_model "code.gitea.io/gitea/models/user"
@ -32,7 +33,7 @@ func TestNotificationsForUser(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase()) assert.NoError(t, unittest.PrepareTestDatabase())
user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2}).(*user_model.User) user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2}).(*user_model.User)
statuses := []NotificationStatus{NotificationStatusRead, NotificationStatusUnread} statuses := []NotificationStatus{NotificationStatusRead, NotificationStatusUnread}
notfs, err := NotificationsForUser(user, statuses, 1, 10) notfs, err := NotificationsForUser(db.DefaultContext, user, statuses, 1, 10)
assert.NoError(t, err) assert.NoError(t, err)
if assert.Len(t, notfs, 3) { if assert.Len(t, notfs, 3) {
assert.EqualValues(t, 5, notfs[0].ID) assert.EqualValues(t, 5, notfs[0].ID)
@ -65,11 +66,11 @@ func TestNotification_GetIssue(t *testing.T) {
func TestGetNotificationCount(t *testing.T) { func TestGetNotificationCount(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase()) assert.NoError(t, unittest.PrepareTestDatabase())
user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 1}).(*user_model.User) user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 1}).(*user_model.User)
cnt, err := GetNotificationCount(user, NotificationStatusRead) cnt, err := GetNotificationCount(db.DefaultContext, user, NotificationStatusRead)
assert.NoError(t, err) assert.NoError(t, err)
assert.EqualValues(t, 0, cnt) assert.EqualValues(t, 0, cnt)
cnt, err = GetNotificationCount(user, NotificationStatusUnread) cnt, err = GetNotificationCount(db.DefaultContext, user, NotificationStatusUnread)
assert.NoError(t, err) assert.NoError(t, err)
assert.EqualValues(t, 1, cnt) assert.EqualValues(t, 1, cnt)
} }

@ -95,7 +95,7 @@ func removeOrgUser(ctx context.Context, orgID, userID int64) error {
return nil return nil
} }
org, err := organization.GetOrgByIDCtx(ctx, orgID) org, err := organization.GetOrgByID(ctx, orgID)
if err != nil { if err != nil {
return fmt.Errorf("GetUserByID [%d]: %v", orgID, err) return fmt.Errorf("GetUserByID [%d]: %v", orgID, err)
} }
@ -120,7 +120,7 @@ func removeOrgUser(ctx context.Context, orgID, userID int64) error {
if _, err := sess.ID(ou.ID).Delete(ou); err != nil { if _, err := sess.ID(ou.ID).Delete(ou); err != nil {
return err return err
} else if _, err = sess.Exec("UPDATE `user` SET num_members=num_members-1 WHERE id=?", orgID); err != nil { } else if _, err = db.Exec(ctx, "UPDATE `user` SET num_members=num_members-1 WHERE id=?", orgID); err != nil {
return err return err
} }
@ -134,7 +134,7 @@ func removeOrgUser(ctx context.Context, orgID, userID int64) error {
return fmt.Errorf("GetUserRepositories [%d]: %v", userID, err) return fmt.Errorf("GetUserRepositories [%d]: %v", userID, err)
} }
for _, repoID := range repoIDs { for _, repoID := range repoIDs {
if err = repo_model.WatchRepoCtx(ctx, userID, repoID, false); err != nil { if err = repo_model.WatchRepo(ctx, userID, repoID, false); err != nil {
return err return err
} }
} }

@ -44,7 +44,7 @@ func addRepository(ctx context.Context, t *organization.Team, repo *repo_model.R
return fmt.Errorf("getMembers: %v", err) return fmt.Errorf("getMembers: %v", err)
} }
for _, u := range t.Members { for _, u := range t.Members {
if err = repo_model.WatchRepoCtx(ctx, u.ID, repo.ID, true); err != nil { if err = repo_model.WatchRepo(ctx, u.ID, repo.ID, true); err != nil {
return fmt.Errorf("watchRepo: %v", err) return fmt.Errorf("watchRepo: %v", err)
} }
} }
@ -147,12 +147,12 @@ func removeAllRepositories(ctx context.Context, t *organization.Team) (err error
continue continue
} }
if err = repo_model.WatchRepoCtx(ctx, user.ID, repo.ID, false); err != nil { if err = repo_model.WatchRepo(ctx, user.ID, repo.ID, false); err != nil {
return err return err
} }
// Remove all IssueWatches a user has subscribed to in the repositories // Remove all IssueWatches a user has subscribed to in the repositories
if err = removeIssueWatchersByRepoID(e, user.ID, repo.ID); err != nil { if err = removeIssueWatchersByRepoID(ctx, user.ID, repo.ID); err != nil {
return err return err
} }
} }
@ -210,12 +210,12 @@ func removeRepository(ctx context.Context, t *organization.Team, repo *repo_mode
continue continue
} }
if err = repo_model.WatchRepoCtx(ctx, teamUser.UID, repo.ID, false); err != nil { if err = repo_model.WatchRepo(ctx, teamUser.UID, repo.ID, false); err != nil {
return err return err
} }
// Remove all IssueWatches a user has subscribed to in the repositories // Remove all IssueWatches a user has subscribed to in the repositories
if err := removeIssueWatchersByRepoID(e, teamUser.UID, repo.ID); err != nil { if err := removeIssueWatchersByRepoID(ctx, teamUser.UID, repo.ID); err != nil {
return err return err
} }
} }
@ -555,7 +555,7 @@ func AddTeamMember(team *organization.Team, userID int64) error {
} }
go func(repos []*repo_model.Repository) { go func(repos []*repo_model.Repository) {
for _, repo := range repos { for _, repo := range repos {
if err = repo_model.WatchRepoCtx(db.DefaultContext, userID, repo.ID, true); err != nil { if err = repo_model.WatchRepo(db.DefaultContext, userID, repo.ID, true); err != nil {
log.Error("watch repo failed: %v", err) log.Error("watch repo failed: %v", err)
} }
} }

@ -102,7 +102,7 @@ func (org *Organization) CanCreateOrgRepo(uid int64) (bool, error) {
} }
func (org *Organization) getTeam(ctx context.Context, name string) (*Team, error) { func (org *Organization) getTeam(ctx context.Context, name string) (*Team, error) {
return getTeam(ctx, org.ID, name) return GetTeam(ctx, org.ID, name)
} }
// GetTeam returns named team of organization. // GetTeam returns named team of organization.
@ -203,7 +203,7 @@ func CountOrgMembers(opts *FindOrgMembersOpts) (int64, error) {
// FindOrgMembers loads organization members according conditions // FindOrgMembers loads organization members according conditions
func FindOrgMembers(opts *FindOrgMembersOpts) (user_model.UserList, map[int64]bool, error) { func FindOrgMembers(opts *FindOrgMembersOpts) (user_model.UserList, map[int64]bool, error) {
ous, err := GetOrgUsersByOrgID(opts) ous, err := GetOrgUsersByOrgID(db.DefaultContext, opts)
if err != nil { if err != nil {
return nil, nil, err return nil, nil, err
} }
@ -248,7 +248,7 @@ func CreateOrganization(org *Organization, owner *user_model.User) (err error) {
return err return err
} }
isExist, err := user_model.IsUserExist(0, org.Name) isExist, err := user_model.IsUserExist(db.DefaultContext, 0, org.Name)
if err != nil { if err != nil {
return err return err
} else if isExist { } else if isExist {
@ -281,7 +281,7 @@ func CreateOrganization(org *Organization, owner *user_model.User) (err error) {
if err = db.Insert(ctx, org); err != nil { if err = db.Insert(ctx, org); err != nil {
return fmt.Errorf("insert organization: %v", err) return fmt.Errorf("insert organization: %v", err)
} }
if err = user_model.GenerateRandomAvatarCtx(ctx, org.AsUser()); err != nil { if err = user_model.GenerateRandomAvatar(ctx, org.AsUser()); err != nil {
return fmt.Errorf("generate random avatar: %v", err) return fmt.Errorf("generate random avatar: %v", err)
} }
@ -350,14 +350,6 @@ func GetOrgByName(name string) (*Organization, error) {
return u, nil return u, nil
} }
// CountOrganizations returns number of organizations.
func CountOrganizations() int64 {
count, _ := db.GetEngine(db.DefaultContext).
Where("type=1").
Count(new(Organization))
return count
}
// DeleteOrganization deletes models associated to an organization. // DeleteOrganization deletes models associated to an organization.
func DeleteOrganization(ctx context.Context, org *Organization) error { func DeleteOrganization(ctx context.Context, org *Organization) error {
if org.Type != user_model.UserTypeOrganization { if org.Type != user_model.UserTypeOrganization {
@ -425,7 +417,7 @@ func queryUserOrgIDs(userID int64, includePrivate bool) *builder.Builder {
} }
func (opts FindOrgOptions) toConds() builder.Cond { func (opts FindOrgOptions) toConds() builder.Cond {
cond := builder.NewCond() var cond builder.Cond = builder.Eq{"`user`.`type`": user_model.UserTypeOrganization}
if opts.UserID > 0 { if opts.UserID > 0 {
cond = cond.And(builder.In("`user`.`id`", queryUserOrgIDs(opts.UserID, opts.IncludePrivate))) cond = cond.And(builder.In("`user`.`id`", queryUserOrgIDs(opts.UserID, opts.IncludePrivate)))
} }
@ -451,18 +443,7 @@ func FindOrgs(opts FindOrgOptions) ([]*Organization, error) {
func CountOrgs(opts FindOrgOptions) (int64, error) { func CountOrgs(opts FindOrgOptions) (int64, error) {
return db.GetEngine(db.DefaultContext). return db.GetEngine(db.DefaultContext).
Where(opts.toConds()). Where(opts.toConds()).
Count(new(user_model.User)) Count(new(Organization))
}
func getOwnedOrgsByUserID(sess db.Engine, userID int64) ([]*Organization, error) {
orgs := make([]*Organization, 0, 10)
return orgs, sess.
Join("INNER", "`team_user`", "`team_user`.org_id=`user`.id").
Join("INNER", "`team`", "`team`.id=`team_user`.team_id").
Where("`team_user`.uid=?", userID).
And("`team`.authorize=?", perm.AccessModeOwner).
Asc("`user`.name").
Find(&orgs)
} }
// HasOrgOrUserVisible tells if the given user can see the given org or user // HasOrgOrUserVisible tells if the given user can see the given org or user
@ -496,17 +477,6 @@ func HasOrgsVisible(orgs []*Organization, user *user_model.User) bool {
return false return false
} }
// GetOwnedOrgsByUserID returns a list of organizations are owned by given user ID.
func GetOwnedOrgsByUserID(userID int64) ([]*Organization, error) {
return getOwnedOrgsByUserID(db.GetEngine(db.DefaultContext), userID)
}
// GetOwnedOrgsByUserIDDesc returns a list of organizations are owned by
// given user ID, ordered descending by the given condition.
func GetOwnedOrgsByUserIDDesc(userID int64, desc string) ([]*Organization, error) {
return getOwnedOrgsByUserID(db.GetEngine(db.DefaultContext).Desc(desc), userID)
}
// GetOrgsCanCreateRepoByUserID returns a list of organizations where given user ID // GetOrgsCanCreateRepoByUserID returns a list of organizations where given user ID
// are allowed to create repos. // are allowed to create repos.
func GetOrgsCanCreateRepoByUserID(userID int64) ([]*Organization, error) { func GetOrgsCanCreateRepoByUserID(userID int64) ([]*Organization, error) {
@ -543,12 +513,8 @@ func GetOrgUsersByUserID(uid int64, opts *SearchOrganizationsOptions) ([]*OrgUse
} }
// GetOrgUsersByOrgID returns all organization-user relations by organization ID. // GetOrgUsersByOrgID returns all organization-user relations by organization ID.
func GetOrgUsersByOrgID(opts *FindOrgMembersOpts) ([]*OrgUser, error) { func GetOrgUsersByOrgID(ctx context.Context, opts *FindOrgMembersOpts) ([]*OrgUser, error) {
return getOrgUsersByOrgID(db.GetEngine(db.DefaultContext), opts) sess := db.GetEngine(ctx).Where("org_id=?", opts.OrgID)
}
func getOrgUsersByOrgID(e db.Engine, opts *FindOrgMembersOpts) ([]*OrgUser, error) {
sess := e.Where("org_id=?", opts.OrgID)
if opts.PublicOnly { if opts.PublicOnly {
sess.And("is_public = ?", true) sess.And("is_public = ?", true)
} }
@ -615,8 +581,8 @@ func AddOrgUser(orgID, uid int64) error {
return committer.Commit() return committer.Commit()
} }
// GetOrgByIDCtx returns the user object by given ID if exists. // GetOrgByID returns the user object by given ID if exists.
func GetOrgByIDCtx(ctx context.Context, id int64) (*Organization, error) { func GetOrgByID(ctx context.Context, id int64) (*Organization, error) {
u := new(Organization) u := new(Organization)
has, err := db.GetEngine(ctx).ID(id).Get(u) has, err := db.GetEngine(ctx).ID(id).Get(u)
if err != nil { if err != nil {
@ -631,11 +597,6 @@ func GetOrgByIDCtx(ctx context.Context, id int64) (*Organization, error) {
return u, nil return u, nil
} }
// GetOrgByID returns the user object by given ID if exists.
func GetOrgByID(id int64) (*Organization, error) {
return GetOrgByIDCtx(db.DefaultContext, id)
}
// RemoveOrgRepo removes all team-repository relations of organization. // RemoveOrgRepo removes all team-repository relations of organization.
func RemoveOrgRepo(ctx context.Context, orgID, repoID int64) error { func RemoveOrgRepo(ctx context.Context, orgID, repoID int64) error {
teamRepos := make([]*TeamRepo, 0, 10) teamRepos := make([]*TeamRepo, 0, 10)
@ -664,9 +625,9 @@ func RemoveOrgRepo(ctx context.Context, orgID, repoID int64) error {
return err return err
} }
func (org *Organization) getUserTeams(e db.Engine, userID int64, cols ...string) ([]*Team, error) { func (org *Organization) getUserTeams(ctx context.Context, userID int64, cols ...string) ([]*Team, error) {
teams := make([]*Team, 0, org.NumTeams) teams := make([]*Team, 0, org.NumTeams)
return teams, e. return teams, db.GetEngine(ctx).
Where("`team_user`.org_id = ?", org.ID). Where("`team_user`.org_id = ?", org.ID).
Join("INNER", "team_user", "`team_user`.team_id = team.id"). Join("INNER", "team_user", "`team_user`.team_id = team.id").
Join("INNER", "`user`", "`user`.id=team_user.uid"). Join("INNER", "`user`", "`user`.id=team_user.uid").
@ -700,7 +661,7 @@ func (org *Organization) GetUserTeamIDs(userID int64) ([]int64, error) {
// GetUserTeams returns all teams that belong to user, // GetUserTeams returns all teams that belong to user,
// and that the user has joined. // and that the user has joined.
func (org *Organization) GetUserTeams(userID int64) ([]*Team, error) { func (org *Organization) GetUserTeams(userID int64) ([]*Team, error) {
return org.getUserTeams(db.GetEngine(db.DefaultContext), userID) return org.getUserTeams(db.DefaultContext, userID)
} }
// AccessibleReposEnvironment operations involving the repositories that are // AccessibleReposEnvironment operations involving the repositories that are

@ -128,9 +128,11 @@ func TestGetOrgByName(t *testing.T) {
func TestCountOrganizations(t *testing.T) { func TestCountOrganizations(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase()) assert.NoError(t, unittest.PrepareTestDatabase())
expected, err := db.GetEngine(db.DefaultContext).Where("type=?", user_model.UserTypeOrganization).Count(&user_model.User{}) expected, err := db.GetEngine(db.DefaultContext).Where("type=?", user_model.UserTypeOrganization).Count(&Organization{})
assert.NoError(t, err) assert.NoError(t, err)
assert.Equal(t, expected, CountOrganizations()) cnt, err := CountOrgs(FindOrgOptions{IncludePrivate: true})
assert.NoError(t, err)
assert.Equal(t, expected, cnt)
} }
func TestIsOrganizationOwner(t *testing.T) { func TestIsOrganizationOwner(t *testing.T) {
@ -204,35 +206,6 @@ func TestFindOrgs(t *testing.T) {
assert.EqualValues(t, 1, total) assert.EqualValues(t, 1, total)
} }
func TestGetOwnedOrgsByUserID(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase())
orgs, err := GetOwnedOrgsByUserID(2)
assert.NoError(t, err)
if assert.Len(t, orgs, 1) {
assert.EqualValues(t, 3, orgs[0].ID)
}
orgs, err = GetOwnedOrgsByUserID(4)
assert.NoError(t, err)
assert.Len(t, orgs, 0)
}
func TestGetOwnedOrgsByUserIDDesc(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase())
orgs, err := GetOwnedOrgsByUserIDDesc(5, "id")
assert.NoError(t, err)
if assert.Len(t, orgs, 2) {
assert.EqualValues(t, 7, orgs[0].ID)
assert.EqualValues(t, 6, orgs[1].ID)
}
orgs, err = GetOwnedOrgsByUserIDDesc(4, "id")
assert.NoError(t, err)
assert.Len(t, orgs, 0)
}
func TestGetOrgUsersByUserID(t *testing.T) { func TestGetOrgUsersByUserID(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase()) assert.NoError(t, unittest.PrepareTestDatabase())
@ -266,7 +239,7 @@ func TestGetOrgUsersByUserID(t *testing.T) {
func TestGetOrgUsersByOrgID(t *testing.T) { func TestGetOrgUsersByOrgID(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase()) assert.NoError(t, unittest.PrepareTestDatabase())
orgUsers, err := GetOrgUsersByOrgID(&FindOrgMembersOpts{ orgUsers, err := GetOrgUsersByOrgID(db.DefaultContext, &FindOrgMembersOpts{
ListOptions: db.ListOptions{}, ListOptions: db.ListOptions{},
OrgID: 3, OrgID: 3,
PublicOnly: false, PublicOnly: false,
@ -287,7 +260,7 @@ func TestGetOrgUsersByOrgID(t *testing.T) {
}, *orgUsers[1]) }, *orgUsers[1])
} }
orgUsers, err = GetOrgUsersByOrgID(&FindOrgMembersOpts{ orgUsers, err = GetOrgUsersByOrgID(db.DefaultContext, &FindOrgMembersOpts{
ListOptions: db.ListOptions{}, ListOptions: db.ListOptions{},
OrgID: unittest.NonexistentID, OrgID: unittest.NonexistentID,
PublicOnly: false, PublicOnly: false,

@ -91,7 +91,7 @@ func TestUserListIsPublicMember(t *testing.T) {
} }
func testUserListIsPublicMember(t *testing.T, orgID int64, expected map[int64]bool) { func testUserListIsPublicMember(t *testing.T, orgID int64, expected map[int64]bool) {
org, err := GetOrgByID(orgID) org, err := GetOrgByID(db.DefaultContext, orgID)
assert.NoError(t, err) assert.NoError(t, err)
_, membersIsPublic, err := org.GetMembers() _, membersIsPublic, err := org.GetMembers()
assert.NoError(t, err) assert.NoError(t, err)
@ -118,7 +118,7 @@ func TestUserListIsUserOrgOwner(t *testing.T) {
} }
func testUserListIsUserOrgOwner(t *testing.T, orgID int64, expected map[int64]bool) { func testUserListIsUserOrgOwner(t *testing.T, orgID int64, expected map[int64]bool) {
org, err := GetOrgByID(orgID) org, err := GetOrgByID(db.DefaultContext, orgID)
assert.NoError(t, err) assert.NoError(t, err)
members, _, err := org.GetMembers() members, _, err := org.GetMembers()
assert.NoError(t, err) assert.NoError(t, err)

@ -272,7 +272,8 @@ func IsUsableTeamName(name string) error {
} }
} }
func getTeam(ctx context.Context, orgID int64, name string) (*Team, error) { // GetTeam returns team by given team name and organization.
func GetTeam(ctx context.Context, orgID int64, name string) (*Team, error) {
t := &Team{ t := &Team{
OrgID: orgID, OrgID: orgID,
LowerName: strings.ToLower(name), LowerName: strings.ToLower(name),
@ -286,16 +287,11 @@ func getTeam(ctx context.Context, orgID int64, name string) (*Team, error) {
return t, nil return t, nil
} }
// GetTeam returns team by given team name and organization.
func GetTeam(orgID int64, name string) (*Team, error) {
return getTeam(db.DefaultContext, orgID, name)
}
// GetTeamIDsByNames returns a slice of team ids corresponds to names. // GetTeamIDsByNames returns a slice of team ids corresponds to names.
func GetTeamIDsByNames(orgID int64, names []string, ignoreNonExistent bool) ([]int64, error) { func GetTeamIDsByNames(orgID int64, names []string, ignoreNonExistent bool) ([]int64, error) {
ids := make([]int64, 0, len(names)) ids := make([]int64, 0, len(names))
for _, name := range names { for _, name := range names {
u, err := GetTeam(orgID, name) u, err := GetTeam(db.DefaultContext, orgID, name)
if err != nil { if err != nil {
if ignoreNonExistent { if ignoreNonExistent {
continue continue
@ -310,11 +306,11 @@ func GetTeamIDsByNames(orgID int64, names []string, ignoreNonExistent bool) ([]i
// GetOwnerTeam returns team by given team name and organization. // GetOwnerTeam returns team by given team name and organization.
func GetOwnerTeam(ctx context.Context, orgID int64) (*Team, error) { func GetOwnerTeam(ctx context.Context, orgID int64) (*Team, error) {
return getTeam(ctx, orgID, OwnerTeamName) return GetTeam(ctx, orgID, OwnerTeamName)
} }
// GetTeamByIDCtx returns team by given ID. // GetTeamByID returns team by given ID.
func GetTeamByIDCtx(ctx context.Context, teamID int64) (*Team, error) { func GetTeamByID(ctx context.Context, teamID int64) (*Team, error) {
t := new(Team) t := new(Team)
has, err := db.GetEngine(ctx).ID(teamID).Get(t) has, err := db.GetEngine(ctx).ID(teamID).Get(t)
if err != nil { if err != nil {
@ -325,11 +321,6 @@ func GetTeamByIDCtx(ctx context.Context, teamID int64) (*Team, error) {
return t, nil return t, nil
} }
// GetTeamByID returns team by given ID.
func GetTeamByID(teamID int64) (*Team, error) {
return GetTeamByIDCtx(db.DefaultContext, teamID)
}
// GetTeamNamesByID returns team's lower name from a list of team ids. // GetTeamNamesByID returns team's lower name from a list of team ids.
func GetTeamNamesByID(teamIDs []int64) ([]string, error) { func GetTeamNamesByID(teamIDs []int64) ([]string, error) {
if len(teamIDs) == 0 { if len(teamIDs) == 0 {
@ -346,16 +337,12 @@ func GetTeamNamesByID(teamIDs []int64) ([]string, error) {
return teamNames, err return teamNames, err
} }
func getRepoTeams(e db.Engine, repo *repo_model.Repository) (teams []*Team, err error) { // GetRepoTeams gets the list of teams that has access to the repository
return teams, e. func GetRepoTeams(ctx context.Context, repo *repo_model.Repository) (teams []*Team, err error) {
return teams, db.GetEngine(ctx).
Join("INNER", "team_repo", "team_repo.team_id = team.id"). Join("INNER", "team_repo", "team_repo.team_id = team.id").
Where("team.org_id = ?", repo.OwnerID). Where("team.org_id = ?", repo.OwnerID).
And("team_repo.repo_id=?", repo.ID). And("team_repo.repo_id=?", repo.ID).
OrderBy("CASE WHEN name LIKE '" + OwnerTeamName + "' THEN '' ELSE name END"). OrderBy("CASE WHEN name LIKE '" + OwnerTeamName + "' THEN '' ELSE name END").
Find(&teams) Find(&teams)
} }
// GetRepoTeams gets the list of teams that has access to the repository
func GetRepoTeams(repo *repo_model.Repository) ([]*Team, error) {
return getRepoTeams(db.GetEngine(db.DefaultContext), repo)
}

@ -71,7 +71,7 @@ func TestGetTeam(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase()) assert.NoError(t, unittest.PrepareTestDatabase())
testSuccess := func(orgID int64, name string) { testSuccess := func(orgID int64, name string) {
team, err := GetTeam(orgID, name) team, err := GetTeam(db.DefaultContext, orgID, name)
assert.NoError(t, err) assert.NoError(t, err)
assert.EqualValues(t, orgID, team.OrgID) assert.EqualValues(t, orgID, team.OrgID)
assert.Equal(t, name, team.Name) assert.Equal(t, name, team.Name)
@ -79,9 +79,9 @@ func TestGetTeam(t *testing.T) {
testSuccess(3, "Owners") testSuccess(3, "Owners")
testSuccess(3, "team1") testSuccess(3, "team1")
_, err := GetTeam(3, "nonexistent") _, err := GetTeam(db.DefaultContext, 3, "nonexistent")
assert.Error(t, err) assert.Error(t, err)
_, err = GetTeam(unittest.NonexistentID, "Owners") _, err = GetTeam(db.DefaultContext, unittest.NonexistentID, "Owners")
assert.Error(t, err) assert.Error(t, err)
} }
@ -89,7 +89,7 @@ func TestGetTeamByID(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase()) assert.NoError(t, unittest.PrepareTestDatabase())
testSuccess := func(teamID int64) { testSuccess := func(teamID int64) {
team, err := GetTeamByID(teamID) team, err := GetTeamByID(db.DefaultContext, teamID)
assert.NoError(t, err) assert.NoError(t, err)
assert.EqualValues(t, teamID, team.ID) assert.EqualValues(t, teamID, team.ID)
} }
@ -98,7 +98,7 @@ func TestGetTeamByID(t *testing.T) {
testSuccess(3) testSuccess(3)
testSuccess(4) testSuccess(4)
_, err := GetTeamByID(unittest.NonexistentID) _, err := GetTeamByID(db.DefaultContext, unittest.NonexistentID)
assert.Error(t, err) assert.Error(t, err)
} }

@ -30,7 +30,7 @@ func init() {
db.RegisterModel(new(Access)) db.RegisterModel(new(Access))
} }
func accessLevel(e db.Engine, user *user_model.User, repo *repo_model.Repository) (perm.AccessMode, error) { func accessLevel(ctx context.Context, user *user_model.User, repo *repo_model.Repository) (perm.AccessMode, error) {
mode := perm.AccessModeNone mode := perm.AccessModeNone
var userID int64 var userID int64
restricted := false restricted := false
@ -53,7 +53,7 @@ func accessLevel(e db.Engine, user *user_model.User, repo *repo_model.Repository
} }
a := &Access{UserID: userID, RepoID: repo.ID} a := &Access{UserID: userID, RepoID: repo.ID}
if has, err := e.Get(a); !has || err != nil { if has, err := db.GetByBean(ctx, a); !has || err != nil {
return mode, err return mode, err
} }
return a.Mode, nil return a.Mode, nil
@ -84,7 +84,7 @@ func updateUserAccess(accessMap map[int64]*userAccess, user *user_model.User, mo
} }
// FIXME: do cross-comparison so reduce deletions and additions to the minimum? // FIXME: do cross-comparison so reduce deletions and additions to the minimum?
func refreshAccesses(e db.Engine, repo *repo_model.Repository, accessMap map[int64]*userAccess) (err error) { func refreshAccesses(ctx context.Context, repo *repo_model.Repository, accessMap map[int64]*userAccess) (err error) {
minMode := perm.AccessModeRead minMode := perm.AccessModeRead
if !repo.IsPrivate { if !repo.IsPrivate {
minMode = perm.AccessModeWrite minMode = perm.AccessModeWrite
@ -104,14 +104,14 @@ func refreshAccesses(e db.Engine, repo *repo_model.Repository, accessMap map[int
} }
// Delete old accesses and insert new ones for repository. // Delete old accesses and insert new ones for repository.
if _, err = e.Delete(&Access{RepoID: repo.ID}); err != nil { if _, err = db.DeleteByBean(ctx, &Access{RepoID: repo.ID}); err != nil {
return fmt.Errorf("delete old accesses: %v", err) return fmt.Errorf("delete old accesses: %v", err)
} }
if len(newAccesses) == 0 { if len(newAccesses) == 0 {
return nil return nil
} }
if _, err = e.Insert(newAccesses); err != nil { if err = db.Insert(ctx, newAccesses); err != nil {
return fmt.Errorf("insert new accesses: %v", err) return fmt.Errorf("insert new accesses: %v", err)
} }
return nil return nil
@ -144,8 +144,6 @@ func RecalculateTeamAccesses(ctx context.Context, repo *repo_model.Repository, i
return fmt.Errorf("owner is not an organization: %d", repo.OwnerID) return fmt.Errorf("owner is not an organization: %d", repo.OwnerID)
} }
e := db.GetEngine(ctx)
if err = refreshCollaboratorAccesses(ctx, repo.ID, accessMap); err != nil { if err = refreshCollaboratorAccesses(ctx, repo.ID, accessMap); err != nil {
return fmt.Errorf("refreshCollaboratorAccesses: %v", err) return fmt.Errorf("refreshCollaboratorAccesses: %v", err)
} }
@ -176,7 +174,7 @@ func RecalculateTeamAccesses(ctx context.Context, repo *repo_model.Repository, i
} }
} }
return refreshAccesses(e, repo, accessMap) return refreshAccesses(ctx, repo, accessMap)
} }
// RecalculateUserAccess recalculates new access for a single user // RecalculateUserAccess recalculates new access for a single user
@ -235,10 +233,9 @@ func RecalculateAccesses(ctx context.Context, repo *repo_model.Repository) error
return RecalculateTeamAccesses(ctx, repo, 0) return RecalculateTeamAccesses(ctx, repo, 0)
} }
e := db.GetEngine(ctx)
accessMap := make(map[int64]*userAccess, 20) accessMap := make(map[int64]*userAccess, 20)
if err := refreshCollaboratorAccesses(ctx, repo.ID, accessMap); err != nil { if err := refreshCollaboratorAccesses(ctx, repo.ID, accessMap); err != nil {
return fmt.Errorf("refreshCollaboratorAccesses: %v", err) return fmt.Errorf("refreshCollaboratorAccesses: %v", err)
} }
return refreshAccesses(e, repo, accessMap) return refreshAccesses(ctx, repo, accessMap)
} }

@ -168,8 +168,6 @@ func GetUserRepoPermission(ctx context.Context, repo *repo_model.Repository, use
return return
} }
e := db.GetEngine(ctx)
var is bool var is bool
if user != nil { if user != nil {
is, err = repo_model.IsCollaborator(ctx, repo.ID, user.ID) is, err = repo_model.IsCollaborator(ctx, repo.ID, user.ID)
@ -208,7 +206,7 @@ func GetUserRepoPermission(ctx context.Context, repo *repo_model.Repository, use
} }
// plain user // plain user
perm.AccessMode, err = accessLevel(e, user, repo) perm.AccessMode, err = accessLevel(ctx, user, repo)
if err != nil { if err != nil {
return return
} }
@ -288,7 +286,7 @@ func IsUserRealRepoAdmin(repo *repo_model.Repository, user *user_model.User) (bo
return false, err return false, err
} }
accessMode, err := accessLevel(db.GetEngine(db.DefaultContext), user, repo) accessMode, err := accessLevel(db.DefaultContext, user, repo)
if err != nil { if err != nil {
return false, err return false, err
} }
@ -297,12 +295,7 @@ func IsUserRealRepoAdmin(repo *repo_model.Repository, user *user_model.User) (bo
} }
// IsUserRepoAdmin return true if user has admin right of a repo // IsUserRepoAdmin return true if user has admin right of a repo
func IsUserRepoAdmin(repo *repo_model.Repository, user *user_model.User) (bool, error) { func IsUserRepoAdmin(ctx context.Context, repo *repo_model.Repository, user *user_model.User) (bool, error) {
return IsUserRepoAdminCtx(db.DefaultContext, repo, user)
}
// IsUserRepoAdminCtx return true if user has admin right of a repo
func IsUserRepoAdminCtx(ctx context.Context, repo *repo_model.Repository, user *user_model.User) (bool, error) {
if user == nil || repo == nil { if user == nil || repo == nil {
return false, nil return false, nil
} }
@ -310,8 +303,7 @@ func IsUserRepoAdminCtx(ctx context.Context, repo *repo_model.Repository, user *
return true, nil return true, nil
} }
e := db.GetEngine(ctx) mode, err := accessLevel(ctx, user, repo)
mode, err := accessLevel(e, user, repo)
if err != nil { if err != nil {
return false, err return false, err
} }
@ -377,7 +369,7 @@ func HasAccess(ctx context.Context, userID int64, repo *repo_model.Repository) (
var user *user_model.User var user *user_model.User
var err error var err error
if userID > 0 { if userID > 0 {
user, err = user_model.GetUserByIDEngine(db.GetEngine(ctx), userID) user, err = user_model.GetUserByIDCtx(ctx, userID)
if err != nil { if err != nil {
return false, err return false, err
} }

@ -147,8 +147,7 @@ func DeleteBoardByID(boardID int64) error {
} }
func deleteBoardByID(ctx context.Context, boardID int64) error { func deleteBoardByID(ctx context.Context, boardID int64) error {
e := db.GetEngine(ctx) board, err := GetBoard(ctx, boardID)
board, err := getBoard(e, boardID)
if err != nil { if err != nil {
if IsErrProjectBoardNotExist(err) { if IsErrProjectBoardNotExist(err) {
return nil return nil
@ -157,30 +156,26 @@ func deleteBoardByID(ctx context.Context, boardID int64) error {
return err return err
} }
if err = board.removeIssues(e); err != nil { if err = board.removeIssues(ctx); err != nil {
return err return err
} }
if _, err := e.ID(board.ID).Delete(board); err != nil { if _, err := db.GetEngine(ctx).ID(board.ID).NoAutoCondition().Delete(board); err != nil {
return err return err
} }
return nil return nil
} }
func deleteBoardByProjectID(e db.Engine, projectID int64) error { func deleteBoardByProjectID(ctx context.Context, projectID int64) error {
_, err := e.Where("project_id=?", projectID).Delete(&Board{}) _, err := db.GetEngine(ctx).Where("project_id=?", projectID).Delete(&Board{})
return err return err
} }
// GetBoard fetches the current board of a project // GetBoard fetches the current board of a project
func GetBoard(boardID int64) (*Board, error) { func GetBoard(ctx context.Context, boardID int64) (*Board, error) {
return getBoard(db.GetEngine(db.DefaultContext), boardID)
}
func getBoard(e db.Engine, boardID int64) (*Board, error) {
board := new(Board) board := new(Board)
has, err := e.ID(boardID).Get(board) has, err := db.GetEngine(ctx).ID(boardID).Get(board)
if err != nil { if err != nil {
return nil, err return nil, err
} else if !has { } else if !has {
@ -191,11 +186,7 @@ func getBoard(e db.Engine, boardID int64) (*Board, error) {
} }
// UpdateBoard updates a project board // UpdateBoard updates a project board
func UpdateBoard(board *Board) error { func UpdateBoard(ctx context.Context, board *Board) error {
return updateBoard(db.GetEngine(db.DefaultContext), board)
}
func updateBoard(e db.Engine, board *Board) error {
var fieldToUpdate []string var fieldToUpdate []string
if board.Sorting != 0 { if board.Sorting != 0 {
@ -211,25 +202,21 @@ func updateBoard(e db.Engine, board *Board) error {
} }
fieldToUpdate = append(fieldToUpdate, "color") fieldToUpdate = append(fieldToUpdate, "color")
_, err := e.ID(board.ID).Cols(fieldToUpdate...).Update(board) _, err := db.GetEngine(ctx).ID(board.ID).Cols(fieldToUpdate...).Update(board)
return err return err
} }
// GetBoards fetches all boards related to a project // GetBoards fetches all boards related to a project
// if no default board set, first board is a temporary "Uncategorized" board // if no default board set, first board is a temporary "Uncategorized" board
func GetBoards(projectID int64) (BoardList, error) { func GetBoards(ctx context.Context, projectID int64) (BoardList, error) {
return getBoards(db.GetEngine(db.DefaultContext), projectID)
}
func getBoards(e db.Engine, projectID int64) ([]*Board, error) {
boards := make([]*Board, 0, 5) boards := make([]*Board, 0, 5)
if err := e.Where("project_id=? AND `default`=?", projectID, false).OrderBy("Sorting").Find(&boards); err != nil { if err := db.GetEngine(ctx).Where("project_id=? AND `default`=?", projectID, false).OrderBy("Sorting").Find(&boards); err != nil {
return nil, err return nil, err
} }
defaultB, err := getDefaultBoard(e, projectID) defaultB, err := getDefaultBoard(ctx, projectID)
if err != nil { if err != nil {
return nil, err return nil, err
} }
@ -238,9 +225,9 @@ func getBoards(e db.Engine, projectID int64) ([]*Board, error) {
} }
// getDefaultBoard return default board and create a dummy if none exist // getDefaultBoard return default board and create a dummy if none exist
func getDefaultBoard(e db.Engine, projectID int64) (*Board, error) { func getDefaultBoard(ctx context.Context, projectID int64) (*Board, error) {
var board Board var board Board
exist, err := e.Where("project_id=? AND `default`=?", projectID, true).Get(&board) exist, err := db.GetEngine(ctx).Where("project_id=? AND `default`=?", projectID, true).Get(&board)
if err != nil { if err != nil {
return nil, err return nil, err
} }

@ -28,8 +28,8 @@ func init() {
db.RegisterModel(new(ProjectIssue)) db.RegisterModel(new(ProjectIssue))
} }
func deleteProjectIssuesByProjectID(e db.Engine, projectID int64) error { func deleteProjectIssuesByProjectID(ctx context.Context, projectID int64) error {
_, err := e.Where("project_id=?", projectID).Delete(&ProjectIssue{}) _, err := db.GetEngine(ctx).Where("project_id=?", projectID).Delete(&ProjectIssue{})
return err return err
} }
@ -97,7 +97,7 @@ func MoveIssuesOnProjectBoard(board *Board, sortedIssueIDs map[int64]int64) erro
}) })
} }
func (pb *Board) removeIssues(e db.Engine) error { func (pb *Board) removeIssues(ctx context.Context) error {
_, err := e.Exec("UPDATE `project_issue` SET project_board_id = 0 WHERE project_board_id = ? ", pb.ID) _, err := db.GetEngine(ctx).Exec("UPDATE `project_issue` SET project_board_id = 0 WHERE project_board_id = ? ", pb.ID)
return err return err
} }

@ -121,12 +121,7 @@ type SearchOptions struct {
} }
// GetProjects returns a list of all projects that have been created in the repository // GetProjects returns a list of all projects that have been created in the repository
func GetProjects(opts SearchOptions) ([]*Project, int64, error) { func GetProjects(ctx context.Context, opts SearchOptions) ([]*Project, int64, error) {
return GetProjectsCtx(db.DefaultContext, opts)
}
// GetProjectsCtx returns a list of all projects that have been created in the repository
func GetProjectsCtx(ctx context.Context, opts SearchOptions) ([]*Project, int64, error) {
e := db.GetEngine(ctx) e := db.GetEngine(ctx)
projects := make([]*Project, 0, setting.UI.IssuePagingNum) projects := make([]*Project, 0, setting.UI.IssuePagingNum)
@ -199,14 +194,10 @@ func NewProject(p *Project) error {
} }
// GetProjectByID returns the projects in a repository // GetProjectByID returns the projects in a repository
func GetProjectByID(id int64) (*Project, error) { func GetProjectByID(ctx context.Context, id int64) (*Project, error) {
return getProjectByID(db.GetEngine(db.DefaultContext), id)
}
func getProjectByID(e db.Engine, id int64) (*Project, error) {
p := new(Project) p := new(Project)
has, err := e.ID(id).Get(p) has, err := db.GetEngine(ctx).ID(id).Get(p)
if err != nil { if err != nil {
return nil, err return nil, err
} else if !has { } else if !has {
@ -217,20 +208,16 @@ func getProjectByID(e db.Engine, id int64) (*Project, error) {
} }
// UpdateProject updates project properties // UpdateProject updates project properties
func UpdateProject(p *Project) error { func UpdateProject(ctx context.Context, p *Project) error {
return updateProject(db.GetEngine(db.DefaultContext), p) _, err := db.GetEngine(ctx).ID(p.ID).Cols(
}
func updateProject(e db.Engine, p *Project) error {
_, err := e.ID(p.ID).Cols(
"title", "title",
"description", "description",
).Update(p) ).Update(p)
return err return err
} }
func updateRepositoryProjectCount(e db.Engine, repoID int64) error { func updateRepositoryProjectCount(ctx context.Context, repoID int64) error {
if _, err := e.Exec(builder.Update( if _, err := db.GetEngine(ctx).Exec(builder.Update(
builder.Eq{ builder.Eq{
"`num_projects`": builder.Select("count(*)").From("`project`"). "`num_projects`": builder.Select("count(*)").From("`project`").
Where(builder.Eq{"`project`.`repo_id`": repoID}. Where(builder.Eq{"`project`.`repo_id`": repoID}.
@ -239,7 +226,7 @@ func updateRepositoryProjectCount(e db.Engine, repoID int64) error {
return err return err
} }
if _, err := e.Exec(builder.Update( if _, err := db.GetEngine(ctx).Exec(builder.Update(
builder.Eq{ builder.Eq{
"`num_closed_projects`": builder.Select("count(*)").From("`project`"). "`num_closed_projects`": builder.Select("count(*)").From("`project`").
Where(builder.Eq{"`project`.`repo_id`": repoID}. Where(builder.Eq{"`project`.`repo_id`": repoID}.
@ -293,8 +280,7 @@ func ChangeProjectStatus(p *Project, isClosed bool) error {
func changeProjectStatus(ctx context.Context, p *Project, isClosed bool) error { func changeProjectStatus(ctx context.Context, p *Project, isClosed bool) error {
p.IsClosed = isClosed p.IsClosed = isClosed
p.ClosedDateUnix = timeutil.TimeStampNow() p.ClosedDateUnix = timeutil.TimeStampNow()
e := db.GetEngine(ctx) count, err := db.GetEngine(ctx).ID(p.ID).Where("repo_id = ? AND is_closed = ?", p.RepoID, !isClosed).Cols("is_closed", "closed_date_unix").Update(p)
count, err := e.ID(p.ID).Where("repo_id = ? AND is_closed = ?", p.RepoID, !isClosed).Cols("is_closed", "closed_date_unix").Update(p)
if err != nil { if err != nil {
return err return err
} }
@ -302,7 +288,7 @@ func changeProjectStatus(ctx context.Context, p *Project, isClosed bool) error {
return nil return nil
} }
return updateRepositoryProjectCount(e, p.RepoID) return updateRepositoryProjectCount(ctx, p.RepoID)
} }
// DeleteProjectByID deletes a project from a repository. // DeleteProjectByID deletes a project from a repository.
@ -322,8 +308,7 @@ func DeleteProjectByID(id int64) error {
// DeleteProjectByIDCtx deletes a project from a repository. // DeleteProjectByIDCtx deletes a project from a repository.
func DeleteProjectByIDCtx(ctx context.Context, id int64) error { func DeleteProjectByIDCtx(ctx context.Context, id int64) error {
e := db.GetEngine(ctx) p, err := GetProjectByID(ctx, id)
p, err := getProjectByID(e, id)
if err != nil { if err != nil {
if IsErrProjectNotExist(err) { if IsErrProjectNotExist(err) {
return nil return nil
@ -331,17 +316,17 @@ func DeleteProjectByIDCtx(ctx context.Context, id int64) error {
return err return err
} }
if err := deleteProjectIssuesByProjectID(e, id); err != nil { if err := deleteProjectIssuesByProjectID(ctx, id); err != nil {
return err return err
} }
if err := deleteBoardByProjectID(e, id); err != nil { if err := deleteBoardByProjectID(ctx, id); err != nil {
return err return err
} }
if _, err = e.ID(p.ID).Delete(new(Project)); err != nil { if _, err = db.GetEngine(ctx).ID(p.ID).Delete(new(Project)); err != nil {
return err return err
} }
return updateRepositoryProjectCount(e, p.RepoID) return updateRepositoryProjectCount(ctx, p.RepoID)
} }

@ -7,6 +7,7 @@ package project
import ( import (
"testing" "testing"
"code.gitea.io/gitea/models/db"
"code.gitea.io/gitea/models/unittest" "code.gitea.io/gitea/models/unittest"
"code.gitea.io/gitea/modules/timeutil" "code.gitea.io/gitea/modules/timeutil"
@ -34,13 +35,13 @@ func TestIsProjectTypeValid(t *testing.T) {
func TestGetProjects(t *testing.T) { func TestGetProjects(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase()) assert.NoError(t, unittest.PrepareTestDatabase())
projects, _, err := GetProjects(SearchOptions{RepoID: 1}) projects, _, err := GetProjects(db.DefaultContext, SearchOptions{RepoID: 1})
assert.NoError(t, err) assert.NoError(t, err)
// 1 value for this repo exists in the fixtures // 1 value for this repo exists in the fixtures
assert.Len(t, projects, 1) assert.Len(t, projects, 1)
projects, _, err = GetProjects(SearchOptions{RepoID: 3}) projects, _, err = GetProjects(db.DefaultContext, SearchOptions{RepoID: 3})
assert.NoError(t, err) assert.NoError(t, err)
// 1 value for this repo exists in the fixtures // 1 value for this repo exists in the fixtures
@ -61,14 +62,14 @@ func TestProject(t *testing.T) {
assert.NoError(t, NewProject(project)) assert.NoError(t, NewProject(project))
_, err := GetProjectByID(project.ID) _, err := GetProjectByID(db.DefaultContext, project.ID)
assert.NoError(t, err) assert.NoError(t, err)
// Update project // Update project
project.Title = "Updated title" project.Title = "Updated title"
assert.NoError(t, UpdateProject(project)) assert.NoError(t, UpdateProject(db.DefaultContext, project))
projectFromDB, err := GetProjectByID(project.ID) projectFromDB, err := GetProjectByID(db.DefaultContext, project.ID)
assert.NoError(t, err) assert.NoError(t, err)
assert.Equal(t, project.Title, projectFromDB.Title) assert.Equal(t, project.Title, projectFromDB.Title)
@ -76,7 +77,7 @@ func TestProject(t *testing.T) {
assert.NoError(t, ChangeProjectStatus(project, true)) assert.NoError(t, ChangeProjectStatus(project, true))
// Retrieve from DB afresh to check if it is truly closed // Retrieve from DB afresh to check if it is truly closed
projectFromDB, err = GetProjectByID(project.ID) projectFromDB, err = GetProjectByID(db.DefaultContext, project.ID)
assert.NoError(t, err) assert.NoError(t, err)
assert.True(t, projectFromDB.IsClosed) assert.True(t, projectFromDB.IsClosed)

@ -97,22 +97,22 @@ func init() {
db.RegisterModel(new(PullRequest)) db.RegisterModel(new(PullRequest))
} }
func deletePullsByBaseRepoID(sess db.Engine, repoID int64) error { func deletePullsByBaseRepoID(ctx context.Context, repoID int64) error {
deleteCond := builder.Select("id").From("pull_request").Where(builder.Eq{"pull_request.base_repo_id": repoID}) deleteCond := builder.Select("id").From("pull_request").Where(builder.Eq{"pull_request.base_repo_id": repoID})
// Delete scheduled auto merges // Delete scheduled auto merges
if _, err := sess.In("pull_id", deleteCond). if _, err := db.GetEngine(ctx).In("pull_id", deleteCond).
Delete(&pull_model.AutoMerge{}); err != nil { Delete(&pull_model.AutoMerge{}); err != nil {
return err return err
} }
// Delete review states // Delete review states
if _, err := sess.In("pull_id", deleteCond). if _, err := db.GetEngine(ctx).In("pull_id", deleteCond).
Delete(&pull_model.ReviewState{}); err != nil { Delete(&pull_model.ReviewState{}); err != nil {
return err return err
} }
_, err := sess.Delete(&PullRequest{BaseRepoID: repoID}) _, err := db.DeleteByBean(ctx, &PullRequest{BaseRepoID: repoID})
return err return err
} }
@ -133,9 +133,9 @@ func (pr *PullRequest) MustHeadUserName() string {
} }
// Note: don't try to get Issue because will end up recursive querying. // Note: don't try to get Issue because will end up recursive querying.
func (pr *PullRequest) loadAttributes(e db.Engine) (err error) { func (pr *PullRequest) loadAttributes(ctx context.Context) (err error) {
if pr.HasMerged && pr.Merger == nil { if pr.HasMerged && pr.Merger == nil {
pr.Merger, err = user_model.GetUserByIDEngine(e, pr.MergerID) pr.Merger, err = user_model.GetUserByIDCtx(ctx, pr.MergerID)
if user_model.IsErrUserNotExist(err) { if user_model.IsErrUserNotExist(err) {
pr.MergerID = -1 pr.MergerID = -1
pr.Merger = user_model.NewGhostUser() pr.Merger = user_model.NewGhostUser()
@ -149,7 +149,7 @@ func (pr *PullRequest) loadAttributes(e db.Engine) (err error) {
// LoadAttributes loads pull request attributes from database // LoadAttributes loads pull request attributes from database
func (pr *PullRequest) LoadAttributes() error { func (pr *PullRequest) LoadAttributes() error {
return pr.loadAttributes(db.GetEngine(db.DefaultContext)) return pr.loadAttributes(db.DefaultContext)
} }
// LoadHeadRepoCtx loads the head repository // LoadHeadRepoCtx loads the head repository
@ -218,7 +218,7 @@ func (pr *PullRequest) LoadIssueCtx(ctx context.Context) (err error) {
return nil return nil
} }
pr.Issue, err = getIssueByID(db.GetEngine(ctx), pr.IssueID) pr.Issue, err = getIssueByID(ctx, pr.IssueID)
if err == nil { if err == nil {
pr.Issue.PullRequest = pr pr.Issue.PullRequest = pr
} }
@ -242,7 +242,7 @@ func (pr *PullRequest) LoadProtectedBranchCtx(ctx context.Context) (err error) {
return return
} }
} }
pr.ProtectedBranch, err = getProtectedBranchBy(db.GetEngine(ctx), pr.BaseRepo.ID, pr.BaseBranch) pr.ProtectedBranch, err = GetProtectedBranchBy(ctx, pr.BaseRepo.ID, pr.BaseBranch)
} }
return return
} }
@ -256,13 +256,9 @@ type ReviewCount struct {
// GetApprovalCounts returns the approval counts by type // GetApprovalCounts returns the approval counts by type
// FIXME: Only returns official counts due to double counting of non-official counts // FIXME: Only returns official counts due to double counting of non-official counts
func (pr *PullRequest) GetApprovalCounts() ([]*ReviewCount, error) { func (pr *PullRequest) GetApprovalCounts(ctx context.Context) ([]*ReviewCount, error) {
return pr.getApprovalCounts(db.GetEngine(db.DefaultContext))
}
func (pr *PullRequest) getApprovalCounts(e db.Engine) ([]*ReviewCount, error) {
rCounts := make([]*ReviewCount, 0, 6) rCounts := make([]*ReviewCount, 0, 6)
sess := e.Where("issue_id = ?", pr.IssueID) sess := db.GetEngine(ctx).Where("issue_id = ?", pr.IssueID)
return rCounts, sess.Select("issue_id, type, count(id) as `count`").Where("official = ? AND dismissed = ?", true, false).GroupBy("issue_id, type").Table("review").Find(&rCounts) return rCounts, sess.Select("issue_id, type, count(id) as `count`").Where("official = ? AND dismissed = ?", true, false).GroupBy("issue_id, type").Table("review").Find(&rCounts)
} }
@ -289,10 +285,9 @@ func (pr *PullRequest) getReviewedByLines(writer io.Writer) error {
return err return err
} }
defer committer.Close() defer committer.Close()
sess := db.GetEngine(ctx)
// Note: This doesn't page as we only expect a very limited number of reviews // Note: This doesn't page as we only expect a very limited number of reviews
reviews, err := findReviews(sess, FindReviewOptions{ reviews, err := FindReviews(ctx, FindReviewOptions{
Type: ReviewTypeApprove, Type: ReviewTypeApprove,
IssueID: pr.IssueID, IssueID: pr.IssueID,
OfficialOnly: setting.Repository.PullRequest.DefaultMergeMessageOfficialApproversOnly, OfficialOnly: setting.Repository.PullRequest.DefaultMergeMessageOfficialApproversOnly,
@ -309,7 +304,7 @@ func (pr *PullRequest) getReviewedByLines(writer io.Writer) error {
break break
} }
if err := review.loadReviewer(sess); err != nil && !user_model.IsErrUserNotExist(err) { if err := review.loadReviewer(ctx); err != nil && !user_model.IsErrUserNotExist(err) {
log.Error("Unable to LoadReviewer[%d] for PR ID %d : %v", review.ReviewerID, pr.ID, err) log.Error("Unable to LoadReviewer[%d] for PR ID %d : %v", review.ReviewerID, pr.ID, err)
return err return err
} else if review.Reviewer == nil { } else if review.Reviewer == nil {
@ -374,7 +369,7 @@ func (pr *PullRequest) SetMerged(ctx context.Context) (bool, error) {
return false, err return false, err
} }
if tmpPr, err := getPullRequestByID(sess, pr.ID); err != nil { if tmpPr, err := GetPullRequestByID(ctx, pr.ID); err != nil {
return false, err return false, err
} else if tmpPr.HasMerged { } else if tmpPr.HasMerged {
if pr.Issue.IsClosed { if pr.Issue.IsClosed {
@ -484,12 +479,7 @@ func GetLatestPullRequestByHeadInfo(repoID int64, branch string) (*PullRequest,
} }
// GetPullRequestByIndex returns a pull request by the given index // GetPullRequestByIndex returns a pull request by the given index
func GetPullRequestByIndex(repoID, index int64) (*PullRequest, error) { func GetPullRequestByIndex(ctx context.Context, 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 { if index < 1 {
return nil, ErrPullRequestNotExist{} return nil, ErrPullRequestNotExist{}
} }
@ -505,7 +495,7 @@ func GetPullRequestByIndexCtx(ctx context.Context, repoID, index int64) (*PullRe
return nil, ErrPullRequestNotExist{0, 0, 0, repoID, "", ""} return nil, ErrPullRequestNotExist{0, 0, 0, repoID, "", ""}
} }
if err = pr.loadAttributes(db.GetEngine(ctx)); err != nil { if err = pr.loadAttributes(ctx); err != nil {
return nil, err return nil, err
} }
if err = pr.LoadIssueCtx(ctx); err != nil { if err = pr.LoadIssueCtx(ctx); err != nil {
@ -515,20 +505,16 @@ func GetPullRequestByIndexCtx(ctx context.Context, repoID, index int64) (*PullRe
return pr, nil return pr, nil
} }
func getPullRequestByID(e db.Engine, id int64) (*PullRequest, error) { // GetPullRequestByID returns a pull request by given ID.
func GetPullRequestByID(ctx context.Context, id int64) (*PullRequest, error) {
pr := new(PullRequest) pr := new(PullRequest)
has, err := e.ID(id).Get(pr) has, err := db.GetEngine(ctx).ID(id).Get(pr)
if err != nil { if err != nil {
return nil, err return nil, err
} else if !has { } else if !has {
return nil, ErrPullRequestNotExist{id, 0, 0, 0, "", ""} return nil, ErrPullRequestNotExist{id, 0, 0, 0, "", ""}
} }
return pr, pr.loadAttributes(e) return pr, pr.loadAttributes(ctx)
}
// GetPullRequestByID returns a pull request by given 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. // GetPullRequestByIssueIDWithNoAttributes returns pull request with no attributes loaded by given issue ID.
@ -544,17 +530,18 @@ func GetPullRequestByIssueIDWithNoAttributes(issueID int64) (*PullRequest, error
return &pr, nil return &pr, nil
} }
func getPullRequestByIssueID(e db.Engine, issueID int64) (*PullRequest, error) { // GetPullRequestByIssueID returns pull request by given issue ID.
func GetPullRequestByIssueID(ctx context.Context, issueID int64) (*PullRequest, error) {
pr := &PullRequest{ pr := &PullRequest{
IssueID: issueID, IssueID: issueID,
} }
has, err := e.Get(pr) has, err := db.GetByBean(ctx, pr)
if err != nil { if err != nil {
return nil, err return nil, err
} else if !has { } else if !has {
return nil, ErrPullRequestNotExist{0, issueID, 0, 0, "", ""} return nil, ErrPullRequestNotExist{0, issueID, 0, 0, "", ""}
} }
return pr, pr.loadAttributes(e) return pr, pr.loadAttributes(ctx)
} }
// GetAllUnmergedAgitPullRequestByPoster get all unmerged agit flow pull request // GetAllUnmergedAgitPullRequestByPoster get all unmerged agit flow pull request
@ -571,11 +558,6 @@ func GetAllUnmergedAgitPullRequestByPoster(uid int64) ([]*PullRequest, error) {
return pulls, err return pulls, err
} }
// GetPullRequestByIssueID returns pull request by given issue ID.
func GetPullRequestByIssueID(issueID int64) (*PullRequest, error) {
return getPullRequestByIssueID(db.GetEngine(db.DefaultContext), issueID)
}
// Update updates all fields of pull request. // Update updates all fields of pull request.
func (pr *PullRequest) Update() error { func (pr *PullRequest) Update() error {
_, err := db.GetEngine(db.DefaultContext).ID(pr.ID).AllCols().Update(pr) _, err := db.GetEngine(db.DefaultContext).ID(pr.ID).AllCols().Update(pr)
@ -635,17 +617,13 @@ func (pr *PullRequest) GetWorkInProgressPrefix() string {
} }
// UpdateCommitDivergence update Divergence of a pull request // UpdateCommitDivergence update Divergence of a pull request
func (pr *PullRequest) UpdateCommitDivergence(ahead, behind int) error { func (pr *PullRequest) UpdateCommitDivergence(ctx context.Context, ahead, behind int) error {
return pr.updateCommitDivergence(db.GetEngine(db.DefaultContext), ahead, behind)
}
func (pr *PullRequest) updateCommitDivergence(e db.Engine, ahead, behind int) error {
if pr.ID == 0 { if pr.ID == 0 {
return fmt.Errorf("pull ID is 0") return fmt.Errorf("pull ID is 0")
} }
pr.CommitsAhead = ahead pr.CommitsAhead = ahead
pr.CommitsBehind = behind pr.CommitsBehind = behind
_, err := e.ID(pr.ID).Cols("commits_ahead", "commits_behind").Update(pr) _, err := db.GetEngine(ctx).ID(pr.ID).Cols("commits_ahead", "commits_behind").Update(pr)
return err return err
} }

@ -156,7 +156,7 @@ func PullRequests(baseRepoID int64, opts *PullRequestsOptions) ([]*PullRequest,
// PullRequestList defines a list of pull requests // PullRequestList defines a list of pull requests
type PullRequestList []*PullRequest type PullRequestList []*PullRequest
func (prs PullRequestList) loadAttributes(e db.Engine) error { func (prs PullRequestList) loadAttributes(ctx context.Context) error {
if len(prs) == 0 { if len(prs) == 0 {
return nil return nil
} }
@ -164,7 +164,7 @@ func (prs PullRequestList) loadAttributes(e db.Engine) error {
// Load issues. // Load issues.
issueIDs := prs.getIssueIDs() issueIDs := prs.getIssueIDs()
issues := make([]*Issue, 0, len(issueIDs)) issues := make([]*Issue, 0, len(issueIDs))
if err := e. if err := db.GetEngine(ctx).
Where("id > 0"). Where("id > 0").
In("id", issueIDs). In("id", issueIDs).
Find(&issues); err != nil { Find(&issues); err != nil {
@ -191,7 +191,7 @@ func (prs PullRequestList) getIssueIDs() []int64 {
// LoadAttributes load all the prs attributes // LoadAttributes load all the prs attributes
func (prs PullRequestList) LoadAttributes() error { func (prs PullRequestList) LoadAttributes() error {
return prs.loadAttributes(db.GetEngine(db.DefaultContext)) return prs.loadAttributes(db.DefaultContext)
} }
// InvalidateCodeComments will lookup the prs for code comments which got invalidated by change // InvalidateCodeComments will lookup the prs for code comments which got invalidated by change

@ -140,16 +140,16 @@ func TestGetUnmergedPullRequestsByBaseInfo(t *testing.T) {
func TestGetPullRequestByIndex(t *testing.T) { func TestGetPullRequestByIndex(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase()) assert.NoError(t, unittest.PrepareTestDatabase())
pr, err := GetPullRequestByIndex(1, 2) pr, err := GetPullRequestByIndex(db.DefaultContext, 1, 2)
assert.NoError(t, err) assert.NoError(t, err)
assert.Equal(t, int64(1), pr.BaseRepoID) assert.Equal(t, int64(1), pr.BaseRepoID)
assert.Equal(t, int64(2), pr.Index) assert.Equal(t, int64(2), pr.Index)
_, err = GetPullRequestByIndex(9223372036854775807, 9223372036854775807) _, err = GetPullRequestByIndex(db.DefaultContext, 9223372036854775807, 9223372036854775807)
assert.Error(t, err) assert.Error(t, err)
assert.True(t, IsErrPullRequestNotExist(err)) assert.True(t, IsErrPullRequestNotExist(err))
_, err = GetPullRequestByIndex(1, 0) _, err = GetPullRequestByIndex(db.DefaultContext, 1, 0)
assert.Error(t, err) assert.Error(t, err)
assert.True(t, IsErrPullRequestNotExist(err)) assert.True(t, IsErrPullRequestNotExist(err))
} }
@ -168,11 +168,11 @@ func TestGetPullRequestByID(t *testing.T) {
func TestGetPullRequestByIssueID(t *testing.T) { func TestGetPullRequestByIssueID(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase()) assert.NoError(t, unittest.PrepareTestDatabase())
pr, err := GetPullRequestByIssueID(2) pr, err := GetPullRequestByIssueID(db.DefaultContext, 2)
assert.NoError(t, err) assert.NoError(t, err)
assert.Equal(t, int64(2), pr.IssueID) assert.Equal(t, int64(2), pr.IssueID)
_, err = GetPullRequestByIssueID(9223372036854775807) _, err = GetPullRequestByIssueID(db.DefaultContext, 9223372036854775807)
assert.Error(t, err) assert.Error(t, err)
assert.True(t, IsErrPullRequestNotExist(err)) assert.True(t, IsErrPullRequestNotExist(err))
} }

@ -52,7 +52,7 @@ func init() {
db.RegisterModel(new(Release)) db.RegisterModel(new(Release))
} }
func (r *Release) loadAttributes(e db.Engine) error { func (r *Release) loadAttributes(ctx context.Context) error {
var err error var err error
if r.Repo == nil { if r.Repo == nil {
r.Repo, err = repo_model.GetRepositoryByID(r.RepoID) r.Repo, err = repo_model.GetRepositoryByID(r.RepoID)
@ -61,7 +61,7 @@ func (r *Release) loadAttributes(e db.Engine) error {
} }
} }
if r.Publisher == nil { if r.Publisher == nil {
r.Publisher, err = user_model.GetUserByIDEngine(e, r.PublisherID) r.Publisher, err = user_model.GetUserByIDCtx(ctx, r.PublisherID)
if err != nil { if err != nil {
if user_model.IsErrUserNotExist(err) { if user_model.IsErrUserNotExist(err) {
r.Publisher = user_model.NewGhostUser() r.Publisher = user_model.NewGhostUser()
@ -70,12 +70,12 @@ func (r *Release) loadAttributes(e db.Engine) error {
} }
} }
} }
return getReleaseAttachments(e, r) return GetReleaseAttachments(ctx, r)
} }
// LoadAttributes load repo and publisher attributes for a release // LoadAttributes load repo and publisher attributes for a release
func (r *Release) LoadAttributes() error { func (r *Release) LoadAttributes() error {
return r.loadAttributes(db.GetEngine(db.DefaultContext)) return r.loadAttributes(db.DefaultContext)
} }
// APIURL the api url for a release. release must have attributes loaded // APIURL the api url for a release. release must have attributes loaded
@ -282,11 +282,7 @@ func (s releaseMetaSearch) Less(i, j int) bool {
} }
// GetReleaseAttachments retrieves the attachments for releases // GetReleaseAttachments retrieves the attachments for releases
func GetReleaseAttachments(rels ...*Release) (err error) { func GetReleaseAttachments(ctx context.Context, rels ...*Release) (err error) {
return getReleaseAttachments(db.GetEngine(db.DefaultContext), rels...)
}
func getReleaseAttachments(e db.Engine, rels ...*Release) (err error) {
if len(rels) == 0 { if len(rels) == 0 {
return return
} }
@ -306,7 +302,7 @@ func getReleaseAttachments(e db.Engine, rels ...*Release) (err error) {
sort.Sort(sortedRels) sort.Sort(sortedRels)
// Select attachments // Select attachments
err = e. err = db.GetEngine(ctx).
Asc("release_id", "name"). Asc("release_id", "name").
In("release_id", sortedRels.ID). In("release_id", sortedRels.ID).
Find(&attachments, repo_model.Attachment{}) Find(&attachments, repo_model.Attachment{})
@ -373,10 +369,6 @@ func UpdateReleasesMigrationsByType(gitServiceType structs.GitServiceType, origi
// PushUpdateDeleteTagsContext updates a number of delete tags with context // PushUpdateDeleteTagsContext updates a number of delete tags with context
func PushUpdateDeleteTagsContext(ctx context.Context, repo *repo_model.Repository, tags []string) error { func PushUpdateDeleteTagsContext(ctx context.Context, repo *repo_model.Repository, tags []string) error {
return pushUpdateDeleteTags(db.GetEngine(ctx), repo, tags)
}
func pushUpdateDeleteTags(e db.Engine, repo *repo_model.Repository, tags []string) error {
if len(tags) == 0 { if len(tags) == 0 {
return nil return nil
} }
@ -385,14 +377,14 @@ func pushUpdateDeleteTags(e db.Engine, repo *repo_model.Repository, tags []strin
lowerTags = append(lowerTags, strings.ToLower(tag)) lowerTags = append(lowerTags, strings.ToLower(tag))
} }
if _, err := e. if _, err := db.GetEngine(ctx).
Where("repo_id = ? AND is_tag = ?", repo.ID, true). Where("repo_id = ? AND is_tag = ?", repo.ID, true).
In("lower_tag_name", lowerTags). In("lower_tag_name", lowerTags).
Delete(new(Release)); err != nil { Delete(new(Release)); err != nil {
return fmt.Errorf("Delete: %v", err) return fmt.Errorf("Delete: %v", err)
} }
if _, err := e. if _, err := db.GetEngine(ctx).
Where("repo_id = ? AND is_tag = ?", repo.ID, false). Where("repo_id = ? AND is_tag = ?", repo.ID, false).
In("lower_tag_name", lowerTags). In("lower_tag_name", lowerTags).
Cols("is_draft", "num_commits", "sha1"). Cols("is_draft", "num_commits", "sha1").

@ -204,27 +204,23 @@ func GetReviewerTeams(repo *repo_model.Repository) ([]*organization.Team, error)
return teams, err return teams, err
} }
func updateRepoSize(e db.Engine, repo *repo_model.Repository) error { // UpdateRepoSize updates the repository size, calculating it using util.GetDirectorySize
func UpdateRepoSize(ctx context.Context, repo *repo_model.Repository) error {
size, err := util.GetDirectorySize(repo.RepoPath()) size, err := util.GetDirectorySize(repo.RepoPath())
if err != nil { if err != nil {
return fmt.Errorf("updateSize: %v", err) return fmt.Errorf("updateSize: %v", err)
} }
lfsSize, err := e.Where("repository_id = ?", repo.ID).SumInt(new(LFSMetaObject), "size") lfsSize, err := db.GetEngine(ctx).Where("repository_id = ?", repo.ID).SumInt(new(LFSMetaObject), "size")
if err != nil { if err != nil {
return fmt.Errorf("updateSize: GetLFSMetaObjects: %v", err) return fmt.Errorf("updateSize: GetLFSMetaObjects: %v", err)
} }
repo.Size = size + lfsSize repo.Size = size + lfsSize
_, err = e.ID(repo.ID).Cols("size").NoAutoTime().Update(repo) _, err = db.GetEngine(ctx).ID(repo.ID).Cols("size").NoAutoTime().Update(repo)
return err return err
} }
// UpdateRepoSize updates the repository size, calculating it using util.GetDirectorySize
func UpdateRepoSize(ctx context.Context, repo *repo_model.Repository) error {
return updateRepoSize(db.GetEngine(ctx), repo)
}
// CanUserForkRepo returns true if specified user can fork repository. // CanUserForkRepo returns true if specified user can fork repository.
func CanUserForkRepo(user *user_model.User, repo *repo_model.Repository) (bool, error) { func CanUserForkRepo(user *user_model.User, repo *repo_model.Repository) (bool, error) {
if user == nil { if user == nil {
@ -303,11 +299,6 @@ func CanUserDelete(repo *repo_model.Repository, user *user_model.User) (bool, er
return false, nil return false, nil
} }
// SetRepoReadBy sets repo to be visited by given user.
func SetRepoReadBy(repoID, userID int64) error {
return setRepoNotificationStatusReadIfUnread(db.GetEngine(db.DefaultContext), userID, repoID)
}
// CreateRepoOptions contains the create repository options // CreateRepoOptions contains the create repository options
type CreateRepoOptions struct { type CreateRepoOptions struct {
Name string Name string
@ -334,7 +325,7 @@ func CreateRepository(ctx context.Context, doer, u *user_model.User, repo *repo_
return err return err
} }
has, err := repo_model.IsRepositoryExistCtx(ctx, u, repo.Name) has, err := repo_model.IsRepositoryExist(ctx, u, repo.Name)
if err != nil { if err != nil {
return fmt.Errorf("IsRepositoryExist: %v", err) return fmt.Errorf("IsRepositoryExist: %v", err)
} else if has { } else if has {
@ -398,7 +389,7 @@ func CreateRepository(ctx context.Context, doer, u *user_model.User, repo *repo_
// Remember visibility preference. // Remember visibility preference.
u.LastRepoVisibility = repo.IsPrivate u.LastRepoVisibility = repo.IsPrivate
if err = user_model.UpdateUserColsEngine(db.GetEngine(ctx), u, "last_repo_visibility"); err != nil { if err = user_model.UpdateUserCols(ctx, u, "last_repo_visibility"); err != nil {
return fmt.Errorf("updateUser: %v", err) return fmt.Errorf("updateUser: %v", err)
} }
@ -421,7 +412,7 @@ func CreateRepository(ctx context.Context, doer, u *user_model.User, repo *repo_
} }
} }
if isAdmin, err := access_model.IsUserRepoAdminCtx(ctx, repo, doer); err != nil { if isAdmin, err := access_model.IsUserRepoAdmin(ctx, repo, doer); err != nil {
return fmt.Errorf("IsUserRepoAdminCtx: %v", err) return fmt.Errorf("IsUserRepoAdminCtx: %v", err)
} else if !isAdmin { } else if !isAdmin {
// Make creator repo admin if it wasn't assigned automatically // Make creator repo admin if it wasn't assigned automatically
@ -438,7 +429,7 @@ func CreateRepository(ctx context.Context, doer, u *user_model.User, repo *repo_
} }
if setting.Service.AutoWatchNewRepos { if setting.Service.AutoWatchNewRepos {
if err = repo_model.WatchRepoCtx(ctx, doer.ID, repo.ID, true); err != nil { if err = repo_model.WatchRepo(ctx, doer.ID, repo.ID, true); err != nil {
return fmt.Errorf("watchRepo: %v", err) return fmt.Errorf("watchRepo: %v", err)
} }
} }
@ -510,7 +501,7 @@ func UpdateRepositoryCtx(ctx context.Context, repo *repo_model.Repository, visib
return fmt.Errorf("update: %v", err) return fmt.Errorf("update: %v", err)
} }
if err = updateRepoSize(e, repo); err != nil { if err = UpdateRepoSize(ctx, repo); err != nil {
log.Error("Failed to update size for repository: %v", err) log.Error("Failed to update size for repository: %v", err)
} }
@ -536,13 +527,13 @@ func UpdateRepositoryCtx(ctx context.Context, repo *repo_model.Repository, visib
} }
// Create/Remove git-daemon-export-ok for git-daemon... // Create/Remove git-daemon-export-ok for git-daemon...
if err := CheckDaemonExportOK(db.WithEngine(ctx, e), repo); err != nil { if err := CheckDaemonExportOK(ctx, repo); err != nil {
return err return err
} }
forkRepos, err := repo_model.GetRepositoriesByForkID(ctx, repo.ID) forkRepos, err := repo_model.GetRepositoriesByForkID(ctx, repo.ID)
if err != nil { if err != nil {
return fmt.Errorf("getRepositoriesByForkID: %v", err) return fmt.Errorf("GetRepositoriesByForkID: %v", err)
} }
for i := range forkRepos { for i := range forkRepos {
forkRepos[i].IsPrivate = repo.IsPrivate || repo.Owner.Visibility == api.VisibleTypePrivate forkRepos[i].IsPrivate = repo.IsPrivate || repo.Owner.Visibility == api.VisibleTypePrivate
@ -581,7 +572,7 @@ func DeleteRepository(doer *user_model.User, uid, repoID int64) error {
sess := db.GetEngine(ctx) sess := db.GetEngine(ctx)
// In case is a organization. // In case is a organization.
org, err := user_model.GetUserByIDEngine(sess, uid) org, err := user_model.GetUserByIDCtx(ctx, uid)
if err != nil { if err != nil {
return err return err
} }
@ -647,7 +638,7 @@ func DeleteRepository(doer *user_model.User, uid, repoID int64) error {
releaseAttachments = append(releaseAttachments, attachments[i].RelativePath()) releaseAttachments = append(releaseAttachments, attachments[i].RelativePath())
} }
if _, err := sess.Exec("UPDATE `user` SET num_stars=num_stars-1 WHERE id IN (SELECT `uid` FROM `star` WHERE repo_id = ?)", repo.ID); err != nil { if _, err := db.Exec(ctx, "UPDATE `user` SET num_stars=num_stars-1 WHERE id IN (SELECT `uid` FROM `star` WHERE repo_id = ?)", repo.ID); err != nil {
return err return err
} }
@ -680,33 +671,33 @@ func DeleteRepository(doer *user_model.User, uid, repoID int64) error {
} }
// Delete Labels and related objects // Delete Labels and related objects
if err := deleteLabelsByRepoID(sess, repoID); err != nil { if err := deleteLabelsByRepoID(ctx, repoID); err != nil {
return err return err
} }
// Delete Pulls and related objects // Delete Pulls and related objects
if err := deletePullsByBaseRepoID(sess, repoID); err != nil { if err := deletePullsByBaseRepoID(ctx, repoID); err != nil {
return err return err
} }
// Delete Issues and related objects // Delete Issues and related objects
var attachmentPaths []string var attachmentPaths []string
if attachmentPaths, err = deleteIssuesByRepoID(sess, repoID); err != nil { if attachmentPaths, err = deleteIssuesByRepoID(ctx, repoID); err != nil {
return err return err
} }
// Delete issue index // Delete issue index
if err := db.DeleteResouceIndex(sess, "issue_index", repoID); err != nil { if err := db.DeleteResouceIndex(ctx, "issue_index", repoID); err != nil {
return err return err
} }
if repo.IsFork { if repo.IsFork {
if _, err := sess.Exec("UPDATE `repository` SET num_forks=num_forks-1 WHERE id=?", repo.ForkID); err != nil { if _, err := db.Exec(ctx, "UPDATE `repository` SET num_forks=num_forks-1 WHERE id=?", repo.ForkID); err != nil {
return fmt.Errorf("decrease fork count: %v", err) return fmt.Errorf("decrease fork count: %v", err)
} }
} }
if _, err := sess.Exec("UPDATE `user` SET num_repos=num_repos-1 WHERE id=?", uid); err != nil { if _, err := db.Exec(ctx, "UPDATE `user` SET num_repos=num_repos-1 WHERE id=?", uid); err != nil {
return err return err
} }
@ -716,7 +707,7 @@ func DeleteRepository(doer *user_model.User, uid, repoID int64) error {
} }
} }
projects, _, err := project_model.GetProjectsCtx(ctx, project_model.SearchOptions{ projects, _, err := project_model.GetProjects(ctx, project_model.SearchOptions{
RepoID: repoID, RepoID: repoID,
}) })
if err != nil { if err != nil {
@ -736,7 +727,7 @@ func DeleteRepository(doer *user_model.User, uid, repoID int64) error {
lfsPaths := make([]string, 0, len(lfsObjects)) lfsPaths := make([]string, 0, len(lfsObjects))
for _, v := range lfsObjects { for _, v := range lfsObjects {
count, err := sess.Count(&LFSMetaObject{Pointer: lfs.Pointer{Oid: v.Oid}}) count, err := db.CountByBean(ctx, &LFSMetaObject{Pointer: lfs.Pointer{Oid: v.Oid}})
if err != nil { if err != nil {
return err return err
} }
@ -747,7 +738,7 @@ func DeleteRepository(doer *user_model.User, uid, repoID int64) error {
lfsPaths = append(lfsPaths, v.RelativePath()) lfsPaths = append(lfsPaths, v.RelativePath())
} }
if _, err := sess.Delete(&LFSMetaObject{RepositoryID: repoID}); err != nil { if _, err := db.DeleteByBean(ctx, &LFSMetaObject{RepositoryID: repoID}); err != nil {
return err return err
} }
@ -763,7 +754,7 @@ func DeleteRepository(doer *user_model.User, uid, repoID int64) error {
archivePaths = append(archivePaths, p) archivePaths = append(archivePaths, p)
} }
if _, err := sess.Delete(&repo_model.RepoArchiver{RepoID: repoID}); err != nil { if _, err := db.DeleteByBean(ctx, &repo_model.RepoArchiver{RepoID: repoID}); err != nil {
return err return err
} }
@ -1181,7 +1172,7 @@ func DeleteDeployKey(ctx context.Context, doer *user_model.User, id int64) error
if err != nil { if err != nil {
return fmt.Errorf("GetRepositoryByID: %v", err) return fmt.Errorf("GetRepositoryByID: %v", err)
} }
has, err := access_model.IsUserRepoAdminCtx(ctx, repo, doer) has, err := access_model.IsUserRepoAdmin(ctx, repo, doer)
if err != nil { if err != nil {
return fmt.Errorf("GetUserRepoPermission: %v", err) return fmt.Errorf("GetUserRepoPermission: %v", err)
} else if !has { } else if !has {

@ -60,11 +60,6 @@ func (a *Attachment) DownloadURL() string {
return setting.AppURL + "attachments/" + url.PathEscape(a.UUID) return setting.AppURL + "attachments/" + url.PathEscape(a.UUID)
} }
// GetAttachmentByID returns attachment by given id
func GetAttachmentByID(id int64) (*Attachment, error) {
return getAttachmentByID(db.GetEngine(db.DefaultContext), id)
}
// _____ __ __ .__ __ // _____ __ __ .__ __
// / _ \_/ |__/ |______ ____ | |__ _____ ____ _____/ |_ // / _ \_/ |__/ |______ ____ | |__ _____ ____ _____/ |_
// / /_\ \ __\ __\__ \ _/ ___\| | \ / \_/ __ \ / \ __\ // / /_\ \ __\ __\__ \ _/ ___\| | \ / \_/ __ \ / \ __\
@ -88,9 +83,10 @@ func (err ErrAttachmentNotExist) Error() string {
return fmt.Sprintf("attachment does not exist [id: %d, uuid: %s]", err.ID, err.UUID) return fmt.Sprintf("attachment does not exist [id: %d, uuid: %s]", err.ID, err.UUID)
} }
func getAttachmentByID(e db.Engine, id int64) (*Attachment, error) { // GetAttachmentByID returns attachment by given id
func GetAttachmentByID(ctx context.Context, id int64) (*Attachment, error) {
attach := &Attachment{} attach := &Attachment{}
if has, err := e.ID(id).Get(attach); err != nil { if has, err := db.GetEngine(ctx).ID(id).Get(attach); err != nil {
return nil, err return nil, err
} else if !has { } else if !has {
return nil, ErrAttachmentNotExist{ID: id, UUID: ""} return nil, ErrAttachmentNotExist{ID: id, UUID: ""}
@ -98,9 +94,10 @@ func getAttachmentByID(e db.Engine, id int64) (*Attachment, error) {
return attach, nil return attach, nil
} }
func getAttachmentByUUID(e db.Engine, uuid string) (*Attachment, error) { // GetAttachmentByUUID returns attachment by given UUID.
func GetAttachmentByUUID(ctx context.Context, uuid string) (*Attachment, error) {
attach := &Attachment{} attach := &Attachment{}
has, err := e.Where("uuid=?", uuid).Get(attach) has, err := db.GetEngine(ctx).Where("uuid=?", uuid).Get(attach)
if err != nil { if err != nil {
return nil, err return nil, err
} else if !has { } else if !has {
@ -111,22 +108,13 @@ func getAttachmentByUUID(e db.Engine, uuid string) (*Attachment, error) {
// GetAttachmentsByUUIDs returns attachment by given UUID list. // GetAttachmentsByUUIDs returns attachment by given UUID list.
func GetAttachmentsByUUIDs(ctx context.Context, uuids []string) ([]*Attachment, error) { func GetAttachmentsByUUIDs(ctx context.Context, uuids []string) ([]*Attachment, error) {
return getAttachmentsByUUIDs(db.GetEngine(ctx), uuids)
}
func getAttachmentsByUUIDs(e db.Engine, uuids []string) ([]*Attachment, error) {
if len(uuids) == 0 { if len(uuids) == 0 {
return []*Attachment{}, nil return []*Attachment{}, nil
} }
// Silently drop invalid uuids. // Silently drop invalid uuids.
attachments := make([]*Attachment, 0, len(uuids)) attachments := make([]*Attachment, 0, len(uuids))
return attachments, e.In("uuid", uuids).Find(&attachments) return attachments, db.GetEngine(ctx).In("uuid", uuids).Find(&attachments)
}
// GetAttachmentByUUID returns attachment by given UUID.
func GetAttachmentByUUID(uuid string) (*Attachment, error) {
return getAttachmentByUUID(db.GetEngine(db.DefaultContext), uuid)
} }
// ExistAttachmentsByUUID returns true if attachment is exist by given UUID // ExistAttachmentsByUUID returns true if attachment is exist by given UUID
@ -134,37 +122,22 @@ func ExistAttachmentsByUUID(uuid string) (bool, error) {
return db.GetEngine(db.DefaultContext).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. // GetAttachmentsByIssueID returns all attachments of an issue.
func GetAttachmentByReleaseIDFileName(releaseID int64, fileName string) (*Attachment, error) { func GetAttachmentsByIssueID(ctx context.Context, issueID int64) ([]*Attachment, error) {
return getAttachmentByReleaseIDFileName(db.GetEngine(db.DefaultContext), releaseID, fileName)
}
// GetAttachmentsByIssueIDCtx returns all attachments of an issue.
func GetAttachmentsByIssueIDCtx(ctx context.Context, issueID int64) ([]*Attachment, error) {
attachments := make([]*Attachment, 0, 10) attachments := make([]*Attachment, 0, 10)
return attachments, db.GetEngine(ctx).Where("issue_id = ? AND comment_id = 0", issueID).Find(&attachments) return attachments, db.GetEngine(ctx).Where("issue_id = ? AND comment_id = 0", issueID).Find(&attachments)
} }
// GetAttachmentsByIssueID returns all attachments of an issue.
func GetAttachmentsByIssueID(issueID int64) ([]*Attachment, error) {
return GetAttachmentsByIssueIDCtx(db.DefaultContext, issueID)
}
// GetAttachmentsByCommentID returns all attachments if comment by given ID. // GetAttachmentsByCommentID returns all attachments if comment by given ID.
func GetAttachmentsByCommentID(commentID int64) ([]*Attachment, error) { func GetAttachmentsByCommentID(ctx context.Context, commentID int64) ([]*Attachment, error) {
return GetAttachmentsByCommentIDCtx(db.DefaultContext, commentID)
}
// GetAttachmentsByCommentIDCtx returns all attachments if comment by given ID.
func GetAttachmentsByCommentIDCtx(ctx context.Context, commentID int64) ([]*Attachment, error) {
attachments := make([]*Attachment, 0, 10) attachments := make([]*Attachment, 0, 10)
return attachments, db.GetEngine(ctx).Where("comment_id=?", commentID).Find(&attachments) return attachments, db.GetEngine(ctx).Where("comment_id=?", commentID).Find(&attachments)
} }
// getAttachmentByReleaseIDFileName return a file based on the the following infos: // GetAttachmentByReleaseIDFileName returns attachment by given releaseId and fileName.
func getAttachmentByReleaseIDFileName(e db.Engine, releaseID int64, fileName string) (*Attachment, error) { func GetAttachmentByReleaseIDFileName(ctx context.Context, releaseID int64, fileName string) (*Attachment, error) {
attach := &Attachment{ReleaseID: releaseID, Name: fileName} attach := &Attachment{ReleaseID: releaseID, Name: fileName}
has, err := e.Get(attach) has, err := db.GetEngine(ctx).Get(attach)
if err != nil { if err != nil {
return nil, err return nil, err
} else if !has { } else if !has {
@ -207,7 +180,7 @@ func DeleteAttachments(ctx context.Context, attachments []*Attachment, remove bo
// DeleteAttachmentsByIssue deletes all attachments associated with the given issue. // DeleteAttachmentsByIssue deletes all attachments associated with the given issue.
func DeleteAttachmentsByIssue(issueID int64, remove bool) (int, error) { func DeleteAttachmentsByIssue(issueID int64, remove bool) (int, error) {
attachments, err := GetAttachmentsByIssueID(issueID) attachments, err := GetAttachmentsByIssueID(db.DefaultContext, issueID)
if err != nil { if err != nil {
return 0, err return 0, err
} }
@ -217,7 +190,7 @@ func DeleteAttachmentsByIssue(issueID int64, remove bool) (int, error) {
// DeleteAttachmentsByComment deletes all attachments associated with the given comment. // DeleteAttachmentsByComment deletes all attachments associated with the given comment.
func DeleteAttachmentsByComment(commentID int64, remove bool) (int, error) { func DeleteAttachmentsByComment(commentID int64, remove bool) (int, error) {
attachments, err := GetAttachmentsByCommentID(commentID) attachments, err := GetAttachmentsByCommentID(db.DefaultContext, commentID)
if err != nil { if err != nil {
return 0, err return 0, err
} }
@ -225,11 +198,6 @@ func DeleteAttachmentsByComment(commentID int64, remove bool) (int, error) {
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 UpdateAttachmentCtx(db.DefaultContext, atta)
}
// UpdateAttachmentByUUID Updates attachment via uuid // UpdateAttachmentByUUID Updates attachment via uuid
func UpdateAttachmentByUUID(ctx context.Context, attach *Attachment, cols ...string) error { func UpdateAttachmentByUUID(ctx context.Context, attach *Attachment, cols ...string) error {
if attach.UUID == "" { if attach.UUID == "" {
@ -239,8 +207,8 @@ func UpdateAttachmentByUUID(ctx context.Context, attach *Attachment, cols ...str
return err return err
} }
// UpdateAttachmentCtx updates the given attachment in database // UpdateAttachment updates the given attachment in database
func UpdateAttachmentCtx(ctx context.Context, atta *Attachment) error { func UpdateAttachment(ctx context.Context, atta *Attachment) error {
sess := db.GetEngine(ctx).Cols("name", "issue_id", "release_id", "comment_id", "download_count") sess := db.GetEngine(ctx).Cols("name", "issue_id", "release_id", "comment_id", "download_count")
if atta.ID != 0 && atta.UUID == "" { if atta.ID != 0 && atta.UUID == "" {
sess = sess.ID(atta.ID) sess = sess.ID(atta.ID)

@ -16,7 +16,7 @@ import (
func TestIncreaseDownloadCount(t *testing.T) { func TestIncreaseDownloadCount(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase()) assert.NoError(t, unittest.PrepareTestDatabase())
attachment, err := GetAttachmentByUUID("a0eebc99-9c0b-4ef8-bb6d-6bb9bd380a11") attachment, err := GetAttachmentByUUID(db.DefaultContext, "a0eebc99-9c0b-4ef8-bb6d-6bb9bd380a11")
assert.NoError(t, err) assert.NoError(t, err)
assert.Equal(t, int64(0), attachment.DownloadCount) assert.Equal(t, int64(0), attachment.DownloadCount)
@ -24,7 +24,7 @@ func TestIncreaseDownloadCount(t *testing.T) {
err = attachment.IncreaseDownloadCount() err = attachment.IncreaseDownloadCount()
assert.NoError(t, err) assert.NoError(t, err)
attachment, err = GetAttachmentByUUID("a0eebc99-9c0b-4ef8-bb6d-6bb9bd380a11") attachment, err = GetAttachmentByUUID(db.DefaultContext, "a0eebc99-9c0b-4ef8-bb6d-6bb9bd380a11")
assert.NoError(t, err) assert.NoError(t, err)
assert.Equal(t, int64(1), attachment.DownloadCount) assert.Equal(t, int64(1), attachment.DownloadCount)
} }
@ -33,11 +33,11 @@ func TestGetByCommentOrIssueID(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase()) assert.NoError(t, unittest.PrepareTestDatabase())
// count of attachments from issue ID // count of attachments from issue ID
attachments, err := GetAttachmentsByIssueID(1) attachments, err := GetAttachmentsByIssueID(db.DefaultContext, 1)
assert.NoError(t, err) assert.NoError(t, err)
assert.Len(t, attachments, 1) assert.Len(t, attachments, 1)
attachments, err = GetAttachmentsByCommentID(1) attachments, err = GetAttachmentsByCommentID(db.DefaultContext, 1)
assert.NoError(t, err) assert.NoError(t, err)
assert.Len(t, attachments, 2) assert.Len(t, attachments, 2)
} }
@ -56,7 +56,7 @@ func TestDeleteAttachments(t *testing.T) {
err = DeleteAttachment(&Attachment{ID: 8}, false) err = DeleteAttachment(&Attachment{ID: 8}, false)
assert.NoError(t, err) assert.NoError(t, err)
attachment, err := GetAttachmentByUUID("a0eebc99-9c0b-4ef8-bb6d-6bb9bd380a18") attachment, err := GetAttachmentByUUID(db.DefaultContext, "a0eebc99-9c0b-4ef8-bb6d-6bb9bd380a18")
assert.Error(t, err) assert.Error(t, err)
assert.True(t, IsErrAttachmentNotExist(err)) assert.True(t, IsErrAttachmentNotExist(err))
assert.Nil(t, attachment) assert.Nil(t, attachment)
@ -65,7 +65,7 @@ func TestDeleteAttachments(t *testing.T) {
func TestGetAttachmentByID(t *testing.T) { func TestGetAttachmentByID(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase()) assert.NoError(t, unittest.PrepareTestDatabase())
attach, err := GetAttachmentByID(1) attach, err := GetAttachmentByID(db.DefaultContext, 1)
assert.NoError(t, err) assert.NoError(t, err)
assert.Equal(t, "a0eebc99-9c0b-4ef8-bb6d-6bb9bd380a11", attach.UUID) assert.Equal(t, "a0eebc99-9c0b-4ef8-bb6d-6bb9bd380a11", attach.UUID)
} }
@ -81,12 +81,12 @@ func TestAttachment_DownloadURL(t *testing.T) {
func TestUpdateAttachment(t *testing.T) { func TestUpdateAttachment(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase()) assert.NoError(t, unittest.PrepareTestDatabase())
attach, err := GetAttachmentByID(1) attach, err := GetAttachmentByID(db.DefaultContext, 1)
assert.NoError(t, err) assert.NoError(t, err)
assert.Equal(t, "a0eebc99-9c0b-4ef8-bb6d-6bb9bd380a11", attach.UUID) assert.Equal(t, "a0eebc99-9c0b-4ef8-bb6d-6bb9bd380a11", attach.UUID)
attach.Name = "new_name" attach.Name = "new_name"
assert.NoError(t, UpdateAttachment(attach)) assert.NoError(t, UpdateAttachment(db.DefaultContext, attach))
unittest.AssertExistsAndLoadBean(t, &Attachment{Name: "new_name"}) unittest.AssertExistsAndLoadBean(t, &Attachment{Name: "new_name"})
} }

@ -5,6 +5,7 @@
package repo package repo
import ( import (
"context"
"fmt" "fmt"
"image/png" "image/png"
"io" "io"
@ -25,11 +26,11 @@ func (repo *Repository) CustomAvatarRelativePath() string {
// RelAvatarLink returns a relative link to the repository's avatar. // RelAvatarLink returns a relative link to the repository's avatar.
func (repo *Repository) RelAvatarLink() string { func (repo *Repository) RelAvatarLink() string {
return repo.relAvatarLink(db.GetEngine(db.DefaultContext)) return repo.relAvatarLink(db.DefaultContext)
} }
// generateRandomAvatar generates a random avatar for repository. // generateRandomAvatar generates a random avatar for repository.
func generateRandomAvatar(e db.Engine, repo *Repository) error { func generateRandomAvatar(ctx context.Context, repo *Repository) error {
idToString := fmt.Sprintf("%d", repo.ID) idToString := fmt.Sprintf("%d", repo.ID)
seed := idToString seed := idToString
@ -51,14 +52,14 @@ func generateRandomAvatar(e db.Engine, repo *Repository) error {
log.Info("New random avatar created for repository: %d", repo.ID) log.Info("New random avatar created for repository: %d", repo.ID)
if _, err := e.ID(repo.ID).Cols("avatar").NoAutoTime().Update(repo); err != nil { if _, err := db.GetEngine(ctx).ID(repo.ID).Cols("avatar").NoAutoTime().Update(repo); err != nil {
return err return err
} }
return nil return nil
} }
func (repo *Repository) relAvatarLink(e db.Engine) string { func (repo *Repository) relAvatarLink(ctx context.Context) string {
// If no avatar - path is empty // If no avatar - path is empty
avatarPath := repo.CustomAvatarRelativePath() avatarPath := repo.CustomAvatarRelativePath()
if len(avatarPath) == 0 { if len(avatarPath) == 0 {
@ -66,7 +67,7 @@ func (repo *Repository) relAvatarLink(e db.Engine) string {
case "image": case "image":
return setting.RepoAvatar.FallbackImage return setting.RepoAvatar.FallbackImage
case "random": case "random":
if err := generateRandomAvatar(e, repo); err != nil { if err := generateRandomAvatar(ctx, repo); err != nil {
log.Error("generateRandomAvatar: %v", err) log.Error("generateRandomAvatar: %v", err)
} }
default: default:
@ -79,12 +80,12 @@ func (repo *Repository) relAvatarLink(e db.Engine) string {
// AvatarLink returns a link to the repository's avatar. // AvatarLink returns a link to the repository's avatar.
func (repo *Repository) AvatarLink() string { func (repo *Repository) AvatarLink() string {
return repo.avatarLink(db.GetEngine(db.DefaultContext)) return repo.avatarLink(db.DefaultContext)
} }
// avatarLink returns user avatar absolute link. // avatarLink returns user avatar absolute link.
func (repo *Repository) avatarLink(e db.Engine) string { func (repo *Repository) avatarLink(ctx context.Context) string {
link := repo.relAvatarLink(e) link := repo.relAvatarLink(ctx)
// we only prepend our AppURL to our known (relative, internal) avatar link to get an absolute URL // we only prepend our AppURL to our known (relative, internal) avatar link to get an absolute URL
if strings.HasPrefix(link, "/") && !strings.HasPrefix(link, "//") { if strings.HasPrefix(link, "/") && !strings.HasPrefix(link, "//") {
return setting.AppURL + strings.TrimPrefix(link, setting.AppSubURL)[1:] return setting.AppURL + strings.TrimPrefix(link, setting.AppSubURL)[1:]

@ -37,15 +37,14 @@ type Collaborator struct {
// GetCollaborators returns the collaborators for a repository // GetCollaborators returns the collaborators for a repository
func GetCollaborators(ctx context.Context, repoID int64, listOptions db.ListOptions) ([]*Collaborator, error) { func GetCollaborators(ctx context.Context, repoID int64, listOptions db.ListOptions) ([]*Collaborator, error) {
e := db.GetEngine(ctx) collaborations, err := getCollaborations(ctx, repoID, listOptions)
collaborations, err := getCollaborations(e, repoID, listOptions)
if err != nil { if err != nil {
return nil, fmt.Errorf("getCollaborations: %v", err) return nil, fmt.Errorf("getCollaborations: %v", err)
} }
collaborators := make([]*Collaborator, 0, len(collaborations)) collaborators := make([]*Collaborator, 0, len(collaborations))
for _, c := range collaborations { for _, c := range collaborations {
user, err := user_model.GetUserByIDEngine(e, c.UserID) user, err := user_model.GetUserByIDCtx(ctx, c.UserID)
if err != nil { if err != nil {
if user_model.IsErrUserNotExist(err) { if user_model.IsErrUserNotExist(err) {
log.Warn("Inconsistent DB: User: %d is listed as collaborator of %-v but does not exist", c.UserID, repoID) log.Warn("Inconsistent DB: User: %d is listed as collaborator of %-v but does not exist", c.UserID, repoID)
@ -85,12 +84,14 @@ func IsCollaborator(ctx context.Context, repoID, userID int64) (bool, error) {
return db.GetEngine(ctx).Get(&Collaboration{RepoID: repoID, UserID: userID}) return db.GetEngine(ctx).Get(&Collaboration{RepoID: repoID, UserID: userID})
} }
func getCollaborations(e db.Engine, repoID int64, listOptions db.ListOptions) ([]*Collaboration, error) { func getCollaborations(ctx context.Context, repoID int64, listOptions db.ListOptions) ([]*Collaboration, error) {
if listOptions.Page == 0 { if listOptions.Page == 0 {
collaborations := make([]*Collaboration, 0, 8) collaborations := make([]*Collaboration, 0, 8)
return collaborations, e.Find(&collaborations, &Collaboration{RepoID: repoID}) return collaborations, db.GetEngine(ctx).Find(&collaborations, &Collaboration{RepoID: repoID})
} }
e := db.GetEngine(ctx)
e = db.SetEnginePagination(e, &listOptions) e = db.SetEnginePagination(e, &listOptions)
collaborations := make([]*Collaboration, 0, listOptions.PageSize) collaborations := make([]*Collaboration, 0, listOptions.PageSize)

@ -10,18 +10,14 @@ import (
"code.gitea.io/gitea/models/db" "code.gitea.io/gitea/models/db"
) )
func getRepositoriesByForkID(e db.Engine, forkID int64) ([]*Repository, error) { // GetRepositoriesByForkID returns all repositories with given fork ID.
func GetRepositoriesByForkID(ctx context.Context, forkID int64) ([]*Repository, error) {
repos := make([]*Repository, 0, 10) repos := make([]*Repository, 0, 10)
return repos, e. return repos, db.GetEngine(ctx).
Where("fork_id=?", forkID). Where("fork_id=?", forkID).
Find(&repos) Find(&repos)
} }
// GetRepositoriesByForkID returns all repositories with given fork ID.
func GetRepositoriesByForkID(ctx context.Context, forkID int64) ([]*Repository, error) {
return getRepositoriesByForkID(db.GetEngine(ctx), forkID)
}
// GetForkedRepo checks if given user has already forked a repository with given ID. // GetForkedRepo checks if given user has already forked a repository with given ID.
func GetForkedRepo(ownerID, repoID int64) *Repository { func GetForkedRepo(ownerID, repoID int64) *Repository {
repo := new(Repository) repo := new(Repository)

@ -5,6 +5,7 @@
package repo package repo
import ( import (
"context"
"math" "math"
"strings" "strings"
@ -66,22 +67,18 @@ func (stats LanguageStatList) getLanguagePercentages() map[string]float32 {
return langPerc return langPerc
} }
func getLanguageStats(e db.Engine, repo *Repository) (LanguageStatList, error) { // GetLanguageStats returns the language statistics for a repository
func GetLanguageStats(ctx context.Context, repo *Repository) (LanguageStatList, error) {
stats := make(LanguageStatList, 0, 6) stats := make(LanguageStatList, 0, 6)
if err := e.Where("`repo_id` = ?", repo.ID).Desc("`size`").Find(&stats); err != nil { if err := db.GetEngine(ctx).Where("`repo_id` = ?", repo.ID).Desc("`size`").Find(&stats); err != nil {
return nil, err return nil, err
} }
return stats, nil return stats, nil
} }
// GetLanguageStats returns the language statistics for a repository
func GetLanguageStats(repo *Repository) (LanguageStatList, error) {
return getLanguageStats(db.GetEngine(db.DefaultContext), repo)
}
// GetTopLanguageStats returns the top language statistics for a repository // GetTopLanguageStats returns the top language statistics for a repository
func GetTopLanguageStats(repo *Repository, limit int) (LanguageStatList, error) { func GetTopLanguageStats(repo *Repository, limit int) (LanguageStatList, error) {
stats, err := getLanguageStats(db.GetEngine(db.DefaultContext), repo) stats, err := GetLanguageStats(db.DefaultContext, repo)
if err != nil { if err != nil {
return nil, err return nil, err
} }
@ -120,7 +117,7 @@ func UpdateLanguageStats(repo *Repository, commitID string, stats map[string]int
defer committer.Close() defer committer.Close()
sess := db.GetEngine(ctx) sess := db.GetEngine(ctx)
oldstats, err := getLanguageStats(sess, repo) oldstats, err := GetLanguageStats(ctx, repo)
if err != nil { if err != nil {
return err return err
} }
@ -151,7 +148,7 @@ func UpdateLanguageStats(repo *Repository, commitID string, stats map[string]int
} }
// Insert new language // Insert new language
if !upd { if !upd {
if _, err := sess.Insert(&LanguageStat{ if err := db.Insert(ctx, &LanguageStat{
RepoID: repo.ID, RepoID: repo.ID,
CommitID: commitID, CommitID: commitID,
IsPrimary: llang == topLang, IsPrimary: llang == topLang,
@ -176,7 +173,7 @@ func UpdateLanguageStats(repo *Repository, commitID string, stats map[string]int
} }
// Update indexer status // Update indexer status
if err = updateIndexerStatus(sess, repo, RepoIndexerTypeStats, commitID); err != nil { if err = UpdateIndexerStatus(ctx, repo, RepoIndexerTypeStats, commitID); err != nil {
return err return err
} }
@ -190,10 +187,9 @@ func CopyLanguageStat(originalRepo, destRepo *Repository) error {
return err return err
} }
defer committer.Close() defer committer.Close()
sess := db.GetEngine(ctx)
RepoLang := make(LanguageStatList, 0, 6) RepoLang := make(LanguageStatList, 0, 6)
if err := sess.Where("`repo_id` = ?", originalRepo.ID).Desc("`size`").Find(&RepoLang); err != nil { if err := db.GetEngine(ctx).Where("`repo_id` = ?", originalRepo.ID).Desc("`size`").Find(&RepoLang); err != nil {
return err return err
} }
if len(RepoLang) > 0 { if len(RepoLang) > 0 {
@ -204,10 +200,10 @@ func CopyLanguageStat(originalRepo, destRepo *Repository) error {
} }
// update destRepo's indexer status // update destRepo's indexer status
tmpCommitID := RepoLang[0].CommitID tmpCommitID := RepoLang[0].CommitID
if err := updateIndexerStatus(sess, destRepo, RepoIndexerTypeStats, tmpCommitID); err != nil { if err := UpdateIndexerStatus(ctx, destRepo, RepoIndexerTypeStats, tmpCommitID); err != nil {
return err return err
} }
if _, err := sess.Insert(&RepoLang); err != nil { if err := db.Insert(ctx, &RepoLang); err != nil {
return err return err
} }
} }

@ -14,8 +14,6 @@ import (
"code.gitea.io/gitea/models/db" "code.gitea.io/gitea/models/db"
"code.gitea.io/gitea/modules/log" "code.gitea.io/gitea/modules/log"
"code.gitea.io/gitea/modules/timeutil" "code.gitea.io/gitea/modules/timeutil"
"xorm.io/xorm"
) )
// ErrMirrorNotExist mirror does not exist error // ErrMirrorNotExist mirror does not exist error
@ -56,21 +54,16 @@ func (m *Mirror) BeforeInsert() {
} }
} }
// AfterLoad is invoked from XORM after setting the values of all fields of this object. // GetRepository returns the repository.
func (m *Mirror) AfterLoad(session *xorm.Session) { func (m *Mirror) GetRepository() *Repository {
if m == nil { if m.Repo != nil {
return return m.Repo
} }
var err error var err error
m.Repo, err = getRepositoryByID(session, m.RepoID) m.Repo, err = GetRepositoryByIDCtx(db.DefaultContext, m.RepoID)
if err != nil { if err != nil {
log.Error("getRepositoryByID[%d]: %v", m.ID, err) log.Error("getRepositoryByID[%d]: %v", m.ID, err)
} }
}
// GetRepository returns the repository.
func (m *Mirror) GetRepository() *Repository {
return m.Repo return m.Repo
} }
@ -88,9 +81,10 @@ func (m *Mirror) ScheduleNextUpdate() {
} }
} }
func getMirrorByRepoID(e db.Engine, repoID int64) (*Mirror, error) { // GetMirrorByRepoID returns mirror information of a repository.
func GetMirrorByRepoID(ctx context.Context, repoID int64) (*Mirror, error) {
m := &Mirror{RepoID: repoID} m := &Mirror{RepoID: repoID}
has, err := e.Get(m) has, err := db.GetEngine(ctx).Get(m)
if err != nil { if err != nil {
return nil, err return nil, err
} else if !has { } else if !has {
@ -99,19 +93,10 @@ func getMirrorByRepoID(e db.Engine, repoID int64) (*Mirror, error) {
return m, nil return m, nil
} }
// GetMirrorByRepoID returns mirror information of a repository.
func GetMirrorByRepoID(repoID int64) (*Mirror, error) {
return getMirrorByRepoID(db.GetEngine(db.DefaultContext), repoID)
}
func updateMirror(e db.Engine, m *Mirror) error {
_, err := e.ID(m.ID).AllCols().Update(m)
return err
}
// UpdateMirror updates the mirror // UpdateMirror updates the mirror
func UpdateMirror(m *Mirror) error { func UpdateMirror(ctx context.Context, m *Mirror) error {
return updateMirror(db.GetEngine(db.DefaultContext), m) _, err := db.GetEngine(ctx).ID(m.ID).AllCols().Update(m)
return err
} }
// TouchMirror updates the mirror updatedUnix // TouchMirror updates the mirror updatedUnix
@ -146,7 +131,7 @@ func InsertMirror(mirror *Mirror) error {
// MirrorRepositoryList contains the mirror repositories // MirrorRepositoryList contains the mirror repositories
type MirrorRepositoryList []*Repository type MirrorRepositoryList []*Repository
func (repos MirrorRepositoryList) loadAttributes(e db.Engine) error { func (repos MirrorRepositoryList) loadAttributes(ctx context.Context) error {
if len(repos) == 0 { if len(repos) == 0 {
return nil return nil
} }
@ -161,7 +146,7 @@ func (repos MirrorRepositoryList) loadAttributes(e db.Engine) error {
repoIDs = append(repoIDs, repos[i].ID) repoIDs = append(repoIDs, repos[i].ID)
} }
mirrors := make([]*Mirror, 0, len(repoIDs)) mirrors := make([]*Mirror, 0, len(repoIDs))
if err := e. if err := db.GetEngine(ctx).
Where("id > 0"). Where("id > 0").
In("repo_id", repoIDs). In("repo_id", repoIDs).
Find(&mirrors); err != nil { Find(&mirrors); err != nil {
@ -174,11 +159,12 @@ func (repos MirrorRepositoryList) loadAttributes(e db.Engine) error {
} }
for i := range repos { for i := range repos {
repos[i].Mirror = set[repos[i].ID] repos[i].Mirror = set[repos[i].ID]
repos[i].Mirror.Repo = repos[i]
} }
return nil return nil
} }
// LoadAttributes loads the attributes for the given MirrorRepositoryList // LoadAttributes loads the attributes for the given MirrorRepositoryList
func (repos MirrorRepositoryList) LoadAttributes() error { func (repos MirrorRepositoryList) LoadAttributes() error {
return repos.loadAttributes(db.GetEngine(db.DefaultContext)) return repos.loadAttributes(db.DefaultContext)
} }

@ -11,8 +11,6 @@ import (
"code.gitea.io/gitea/models/db" "code.gitea.io/gitea/models/db"
"code.gitea.io/gitea/modules/log" "code.gitea.io/gitea/modules/log"
"code.gitea.io/gitea/modules/timeutil" "code.gitea.io/gitea/modules/timeutil"
"xorm.io/xorm"
) )
// ErrPushMirrorNotExist mirror does not exist error // ErrPushMirrorNotExist mirror does not exist error
@ -35,21 +33,16 @@ func init() {
db.RegisterModel(new(PushMirror)) db.RegisterModel(new(PushMirror))
} }
// AfterLoad is invoked from XORM after setting the values of all fields of this object. // GetRepository returns the path of the repository.
func (m *PushMirror) AfterLoad(session *xorm.Session) { func (m *PushMirror) GetRepository() *Repository {
if m == nil { if m.Repo != nil {
return return m.Repo
} }
var err error var err error
m.Repo, err = getRepositoryByID(session, m.RepoID) m.Repo, err = GetRepositoryByIDCtx(db.DefaultContext, m.RepoID)
if err != nil { if err != nil {
log.Error("getRepositoryByID[%d]: %v", m.ID, err) log.Error("getRepositoryByID[%d]: %v", m.ID, err)
} }
}
// GetRepository returns the path of the repository.
func (m *PushMirror) GetRepository() *Repository {
return m.Repo return m.Repo
} }

@ -289,7 +289,7 @@ func (repo *Repository) LoadUnits(ctx context.Context) (err error) {
return nil return nil
} }
repo.Units, err = getUnitsByRepoID(db.GetEngine(ctx), repo.ID) repo.Units, err = getUnitsByRepoID(ctx, repo.ID)
if log.IsTrace() { if log.IsTrace() {
unitTypeStrings := make([]string, len(repo.Units)) unitTypeStrings := make([]string, len(repo.Units))
for i, unit := range repo.Units { for i, unit := range repo.Units {
@ -383,7 +383,7 @@ func (repo *Repository) GetOwner(ctx context.Context) (err error) {
return nil return nil
} }
repo.Owner, err = user_model.GetUserByIDEngine(db.GetEngine(ctx), repo.OwnerID) repo.Owner, err = user_model.GetUserByIDCtx(ctx, repo.OwnerID)
return err return err
} }
@ -454,15 +454,15 @@ func (repo *Repository) ComposeDocumentMetas() map[string]string {
// returns an error on failure (NOTE: no error is returned for // returns an error on failure (NOTE: no error is returned for
// non-fork repositories, and BaseRepo will be left untouched) // non-fork repositories, and BaseRepo will be left untouched)
func (repo *Repository) GetBaseRepo() (err error) { func (repo *Repository) GetBaseRepo() (err error) {
return repo.getBaseRepo(db.GetEngine(db.DefaultContext)) return repo.getBaseRepo(db.DefaultContext)
} }
func (repo *Repository) getBaseRepo(e db.Engine) (err error) { func (repo *Repository) getBaseRepo(ctx context.Context) (err error) {
if !repo.IsFork { if !repo.IsFork {
return nil return nil
} }
repo.BaseRepo, err = getRepositoryByID(e, repo.ForkID) repo.BaseRepo, err = GetRepositoryByIDCtx(ctx, repo.ForkID)
return err return err
} }
@ -481,16 +481,6 @@ func (repo *Repository) RepoPath() string {
return RepoPath(repo.OwnerName, repo.Name) return RepoPath(repo.OwnerName, repo.Name)
} }
// GitConfigPath returns the path to a repository's git config/ directory
func GitConfigPath(repoPath string) string {
return filepath.Join(repoPath, "config")
}
// GitConfigPath returns the repository git config path
func (repo *Repository) GitConfigPath() string {
return GitConfigPath(repo.RepoPath())
}
// Link returns the repository link // Link returns the repository link
func (repo *Repository) Link() string { func (repo *Repository) Link() string {
return setting.AppSubURL + "/" + url.PathEscape(repo.OwnerName) + "/" + url.PathEscape(repo.Name) return setting.AppSubURL + "/" + url.PathEscape(repo.OwnerName) + "/" + url.PathEscape(repo.Name)
@ -669,9 +659,10 @@ func GetRepositoryByName(ownerID int64, name string) (*Repository, error) {
return repo, err return repo, err
} }
func getRepositoryByID(e db.Engine, id int64) (*Repository, error) { // GetRepositoryByIDCtx returns the repository by given id if exists.
func GetRepositoryByIDCtx(ctx context.Context, id int64) (*Repository, error) {
repo := new(Repository) repo := new(Repository)
has, err := e.ID(id).Get(repo) has, err := db.GetEngine(ctx).ID(id).Get(repo)
if err != nil { if err != nil {
return nil, err return nil, err
} else if !has { } else if !has {
@ -682,12 +673,7 @@ func getRepositoryByID(e db.Engine, id int64) (*Repository, error) {
// GetRepositoryByID returns the repository by given id if exists. // GetRepositoryByID returns the repository by given id if exists.
func GetRepositoryByID(id int64) (*Repository, error) { func GetRepositoryByID(id int64) (*Repository, error) {
return getRepositoryByID(db.GetEngine(db.DefaultContext), id) return GetRepositoryByIDCtx(db.DefaultContext, id)
}
// GetRepositoryByIDCtx returns the repository by given id if exists.
func GetRepositoryByIDCtx(ctx context.Context, id int64) (*Repository, error) {
return getRepositoryByID(db.GetEngine(ctx), id)
} }
// GetRepositoriesMapByIDs returns the repositories by given id slice. // GetRepositoriesMapByIDs returns the repositories by given id slice.
@ -696,8 +682,8 @@ func GetRepositoriesMapByIDs(ids []int64) (map[int64]*Repository, error) {
return repos, db.GetEngine(db.DefaultContext).In("id", ids).Find(&repos) return repos, db.GetEngine(db.DefaultContext).In("id", ids).Find(&repos)
} }
// IsRepositoryExistCtx returns true if the repository with given name under user has already existed. // IsRepositoryExist returns true if the repository with given name under user has already existed.
func IsRepositoryExistCtx(ctx context.Context, u *user_model.User, repoName string) (bool, error) { func IsRepositoryExist(ctx context.Context, u *user_model.User, repoName string) (bool, error) {
has, err := db.GetEngine(ctx).Get(&Repository{ has, err := db.GetEngine(ctx).Get(&Repository{
OwnerID: u.ID, OwnerID: u.ID,
LowerName: strings.ToLower(repoName), LowerName: strings.ToLower(repoName),
@ -709,29 +695,20 @@ func IsRepositoryExistCtx(ctx context.Context, u *user_model.User, repoName stri
return has && isDir, err return has && isDir, err
} }
// IsRepositoryExist returns true if the repository with given name under user has already existed.
func IsRepositoryExist(u *user_model.User, repoName string) (bool, error) {
return IsRepositoryExistCtx(db.DefaultContext, u, repoName)
}
// GetTemplateRepo populates repo.TemplateRepo for a generated repository and // GetTemplateRepo populates repo.TemplateRepo for a generated repository and
// returns an error on failure (NOTE: no error is returned for // returns an error on failure (NOTE: no error is returned for
// non-generated repositories, and TemplateRepo will be left untouched) // non-generated repositories, and TemplateRepo will be left untouched)
func GetTemplateRepo(repo *Repository) (*Repository, error) { func GetTemplateRepo(ctx context.Context, repo *Repository) (*Repository, error) {
return getTemplateRepo(db.GetEngine(db.DefaultContext), repo)
}
func getTemplateRepo(e db.Engine, repo *Repository) (*Repository, error) {
if !repo.IsGenerated() { if !repo.IsGenerated() {
return nil, nil return nil, nil
} }
return getRepositoryByID(e, repo.TemplateID) return GetRepositoryByIDCtx(ctx, repo.TemplateID)
} }
// TemplateRepo returns the repository, which is template of this repository // TemplateRepo returns the repository, which is template of this repository
func (repo *Repository) TemplateRepo() *Repository { func (repo *Repository) TemplateRepo() *Repository {
repo, err := GetTemplateRepo(repo) repo, err := GetTemplateRepo(db.DefaultContext, repo)
if err != nil { if err != nil {
log.Error("TemplateRepo: %v", err) log.Error("TemplateRepo: %v", err)
return nil return nil
@ -739,26 +716,27 @@ func (repo *Repository) TemplateRepo() *Repository {
return repo return repo
} }
func countRepositories(userID int64, private bool) int64 { type CountRepositoryOptions struct {
sess := db.GetEngine(db.DefaultContext).Where("id > 0") OwnerID int64
Private util.OptionalBool
}
if userID > 0 { // CountRepositories returns number of repositories.
sess.And("owner_id = ?", userID) // Argument private only takes effect when it is false,
// set it true to count all repositories.
func CountRepositories(ctx context.Context, opts CountRepositoryOptions) (int64, error) {
sess := db.GetEngine(ctx).Where("id > 0")
if opts.OwnerID > 0 {
sess.And("owner_id = ?", opts.OwnerID)
} }
if !private { if !opts.Private.IsNone() {
sess.And("is_private=?", false) sess.And("is_private=?", opts.Private.IsTrue())
} }
count, err := sess.Count(new(Repository)) count, err := sess.Count(new(Repository))
if err != nil { if err != nil {
log.Error("countRepositories: %v", err) return 0, fmt.Errorf("countRepositories: %v", err)
}
return count
} }
return count, nil
// CountRepositories returns number of repositories.
// Argument private only takes effect when it is false,
// set it true to count all repositories.
func CountRepositories(private bool) int64 {
return countRepositories(-1, private)
} }

@ -5,6 +5,7 @@
package repo package repo
import ( import (
"context"
"fmt" "fmt"
"code.gitea.io/gitea/models/db" "code.gitea.io/gitea/models/db"
@ -62,8 +63,8 @@ func GetUnindexedRepos(indexerType RepoIndexerType, maxRepoID int64, page, pageS
return ids, err return ids, err
} }
// getIndexerStatus loads repo codes indxer status // GetIndexerStatus loads repo codes indxer status
func getIndexerStatus(e db.Engine, repo *Repository, indexerType RepoIndexerType) (*RepoIndexerStatus, error) { func GetIndexerStatus(ctx context.Context, repo *Repository, indexerType RepoIndexerType) (*RepoIndexerStatus, error) {
switch indexerType { switch indexerType {
case RepoIndexerTypeCode: case RepoIndexerTypeCode:
if repo.CodeIndexerStatus != nil { if repo.CodeIndexerStatus != nil {
@ -75,7 +76,7 @@ func getIndexerStatus(e db.Engine, repo *Repository, indexerType RepoIndexerType
} }
} }
status := &RepoIndexerStatus{RepoID: repo.ID} status := &RepoIndexerStatus{RepoID: repo.ID}
if has, err := e.Where("`indexer_type` = ?", indexerType).Get(status); err != nil { if has, err := db.GetEngine(ctx).Where("`indexer_type` = ?", indexerType).Get(status); err != nil {
return nil, err return nil, err
} else if !has { } else if !has {
status.IndexerType = indexerType status.IndexerType = indexerType
@ -90,36 +91,25 @@ func getIndexerStatus(e db.Engine, repo *Repository, indexerType RepoIndexerType
return status, nil return status, nil
} }
// GetIndexerStatus loads repo codes indxer status // UpdateIndexerStatus updates indexer status
func GetIndexerStatus(repo *Repository, indexerType RepoIndexerType) (*RepoIndexerStatus, error) { func UpdateIndexerStatus(ctx context.Context, repo *Repository, indexerType RepoIndexerType, sha string) error {
return getIndexerStatus(db.GetEngine(db.DefaultContext), repo, indexerType) status, err := GetIndexerStatus(ctx, repo, indexerType)
}
// updateIndexerStatus updates indexer status
func updateIndexerStatus(e db.Engine, repo *Repository, indexerType RepoIndexerType, sha string) error {
status, err := getIndexerStatus(e, repo, indexerType)
if err != nil { if err != nil {
return fmt.Errorf("UpdateIndexerStatus: Unable to getIndexerStatus for repo: %s Error: %v", repo.FullName(), err) return fmt.Errorf("UpdateIndexerStatus: Unable to getIndexerStatus for repo: %s Error: %v", repo.FullName(), err)
} }
if len(status.CommitSha) == 0 { if len(status.CommitSha) == 0 {
status.CommitSha = sha status.CommitSha = sha
_, err := e.Insert(status) if err := db.Insert(ctx, status); err != nil {
if err != nil {
return fmt.Errorf("UpdateIndexerStatus: Unable to insert repoIndexerStatus for repo: %s Sha: %s Error: %v", repo.FullName(), sha, err) return fmt.Errorf("UpdateIndexerStatus: Unable to insert repoIndexerStatus for repo: %s Sha: %s Error: %v", repo.FullName(), sha, err)
} }
return nil return nil
} }
status.CommitSha = sha status.CommitSha = sha
_, err = e.ID(status.ID).Cols("commit_sha"). _, err = db.GetEngine(ctx).ID(status.ID).Cols("commit_sha").
Update(status) Update(status)
if err != nil { if err != nil {
return fmt.Errorf("UpdateIndexerStatus: Unable to update repoIndexerStatus for repo: %s Sha: %s Error: %v", repo.FullName(), sha, err) return fmt.Errorf("UpdateIndexerStatus: Unable to update repoIndexerStatus for repo: %s Sha: %s Error: %v", repo.FullName(), sha, err)
} }
return nil return nil
} }
// UpdateIndexerStatus updates indexer status
func UpdateIndexerStatus(repo *Repository, indexerType RepoIndexerType, sha string) error {
return updateIndexerStatus(db.GetEngine(db.DefaultContext), repo, indexerType, sha)
}

@ -22,9 +22,10 @@ func GetUserMirrorRepositories(userID int64) ([]*Repository, error) {
func IterateRepository(f func(repo *Repository) error) error { func IterateRepository(f func(repo *Repository) error) error {
var start int var start int
batchSize := setting.Database.IterateBufferSize batchSize := setting.Database.IterateBufferSize
sess := db.GetEngine(db.DefaultContext)
for { for {
repos := make([]*Repository, 0, batchSize) repos := make([]*Repository, 0, batchSize)
if err := db.GetEngine(db.DefaultContext).Limit(batchSize, start).Find(&repos); err != nil { if err := sess.Limit(batchSize, start).Find(&repos); err != nil {
return err return err
} }
if len(repos) == 0 { if len(repos) == 0 {

@ -9,17 +9,24 @@ import (
"code.gitea.io/gitea/models/db" "code.gitea.io/gitea/models/db"
"code.gitea.io/gitea/models/unittest" "code.gitea.io/gitea/models/unittest"
user_model "code.gitea.io/gitea/models/user" "code.gitea.io/gitea/modules/util"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
) )
var (
countRepospts = CountRepositoryOptions{OwnerID: 10}
countReposptsPublic = CountRepositoryOptions{OwnerID: 10, Private: util.OptionalBoolFalse}
countReposptsPrivate = CountRepositoryOptions{OwnerID: 10, Private: util.OptionalBoolTrue}
)
func TestGetRepositoryCount(t *testing.T) { func TestGetRepositoryCount(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase()) assert.NoError(t, unittest.PrepareTestDatabase())
count, err1 := GetRepositoryCount(db.DefaultContext, 10) ctx := db.DefaultContext
privateCount, err2 := GetPrivateRepositoryCount(&user_model.User{ID: int64(10)}) count, err1 := CountRepositories(ctx, countRepospts)
publicCount, err3 := GetPublicRepositoryCount(&user_model.User{ID: int64(10)}) privateCount, err2 := CountRepositories(ctx, countReposptsPrivate)
publicCount, err3 := CountRepositories(ctx, countReposptsPublic)
assert.NoError(t, err1) assert.NoError(t, err1)
assert.NoError(t, err2) assert.NoError(t, err2)
assert.NoError(t, err3) assert.NoError(t, err3)
@ -30,7 +37,7 @@ func TestGetRepositoryCount(t *testing.T) {
func TestGetPublicRepositoryCount(t *testing.T) { func TestGetPublicRepositoryCount(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase()) assert.NoError(t, unittest.PrepareTestDatabase())
count, err := GetPublicRepositoryCount(&user_model.User{ID: int64(10)}) count, err := CountRepositories(db.DefaultContext, countReposptsPublic)
assert.NoError(t, err) assert.NoError(t, err)
assert.Equal(t, int64(1), count) assert.Equal(t, int64(1), count)
} }
@ -38,7 +45,7 @@ func TestGetPublicRepositoryCount(t *testing.T) {
func TestGetPrivateRepositoryCount(t *testing.T) { func TestGetPrivateRepositoryCount(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase()) assert.NoError(t, unittest.PrepareTestDatabase())
count, err := GetPrivateRepositoryCount(&user_model.User{ID: int64(10)}) count, err := CountRepositories(db.DefaultContext, countReposptsPrivate)
assert.NoError(t, err) assert.NoError(t, err)
assert.Equal(t, int64(2), count) assert.Equal(t, int64(2), count)
} }

@ -5,6 +5,7 @@
package repo package repo
import ( import (
"context"
"fmt" "fmt"
"code.gitea.io/gitea/models/db" "code.gitea.io/gitea/models/db"
@ -206,9 +207,9 @@ func (r *RepoUnit) ExternalTrackerConfig() *ExternalTrackerConfig {
return r.Config.(*ExternalTrackerConfig) return r.Config.(*ExternalTrackerConfig)
} }
func getUnitsByRepoID(e db.Engine, repoID int64) (units []*RepoUnit, err error) { func getUnitsByRepoID(ctx context.Context, repoID int64) (units []*RepoUnit, err error) {
var tmpUnits []*RepoUnit var tmpUnits []*RepoUnit
if err := e.Where("repo_id = ?", repoID).Find(&tmpUnits); err != nil { if err := db.GetEngine(ctx).Where("repo_id = ?", repoID).Find(&tmpUnits); err != nil {
return nil, err return nil, err
} }

@ -5,6 +5,8 @@
package repo package repo
import ( import (
"context"
"code.gitea.io/gitea/models/db" "code.gitea.io/gitea/models/db"
user_model "code.gitea.io/gitea/models/user" user_model "code.gitea.io/gitea/models/user"
"code.gitea.io/gitea/modules/timeutil" "code.gitea.io/gitea/modules/timeutil"
@ -29,7 +31,7 @@ func StarRepo(userID, repoID int64, star bool) error {
return err return err
} }
defer committer.Close() defer committer.Close()
staring := isStaring(db.GetEngine(ctx), userID, repoID) staring := IsStaring(ctx, userID, repoID)
if star { if star {
if staring { if staring {
@ -65,12 +67,8 @@ func StarRepo(userID, repoID int64, star bool) error {
} }
// IsStaring checks if user has starred given repository. // IsStaring checks if user has starred given repository.
func IsStaring(userID, repoID int64) bool { func IsStaring(ctx context.Context, userID, repoID int64) bool {
return isStaring(db.GetEngine(db.DefaultContext), userID, repoID) has, _ := db.GetEngine(ctx).Get(&Star{UID: userID, RepoID: repoID})
}
func isStaring(e db.Engine, userID, repoID int64) bool {
has, _ := e.Get(&Star{UID: userID, RepoID: repoID})
return has return has
} }

@ -28,8 +28,8 @@ func TestStarRepo(t *testing.T) {
func TestIsStaring(t *testing.T) { func TestIsStaring(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase()) assert.NoError(t, unittest.PrepareTestDatabase())
assert.True(t, IsStaring(2, 4)) assert.True(t, IsStaring(db.DefaultContext, 2, 4))
assert.False(t, IsStaring(3, 4)) assert.False(t, IsStaring(db.DefaultContext, 3, 4))
} }
func TestRepository_GetStargazers(t *testing.T) { func TestRepository_GetStargazers(t *testing.T) {

@ -99,8 +99,9 @@ func GetTopicByName(name string) (*Topic, error) {
// addTopicByNameToRepo adds a topic name to a repo and increments the topic count. // addTopicByNameToRepo adds a topic name to a repo and increments the topic count.
// Returns topic after the addition // Returns topic after the addition
func addTopicByNameToRepo(e db.Engine, repoID int64, topicName string) (*Topic, error) { func addTopicByNameToRepo(ctx context.Context, repoID int64, topicName string) (*Topic, error) {
var topic Topic var topic Topic
e := db.GetEngine(ctx)
has, err := e.Where("name = ?", topicName).Get(&topic) has, err := e.Where("name = ?", topicName).Get(&topic)
if err != nil { if err != nil {
return nil, err return nil, err
@ -108,7 +109,7 @@ func addTopicByNameToRepo(e db.Engine, repoID int64, topicName string) (*Topic,
if !has { if !has {
topic.Name = topicName topic.Name = topicName
topic.RepoCount = 1 topic.RepoCount = 1
if _, err := e.Insert(&topic); err != nil { if err := db.Insert(ctx, &topic); err != nil {
return nil, err return nil, err
} }
} else { } else {
@ -118,7 +119,7 @@ func addTopicByNameToRepo(e db.Engine, repoID int64, topicName string) (*Topic,
} }
} }
if _, err := e.Insert(&RepoTopic{ if err := db.Insert(ctx, &RepoTopic{
RepoID: repoID, RepoID: repoID,
TopicID: topic.ID, TopicID: topic.ID,
}); err != nil { }); err != nil {
@ -129,8 +130,9 @@ func addTopicByNameToRepo(e db.Engine, repoID int64, topicName string) (*Topic,
} }
// removeTopicFromRepo remove a topic from a repo and decrements the topic repo count // removeTopicFromRepo remove a topic from a repo and decrements the topic repo count
func removeTopicFromRepo(e db.Engine, repoID int64, topic *Topic) error { func removeTopicFromRepo(ctx context.Context, repoID int64, topic *Topic) error {
topic.RepoCount-- topic.RepoCount--
e := db.GetEngine(ctx)
if _, err := e.ID(topic.ID).Cols("repo_count").Update(topic); err != nil { if _, err := e.ID(topic.ID).Cols("repo_count").Update(topic); err != nil {
return err return err
} }
@ -208,17 +210,13 @@ func CountTopics(opts *FindTopicOptions) (int64, error) {
} }
// GetRepoTopicByName retrieves topic from name for a repo if it exist // GetRepoTopicByName retrieves topic from name for a repo if it exist
func GetRepoTopicByName(repoID int64, topicName string) (*Topic, error) { func GetRepoTopicByName(ctx context.Context, repoID int64, topicName string) (*Topic, error) {
return getRepoTopicByName(db.GetEngine(db.DefaultContext), repoID, topicName)
}
func getRepoTopicByName(e db.Engine, repoID int64, topicName string) (*Topic, error) {
cond := builder.NewCond() cond := builder.NewCond()
var topic Topic var topic Topic
cond = cond.And(builder.Eq{"repo_topic.repo_id": repoID}).And(builder.Eq{"topic.name": topicName}) cond = cond.And(builder.Eq{"repo_topic.repo_id": repoID}).And(builder.Eq{"topic.name": topicName})
sess := e.Table("topic").Where(cond) sess := db.GetEngine(ctx).Table("topic").Where(cond)
sess.Join("INNER", "repo_topic", "repo_topic.topic_id = topic.id") sess.Join("INNER", "repo_topic", "repo_topic.topic_id = topic.id")
has, err := sess.Get(&topic) has, err := sess.Select("topic.*").Get(&topic)
if has { if has {
return &topic, err return &topic, err
} }
@ -234,7 +232,7 @@ func AddTopic(repoID int64, topicName string) (*Topic, error) {
defer committer.Close() defer committer.Close()
sess := db.GetEngine(ctx) sess := db.GetEngine(ctx)
topic, err := getRepoTopicByName(sess, repoID, topicName) topic, err := GetRepoTopicByName(ctx, repoID, topicName)
if err != nil { if err != nil {
return nil, err return nil, err
} }
@ -243,7 +241,7 @@ func AddTopic(repoID int64, topicName string) (*Topic, error) {
return topic, nil return topic, nil
} }
topic, err = addTopicByNameToRepo(sess, repoID, topicName) topic, err = addTopicByNameToRepo(ctx, repoID, topicName)
if err != nil { if err != nil {
return nil, err return nil, err
} }
@ -266,7 +264,7 @@ func AddTopic(repoID int64, topicName string) (*Topic, error) {
// DeleteTopic removes a topic name from a repository (if it has it) // DeleteTopic removes a topic name from a repository (if it has it)
func DeleteTopic(repoID int64, topicName string) (*Topic, error) { func DeleteTopic(repoID int64, topicName string) (*Topic, error) {
topic, err := GetRepoTopicByName(repoID, topicName) topic, err := GetRepoTopicByName(db.DefaultContext, repoID, topicName)
if err != nil { if err != nil {
return nil, err return nil, err
} }
@ -275,7 +273,7 @@ func DeleteTopic(repoID int64, topicName string) (*Topic, error) {
return nil, nil return nil, nil
} }
err = removeTopicFromRepo(db.GetEngine(db.DefaultContext), repoID, topic) err = removeTopicFromRepo(db.DefaultContext, repoID, topic)
return topic, err return topic, err
} }
@ -329,14 +327,14 @@ func SaveTopics(repoID int64, topicNames ...string) error {
} }
for _, topicName := range addedTopicNames { for _, topicName := range addedTopicNames {
_, err := addTopicByNameToRepo(sess, repoID, topicName) _, err := addTopicByNameToRepo(ctx, repoID, topicName)
if err != nil { if err != nil {
return err return err
} }
} }
for _, topic := range removeTopics { for _, topic := range removeTopics {
err := removeTopicFromRepo(sess, repoID, topic) err := removeTopicFromRepo(ctx, repoID, topic)
if err != nil { if err != nil {
return err return err
} }
@ -361,7 +359,7 @@ func SaveTopics(repoID int64, topicNames ...string) error {
// GenerateTopics generates topics from a template repository // GenerateTopics generates topics from a template repository
func GenerateTopics(ctx context.Context, templateRepo, generateRepo *Repository) error { func GenerateTopics(ctx context.Context, templateRepo, generateRepo *Repository) error {
for _, topic := range templateRepo.Topics { for _, topic := range templateRepo.Topics {
if _, err := addTopicByNameToRepo(db.GetEngine(ctx), generateRepo.ID, topic); err != nil { if _, err := addTopicByNameToRepo(ctx, generateRepo.ID, topic); err != nil {
return err return err
} }
} }

@ -42,17 +42,12 @@ func UpdateRepositoryUpdatedTime(repoID int64, updateTime time.Time) error {
return err return err
} }
// UpdateRepositoryColsCtx updates repository's columns // UpdateRepositoryCols updates repository's columns
func UpdateRepositoryColsCtx(ctx context.Context, repo *Repository, cols ...string) error { func UpdateRepositoryCols(ctx context.Context, repo *Repository, cols ...string) error {
_, err := db.GetEngine(ctx).ID(repo.ID).Cols(cols...).Update(repo) _, err := db.GetEngine(ctx).ID(repo.ID).Cols(cols...).Update(repo)
return err return err
} }
// UpdateRepositoryCols updates repository's columns
func UpdateRepositoryCols(repo *Repository, cols ...string) error {
return UpdateRepositoryColsCtx(db.DefaultContext, repo, cols...)
}
// ErrReachLimitOfRepo represents a "ReachLimitOfRepo" kind of error. // ErrReachLimitOfRepo represents a "ReachLimitOfRepo" kind of error.
type ErrReachLimitOfRepo struct { type ErrReachLimitOfRepo struct {
Limit int Limit int
@ -110,7 +105,7 @@ func CheckCreateRepository(doer, u *user_model.User, name string, overwriteOrAdo
return err return err
} }
has, err := IsRepositoryExist(u, name) has, err := IsRepositoryExist(db.DefaultContext, u, name)
if err != nil { if err != nil {
return fmt.Errorf("IsRepositoryExist: %v", err) return fmt.Errorf("IsRepositoryExist: %v", err)
} else if has { } else if has {
@ -141,7 +136,7 @@ func ChangeRepositoryName(doer *user_model.User, repo *Repository, newRepoName s
return err return err
} }
has, err := IsRepositoryExist(repo.Owner, newRepoName) has, err := IsRepositoryExist(db.DefaultContext, repo.Owner, newRepoName)
if err != nil { if err != nil {
return fmt.Errorf("IsRepositoryExist: %v", err) return fmt.Errorf("IsRepositoryExist: %v", err)
} else if has { } else if has {

@ -5,10 +5,7 @@
package repo package repo
import ( import (
"context"
"code.gitea.io/gitea/models/db" "code.gitea.io/gitea/models/db"
user_model "code.gitea.io/gitea/models/user"
) )
// GetStarredRepos returns the repos starred by a particular user // GetStarredRepos returns the repos starred by a particular user
@ -51,37 +48,3 @@ func GetWatchedRepos(userID int64, private bool, listOptions db.ListOptions) ([]
total, err := sess.FindAndCount(&repos) total, err := sess.FindAndCount(&repos)
return repos, total, err return repos, total, err
} }
// CountUserRepositories returns number of repositories user owns.
// Argument private only takes effect when it is false,
// set it true to count all repositories.
func CountUserRepositories(userID int64, private bool) int64 {
return countRepositories(userID, private)
}
func getRepositoryCount(e db.Engine, ownerID int64) (int64, error) {
return e.Count(&Repository{OwnerID: ownerID})
}
func getPublicRepositoryCount(e db.Engine, u *user_model.User) (int64, error) {
return e.Where("is_private = ?", false).Count(&Repository{OwnerID: u.ID})
}
func getPrivateRepositoryCount(e db.Engine, u *user_model.User) (int64, error) {
return e.Where("is_private = ?", true).Count(&Repository{OwnerID: u.ID})
}
// GetRepositoryCount returns the total number of repositories of user.
func GetRepositoryCount(ctx context.Context, ownerID int64) (int64, error) {
return getRepositoryCount(db.GetEngine(ctx), ownerID)
}
// GetPublicRepositoryCount returns the total number of public repositories of user.
func GetPublicRepositoryCount(u *user_model.User) (int64, error) {
return getPublicRepositoryCount(db.GetEngine(db.DefaultContext), u)
}
// GetPrivateRepositoryCount returns the total number of private repositories of user.
func GetPrivateRepositoryCount(u *user_model.User) (int64, error) {
return getPrivateRepositoryCount(db.GetEngine(db.DefaultContext), u)
}

@ -116,8 +116,8 @@ func WatchRepoMode(userID, repoID int64, mode WatchMode) (err error) {
return watchRepoMode(db.DefaultContext, watch, mode) return watchRepoMode(db.DefaultContext, watch, mode)
} }
// WatchRepoCtx watch or unwatch repository. // WatchRepo watch or unwatch repository.
func WatchRepoCtx(ctx context.Context, userID, repoID int64, doWatch bool) (err error) { func WatchRepo(ctx context.Context, userID, repoID int64, doWatch bool) (err error) {
var watch Watch var watch Watch
if watch, err = GetWatch(ctx, userID, repoID); err != nil { if watch, err = GetWatch(ctx, userID, repoID); err != nil {
return err return err
@ -132,11 +132,6 @@ func WatchRepoCtx(ctx context.Context, userID, repoID int64, doWatch bool) (err
return err return err
} }
// WatchRepo watch or unwatch repository.
func WatchRepo(userID, repoID int64, watch bool) (err error) {
return WatchRepoCtx(db.DefaultContext, userID, repoID, watch)
}
// GetWatchers returns all watchers of given repository. // GetWatchers returns all watchers of given repository.
func GetWatchers(ctx context.Context, repoID int64) ([]*Watch, error) { func GetWatchers(ctx context.Context, repoID int64) ([]*Watch, error) {
watches := make([]*Watch, 0, 10) watches := make([]*Watch, 0, 10)
@ -176,7 +171,8 @@ func GetRepoWatchers(repoID int64, opts db.ListOptions) ([]*user_model.User, err
return users, sess.Find(&users) return users, sess.Find(&users)
} }
func watchIfAuto(ctx context.Context, userID, repoID int64, isWrite bool) error { // WatchIfAuto subscribes to repo if AutoWatchOnChanges is set
func WatchIfAuto(ctx context.Context, userID, repoID int64, isWrite bool) error {
if !isWrite || !setting.Service.AutoWatchOnChanges { if !isWrite || !setting.Service.AutoWatchOnChanges {
return nil return nil
} }
@ -189,8 +185,3 @@ func watchIfAuto(ctx context.Context, userID, repoID int64, isWrite bool) error
} }
return watchRepoMode(ctx, watch, WatchModeAuto) return watchRepoMode(ctx, watch, WatchModeAuto)
} }
// WatchIfAuto subscribes to repo if AutoWatchOnChanges is set
func WatchIfAuto(userID, repoID int64, isWrite bool) error {
return watchIfAuto(db.DefaultContext, userID, repoID, isWrite)
}

@ -73,13 +73,13 @@ func TestWatchIfAuto(t *testing.T) {
prevCount := repo.NumWatches prevCount := repo.NumWatches
// Must not add watch // Must not add watch
assert.NoError(t, WatchIfAuto(8, 1, true)) assert.NoError(t, WatchIfAuto(db.DefaultContext, 8, 1, true))
watchers, err = GetRepoWatchers(repo.ID, db.ListOptions{Page: 1}) watchers, err = GetRepoWatchers(repo.ID, db.ListOptions{Page: 1})
assert.NoError(t, err) assert.NoError(t, err)
assert.Len(t, watchers, prevCount) assert.Len(t, watchers, prevCount)
// Should not add watch // Should not add watch
assert.NoError(t, WatchIfAuto(10, 1, true)) assert.NoError(t, WatchIfAuto(db.DefaultContext, 10, 1, true))
watchers, err = GetRepoWatchers(repo.ID, db.ListOptions{Page: 1}) watchers, err = GetRepoWatchers(repo.ID, db.ListOptions{Page: 1})
assert.NoError(t, err) assert.NoError(t, err)
assert.Len(t, watchers, prevCount) assert.Len(t, watchers, prevCount)
@ -87,31 +87,31 @@ func TestWatchIfAuto(t *testing.T) {
setting.Service.AutoWatchOnChanges = true setting.Service.AutoWatchOnChanges = true
// Must not add watch // Must not add watch
assert.NoError(t, WatchIfAuto(8, 1, true)) assert.NoError(t, WatchIfAuto(db.DefaultContext, 8, 1, true))
watchers, err = GetRepoWatchers(repo.ID, db.ListOptions{Page: 1}) watchers, err = GetRepoWatchers(repo.ID, db.ListOptions{Page: 1})
assert.NoError(t, err) assert.NoError(t, err)
assert.Len(t, watchers, prevCount) assert.Len(t, watchers, prevCount)
// Should not add watch // Should not add watch
assert.NoError(t, WatchIfAuto(12, 1, false)) assert.NoError(t, WatchIfAuto(db.DefaultContext, 12, 1, false))
watchers, err = GetRepoWatchers(repo.ID, db.ListOptions{Page: 1}) watchers, err = GetRepoWatchers(repo.ID, db.ListOptions{Page: 1})
assert.NoError(t, err) assert.NoError(t, err)
assert.Len(t, watchers, prevCount) assert.Len(t, watchers, prevCount)
// Should add watch // Should add watch
assert.NoError(t, WatchIfAuto(12, 1, true)) assert.NoError(t, WatchIfAuto(db.DefaultContext, 12, 1, true))
watchers, err = GetRepoWatchers(repo.ID, db.ListOptions{Page: 1}) watchers, err = GetRepoWatchers(repo.ID, db.ListOptions{Page: 1})
assert.NoError(t, err) assert.NoError(t, err)
assert.Len(t, watchers, prevCount+1) assert.Len(t, watchers, prevCount+1)
// Should remove watch, inhibit from adding auto // Should remove watch, inhibit from adding auto
assert.NoError(t, WatchRepo(12, 1, false)) assert.NoError(t, WatchRepo(db.DefaultContext, 12, 1, false))
watchers, err = GetRepoWatchers(repo.ID, db.ListOptions{Page: 1}) watchers, err = GetRepoWatchers(repo.ID, db.ListOptions{Page: 1})
assert.NoError(t, err) assert.NoError(t, err)
assert.Len(t, watchers, prevCount) assert.Len(t, watchers, prevCount)
// Must not add watch // Must not add watch
assert.NoError(t, WatchIfAuto(12, 1, true)) assert.NoError(t, WatchIfAuto(db.DefaultContext, 12, 1, true))
watchers, err = GetRepoWatchers(repo.ID, db.ListOptions{Page: 1}) watchers, err = GetRepoWatchers(repo.ID, db.ListOptions{Page: 1})
assert.NoError(t, err) assert.NoError(t, err)
assert.Len(t, watchers, prevCount) assert.Len(t, watchers, prevCount)

@ -76,7 +76,7 @@ func DeleteCollaboration(repo *repo_model.Repository, uid int64) (err error) {
return err return err
} }
if err = repo_model.WatchRepoCtx(ctx, uid, repo.ID, false); err != nil { if err = repo_model.WatchRepo(ctx, uid, repo.ID, false); err != nil {
return err return err
} }
@ -93,7 +93,7 @@ func DeleteCollaboration(repo *repo_model.Repository, uid int64) (err error) {
} }
func reconsiderRepoIssuesAssignee(ctx context.Context, repo *repo_model.Repository, uid int64) error { func reconsiderRepoIssuesAssignee(ctx context.Context, repo *repo_model.Repository, uid int64) error {
user, err := user_model.GetUserByIDEngine(db.GetEngine(ctx), uid) user, err := user_model.GetUserByIDCtx(ctx, uid)
if err != nil { if err != nil {
return err return err
} }
@ -114,12 +114,12 @@ func reconsiderWatches(ctx context.Context, repo *repo_model.Repository, uid int
if has, err := access_model.HasAccess(ctx, uid, repo); err != nil || has { if has, err := access_model.HasAccess(ctx, uid, repo); err != nil || has {
return err return err
} }
if err := repo_model.WatchRepoCtx(ctx, uid, repo.ID, false); err != nil { if err := repo_model.WatchRepo(ctx, uid, repo.ID, false); err != nil {
return err return err
} }
// Remove all IssueWatches a user has subscribed to in the repository // Remove all IssueWatches a user has subscribed to in the repository
return removeIssueWatchersByRepoID(db.GetEngine(ctx), uid, repo.ID) return removeIssueWatchersByRepoID(ctx, uid, repo.ID)
} }
// IsOwnerMemberCollaborator checks if a provided user is the owner, a collaborator or a member of a team in a repository // IsOwnerMemberCollaborator checks if a provided user is the owner, a collaborator or a member of a team in a repository

@ -70,7 +70,7 @@ func (gt GiteaTemplate) Globs() []glob.Glob {
// GenerateWebhooks generates webhooks from a template repository // GenerateWebhooks generates webhooks from a template repository
func GenerateWebhooks(ctx context.Context, templateRepo, generateRepo *repo_model.Repository) error { func GenerateWebhooks(ctx context.Context, templateRepo, generateRepo *repo_model.Repository) error {
templateWebhooks, err := webhook.ListWebhooksByOpts(&webhook.ListWebhookOptions{RepoID: templateRepo.ID}) templateWebhooks, err := webhook.ListWebhooksByOpts(ctx, &webhook.ListWebhookOptions{RepoID: templateRepo.ID})
if err != nil { if err != nil {
return err return err
} }
@ -98,7 +98,7 @@ func GenerateWebhooks(ctx context.Context, templateRepo, generateRepo *repo_mode
// GenerateIssueLabels generates issue labels from a template repository // GenerateIssueLabels generates issue labels from a template repository
func GenerateIssueLabels(ctx context.Context, templateRepo, generateRepo *repo_model.Repository) error { func GenerateIssueLabels(ctx context.Context, templateRepo, generateRepo *repo_model.Repository) error {
templateLabels, err := getLabelsByRepoID(db.GetEngine(ctx), templateRepo.ID, "", db.ListOptions{}) templateLabels, err := GetLabelsByRepoID(ctx, templateRepo.ID, "", db.ListOptions{})
if err != nil { if err != nil {
return err return err
} }

@ -5,6 +5,7 @@
package models package models
import ( import (
"context"
"fmt" "fmt"
"strings" "strings"
@ -57,7 +58,7 @@ func RepositoryListOfMap(repoMap map[int64]*repo_model.Repository) RepositoryLis
return RepositoryList(valuesRepository(repoMap)) return RepositoryList(valuesRepository(repoMap))
} }
func (repos RepositoryList) loadAttributes(e db.Engine) error { func (repos RepositoryList) loadAttributes(ctx context.Context) error {
if len(repos) == 0 { if len(repos) == 0 {
return nil return nil
} }
@ -71,7 +72,7 @@ func (repos RepositoryList) loadAttributes(e db.Engine) error {
// Load owners. // Load owners.
users := make(map[int64]*user_model.User, len(set)) users := make(map[int64]*user_model.User, len(set))
if err := e. if err := db.GetEngine(ctx).
Where("id > 0"). Where("id > 0").
In("id", container.KeysInt64(set)). In("id", container.KeysInt64(set)).
Find(&users); err != nil { Find(&users); err != nil {
@ -83,7 +84,7 @@ func (repos RepositoryList) loadAttributes(e db.Engine) error {
// Load primary language. // Load primary language.
stats := make(repo_model.LanguageStatList, 0, len(repos)) stats := make(repo_model.LanguageStatList, 0, len(repos))
if err := e. if err := db.GetEngine(ctx).
Where("`is_primary` = ? AND `language` != ?", true, "other"). Where("`is_primary` = ? AND `language` != ?", true, "other").
In("`repo_id`", repoIDs). In("`repo_id`", repoIDs).
Find(&stats); err != nil { Find(&stats); err != nil {
@ -104,7 +105,7 @@ func (repos RepositoryList) loadAttributes(e db.Engine) error {
// LoadAttributes loads the attributes for the given RepositoryList // LoadAttributes loads the attributes for the given RepositoryList
func (repos RepositoryList) LoadAttributes() error { func (repos RepositoryList) LoadAttributes() error {
return repos.loadAttributes(db.GetEngine(db.DefaultContext)) return repos.loadAttributes(db.DefaultContext)
} }
// SearchRepoOptions holds the search options // SearchRepoOptions holds the search options
@ -509,7 +510,8 @@ func SearchRepository(opts *SearchRepoOptions) (RepositoryList, int64, error) {
// SearchRepositoryByCondition search repositories by condition // SearchRepositoryByCondition search repositories by condition
func SearchRepositoryByCondition(opts *SearchRepoOptions, cond builder.Cond, loadAttributes bool) (RepositoryList, int64, error) { func SearchRepositoryByCondition(opts *SearchRepoOptions, cond builder.Cond, loadAttributes bool) (RepositoryList, int64, error) {
sess, count, err := searchRepositoryByCondition(opts, cond) ctx := db.DefaultContext
sess, count, err := searchRepositoryByCondition(ctx, opts, cond)
if err != nil { if err != nil {
return nil, 0, err return nil, 0, err
} }
@ -528,7 +530,7 @@ func SearchRepositoryByCondition(opts *SearchRepoOptions, cond builder.Cond, loa
} }
if loadAttributes { if loadAttributes {
if err := repos.loadAttributes(sess); err != nil { if err := repos.loadAttributes(ctx); err != nil {
return nil, 0, fmt.Errorf("LoadAttributes: %v", err) return nil, 0, fmt.Errorf("LoadAttributes: %v", err)
} }
} }
@ -536,7 +538,7 @@ func SearchRepositoryByCondition(opts *SearchRepoOptions, cond builder.Cond, loa
return repos, count, nil return repos, count, nil
} }
func searchRepositoryByCondition(opts *SearchRepoOptions, cond builder.Cond) (db.Engine, int64, error) { func searchRepositoryByCondition(ctx context.Context, opts *SearchRepoOptions, cond builder.Cond) (db.Engine, int64, error) {
if opts.Page <= 0 { if opts.Page <= 0 {
opts.Page = 1 opts.Page = 1
} }
@ -549,7 +551,7 @@ func searchRepositoryByCondition(opts *SearchRepoOptions, cond builder.Cond) (db
opts.OrderBy = db.SearchOrderBy(fmt.Sprintf("CASE WHEN owner_id = %d THEN 0 ELSE owner_id END, %s", opts.PriorityOwnerID, opts.OrderBy)) opts.OrderBy = db.SearchOrderBy(fmt.Sprintf("CASE WHEN owner_id = %d THEN 0 ELSE owner_id END, %s", opts.PriorityOwnerID, opts.OrderBy))
} }
sess := db.GetEngine(db.DefaultContext) sess := db.GetEngine(ctx)
var count int64 var count int64
if opts.PageSize > 0 { if opts.PageSize > 0 {
@ -619,7 +621,7 @@ func SearchRepositoryIDs(opts *SearchRepoOptions) ([]int64, int64, error) {
cond := SearchRepositoryCondition(opts) cond := SearchRepositoryCondition(opts)
sess, count, err := searchRepositoryByCondition(opts, cond) sess, count, err := searchRepositoryByCondition(db.DefaultContext, opts, cond)
if err != nil { if err != nil {
return nil, 0, err return nil, 0, err
} }

@ -27,11 +27,11 @@ func TestWatchRepo(t *testing.T) {
const repoID = 3 const repoID = 3
const userID = 2 const userID = 2
assert.NoError(t, repo_model.WatchRepo(userID, repoID, true)) assert.NoError(t, repo_model.WatchRepo(db.DefaultContext, userID, repoID, true))
unittest.AssertExistsAndLoadBean(t, &repo_model.Watch{RepoID: repoID, UserID: userID}) unittest.AssertExistsAndLoadBean(t, &repo_model.Watch{RepoID: repoID, UserID: userID})
unittest.CheckConsistencyFor(t, &repo_model.Repository{ID: repoID}) unittest.CheckConsistencyFor(t, &repo_model.Repository{ID: repoID})
assert.NoError(t, repo_model.WatchRepo(userID, repoID, false)) assert.NoError(t, repo_model.WatchRepo(db.DefaultContext, userID, repoID, false))
unittest.AssertNotExistsBean(t, &repo_model.Watch{RepoID: repoID, UserID: userID}) unittest.AssertNotExistsBean(t, &repo_model.Watch{RepoID: repoID, UserID: userID})
unittest.CheckConsistencyFor(t, &repo_model.Repository{ID: repoID}) unittest.CheckConsistencyFor(t, &repo_model.Repository{ID: repoID})
} }
@ -179,7 +179,7 @@ func TestLinkedRepository(t *testing.T) {
} }
for _, tc := range testCases { for _, tc := range testCases {
t.Run(tc.name, func(t *testing.T) { t.Run(tc.name, func(t *testing.T) {
attach, err := repo_model.GetAttachmentByID(tc.attachID) attach, err := repo_model.GetAttachmentByID(db.DefaultContext, tc.attachID)
assert.NoError(t, err) assert.NoError(t, err)
repo, unitType, err := LinkedRepository(attach) repo, unitType, err := LinkedRepository(attach)
assert.NoError(t, err) assert.NoError(t, err)

@ -51,7 +51,7 @@ func (r *RepoTransfer) LoadAttributes() error {
if r.Recipient.IsOrganization() && len(r.TeamIDs) != len(r.Teams) { if r.Recipient.IsOrganization() && len(r.TeamIDs) != len(r.Teams) {
for _, v := range r.TeamIDs { for _, v := range r.TeamIDs {
team, err := organization.GetTeamByID(v) team, err := organization.GetTeamByID(db.DefaultContext, v)
if err != nil { if err != nil {
return err return err
} }
@ -130,7 +130,7 @@ func CancelRepositoryTransfer(repo *repo_model.Repository) error {
defer committer.Close() defer committer.Close()
repo.Status = repo_model.RepositoryReady repo.Status = repo_model.RepositoryReady
if err := repo_model.UpdateRepositoryColsCtx(ctx, repo, "status"); err != nil { if err := repo_model.UpdateRepositoryCols(ctx, repo, "status"); err != nil {
return err return err
} }
@ -172,12 +172,12 @@ func CreatePendingRepositoryTransfer(doer, newOwner *user_model.User, repoID int
} }
repo.Status = repo_model.RepositoryPendingTransfer repo.Status = repo_model.RepositoryPendingTransfer
if err := repo_model.UpdateRepositoryColsCtx(ctx, repo, "status"); err != nil { if err := repo_model.UpdateRepositoryCols(ctx, repo, "status"); err != nil {
return err return err
} }
// Check if new owner has repository with same name. // Check if new owner has repository with same name.
if has, err := repo_model.IsRepositoryExistCtx(ctx, newOwner, repo.Name); err != nil { if has, err := repo_model.IsRepositoryExist(ctx, newOwner, repo.Name); err != nil {
return fmt.Errorf("IsRepositoryExist: %v", err) return fmt.Errorf("IsRepositoryExist: %v", err)
} else if has { } else if has {
return repo_model.ErrRepoAlreadyExist{ return repo_model.ErrRepoAlreadyExist{
@ -250,14 +250,14 @@ func TransferOwnership(doer *user_model.User, newOwnerName string, repo *repo_mo
sess := db.GetEngine(ctx) sess := db.GetEngine(ctx)
newOwner, err := user_model.GetUserByNameCtx(ctx, newOwnerName) newOwner, err := user_model.GetUserByName(ctx, newOwnerName)
if err != nil { if err != nil {
return fmt.Errorf("get new owner '%s': %v", newOwnerName, err) return fmt.Errorf("get new owner '%s': %v", newOwnerName, err)
} }
newOwnerName = newOwner.Name // ensure capitalisation matches newOwnerName = newOwner.Name // ensure capitalisation matches
// Check if new owner has repository with same name. // Check if new owner has repository with same name.
if has, err := repo_model.IsRepositoryExistCtx(ctx, newOwner, repo.Name); err != nil { if has, err := repo_model.IsRepositoryExist(ctx, newOwner, repo.Name); err != nil {
return fmt.Errorf("IsRepositoryExist: %v", err) return fmt.Errorf("IsRepositoryExist: %v", err)
} else if has { } else if has {
return repo_model.ErrRepoAlreadyExist{ return repo_model.ErrRepoAlreadyExist{
@ -343,13 +343,13 @@ func TransferOwnership(doer *user_model.User, newOwnerName string, repo *repo_mo
return fmt.Errorf("decrease old owner repository count: %v", err) return fmt.Errorf("decrease old owner repository count: %v", err)
} }
if err := repo_model.WatchRepoCtx(ctx, doer.ID, repo.ID, true); err != nil { if err := repo_model.WatchRepo(ctx, doer.ID, repo.ID, true); err != nil {
return fmt.Errorf("watchRepo: %v", err) return fmt.Errorf("watchRepo: %v", err)
} }
// Remove watch for organization. // Remove watch for organization.
if oldOwner.IsOrganization() { if oldOwner.IsOrganization() {
if err := repo_model.WatchRepoCtx(ctx, oldOwner.ID, repo.ID, false); err != nil { if err := repo_model.WatchRepo(ctx, oldOwner.ID, repo.ID, false); err != nil {
return fmt.Errorf("watchRepo [false]: %v", err) return fmt.Errorf("watchRepo [false]: %v", err)
} }
} }
@ -410,7 +410,7 @@ func TransferOwnership(doer *user_model.User, newOwnerName string, repo *repo_mo
return fmt.Errorf("deleteRepositoryTransfer: %v", err) return fmt.Errorf("deleteRepositoryTransfer: %v", err)
} }
repo.Status = repo_model.RepositoryReady repo.Status = repo_model.RepositoryReady
if err := repo_model.UpdateRepositoryColsCtx(ctx, repo, "status"); err != nil { if err := repo_model.UpdateRepositoryCols(ctx, repo, "status"); err != nil {
return err return err
} }

@ -93,26 +93,26 @@ func (r *Review) LoadCodeComments(ctx context.Context) (err error) {
if r.CodeComments != nil { if r.CodeComments != nil {
return return
} }
if err = r.loadIssue(db.GetEngine(ctx)); err != nil { if err = r.loadIssue(ctx); err != nil {
return return
} }
r.CodeComments, err = fetchCodeCommentsByReview(ctx, r.Issue, nil, r) r.CodeComments, err = fetchCodeCommentsByReview(ctx, r.Issue, nil, r)
return return
} }
func (r *Review) loadIssue(e db.Engine) (err error) { func (r *Review) loadIssue(ctx context.Context) (err error) {
if r.Issue != nil { if r.Issue != nil {
return return
} }
r.Issue, err = getIssueByID(e, r.IssueID) r.Issue, err = getIssueByID(ctx, r.IssueID)
return return
} }
func (r *Review) loadReviewer(e db.Engine) (err error) { func (r *Review) loadReviewer(ctx context.Context) (err error) {
if r.ReviewerID == 0 || r.Reviewer != nil { if r.ReviewerID == 0 || r.Reviewer != nil {
return return
} }
r.Reviewer, err = user_model.GetUserByIDEngine(e, r.ReviewerID) r.Reviewer, err = user_model.GetUserByIDCtx(ctx, r.ReviewerID)
return return
} }
@ -121,13 +121,13 @@ func (r *Review) loadReviewerTeam(ctx context.Context) (err error) {
return return
} }
r.ReviewerTeam, err = organization.GetTeamByIDCtx(ctx, r.ReviewerTeamID) r.ReviewerTeam, err = organization.GetTeamByID(ctx, r.ReviewerTeamID)
return return
} }
// LoadReviewer loads reviewer // LoadReviewer loads reviewer
func (r *Review) LoadReviewer() error { func (r *Review) LoadReviewer() error {
return r.loadReviewer(db.GetEngine(db.DefaultContext)) return r.loadReviewer(db.DefaultContext)
} }
// LoadReviewerTeam loads reviewer team // LoadReviewerTeam loads reviewer team
@ -137,14 +137,13 @@ func (r *Review) LoadReviewerTeam() error {
// LoadAttributes loads all attributes except CodeComments // LoadAttributes loads all attributes except CodeComments
func (r *Review) LoadAttributes(ctx context.Context) (err error) { func (r *Review) LoadAttributes(ctx context.Context) (err error) {
e := db.GetEngine(ctx) if err = r.loadIssue(ctx); err != nil {
if err = r.loadIssue(e); err != nil {
return return
} }
if err = r.LoadCodeComments(ctx); err != nil { if err = r.LoadCodeComments(ctx); err != nil {
return return
} }
if err = r.loadReviewer(e); err != nil { if err = r.loadReviewer(ctx); err != nil {
return return
} }
if err = r.loadReviewerTeam(ctx); err != nil { if err = r.loadReviewerTeam(ctx); err != nil {
@ -153,9 +152,10 @@ func (r *Review) LoadAttributes(ctx context.Context) (err error) {
return return
} }
func getReviewByID(e db.Engine, id int64) (*Review, error) { // GetReviewByID returns the review by the given ID
func GetReviewByID(ctx context.Context, id int64) (*Review, error) {
review := new(Review) review := new(Review)
if has, err := e.ID(id).Get(review); err != nil { if has, err := db.GetEngine(ctx).ID(id).Get(review); err != nil {
return nil, err return nil, err
} else if !has { } else if !has {
return nil, ErrReviewNotExist{ID: id} return nil, ErrReviewNotExist{ID: id}
@ -164,11 +164,6 @@ 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.GetEngine(db.DefaultContext), id)
}
// FindReviewOptions represent possible filters to find reviews // FindReviewOptions represent possible filters to find reviews
type FindReviewOptions struct { type FindReviewOptions struct {
db.ListOptions db.ListOptions
@ -195,9 +190,10 @@ func (opts *FindReviewOptions) toCond() builder.Cond {
return cond return cond
} }
func findReviews(e db.Engine, opts FindReviewOptions) ([]*Review, error) { // FindReviews returns reviews passing FindReviewOptions
func FindReviews(ctx context.Context, opts FindReviewOptions) ([]*Review, error) {
reviews := make([]*Review, 0, 10) reviews := make([]*Review, 0, 10)
sess := e.Where(opts.toCond()) sess := db.GetEngine(ctx).Where(opts.toCond())
if opts.Page > 0 { if opts.Page > 0 {
sess = db.SetSessionPagination(sess, &opts) sess = db.SetSessionPagination(sess, &opts)
} }
@ -207,11 +203,6 @@ func findReviews(e db.Engine, opts FindReviewOptions) ([]*Review, error) {
Find(&reviews) Find(&reviews)
} }
// FindReviews returns reviews passing FindReviewOptions
func FindReviews(opts FindReviewOptions) ([]*Review, error) {
return findReviews(db.GetEngine(db.DefaultContext), opts)
}
// CountReviews returns count of reviews passing FindReviewOptions // CountReviews returns count of reviews passing FindReviewOptions
func CountReviews(opts FindReviewOptions) (int64, error) { func CountReviews(opts FindReviewOptions) (int64, error) {
return db.GetEngine(db.DefaultContext).Where(opts.toCond()).Count(&Review{}) return db.GetEngine(db.DefaultContext).Where(opts.toCond()).Count(&Review{})
@ -230,12 +221,8 @@ type CreateReviewOptions struct {
} }
// IsOfficialReviewer check if at least one of the provided reviewers can make official reviews in issue (counts towards required approvals) // 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_model.User) (bool, error) { func IsOfficialReviewer(ctx context.Context, issue *Issue, reviewers ...*user_model.User) (bool, error) {
return isOfficialReviewer(db.DefaultContext, issue, reviewers...) pr, err := GetPullRequestByIssueID(ctx, issue.ID)
}
func isOfficialReviewer(ctx context.Context, issue *Issue, reviewers ...*user_model.User) (bool, error) {
pr, err := getPullRequestByIssueID(db.GetEngine(ctx), issue.ID)
if err != nil { if err != nil {
return false, err return false, err
} }
@ -257,12 +244,8 @@ func isOfficialReviewer(ctx context.Context, issue *Issue, reviewers ...*user_mo
} }
// IsOfficialReviewerTeam check if reviewer in this team can make official reviews in issue (counts towards required approvals) // IsOfficialReviewerTeam check if reviewer in this team can make official reviews in issue (counts towards required approvals)
func IsOfficialReviewerTeam(issue *Issue, team *organization.Team) (bool, error) { func IsOfficialReviewerTeam(ctx context.Context, issue *Issue, team *organization.Team) (bool, error) {
return isOfficialReviewerTeam(db.DefaultContext, issue, team) pr, err := GetPullRequestByIssueID(ctx, issue.ID)
}
func isOfficialReviewerTeam(ctx context.Context, issue *Issue, team *organization.Team) (bool, error) {
pr, err := getPullRequestByIssueID(db.GetEngine(ctx), issue.ID)
if err != nil { if err != nil {
return false, err return false, err
} }
@ -280,7 +263,8 @@ func isOfficialReviewerTeam(ctx context.Context, issue *Issue, team *organizatio
return base.Int64sContains(pr.ProtectedBranch.ApprovalsWhitelistTeamIDs, team.ID), nil return base.Int64sContains(pr.ProtectedBranch.ApprovalsWhitelistTeamIDs, team.ID), nil
} }
func createReview(e db.Engine, opts CreateReviewOptions) (*Review, error) { // CreateReview creates a new review based on opts
func CreateReview(ctx context.Context, opts CreateReviewOptions) (*Review, error) {
review := &Review{ review := &Review{
Type: opts.Type, Type: opts.Type,
Issue: opts.Issue, Issue: opts.Issue,
@ -300,23 +284,15 @@ func createReview(e db.Engine, opts CreateReviewOptions) (*Review, error) {
} }
review.ReviewerTeamID = opts.ReviewerTeam.ID review.ReviewerTeamID = opts.ReviewerTeam.ID
} }
if _, err := e.Insert(review); err != nil { return review, db.Insert(ctx, review)
return nil, err
} }
return review, nil // GetCurrentReview returns the current pending review of reviewer for given issue
} func GetCurrentReview(ctx context.Context, reviewer *user_model.User, issue *Issue) (*Review, error) {
// CreateReview creates a new review based on opts
func CreateReview(opts CreateReviewOptions) (*Review, error) {
return createReview(db.GetEngine(db.DefaultContext), opts)
}
func getCurrentReview(e db.Engine, reviewer *user_model.User, issue *Issue) (*Review, error) {
if reviewer == nil { if reviewer == nil {
return nil, nil return nil, nil
} }
reviews, err := findReviews(e, FindReviewOptions{ reviews, err := FindReviews(ctx, FindReviewOptions{
Type: ReviewTypePending, Type: ReviewTypePending,
IssueID: issue.ID, IssueID: issue.ID,
ReviewerID: reviewer.ID, ReviewerID: reviewer.ID,
@ -337,11 +313,6 @@ func ReviewExists(issue *Issue, treePath string, line int64) (bool, error) {
return db.GetEngine(db.DefaultContext).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_model.User, issue *Issue) (*Review, error) {
return getCurrentReview(db.GetEngine(db.DefaultContext), reviewer, issue)
}
// ContentEmptyErr represents an content empty error // ContentEmptyErr represents an content empty error
type ContentEmptyErr struct{} type ContentEmptyErr struct{}
@ -366,7 +337,7 @@ func SubmitReview(doer *user_model.User, issue *Issue, reviewType ReviewType, co
official := false official := false
review, err := getCurrentReview(sess, doer, issue) review, err := GetCurrentReview(ctx, doer, issue)
if err != nil { if err != nil {
if !IsErrReviewNotExist(err) { if !IsErrReviewNotExist(err) {
return nil, nil, err return nil, nil, err
@ -378,16 +349,16 @@ func SubmitReview(doer *user_model.User, issue *Issue, reviewType ReviewType, co
if reviewType == ReviewTypeApprove || reviewType == ReviewTypeReject { if reviewType == ReviewTypeApprove || reviewType == ReviewTypeReject {
// Only reviewers latest review of type approve and reject shall count as "official", so existing reviews needs to be cleared // Only reviewers latest review of type approve and reject shall count as "official", so existing reviews needs to be cleared
if _, err := sess.Exec("UPDATE `review` SET official=? WHERE issue_id=? AND reviewer_id=?", false, issue.ID, doer.ID); err != nil { if _, err := db.Exec(ctx, "UPDATE `review` SET official=? WHERE issue_id=? AND reviewer_id=?", false, issue.ID, doer.ID); err != nil {
return nil, nil, err return nil, nil, err
} }
if official, err = isOfficialReviewer(ctx, issue, doer); err != nil { if official, err = IsOfficialReviewer(ctx, issue, doer); err != nil {
return nil, nil, err return nil, nil, err
} }
} }
// No current review. Create a new one! // No current review. Create a new one!
if review, err = createReview(sess, CreateReviewOptions{ if review, err = CreateReview(ctx, CreateReviewOptions{
Type: reviewType, Type: reviewType,
Issue: issue, Issue: issue,
Reviewer: doer, Reviewer: doer,
@ -408,10 +379,10 @@ func SubmitReview(doer *user_model.User, issue *Issue, reviewType ReviewType, co
if reviewType == ReviewTypeApprove || reviewType == ReviewTypeReject { if reviewType == ReviewTypeApprove || reviewType == ReviewTypeReject {
// Only reviewers latest review of type approve and reject shall count as "official", so existing reviews needs to be cleared // Only reviewers latest review of type approve and reject shall count as "official", so existing reviews needs to be cleared
if _, err := sess.Exec("UPDATE `review` SET official=? WHERE issue_id=? AND reviewer_id=?", false, issue.ID, doer.ID); err != nil { if _, err := db.Exec(ctx, "UPDATE `review` SET official=? WHERE issue_id=? AND reviewer_id=?", false, issue.ID, doer.ID); err != nil {
return nil, nil, err return nil, nil, err
} }
if official, err = isOfficialReviewer(ctx, issue, doer); err != nil { if official, err = IsOfficialReviewer(ctx, issue, doer); err != nil {
return nil, nil, err return nil, nil, err
} }
} }
@ -456,7 +427,7 @@ func SubmitReview(doer *user_model.User, issue *Issue, reviewType ReviewType, co
continue continue
} }
if _, err := sess.Delete(teamReviewRequest); err != nil { if _, err := sess.ID(teamReviewRequest.ID).NoAutoCondition().Delete(teamReviewRequest); err != nil {
return nil, nil, err return nil, nil, err
} }
} }
@ -508,14 +479,10 @@ func GetReviewersFromOriginalAuthorsByIssueID(issueID int64) ([]*Review, error)
} }
// GetReviewByIssueIDAndUserID get the latest review of reviewer for a pull request // GetReviewByIssueIDAndUserID get the latest review of reviewer for a pull request
func GetReviewByIssueIDAndUserID(issueID, userID int64) (*Review, error) { func GetReviewByIssueIDAndUserID(ctx context.Context, issueID, userID int64) (*Review, error) {
return getReviewByIssueIDAndUserID(db.GetEngine(db.DefaultContext), issueID, userID)
}
func getReviewByIssueIDAndUserID(e db.Engine, issueID, userID int64) (*Review, error) {
review := new(Review) review := new(Review)
has, err := e.SQL("SELECT * FROM review WHERE id IN (SELECT max(id) as id FROM review WHERE issue_id = ? AND reviewer_id = ? AND original_author_id = 0 AND type in (?, ?, ?))", has, err := db.GetEngine(ctx).SQL("SELECT * FROM review WHERE id IN (SELECT max(id) as id FROM review WHERE issue_id = ? AND reviewer_id = ? AND original_author_id = 0 AND type in (?, ?, ?))",
issueID, userID, ReviewTypeApprove, ReviewTypeReject, ReviewTypeRequest). issueID, userID, ReviewTypeApprove, ReviewTypeReject, ReviewTypeRequest).
Get(review) Get(review)
if err != nil { if err != nil {
@ -530,15 +497,11 @@ func getReviewByIssueIDAndUserID(e db.Engine, issueID, userID int64) (*Review, e
} }
// GetTeamReviewerByIssueIDAndTeamID get the latest review request of reviewer team for a pull request // GetTeamReviewerByIssueIDAndTeamID get the latest review request of reviewer team for a pull request
func GetTeamReviewerByIssueIDAndTeamID(issueID, teamID int64) (review *Review, err error) { func GetTeamReviewerByIssueIDAndTeamID(ctx context.Context, issueID, teamID int64) (review *Review, err error) {
return getTeamReviewerByIssueIDAndTeamID(db.GetEngine(db.DefaultContext), issueID, teamID)
}
func getTeamReviewerByIssueIDAndTeamID(e db.Engine, issueID, teamID int64) (review *Review, err error) {
review = new(Review) review = new(Review)
has := false has := false
if has, err = e.SQL("SELECT * FROM review WHERE id IN (SELECT max(id) as id FROM review WHERE issue_id = ? AND reviewer_team_id = ?)", if has, err = db.GetEngine(ctx).SQL("SELECT * FROM review WHERE id IN (SELECT max(id) as id FROM review WHERE issue_id = ? AND reviewer_team_id = ?)",
issueID, teamID). issueID, teamID).
Get(review); err != nil { Get(review); err != nil {
return nil, err return nil, err
@ -633,7 +596,7 @@ func AddReviewRequest(issue *Issue, reviewer, doer *user_model.User) (*Comment,
defer committer.Close() defer committer.Close()
sess := db.GetEngine(ctx) sess := db.GetEngine(ctx)
review, err := getReviewByIssueIDAndUserID(sess, issue.ID, reviewer.ID) review, err := GetReviewByIssueIDAndUserID(ctx, issue.ID, reviewer.ID)
if err != nil && !IsErrReviewNotExist(err) { if err != nil && !IsErrReviewNotExist(err) {
return nil, err return nil, err
} }
@ -643,7 +606,7 @@ func AddReviewRequest(issue *Issue, reviewer, doer *user_model.User) (*Comment,
return nil, nil return nil, nil
} }
official, err := isOfficialReviewer(ctx, issue, reviewer, doer) official, err := IsOfficialReviewer(ctx, issue, reviewer, doer)
if err != nil { if err != nil {
return nil, err return nil, err
} else if official { } else if official {
@ -652,7 +615,7 @@ func AddReviewRequest(issue *Issue, reviewer, doer *user_model.User) (*Comment,
} }
} }
review, err = createReview(sess, CreateReviewOptions{ review, err = CreateReview(ctx, CreateReviewOptions{
Type: ReviewTypeRequest, Type: ReviewTypeRequest,
Issue: issue, Issue: issue,
Reviewer: reviewer, Reviewer: reviewer,
@ -686,9 +649,8 @@ func RemoveReviewRequest(issue *Issue, reviewer, doer *user_model.User) (*Commen
return nil, err return nil, err
} }
defer committer.Close() defer committer.Close()
sess := db.GetEngine(ctx)
review, err := getReviewByIssueIDAndUserID(sess, issue.ID, reviewer.ID) review, err := GetReviewByIssueIDAndUserID(ctx, issue.ID, reviewer.ID)
if err != nil && !IsErrReviewNotExist(err) { if err != nil && !IsErrReviewNotExist(err) {
return nil, err return nil, err
} }
@ -697,22 +659,22 @@ func RemoveReviewRequest(issue *Issue, reviewer, doer *user_model.User) (*Commen
return nil, nil return nil, nil
} }
if _, err = sess.Delete(review); err != nil { if _, err = db.DeleteByBean(ctx, review); err != nil {
return nil, err return nil, err
} }
official, err := isOfficialReviewer(ctx, issue, reviewer) official, err := IsOfficialReviewer(ctx, issue, reviewer)
if err != nil { if err != nil {
return nil, err return nil, err
} else if official { } else if official {
// recalculate the latest official review for reviewer // recalculate the latest official review for reviewer
review, err := getReviewByIssueIDAndUserID(sess, issue.ID, reviewer.ID) review, err := GetReviewByIssueIDAndUserID(ctx, issue.ID, reviewer.ID)
if err != nil && !IsErrReviewNotExist(err) { if err != nil && !IsErrReviewNotExist(err) {
return nil, err return nil, err
} }
if review != nil { if review != nil {
if _, err := sess.Exec("UPDATE `review` SET official=? WHERE id=?", true, review.ID); err != nil { if _, err := db.Exec(ctx, "UPDATE `review` SET official=? WHERE id=?", true, review.ID); err != nil {
return nil, err return nil, err
} }
} }
@ -740,9 +702,8 @@ func AddTeamReviewRequest(issue *Issue, reviewer *organization.Team, doer *user_
return nil, err return nil, err
} }
defer committer.Close() defer committer.Close()
sess := db.GetEngine(ctx)
review, err := getTeamReviewerByIssueIDAndTeamID(sess, issue.ID, reviewer.ID) review, err := GetTeamReviewerByIssueIDAndTeamID(ctx, issue.ID, reviewer.ID)
if err != nil && !IsErrReviewNotExist(err) { if err != nil && !IsErrReviewNotExist(err) {
return nil, err return nil, err
} }
@ -752,16 +713,16 @@ func AddTeamReviewRequest(issue *Issue, reviewer *organization.Team, doer *user_
return nil, nil return nil, nil
} }
official, err := isOfficialReviewerTeam(ctx, issue, reviewer) official, err := IsOfficialReviewerTeam(ctx, issue, reviewer)
if err != nil { if err != nil {
return nil, fmt.Errorf("isOfficialReviewerTeam(): %v", err) return nil, fmt.Errorf("isOfficialReviewerTeam(): %v", err)
} else if !official { } else if !official {
if official, err = isOfficialReviewer(ctx, issue, doer); err != nil { if official, err = IsOfficialReviewer(ctx, issue, doer); err != nil {
return nil, fmt.Errorf("isOfficialReviewer(): %v", err) return nil, fmt.Errorf("isOfficialReviewer(): %v", err)
} }
} }
if review, err = createReview(sess, CreateReviewOptions{ if review, err = CreateReview(ctx, CreateReviewOptions{
Type: ReviewTypeRequest, Type: ReviewTypeRequest,
Issue: issue, Issue: issue,
ReviewerTeam: reviewer, ReviewerTeam: reviewer,
@ -772,7 +733,7 @@ func AddTeamReviewRequest(issue *Issue, reviewer *organization.Team, doer *user_
} }
if official { if official {
if _, err := sess.Exec("UPDATE `review` SET official=? WHERE issue_id=? AND reviewer_team_id=?", false, issue.ID, reviewer.ID); err != nil { if _, err := db.Exec(ctx, "UPDATE `review` SET official=? WHERE issue_id=? AND reviewer_team_id=?", false, issue.ID, reviewer.ID); err != nil {
return nil, err return nil, err
} }
} }
@ -800,9 +761,8 @@ func RemoveTeamReviewRequest(issue *Issue, reviewer *organization.Team, doer *us
return nil, err return nil, err
} }
defer committer.Close() defer committer.Close()
sess := db.GetEngine(ctx)
review, err := getTeamReviewerByIssueIDAndTeamID(sess, issue.ID, reviewer.ID) review, err := GetTeamReviewerByIssueIDAndTeamID(ctx, issue.ID, reviewer.ID)
if err != nil && !IsErrReviewNotExist(err) { if err != nil && !IsErrReviewNotExist(err) {
return nil, err return nil, err
} }
@ -811,24 +771,24 @@ func RemoveTeamReviewRequest(issue *Issue, reviewer *organization.Team, doer *us
return nil, nil return nil, nil
} }
if _, err = sess.Delete(review); err != nil { if _, err = db.DeleteByBean(ctx, review); err != nil {
return nil, err return nil, err
} }
official, err := isOfficialReviewerTeam(ctx, issue, reviewer) official, err := IsOfficialReviewerTeam(ctx, issue, reviewer)
if err != nil { if err != nil {
return nil, fmt.Errorf("isOfficialReviewerTeam(): %v", err) return nil, fmt.Errorf("isOfficialReviewerTeam(): %v", err)
} }
if official { if official {
// recalculate which is the latest official review from that team // recalculate which is the latest official review from that team
review, err := getReviewByIssueIDAndUserID(sess, issue.ID, -reviewer.ID) review, err := GetReviewByIssueIDAndUserID(ctx, issue.ID, -reviewer.ID)
if err != nil && !IsErrReviewNotExist(err) { if err != nil && !IsErrReviewNotExist(err) {
return nil, err return nil, err
} }
if review != nil { if review != nil {
if _, err := sess.Exec("UPDATE `review` SET official=? WHERE id=?", true, review.ID); err != nil { if _, err := db.Exec(ctx, "UPDATE `review` SET official=? WHERE id=?", true, review.ID); err != nil {
return nil, err return nil, err
} }
} }
@ -899,7 +859,7 @@ func CanMarkConversation(issue *Issue, doer *user_model.User) (permResult bool,
permResult = p.CanAccess(perm.AccessModeWrite, unit.TypePullRequests) permResult = p.CanAccess(perm.AccessModeWrite, unit.TypePullRequests)
if !permResult { if !permResult {
if permResult, err = IsOfficialReviewer(issue, doer); err != nil { if permResult, err = IsOfficialReviewer(db.DefaultContext, issue, doer); err != nil {
return false, err return false, err
} }
} }

@ -16,12 +16,12 @@ import (
func TestGetReviewByID(t *testing.T) { func TestGetReviewByID(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase()) assert.NoError(t, unittest.PrepareTestDatabase())
review, err := GetReviewByID(1) review, err := GetReviewByID(db.DefaultContext, 1)
assert.NoError(t, err) assert.NoError(t, err)
assert.Equal(t, "Demo Review", review.Content) assert.Equal(t, "Demo Review", review.Content)
assert.Equal(t, ReviewTypeApprove, review.Type) assert.Equal(t, ReviewTypeApprove, review.Type)
_, err = GetReviewByID(23892) _, err = GetReviewByID(db.DefaultContext, 23892)
assert.Error(t, err) assert.Error(t, err)
assert.True(t, IsErrReviewNotExist(err), "IsErrReviewNotExist") assert.True(t, IsErrReviewNotExist(err), "IsErrReviewNotExist")
} }
@ -61,7 +61,7 @@ func TestReviewType_Icon(t *testing.T) {
func TestFindReviews(t *testing.T) { func TestFindReviews(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase()) assert.NoError(t, unittest.PrepareTestDatabase())
reviews, err := FindReviews(FindReviewOptions{ reviews, err := FindReviews(db.DefaultContext, FindReviewOptions{
Type: ReviewTypeApprove, Type: ReviewTypeApprove,
IssueID: 2, IssueID: 2,
ReviewerID: 1, ReviewerID: 1,
@ -76,14 +76,14 @@ func TestGetCurrentReview(t *testing.T) {
issue := unittest.AssertExistsAndLoadBean(t, &Issue{ID: 2}).(*Issue) issue := unittest.AssertExistsAndLoadBean(t, &Issue{ID: 2}).(*Issue)
user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 1}).(*user_model.User) user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 1}).(*user_model.User)
review, err := GetCurrentReview(user, issue) review, err := GetCurrentReview(db.DefaultContext, user, issue)
assert.NoError(t, err) assert.NoError(t, err)
assert.NotNil(t, review) assert.NotNil(t, review)
assert.Equal(t, ReviewTypePending, review.Type) assert.Equal(t, ReviewTypePending, review.Type)
assert.Equal(t, "Pending Review", review.Content) assert.Equal(t, "Pending Review", review.Content)
user2 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 7}).(*user_model.User) user2 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 7}).(*user_model.User)
review2, err := GetCurrentReview(user2, issue) review2, err := GetCurrentReview(db.DefaultContext, user2, issue)
assert.Error(t, err) assert.Error(t, err)
assert.True(t, IsErrReviewNotExist(err)) assert.True(t, IsErrReviewNotExist(err))
assert.Nil(t, review2) assert.Nil(t, review2)
@ -95,7 +95,7 @@ func TestCreateReview(t *testing.T) {
issue := unittest.AssertExistsAndLoadBean(t, &Issue{ID: 2}).(*Issue) issue := unittest.AssertExistsAndLoadBean(t, &Issue{ID: 2}).(*Issue)
user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 1}).(*user_model.User) user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 1}).(*user_model.User)
review, err := CreateReview(CreateReviewOptions{ review, err := CreateReview(db.DefaultContext, CreateReviewOptions{
Content: "New Review", Content: "New Review",
Type: ReviewTypePending, Type: ReviewTypePending,
Issue: issue, Issue: issue,

@ -51,9 +51,9 @@ type IssueByRepositoryCount struct {
func GetStatistic() (stats Statistic) { func GetStatistic() (stats Statistic) {
e := db.GetEngine(db.DefaultContext) e := db.GetEngine(db.DefaultContext)
stats.Counter.User = user_model.CountUsers(nil) stats.Counter.User = user_model.CountUsers(nil)
stats.Counter.Org = organization.CountOrganizations() stats.Counter.Org, _ = organization.CountOrgs(organization.FindOrgOptions{IncludePrivate: true})
stats.Counter.PublicKey, _ = e.Count(new(asymkey_model.PublicKey)) stats.Counter.PublicKey, _ = e.Count(new(asymkey_model.PublicKey))
stats.Counter.Repo = repo_model.CountRepositories(true) stats.Counter.Repo, _ = repo_model.CountRepositories(db.DefaultContext, repo_model.CountRepositoryOptions{})
stats.Counter.Watch, _ = e.Count(new(repo_model.Watch)) stats.Counter.Watch, _ = e.Count(new(repo_model.Watch))
stats.Counter.Star, _ = e.Count(new(repo_model.Star)) stats.Counter.Star, _ = e.Count(new(repo_model.Star))
stats.Counter.Action, _ = e.Count(new(Action)) stats.Counter.Action, _ = e.Count(new(Action))

@ -5,6 +5,7 @@
package models package models
import ( import (
"context"
"fmt" "fmt"
"code.gitea.io/gitea/models/db" "code.gitea.io/gitea/models/db"
@ -51,15 +52,15 @@ type TranslatableMessage struct {
// LoadRepo loads repository of the task // LoadRepo loads repository of the task
func (task *Task) LoadRepo() error { func (task *Task) LoadRepo() error {
return task.loadRepo(db.GetEngine(db.DefaultContext)) return task.loadRepo(db.DefaultContext)
} }
func (task *Task) loadRepo(e db.Engine) error { func (task *Task) loadRepo(ctx context.Context) error {
if task.Repo != nil { if task.Repo != nil {
return nil return nil
} }
var repo repo_model.Repository var repo repo_model.Repository
has, err := e.ID(task.RepoID).Get(&repo) has, err := db.GetEngine(ctx).ID(task.RepoID).Get(&repo)
if err != nil { if err != nil {
return err return err
} else if !has { } else if !has {
@ -233,12 +234,7 @@ func FindTasks(opts FindTaskOptions) ([]*Task, error) {
// CreateTask creates a task on database // CreateTask creates a task on database
func CreateTask(task *Task) error { func CreateTask(task *Task) error {
return createTask(db.GetEngine(db.DefaultContext), task) return db.Insert(db.DefaultContext, task)
}
func createTask(e db.Engine, task *Task) error {
_, err := e.Insert(task)
return err
} }
// FinishMigrateTask updates database when migrate task finished // FinishMigrateTask updates database when migrate task finished

@ -166,7 +166,7 @@ func DeleteUser(ctx context.Context, u *user_model.User) (err error) {
// ***** END: Branch Protections ***** // ***** END: Branch Protections *****
// ***** START: PublicKey ***** // ***** START: PublicKey *****
if _, err = e.Delete(&asymkey_model.PublicKey{OwnerID: u.ID}); err != nil { if _, err = db.DeleteByBean(ctx, &asymkey_model.PublicKey{OwnerID: u.ID}); err != nil {
return fmt.Errorf("deletePublicKeys: %v", err) return fmt.Errorf("deletePublicKeys: %v", err)
} }
// ***** END: PublicKey ***** // ***** END: PublicKey *****
@ -178,17 +178,17 @@ func DeleteUser(ctx context.Context, u *user_model.User) (err error) {
} }
// Delete GPGKeyImport(s). // Delete GPGKeyImport(s).
for _, key := range keys { for _, key := range keys {
if _, err = e.Delete(&asymkey_model.GPGKeyImport{KeyID: key.KeyID}); err != nil { if _, err = db.DeleteByBean(ctx, &asymkey_model.GPGKeyImport{KeyID: key.KeyID}); err != nil {
return fmt.Errorf("deleteGPGKeyImports: %v", err) return fmt.Errorf("deleteGPGKeyImports: %v", err)
} }
} }
if _, err = e.Delete(&asymkey_model.GPGKey{OwnerID: u.ID}); err != nil { if _, err = db.DeleteByBean(ctx, &asymkey_model.GPGKey{OwnerID: u.ID}); err != nil {
return fmt.Errorf("deleteGPGKeys: %v", err) return fmt.Errorf("deleteGPGKeys: %v", err)
} }
// ***** END: GPGPublicKey ***** // ***** END: GPGPublicKey *****
// Clear assignee. // Clear assignee.
if err = clearAssigneeByUserID(e, u.ID); err != nil { if _, err = db.DeleteByBean(ctx, &IssueAssignees{AssigneeID: u.ID}); err != nil {
return fmt.Errorf("clear assignee: %v", err) return fmt.Errorf("clear assignee: %v", err)
} }

@ -26,12 +26,7 @@ func (u *User) CustomAvatarRelativePath() string {
} }
// GenerateRandomAvatar generates a random avatar for user. // GenerateRandomAvatar generates a random avatar for user.
func GenerateRandomAvatar(u *User) error { func GenerateRandomAvatar(ctx context.Context, u *User) error {
return GenerateRandomAvatarCtx(db.DefaultContext, u)
}
// GenerateRandomAvatarCtx generates a random avatar for user.
func GenerateRandomAvatarCtx(ctx context.Context, u *User) error {
seed := u.Email seed := u.Email
if len(seed) == 0 { if len(seed) == 0 {
seed = u.Name seed = u.Name
@ -82,7 +77,7 @@ func (u *User) AvatarLinkWithSize(size int) string {
if useLocalAvatar { if useLocalAvatar {
if u.Avatar == "" && autoGenerateAvatar { if u.Avatar == "" && autoGenerateAvatar {
if err := GenerateRandomAvatar(u); err != nil { if err := GenerateRandomAvatar(db.DefaultContext, u); err != nil {
log.Error("GenerateRandomAvatar: %v", err) log.Error("GenerateRandomAvatar: %v", err)
} }
} }

@ -207,7 +207,8 @@ func IsEmailUsed(ctx context.Context, email string) (bool, error) {
return db.GetEngine(ctx).Where("lower_email=?", strings.ToLower(email)).Get(&EmailAddress{}) return db.GetEngine(ctx).Where("lower_email=?", strings.ToLower(email)).Get(&EmailAddress{})
} }
func addEmailAddress(ctx context.Context, email *EmailAddress) error { // AddEmailAddress adds an email address to given user.
func AddEmailAddress(ctx context.Context, email *EmailAddress) error {
email.Email = strings.TrimSpace(email.Email) email.Email = strings.TrimSpace(email.Email)
used, err := IsEmailUsed(ctx, email.Email) used, err := IsEmailUsed(ctx, email.Email)
if err != nil { if err != nil {
@ -223,11 +224,6 @@ func addEmailAddress(ctx context.Context, email *EmailAddress) error {
return db.Insert(ctx, email) return db.Insert(ctx, email)
} }
// AddEmailAddress adds an email address to given user.
func AddEmailAddress(email *EmailAddress) error {
return addEmailAddress(db.DefaultContext, email)
}
// AddEmailAddresses adds an email address to given user. // AddEmailAddresses adds an email address to given user.
func AddEmailAddresses(emails []*EmailAddress) error { func AddEmailAddresses(emails []*EmailAddress) error {
if len(emails) == 0 { if len(emails) == 0 {
@ -311,14 +307,14 @@ func ActivateEmail(email *EmailAddress) error {
return err return err
} }
defer committer.Close() defer committer.Close()
if err := updateActivation(db.GetEngine(ctx), email, true); err != nil { if err := updateActivation(ctx, email, true); err != nil {
return err return err
} }
return committer.Commit() return committer.Commit()
} }
func updateActivation(e db.Engine, email *EmailAddress, activate bool) error { func updateActivation(ctx context.Context, email *EmailAddress, activate bool) error {
user, err := GetUserByIDEngine(e, email.UID) user, err := GetUserByIDCtx(ctx, email.UID)
if err != nil { if err != nil {
return err return err
} }
@ -326,10 +322,10 @@ func updateActivation(e db.Engine, email *EmailAddress, activate bool) error {
return err return err
} }
email.IsActivated = activate email.IsActivated = activate
if _, err := e.ID(email.ID).Cols("is_activated").Update(email); err != nil { if _, err := db.GetEngine(ctx).ID(email.ID).Cols("is_activated").Update(email); err != nil {
return err return err
} }
return UpdateUserColsEngine(e, user, "rands") return UpdateUserCols(ctx, user, "rands")
} }
// MakeEmailPrimary sets primary email address of given user. // MakeEmailPrimary sets primary email address of given user.
@ -500,12 +496,11 @@ func ActivateUserEmail(userID int64, email string, activate bool) (err error) {
return err return err
} }
defer committer.Close() defer committer.Close()
sess := db.GetEngine(ctx)
// Activate/deactivate a user's secondary email address // Activate/deactivate a user's secondary email address
// First check if there's another user active with the same address // First check if there's another user active with the same address
addr := EmailAddress{UID: userID, LowerEmail: strings.ToLower(email)} addr := EmailAddress{UID: userID, LowerEmail: strings.ToLower(email)}
if has, err := sess.Get(&addr); err != nil { if has, err := db.GetByBean(ctx, &addr); err != nil {
return err return err
} else if !has { } else if !has {
return fmt.Errorf("no such email: %d (%s)", userID, email) return fmt.Errorf("no such email: %d (%s)", userID, email)
@ -521,14 +516,14 @@ func ActivateUserEmail(userID int64, email string, activate bool) (err error) {
return ErrEmailAlreadyUsed{Email: email} return ErrEmailAlreadyUsed{Email: email}
} }
} }
if err = updateActivation(sess, &addr, activate); err != nil { if err = updateActivation(ctx, &addr, activate); err != nil {
return fmt.Errorf("unable to updateActivation() for %d:%s: %w", addr.ID, addr.Email, err) return fmt.Errorf("unable to updateActivation() for %d:%s: %w", addr.ID, addr.Email, err)
} }
// Activate/deactivate a user's primary email address and account // Activate/deactivate a user's primary email address and account
if addr.IsPrimary { if addr.IsPrimary {
user := User{ID: userID, Email: email} user := User{ID: userID, Email: email}
if has, err := sess.Get(&user); err != nil { if has, err := db.GetByBean(ctx, &user); err != nil {
return err return err
} else if !has { } else if !has {
return fmt.Errorf("no user with ID: %d and Email: %s", userID, email) return fmt.Errorf("no user with ID: %d and Email: %s", userID, email)
@ -539,7 +534,7 @@ func ActivateUserEmail(userID int64, email string, activate bool) (err error) {
if user.Rands, err = GetUserSalt(); err != nil { if user.Rands, err = GetUserSalt(); err != nil {
return fmt.Errorf("unable to generate salt: %v", err) return fmt.Errorf("unable to generate salt: %v", err)
} }
if err = UpdateUserColsEngine(sess, &user, "is_active", "rands"); err != nil { if err = UpdateUserCols(ctx, &user, "is_active", "rands"); err != nil {
return fmt.Errorf("unable to updateUserCols() for user ID: %d: %v", userID, err) return fmt.Errorf("unable to updateUserCols() for user ID: %d: %v", userID, err)
} }
} }

@ -45,7 +45,7 @@ func TestIsEmailUsed(t *testing.T) {
func TestAddEmailAddress(t *testing.T) { func TestAddEmailAddress(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase()) assert.NoError(t, unittest.PrepareTestDatabase())
assert.NoError(t, AddEmailAddress(&EmailAddress{ assert.NoError(t, AddEmailAddress(db.DefaultContext, &EmailAddress{
Email: "user1234567890@example.com", Email: "user1234567890@example.com",
LowerEmail: "user1234567890@example.com", LowerEmail: "user1234567890@example.com",
IsPrimary: true, IsPrimary: true,
@ -53,7 +53,7 @@ func TestAddEmailAddress(t *testing.T) {
})) }))
// ErrEmailAlreadyUsed // ErrEmailAlreadyUsed
err := AddEmailAddress(&EmailAddress{ err := AddEmailAddress(db.DefaultContext, &EmailAddress{
Email: "user1234567890@example.com", Email: "user1234567890@example.com",
LowerEmail: "user1234567890@example.com", LowerEmail: "user1234567890@example.com",
}) })

Some files were not shown because too many files have changed in this diff Show More

Loading…
Cancel
Save