Skip to content

Commit

Permalink
Add context.Context to more methods (go-gitea#21546)
Browse files Browse the repository at this point in the history
This PR adds a context parameter to a bunch of methods. Some helper
`xxxCtx()` methods got replaced with the normal name now.

Co-authored-by: delvh <dev.lh@web.de>
Co-authored-by: Lunny Xiao <xiaolunwen@gmail.com>
  • Loading branch information
3 people authored and fsologureng committed Nov 22, 2022
1 parent fbad0fc commit 82110fe
Show file tree
Hide file tree
Showing 148 changed files with 1,408 additions and 1,561 deletions.
2 changes: 1 addition & 1 deletion cmd/admin.go
Expand Up @@ -727,7 +727,7 @@ func runRepoSyncReleases(_ *cli.Context) error {

log.Trace("Synchronizing repository releases (this may take a while)")
for page := 1; ; page++ {
repos, count, err := repo_model.SearchRepositoryByName(&repo_model.SearchRepoOptions{
repos, count, err := repo_model.SearchRepositoryByName(ctx, &repo_model.SearchRepoOptions{
ListOptions: db.ListOptions{
PageSize: repo_model.RepositoryListDefaultPageSize,
Page: page,
Expand Down
18 changes: 7 additions & 11 deletions models/activities/action.go
Expand Up @@ -461,7 +461,8 @@ func DeleteOldActions(olderThan time.Duration) (err error) {
return err
}

func notifyWatchers(ctx context.Context, actions ...*Action) error {
// NotifyWatchers creates batch of actions for every watcher.
func NotifyWatchers(ctx context.Context, actions ...*Action) error {
var watchers []*repo_model.Watch
var repo *repo_model.Repository
var err error
Expand Down Expand Up @@ -565,11 +566,6 @@ func notifyWatchers(ctx context.Context, actions ...*Action) error {
return nil
}

// NotifyWatchers creates batch of actions for every watcher.
func NotifyWatchers(actions ...*Action) error {
return notifyWatchers(db.DefaultContext, actions...)
}

// NotifyWatchersActions creates batch of actions for every watcher.
func NotifyWatchersActions(acts []*Action) error {
ctx, committer, err := db.TxContext(db.DefaultContext)
Expand All @@ -578,7 +574,7 @@ func NotifyWatchersActions(acts []*Action) error {
}
defer committer.Close()
for _, act := range acts {
if err := notifyWatchers(ctx, act); err != nil {
if err := NotifyWatchers(ctx, act); err != nil {
return err
}
}
Expand All @@ -603,17 +599,17 @@ func DeleteIssueActions(ctx context.Context, repoID, issueID int64) error {
}

// CountActionCreatedUnixString count actions where created_unix is an empty string
func CountActionCreatedUnixString() (int64, error) {
func CountActionCreatedUnixString(ctx context.Context) (int64, error) {
if setting.Database.UseSQLite3 {
return db.GetEngine(db.DefaultContext).Where(`created_unix = ""`).Count(new(Action))
return db.GetEngine(ctx).Where(`created_unix = ""`).Count(new(Action))
}
return 0, nil
}

// FixActionCreatedUnixString set created_unix to zero if it is an empty string
func FixActionCreatedUnixString() (int64, error) {
func FixActionCreatedUnixString(ctx context.Context) (int64, error) {
if setting.Database.UseSQLite3 {
res, err := db.GetEngine(db.DefaultContext).Exec(`UPDATE action SET created_unix = 0 WHERE created_unix = ""`)
res, err := db.GetEngine(ctx).Exec(`UPDATE action SET created_unix = 0 WHERE created_unix = ""`)
if err != nil {
return 0, err
}
Expand Down
10 changes: 5 additions & 5 deletions models/activities/action_test.go
Expand Up @@ -188,7 +188,7 @@ func TestNotifyWatchers(t *testing.T) {
RepoID: 1,
OpType: activities_model.ActionStarRepo,
}
assert.NoError(t, activities_model.NotifyWatchers(action))
assert.NoError(t, activities_model.NotifyWatchers(db.DefaultContext, action))

// One watchers are inactive, thus action is only created for user 8, 1, 4, 11
unittest.AssertExistsAndLoadBean(t, &activities_model.Action{
Expand Down Expand Up @@ -256,17 +256,17 @@ func TestConsistencyUpdateAction(t *testing.T) {
//
// Get rid of incorrectly set created_unix
//
count, err := activities_model.CountActionCreatedUnixString()
count, err := activities_model.CountActionCreatedUnixString(db.DefaultContext)
assert.NoError(t, err)
assert.EqualValues(t, 1, count)
count, err = activities_model.FixActionCreatedUnixString()
count, err = activities_model.FixActionCreatedUnixString(db.DefaultContext)
assert.NoError(t, err)
assert.EqualValues(t, 1, count)

count, err = activities_model.CountActionCreatedUnixString()
count, err = activities_model.CountActionCreatedUnixString(db.DefaultContext)
assert.NoError(t, err)
assert.EqualValues(t, 0, count)
count, err = activities_model.FixActionCreatedUnixString()
count, err = activities_model.FixActionCreatedUnixString(db.DefaultContext)
assert.NoError(t, err)
assert.EqualValues(t, 0, count)

Expand Down
96 changes: 40 additions & 56 deletions models/activities/notification.go
Expand Up @@ -136,49 +136,41 @@ func GetNotifications(ctx context.Context, options *FindNotificationOptions) (nl
}

// CountNotifications count all notifications that fit to the given options and ignore pagination.
func CountNotifications(opts *FindNotificationOptions) (int64, error) {
return db.GetEngine(db.DefaultContext).Where(opts.ToCond()).Count(&Notification{})
func CountNotifications(ctx context.Context, opts *FindNotificationOptions) (int64, error) {
return db.GetEngine(ctx).Where(opts.ToCond()).Count(&Notification{})
}

// CreateRepoTransferNotification creates notification for the user a repository was transferred to
func CreateRepoTransferNotification(doer, newOwner *user_model.User, repo *repo_model.Repository) error {
ctx, committer, err := db.TxContext(db.DefaultContext)
if err != nil {
return err
}
defer committer.Close()

var notify []*Notification
func CreateRepoTransferNotification(ctx context.Context, doer, newOwner *user_model.User, repo *repo_model.Repository) error {
return db.AutoTx(ctx, func(ctx context.Context) error {
var notify []*Notification

if newOwner.IsOrganization() {
users, err := organization.GetUsersWhoCanCreateOrgRepo(ctx, newOwner.ID)
if err != nil || len(users) == 0 {
return err
}
for i := range users {
notify = append(notify, &Notification{
UserID: users[i].ID,
if newOwner.IsOrganization() {
users, err := organization.GetUsersWhoCanCreateOrgRepo(ctx, newOwner.ID)
if err != nil || len(users) == 0 {
return err
}
for i := range users {
notify = append(notify, &Notification{
UserID: users[i].ID,
RepoID: repo.ID,
Status: NotificationStatusUnread,
UpdatedBy: doer.ID,
Source: NotificationSourceRepository,
})
}
} else {
notify = []*Notification{{
UserID: newOwner.ID,
RepoID: repo.ID,
Status: NotificationStatusUnread,
UpdatedBy: doer.ID,
Source: NotificationSourceRepository,
})
}}
}
} else {
notify = []*Notification{{
UserID: newOwner.ID,
RepoID: repo.ID,
Status: NotificationStatusUnread,
UpdatedBy: doer.ID,
Source: NotificationSourceRepository,
}}
}

if err := db.Insert(ctx, notify); err != nil {
return err
}

return committer.Commit()
return db.Insert(ctx, notify)
})
}

// CreateOrUpdateIssueNotifications creates an issue notification
Expand Down Expand Up @@ -379,11 +371,7 @@ func CountUnread(ctx context.Context, userID int64) int64 {
}

// LoadAttributes load Repo Issue User and Comment if not loaded
func (n *Notification) LoadAttributes() (err error) {
return n.loadAttributes(db.DefaultContext)
}

func (n *Notification) loadAttributes(ctx context.Context) (err error) {
func (n *Notification) LoadAttributes(ctx context.Context) (err error) {
if err = n.loadRepo(ctx); err != nil {
return
}
Expand Down Expand Up @@ -481,10 +469,10 @@ func (n *Notification) APIURL() string {
type NotificationList []*Notification

// LoadAttributes load Repo Issue User and Comment if not loaded
func (nl NotificationList) LoadAttributes() error {
func (nl NotificationList) LoadAttributes(ctx context.Context) error {
var err error
for i := 0; i < len(nl); i++ {
err = nl[i].LoadAttributes()
err = nl[i].LoadAttributes(ctx)
if err != nil && !issues_model.IsErrCommentNotExist(err) {
return err
}
Expand All @@ -504,7 +492,7 @@ func (nl NotificationList) getPendingRepoIDs() []int64 {
}

// LoadRepos loads repositories from database
func (nl NotificationList) LoadRepos() (repo_model.RepositoryList, []int, error) {
func (nl NotificationList) LoadRepos(ctx context.Context) (repo_model.RepositoryList, []int, error) {
if len(nl) == 0 {
return repo_model.RepositoryList{}, []int{}, nil
}
Expand All @@ -517,7 +505,7 @@ func (nl NotificationList) LoadRepos() (repo_model.RepositoryList, []int, error)
if left < limit {
limit = left
}
rows, err := db.GetEngine(db.DefaultContext).
rows, err := db.GetEngine(ctx).
In("id", repoIDs[:limit]).
Rows(new(repo_model.Repository))
if err != nil {
Expand Down Expand Up @@ -578,7 +566,7 @@ func (nl NotificationList) getPendingIssueIDs() []int64 {
}

// LoadIssues loads issues from database
func (nl NotificationList) LoadIssues() ([]int, error) {
func (nl NotificationList) LoadIssues(ctx context.Context) ([]int, error) {
if len(nl) == 0 {
return []int{}, nil
}
Expand All @@ -591,7 +579,7 @@ func (nl NotificationList) LoadIssues() ([]int, error) {
if left < limit {
limit = left
}
rows, err := db.GetEngine(db.DefaultContext).
rows, err := db.GetEngine(ctx).
In("id", issueIDs[:limit]).
Rows(new(issues_model.Issue))
if err != nil {
Expand Down Expand Up @@ -662,7 +650,7 @@ func (nl NotificationList) getPendingCommentIDs() []int64 {
}

// LoadComments loads comments from database
func (nl NotificationList) LoadComments() ([]int, error) {
func (nl NotificationList) LoadComments(ctx context.Context) ([]int, error) {
if len(nl) == 0 {
return []int{}, nil
}
Expand All @@ -675,7 +663,7 @@ func (nl NotificationList) LoadComments() ([]int, error) {
if left < limit {
limit = left
}
rows, err := db.GetEngine(db.DefaultContext).
rows, err := db.GetEngine(ctx).
In("id", commentIDs[:limit]).
Rows(new(issues_model.Comment))
if err != nil {
Expand Down Expand Up @@ -775,8 +763,8 @@ func SetRepoReadBy(ctx context.Context, userID, repoID int64) error {
}

// SetNotificationStatus change the notification status
func SetNotificationStatus(notificationID int64, user *user_model.User, status NotificationStatus) (*Notification, error) {
notification, err := getNotificationByID(db.DefaultContext, notificationID)
func SetNotificationStatus(ctx context.Context, notificationID int64, user *user_model.User, status NotificationStatus) (*Notification, error) {
notification, err := GetNotificationByID(ctx, notificationID)
if err != nil {
return notification, err
}
Expand All @@ -787,16 +775,12 @@ func SetNotificationStatus(notificationID int64, user *user_model.User, status N

notification.Status = status

_, err = db.GetEngine(db.DefaultContext).ID(notificationID).Update(notification)
_, err = db.GetEngine(ctx).ID(notificationID).Update(notification)
return notification, err
}

// GetNotificationByID return notification by ID
func GetNotificationByID(notificationID int64) (*Notification, error) {
return getNotificationByID(db.DefaultContext, notificationID)
}

func getNotificationByID(ctx context.Context, notificationID int64) (*Notification, error) {
func GetNotificationByID(ctx context.Context, notificationID int64) (*Notification, error) {
notification := new(Notification)
ok, err := db.GetEngine(ctx).
Where("id = ?", notificationID).
Expand All @@ -813,9 +797,9 @@ func getNotificationByID(ctx context.Context, notificationID int64) (*Notificati
}

// UpdateNotificationStatuses updates the statuses of all of a user's notifications that are of the currentStatus type to the desiredStatus
func UpdateNotificationStatuses(user *user_model.User, currentStatus, desiredStatus NotificationStatus) error {
func UpdateNotificationStatuses(ctx context.Context, user *user_model.User, currentStatus, desiredStatus NotificationStatus) error {
n := &Notification{Status: desiredStatus, UpdatedBy: user.ID}
_, err := db.GetEngine(db.DefaultContext).
_, err := db.GetEngine(ctx).
Where("user_id = ? AND status = ?", user.ID, currentStatus).
Cols("status", "updated_by", "updated_unix").
Update(n)
Expand Down
8 changes: 4 additions & 4 deletions models/activities/notification_test.go
Expand Up @@ -82,14 +82,14 @@ func TestSetNotificationStatus(t *testing.T) {
user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2})
notf := unittest.AssertExistsAndLoadBean(t,
&activities_model.Notification{UserID: user.ID, Status: activities_model.NotificationStatusRead})
_, err := activities_model.SetNotificationStatus(notf.ID, user, activities_model.NotificationStatusPinned)
_, err := activities_model.SetNotificationStatus(db.DefaultContext, notf.ID, user, activities_model.NotificationStatusPinned)
assert.NoError(t, err)
unittest.AssertExistsAndLoadBean(t,
&activities_model.Notification{ID: notf.ID, Status: activities_model.NotificationStatusPinned})

_, err = activities_model.SetNotificationStatus(1, user, activities_model.NotificationStatusRead)
_, err = activities_model.SetNotificationStatus(db.DefaultContext, 1, user, activities_model.NotificationStatusRead)
assert.Error(t, err)
_, err = activities_model.SetNotificationStatus(unittest.NonexistentID, user, activities_model.NotificationStatusRead)
_, err = activities_model.SetNotificationStatus(db.DefaultContext, unittest.NonexistentID, user, activities_model.NotificationStatusRead)
assert.Error(t, err)
}

Expand All @@ -102,7 +102,7 @@ func TestUpdateNotificationStatuses(t *testing.T) {
&activities_model.Notification{UserID: user.ID, Status: activities_model.NotificationStatusRead})
notfPinned := unittest.AssertExistsAndLoadBean(t,
&activities_model.Notification{UserID: user.ID, Status: activities_model.NotificationStatusPinned})
assert.NoError(t, activities_model.UpdateNotificationStatuses(user, activities_model.NotificationStatusUnread, activities_model.NotificationStatusRead))
assert.NoError(t, activities_model.UpdateNotificationStatuses(db.DefaultContext, user, activities_model.NotificationStatusUnread, activities_model.NotificationStatusRead))
unittest.AssertExistsAndLoadBean(t,
&activities_model.Notification{ID: notfUnread.ID, Status: activities_model.NotificationStatusRead})
unittest.AssertExistsAndLoadBean(t,
Expand Down
15 changes: 10 additions & 5 deletions models/db/consistency.go
Expand Up @@ -4,24 +4,29 @@

package db

import "xorm.io/builder"
import (
"context"

"xorm.io/builder"
)

// CountOrphanedObjects count subjects with have no existing refobject anymore
func CountOrphanedObjects(subject, refobject, joinCond string) (int64, error) {
return GetEngine(DefaultContext).Table("`"+subject+"`").
func CountOrphanedObjects(ctx context.Context, subject, refobject, joinCond string) (int64, error) {
return GetEngine(ctx).
Table("`"+subject+"`").
Join("LEFT", "`"+refobject+"`", joinCond).
Where(builder.IsNull{"`" + refobject + "`.id"}).
Select("COUNT(`" + subject + "`.`id`)").
Count()
}

// DeleteOrphanedObjects delete subjects with have no existing refobject anymore
func DeleteOrphanedObjects(subject, refobject, joinCond string) error {
func DeleteOrphanedObjects(ctx context.Context, subject, refobject, joinCond string) error {
subQuery := builder.Select("`"+subject+"`.id").
From("`"+subject+"`").
Join("LEFT", "`"+refobject+"`", joinCond).
Where(builder.IsNull{"`" + refobject + "`.id"})
b := builder.Delete(builder.In("id", subQuery)).From("`" + subject + "`")
_, err := GetEngine(DefaultContext).Exec(b)
_, err := GetEngine(ctx).Exec(b)
return err
}
4 changes: 2 additions & 2 deletions models/db/engine_test.go
Expand Up @@ -41,11 +41,11 @@ func TestDeleteOrphanedObjects(t *testing.T) {
_, err = db.GetEngine(db.DefaultContext).Insert(&issues_model.PullRequest{IssueID: 1000}, &issues_model.PullRequest{IssueID: 1001}, &issues_model.PullRequest{IssueID: 1003})
assert.NoError(t, err)

orphaned, err := db.CountOrphanedObjects("pull_request", "issue", "pull_request.issue_id=issue.id")
orphaned, err := db.CountOrphanedObjects(db.DefaultContext, "pull_request", "issue", "pull_request.issue_id=issue.id")
assert.NoError(t, err)
assert.EqualValues(t, 3, orphaned)

err = db.DeleteOrphanedObjects("pull_request", "issue", "pull_request.issue_id=issue.id")
err = db.DeleteOrphanedObjects(db.DefaultContext, "pull_request", "issue", "pull_request.issue_id=issue.id")
assert.NoError(t, err)

countAfter, err := db.GetEngine(db.DefaultContext).Count(&issues_model.PullRequest{})
Expand Down
5 changes: 3 additions & 2 deletions models/db/sequence.go
Expand Up @@ -5,14 +5,15 @@
package db

import (
"context"
"fmt"
"regexp"

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

// CountBadSequences looks for broken sequences from recreate-table mistakes
func CountBadSequences() (int64, error) {
func CountBadSequences(_ context.Context) (int64, error) {
if !setting.Database.UsePostgreSQL {
return 0, nil
}
Expand All @@ -33,7 +34,7 @@ func CountBadSequences() (int64, error) {
}

// FixBadSequences fixes for broken sequences from recreate-table mistakes
func FixBadSequences() error {
func FixBadSequences(_ context.Context) error {
if !setting.Database.UsePostgreSQL {
return nil
}
Expand Down

0 comments on commit 82110fe

Please sign in to comment.