Another round of db.DefaultContext refactor (#27103)

Part of #27065

---------

Co-authored-by: KN4CK3R <admin@oldschoolhack.me>
This commit is contained in:
JakobDev 2023-09-25 15:17:37 +02:00 committed by GitHub
parent 93bd4351bf
commit 7047df36d4
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
109 changed files with 353 additions and 306 deletions

View File

@ -389,7 +389,7 @@ func runRepoSyncReleases(_ *cli.Context) error {
}
log.Trace(" currentNumReleases is %d, running SyncReleasesWithTags", oldnum)
if err = repo_module.SyncReleasesWithTags(repo, gitRepo); err != nil {
if err = repo_module.SyncReleasesWithTags(ctx, repo, gitRepo); err != nil {
log.Warn(" SyncReleasesWithTags: %v", err)
gitRepo.Close()
continue
@ -438,7 +438,7 @@ func runRegenerateKeys(_ *cli.Context) error {
if err := initDB(ctx); err != nil {
return err
}
return asymkey_model.RewriteAllPublicKeys()
return asymkey_model.RewriteAllPublicKeys(ctx)
}
func parseOAuth2Config(c *cli.Context) *oauth2.Source {

View File

@ -9,6 +9,7 @@ import (
"strings"
"testing"
"code.gitea.io/gitea/models/db"
"code.gitea.io/gitea/models/packages"
"code.gitea.io/gitea/models/unittest"
user_model "code.gitea.io/gitea/models/user"
@ -30,7 +31,7 @@ func TestMigratePackages(t *testing.T) {
assert.NoError(t, err)
defer buf.Close()
v, f, err := packages_service.CreatePackageAndAddFile(&packages_service.PackageCreationInfo{
v, f, err := packages_service.CreatePackageAndAddFile(db.DefaultContext, &packages_service.PackageCreationInfo{
PackageInfo: packages_service.PackageInfo{
Owner: creator,
PackageType: packages.TypeGeneric,

View File

@ -4,6 +4,8 @@
package activities
import (
"context"
"code.gitea.io/gitea/models/db"
"code.gitea.io/gitea/models/organization"
user_model "code.gitea.io/gitea/models/user"
@ -18,16 +20,16 @@ type UserHeatmapData struct {
}
// GetUserHeatmapDataByUser returns an array of UserHeatmapData
func GetUserHeatmapDataByUser(user, doer *user_model.User) ([]*UserHeatmapData, error) {
return getUserHeatmapData(user, nil, doer)
func GetUserHeatmapDataByUser(ctx context.Context, user, doer *user_model.User) ([]*UserHeatmapData, error) {
return getUserHeatmapData(ctx, user, nil, doer)
}
// GetUserHeatmapDataByUserTeam returns an array of UserHeatmapData
func GetUserHeatmapDataByUserTeam(user *user_model.User, team *organization.Team, doer *user_model.User) ([]*UserHeatmapData, error) {
return getUserHeatmapData(user, team, doer)
func GetUserHeatmapDataByUserTeam(ctx context.Context, user *user_model.User, team *organization.Team, doer *user_model.User) ([]*UserHeatmapData, error) {
return getUserHeatmapData(ctx, user, team, doer)
}
func getUserHeatmapData(user *user_model.User, team *organization.Team, doer *user_model.User) ([]*UserHeatmapData, error) {
func getUserHeatmapData(ctx context.Context, user *user_model.User, team *organization.Team, doer *user_model.User) ([]*UserHeatmapData, error) {
hdata := make([]*UserHeatmapData, 0)
if !ActivityReadable(user, doer) {
@ -60,7 +62,7 @@ func getUserHeatmapData(user *user_model.User, team *organization.Team, doer *us
return nil, err
}
return hdata, db.GetEngine(db.DefaultContext).
return hdata, db.GetEngine(ctx).
Select(groupBy+" AS timestamp, count(user_id) as contributions").
Table("action").
Where(cond).

View File

@ -83,7 +83,7 @@ func TestGetUserHeatmapDataByUser(t *testing.T) {
assert.NoError(t, err)
// Get the heatmap and compare
heatmap, err := activities_model.GetUserHeatmapDataByUser(user, doer)
heatmap, err := activities_model.GetUserHeatmapDataByUser(db.DefaultContext, user, doer)
var contributions int
for _, hm := range heatmap {
contributions += int(hm.Contributions)

View File

@ -88,14 +88,14 @@ func ListGPGKeys(ctx context.Context, uid int64, listOptions db.ListOptions) ([]
}
// CountUserGPGKeys return number of gpg keys a user own
func CountUserGPGKeys(userID int64) (int64, error) {
return db.GetEngine(db.DefaultContext).Where("owner_id=? AND primary_key_id=''", userID).Count(&GPGKey{})
func CountUserGPGKeys(ctx context.Context, userID int64) (int64, error) {
return db.GetEngine(ctx).Where("owner_id=? AND primary_key_id=''", userID).Count(&GPGKey{})
}
// GetGPGKeyByID returns public key by given ID.
func GetGPGKeyByID(keyID int64) (*GPGKey, error) {
func GetGPGKeyByID(ctx context.Context, keyID int64) (*GPGKey, error) {
key := new(GPGKey)
has, err := db.GetEngine(db.DefaultContext).ID(keyID).Get(key)
has, err := db.GetEngine(ctx).ID(keyID).Get(key)
if err != nil {
return nil, err
} else if !has {
@ -105,9 +105,9 @@ func GetGPGKeyByID(keyID int64) (*GPGKey, error) {
}
// GetGPGKeysByKeyID returns public key by given ID.
func GetGPGKeysByKeyID(keyID string) ([]*GPGKey, error) {
func GetGPGKeysByKeyID(ctx context.Context, keyID string) ([]*GPGKey, error) {
keys := make([]*GPGKey, 0, 1)
return keys, db.GetEngine(db.DefaultContext).Where("key_id=?", keyID).Find(&keys)
return keys, db.GetEngine(ctx).Where("key_id=?", keyID).Find(&keys)
}
// GPGKeyToEntity retrieve the imported key and the traducted entity
@ -224,8 +224,8 @@ func deleteGPGKey(ctx context.Context, keyID string) (int64, error) {
}
// DeleteGPGKey deletes GPG key information in database.
func DeleteGPGKey(doer *user_model.User, id int64) (err error) {
key, err := GetGPGKeyByID(id)
func DeleteGPGKey(ctx context.Context, doer *user_model.User, id int64) (err error) {
key, err := GetGPGKeyByID(ctx, id)
if err != nil {
if IsErrGPGKeyNotExist(err) {
return nil
@ -238,7 +238,7 @@ func DeleteGPGKey(doer *user_model.User, id int64) (err error) {
return ErrGPGKeyAccessDenied{doer.ID, key.ID}
}
ctx, committer, err := db.TxContext(db.DefaultContext)
ctx, committer, err := db.TxContext(ctx)
if err != nil {
return err
}

View File

@ -66,13 +66,13 @@ func addGPGSubKey(ctx context.Context, key *GPGKey) (err error) {
}
// AddGPGKey adds new public key to database.
func AddGPGKey(ownerID int64, content, token, signature string) ([]*GPGKey, error) {
func AddGPGKey(ctx context.Context, ownerID int64, content, token, signature string) ([]*GPGKey, error) {
ekeys, err := checkArmoredGPGKeyString(content)
if err != nil {
return nil, err
}
ctx, committer, err := db.TxContext(db.DefaultContext)
ctx, committer, err := db.TxContext(ctx)
if err != nil {
return nil, err
}

View File

@ -392,7 +392,7 @@ func hashAndVerifyForKeyID(ctx context.Context, sig *packet.Signature, payload s
if keyID == "" {
return nil
}
keys, err := GetGPGKeysByKeyID(keyID)
keys, err := GetGPGKeysByKeyID(ctx, keyID)
if err != nil {
log.Error("GetGPGKeysByKeyID: %v", err)
return &CommitVerification{
@ -407,7 +407,7 @@ func hashAndVerifyForKeyID(ctx context.Context, sig *packet.Signature, payload s
for _, key := range keys {
var primaryKeys []*GPGKey
if key.PrimaryKeyID != "" {
primaryKeys, err = GetGPGKeysByKeyID(key.PrimaryKeyID)
primaryKeys, err = GetGPGKeysByKeyID(ctx, key.PrimaryKeyID)
if err != nil {
log.Error("GetGPGKeysByKeyID: %v", err)
return &CommitVerification{

View File

@ -7,6 +7,7 @@ import (
"testing"
"time"
"code.gitea.io/gitea/models/db"
"code.gitea.io/gitea/models/unittest"
user_model "code.gitea.io/gitea/models/user"
"code.gitea.io/gitea/modules/timeutil"
@ -228,7 +229,7 @@ Q0KHb+QcycSgbDx0ZAvdIacuKvBBcbxrsmFUI4LR+oIup0G9gUc0roPvr014jYQL
=zHo9
-----END PGP PUBLIC KEY BLOCK-----`
keys, err := AddGPGKey(1, testEmailWithUpperCaseLetters, "", "")
keys, err := AddGPGKey(db.DefaultContext, 1, testEmailWithUpperCaseLetters, "", "")
assert.NoError(t, err)
if assert.NotEmpty(t, keys) {
key := keys[0]

View File

@ -117,7 +117,7 @@ func appendAuthorizedKeysToFile(keys ...*PublicKey) error {
// RewriteAllPublicKeys removes any authorized key 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
// outside any session scope independently.
func RewriteAllPublicKeys() error {
func RewriteAllPublicKeys(ctx context.Context) error {
// Don't rewrite key if internal server
if setting.SSH.StartBuiltinServer || !setting.SSH.CreateAuthorizedKeysFile {
return nil
@ -165,7 +165,7 @@ func RewriteAllPublicKeys() error {
}
}
if err := RegeneratePublicKeys(db.DefaultContext, t); err != nil {
if err := RegeneratePublicKeys(ctx, t); err != nil {
return err
}

View File

@ -3,12 +3,16 @@
package issues
import "code.gitea.io/gitea/models/db"
import (
"context"
"code.gitea.io/gitea/models/db"
)
// RecalculateIssueIndexForRepo create issue_index for repo if not exist and
// update it based on highest index of existing issues assigned to a repo
func RecalculateIssueIndexForRepo(repoID int64) error {
ctx, committer, err := db.TxContext(db.DefaultContext)
func RecalculateIssueIndexForRepo(ctx context.Context, repoID int64) error {
ctx, committer, err := db.TxContext(ctx)
if err != nil {
return err
}

View File

@ -80,9 +80,9 @@ func CountIssues(ctx context.Context, opts *IssuesOptions) (int64, error) {
}
// GetIssueStats returns issue statistic information by given conditions.
func GetIssueStats(opts *IssuesOptions) (*IssueStats, error) {
func GetIssueStats(ctx context.Context, opts *IssuesOptions) (*IssueStats, error) {
if len(opts.IssueIDs) <= MaxQueryParameters {
return getIssueStatsChunk(opts, opts.IssueIDs)
return getIssueStatsChunk(ctx, opts, opts.IssueIDs)
}
// If too long a list of IDs is provided, we get the statistics in
@ -95,7 +95,7 @@ func GetIssueStats(opts *IssuesOptions) (*IssueStats, error) {
if chunk > len(opts.IssueIDs) {
chunk = len(opts.IssueIDs)
}
stats, err := getIssueStatsChunk(opts, opts.IssueIDs[i:chunk])
stats, err := getIssueStatsChunk(ctx, opts, opts.IssueIDs[i:chunk])
if err != nil {
return nil, err
}
@ -112,10 +112,10 @@ func GetIssueStats(opts *IssuesOptions) (*IssueStats, error) {
return accum, nil
}
func getIssueStatsChunk(opts *IssuesOptions, issueIDs []int64) (*IssueStats, error) {
func getIssueStatsChunk(ctx context.Context, opts *IssuesOptions, issueIDs []int64) (*IssueStats, error) {
stats := &IssueStats{}
sess := db.GetEngine(db.DefaultContext).
sess := db.GetEngine(ctx).
Join("INNER", "repository", "`issue`.repo_id = `repository`.id")
var err error

View File

@ -369,7 +369,7 @@ func TestCorrectIssueStats(t *testing.T) {
// Now we will call the GetIssueStats with these IDs and if working,
// get the correct stats back.
issueStats, err := issues_model.GetIssueStats(&issues_model.IssuesOptions{
issueStats, err := issues_model.GetIssueStats(db.DefaultContext, &issues_model.IssuesOptions{
RepoIDs: []int64{1},
IssueIDs: ids,
})

View File

@ -311,7 +311,7 @@ func (pr *PullRequest) LoadRequestedReviewers(ctx context.Context) error {
return nil
}
reviews, err := GetReviewsByIssueID(pr.Issue.ID)
reviews, err := GetReviewsByIssueID(ctx, pr.Issue.ID)
if err != nil {
return err
}

View File

@ -71,11 +71,11 @@ type Reaction struct {
}
// LoadUser load user of reaction
func (r *Reaction) LoadUser() (*user_model.User, error) {
func (r *Reaction) LoadUser(ctx context.Context) (*user_model.User, error) {
if r.User != nil {
return r.User, nil
}
user, err := user_model.GetUserByID(db.DefaultContext, r.UserID)
user, err := user_model.GetUserByID(ctx, r.UserID)
if err != nil {
return nil, err
}
@ -141,16 +141,16 @@ func (opts *FindReactionsOptions) toConds() builder.Cond {
}
// FindCommentReactions returns a ReactionList of all reactions from an comment
func FindCommentReactions(issueID, commentID int64) (ReactionList, int64, error) {
return FindReactions(db.DefaultContext, FindReactionsOptions{
func FindCommentReactions(ctx context.Context, issueID, commentID int64) (ReactionList, int64, error) {
return FindReactions(ctx, FindReactionsOptions{
IssueID: issueID,
CommentID: commentID,
})
}
// FindIssueReactions returns a ReactionList of all reactions from an issue
func FindIssueReactions(issueID int64, listOptions db.ListOptions) (ReactionList, int64, error) {
return FindReactions(db.DefaultContext, FindReactionsOptions{
func FindIssueReactions(ctx context.Context, issueID int64, listOptions db.ListOptions) (ReactionList, int64, error) {
return FindReactions(ctx, FindReactionsOptions{
ListOptions: listOptions,
IssueID: issueID,
CommentID: -1,
@ -218,12 +218,12 @@ type ReactionOptions struct {
}
// CreateReaction creates reaction for issue or comment.
func CreateReaction(opts *ReactionOptions) (*Reaction, error) {
func CreateReaction(ctx context.Context, opts *ReactionOptions) (*Reaction, error) {
if !setting.UI.ReactionsLookup.Contains(opts.Type) {
return nil, ErrForbiddenIssueReaction{opts.Type}
}
ctx, committer, err := db.TxContext(db.DefaultContext)
ctx, committer, err := db.TxContext(ctx)
if err != nil {
return nil, err
}
@ -241,8 +241,8 @@ func CreateReaction(opts *ReactionOptions) (*Reaction, error) {
}
// CreateIssueReaction creates a reaction on issue.
func CreateIssueReaction(doerID, issueID int64, content string) (*Reaction, error) {
return CreateReaction(&ReactionOptions{
func CreateIssueReaction(ctx context.Context, doerID, issueID int64, content string) (*Reaction, error) {
return CreateReaction(ctx, &ReactionOptions{
Type: content,
DoerID: doerID,
IssueID: issueID,
@ -250,8 +250,8 @@ func CreateIssueReaction(doerID, issueID int64, content string) (*Reaction, erro
}
// CreateCommentReaction creates a reaction on comment.
func CreateCommentReaction(doerID, issueID, commentID int64, content string) (*Reaction, error) {
return CreateReaction(&ReactionOptions{
func CreateCommentReaction(ctx context.Context, doerID, issueID, commentID int64, content string) (*Reaction, error) {
return CreateReaction(ctx, &ReactionOptions{
Type: content,
DoerID: doerID,
IssueID: issueID,
@ -279,8 +279,8 @@ func DeleteReaction(ctx context.Context, opts *ReactionOptions) error {
}
// DeleteIssueReaction deletes a reaction on issue.
func DeleteIssueReaction(doerID, issueID int64, content string) error {
return DeleteReaction(db.DefaultContext, &ReactionOptions{
func DeleteIssueReaction(ctx context.Context, doerID, issueID int64, content string) error {
return DeleteReaction(ctx, &ReactionOptions{
Type: content,
DoerID: doerID,
IssueID: issueID,
@ -289,8 +289,8 @@ func DeleteIssueReaction(doerID, issueID int64, content string) error {
}
// DeleteCommentReaction deletes a reaction on comment.
func DeleteCommentReaction(doerID, issueID, commentID int64, content string) error {
return DeleteReaction(db.DefaultContext, &ReactionOptions{
func DeleteCommentReaction(ctx context.Context, doerID, issueID, commentID int64, content string) error {
return DeleteReaction(ctx, &ReactionOptions{
Type: content,
DoerID: doerID,
IssueID: issueID,

View File

@ -20,9 +20,9 @@ func addReaction(t *testing.T, doerID, issueID, commentID int64, content string)
var reaction *issues_model.Reaction
var err error
if commentID == 0 {
reaction, err = issues_model.CreateIssueReaction(doerID, issueID, content)
reaction, err = issues_model.CreateIssueReaction(db.DefaultContext, doerID, issueID, content)
} else {
reaction, err = issues_model.CreateCommentReaction(doerID, issueID, commentID, content)
reaction, err = issues_model.CreateCommentReaction(db.DefaultContext, doerID, issueID, commentID, content)
}
assert.NoError(t, err)
assert.NotNil(t, reaction)
@ -49,7 +49,7 @@ func TestIssueAddDuplicateReaction(t *testing.T) {
addReaction(t, user1.ID, issue1ID, 0, "heart")
reaction, err := issues_model.CreateReaction(&issues_model.ReactionOptions{
reaction, err := issues_model.CreateReaction(db.DefaultContext, &issues_model.ReactionOptions{
DoerID: user1.ID,
IssueID: issue1ID,
Type: "heart",
@ -70,7 +70,7 @@ func TestIssueDeleteReaction(t *testing.T) {
addReaction(t, user1.ID, issue1ID, 0, "heart")
err := issues_model.DeleteIssueReaction(user1.ID, issue1ID, "heart")
err := issues_model.DeleteIssueReaction(db.DefaultContext, user1.ID, issue1ID, "heart")
assert.NoError(t, err)
unittest.AssertNotExistsBean(t, &issues_model.Reaction{Type: "heart", UserID: user1.ID, IssueID: issue1ID})
@ -168,7 +168,7 @@ func TestIssueCommentReactionCount(t *testing.T) {
var comment1ID int64 = 1
addReaction(t, user1.ID, issue1ID, comment1ID, "heart")
assert.NoError(t, issues_model.DeleteCommentReaction(user1.ID, issue1ID, comment1ID, "heart"))
assert.NoError(t, issues_model.DeleteCommentReaction(db.DefaultContext, user1.ID, issue1ID, comment1ID, "heart"))
unittest.AssertNotExistsBean(t, &issues_model.Reaction{Type: "heart", UserID: user1.ID, IssueID: issue1ID, CommentID: comment1ID})
}

View File

@ -126,16 +126,16 @@ func FindLatestReviews(ctx context.Context, opts FindReviewOptions) (ReviewList,
}
// CountReviews returns count of reviews passing FindReviewOptions
func CountReviews(opts FindReviewOptions) (int64, error) {
return db.GetEngine(db.DefaultContext).Where(opts.toCond()).Count(&Review{})
func CountReviews(ctx context.Context, opts FindReviewOptions) (int64, error) {
return db.GetEngine(ctx).Where(opts.toCond()).Count(&Review{})
}
// GetReviewersFromOriginalAuthorsByIssueID gets the latest review of each original authors for a pull request
func GetReviewersFromOriginalAuthorsByIssueID(issueID int64) (ReviewList, error) {
func GetReviewersFromOriginalAuthorsByIssueID(ctx context.Context, issueID int64) (ReviewList, error) {
reviews := make([]*Review, 0, 10)
// Get latest review of each reviewer, sorted in order they were made
if err := db.GetEngine(db.DefaultContext).SQL("SELECT * FROM review WHERE id IN (SELECT max(id) as id FROM review WHERE issue_id = ? AND reviewer_team_id = 0 AND type in (?, ?, ?) AND original_author_id <> 0 GROUP BY issue_id, original_author_id) ORDER BY review.updated_unix ASC",
if 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 = 0 AND type in (?, ?, ?) AND original_author_id <> 0 GROUP BY issue_id, original_author_id) ORDER BY review.updated_unix ASC",
issueID, ReviewTypeApprove, ReviewTypeReject, ReviewTypeRequest).
Find(&reviews); err != nil {
return nil, err
@ -145,10 +145,10 @@ func GetReviewersFromOriginalAuthorsByIssueID(issueID int64) (ReviewList, error)
}
// GetReviewsByIssueID gets the latest review of each reviewer for a pull request
func GetReviewsByIssueID(issueID int64) (ReviewList, error) {
func GetReviewsByIssueID(ctx context.Context, issueID int64) (ReviewList, error) {
reviews := make([]*Review, 0, 10)
sess := db.GetEngine(db.DefaultContext)
sess := db.GetEngine(ctx)
// Get latest review of each reviewer, sorted in order they were made
if err := sess.SQL("SELECT * FROM review WHERE id IN (SELECT max(id) as id FROM review WHERE issue_id = ? AND reviewer_team_id = 0 AND type in (?, ?, ?) AND dismissed = ? AND original_author_id = 0 GROUP BY issue_id, reviewer_id) ORDER BY review.updated_unix ASC",

View File

@ -144,7 +144,7 @@ func TestGetReviewersByIssueID(t *testing.T) {
UpdatedUnix: 946684814,
})
allReviews, err := issues_model.GetReviewsByIssueID(issue.ID)
allReviews, err := issues_model.GetReviewsByIssueID(db.DefaultContext, issue.ID)
assert.NoError(t, err)
for _, review := range allReviews {
assert.NoError(t, review.LoadReviewer(db.DefaultContext))
@ -157,7 +157,7 @@ func TestGetReviewersByIssueID(t *testing.T) {
}
}
allReviews, err = issues_model.GetReviewsByIssueID(issue.ID)
allReviews, err = issues_model.GetReviewsByIssueID(db.DefaultContext, issue.ID)
assert.NoError(t, err)
assert.NoError(t, allReviews.LoadReviewers(db.DefaultContext))
if assert.Len(t, allReviews, 3) {

View File

@ -77,8 +77,8 @@ func (opts *SearchTeamOptions) toCond() builder.Cond {
}
// SearchTeam search for teams. Caller is responsible to check permissions.
func SearchTeam(opts *SearchTeamOptions) (TeamList, int64, error) {
sess := db.GetEngine(db.DefaultContext)
func SearchTeam(ctx context.Context, opts *SearchTeamOptions) (TeamList, int64, error) {
sess := db.GetEngine(ctx)
opts.SetDefaultValues()
cond := opts.toCond()

View File

@ -142,7 +142,7 @@ func TestGetTeamMembers(t *testing.T) {
func TestGetUserTeams(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase())
test := func(userID int64) {
teams, _, err := organization.SearchTeam(&organization.SearchTeamOptions{UserID: userID})
teams, _, err := organization.SearchTeam(db.DefaultContext, &organization.SearchTeamOptions{UserID: userID})
assert.NoError(t, err)
for _, team := range teams {
unittest.AssertExistsAndLoadBean(t, &organization.TeamUser{TeamID: team.ID, UID: userID})

View File

@ -181,9 +181,9 @@ func AddReleaseAttachments(ctx context.Context, releaseID int64, attachmentUUIDs
}
// GetRelease returns release by given ID.
func GetRelease(repoID int64, tagName string) (*Release, error) {
func GetRelease(ctx context.Context, repoID int64, tagName string) (*Release, error) {
rel := &Release{RepoID: repoID, LowerTagName: strings.ToLower(tagName)}
has, err := db.GetEngine(db.DefaultContext).Get(rel)
has, err := db.GetEngine(ctx).Get(rel)
if err != nil {
return nil, err
} else if !has {
@ -284,12 +284,12 @@ func GetTagNamesByRepoID(ctx context.Context, repoID int64) ([]string, error) {
}
// CountReleasesByRepoID returns a number of releases matching FindReleaseOptions and RepoID.
func CountReleasesByRepoID(repoID int64, opts FindReleasesOptions) (int64, error) {
return db.GetEngine(db.DefaultContext).Where(opts.toConds(repoID)).Count(new(Release))
func CountReleasesByRepoID(ctx context.Context, repoID int64, opts FindReleasesOptions) (int64, error) {
return db.GetEngine(ctx).Where(opts.toConds(repoID)).Count(new(Release))
}
// GetLatestReleaseByRepoID returns the latest release for a repository
func GetLatestReleaseByRepoID(repoID int64) (*Release, error) {
func GetLatestReleaseByRepoID(ctx context.Context, repoID int64) (*Release, error) {
cond := builder.NewCond().
And(builder.Eq{"repo_id": repoID}).
And(builder.Eq{"is_draft": false}).
@ -297,7 +297,7 @@ func GetLatestReleaseByRepoID(repoID int64) (*Release, error) {
And(builder.Eq{"is_tag": false})
rel := new(Release)
has, err := db.GetEngine(db.DefaultContext).
has, err := db.GetEngine(ctx).
Desc("created_unix", "id").
Where(cond).
Get(rel)
@ -442,8 +442,8 @@ func DeleteReleaseByID(ctx context.Context, id int64) error {
}
// UpdateReleasesMigrationsByType updates all migrated repositories' releases from gitServiceType to replace originalAuthorID to posterID
func UpdateReleasesMigrationsByType(gitServiceType structs.GitServiceType, originalAuthorID string, posterID int64) error {
_, err := db.GetEngine(db.DefaultContext).Table("release").
func UpdateReleasesMigrationsByType(ctx context.Context, gitServiceType structs.GitServiceType, originalAuthorID string, posterID int64) error {
_, err := db.GetEngine(ctx).Table("release").
Where("repo_id IN (SELECT id FROM repository WHERE original_service_type = ?)", gitServiceType).
And("original_author_id = ?", originalAuthorID).
Update(map[string]any{
@ -485,8 +485,8 @@ func PushUpdateDeleteTagsContext(ctx context.Context, repo *Repository, tags []s
}
// PushUpdateDeleteTag must be called for any push actions to delete tag
func PushUpdateDeleteTag(repo *Repository, tagName string) error {
rel, err := GetRelease(repo.ID, tagName)
func PushUpdateDeleteTag(ctx context.Context, repo *Repository, tagName string) error {
rel, err := GetRelease(ctx, repo.ID, tagName)
if err != nil {
if IsErrReleaseNotExist(err) {
return nil
@ -494,14 +494,14 @@ func PushUpdateDeleteTag(repo *Repository, tagName string) error {
return fmt.Errorf("GetRelease: %w", err)
}
if rel.IsTag {
if _, err = db.GetEngine(db.DefaultContext).ID(rel.ID).Delete(new(Release)); err != nil {
if _, err = db.GetEngine(ctx).ID(rel.ID).Delete(new(Release)); err != nil {
return fmt.Errorf("Delete: %w", err)
}
} else {
rel.IsDraft = true
rel.NumCommits = 0
rel.Sha1 = ""
if _, err = db.GetEngine(db.DefaultContext).ID(rel.ID).AllCols().Update(rel); err != nil {
if _, err = db.GetEngine(ctx).ID(rel.ID).AllCols().Update(rel); err != nil {
return fmt.Errorf("Update: %w", err)
}
}
@ -510,15 +510,15 @@ func PushUpdateDeleteTag(repo *Repository, tagName string) error {
}
// SaveOrUpdateTag must be called for any push actions to add tag
func SaveOrUpdateTag(repo *Repository, newRel *Release) error {
rel, err := GetRelease(repo.ID, newRel.TagName)
func SaveOrUpdateTag(ctx context.Context, repo *Repository, newRel *Release) error {
rel, err := GetRelease(ctx, repo.ID, newRel.TagName)
if err != nil && !IsErrReleaseNotExist(err) {
return fmt.Errorf("GetRelease: %w", err)
}
if rel == nil {
rel = newRel
if _, err = db.GetEngine(db.DefaultContext).Insert(rel); err != nil {
if _, err = db.GetEngine(ctx).Insert(rel); err != nil {
return fmt.Errorf("InsertOne: %w", err)
}
} else {
@ -529,7 +529,7 @@ func SaveOrUpdateTag(repo *Repository, newRel *Release) error {
if rel.IsTag && newRel.PublisherID > 0 {
rel.PublisherID = newRel.PublisherID
}
if _, err = db.GetEngine(db.DefaultContext).ID(rel.ID).AllCols().Update(rel); err != nil {
if _, err = db.GetEngine(ctx).ID(rel.ID).AllCols().Update(rel); err != nil {
return fmt.Errorf("Update: %w", err)
}
}
@ -554,8 +554,8 @@ func (r *Release) GetExternalName() string { return r.OriginalAuthor }
func (r *Release) GetExternalID() int64 { return r.OriginalAuthorID }
// InsertReleases migrates release
func InsertReleases(rels ...*Release) error {
ctx, committer, err := db.TxContext(db.DefaultContext)
func InsertReleases(ctx context.Context, rels ...*Release) error {
ctx, committer, err := db.TxContext(ctx)
if err != nil {
return err
}

View File

@ -6,6 +6,7 @@ package repo
import (
"testing"
"code.gitea.io/gitea/models/db"
"code.gitea.io/gitea/models/unittest"
"github.com/stretchr/testify/assert"
@ -21,6 +22,6 @@ func TestMigrate_InsertReleases(t *testing.T) {
Attachments: []*Attachment{a},
}
err := InsertReleases(r)
err := InsertReleases(db.DefaultContext, r)
assert.NoError(t, err)
}

View File

@ -94,28 +94,28 @@ func CountNotices() int64 {
}
// Notices returns notices in given page.
func Notices(page, pageSize int) ([]*Notice, error) {
func Notices(ctx context.Context, page, pageSize int) ([]*Notice, error) {
notices := make([]*Notice, 0, pageSize)
return notices, db.GetEngine(db.DefaultContext).
return notices, db.GetEngine(ctx).
Limit(pageSize, (page-1)*pageSize).
Desc("created_unix").
Find(&notices)
}
// DeleteNotice deletes a system notice by given ID.
func DeleteNotice(id int64) error {
_, err := db.GetEngine(db.DefaultContext).ID(id).Delete(new(Notice))
func DeleteNotice(ctx context.Context, id int64) error {
_, err := db.GetEngine(ctx).ID(id).Delete(new(Notice))
return err
}
// DeleteNotices deletes all notices with ID from start to end (inclusive).
func DeleteNotices(start, end int64) error {
func DeleteNotices(ctx context.Context, start, end int64) error {
if start == 0 && end == 0 {
_, err := db.GetEngine(db.DefaultContext).Exec("DELETE FROM notice")
_, err := db.GetEngine(ctx).Exec("DELETE FROM notice")
return err
}
sess := db.GetEngine(db.DefaultContext).Where("id >= ?", start)
sess := db.GetEngine(ctx).Where("id >= ?", start)
if end > 0 {
sess.And("id <= ?", end)
}
@ -124,22 +124,22 @@ func DeleteNotices(start, end int64) error {
}
// DeleteNoticesByIDs deletes notices by given IDs.
func DeleteNoticesByIDs(ids []int64) error {
func DeleteNoticesByIDs(ctx context.Context, ids []int64) error {
if len(ids) == 0 {
return nil
}
_, err := db.GetEngine(db.DefaultContext).
_, err := db.GetEngine(ctx).
In("id", ids).
Delete(new(Notice))
return err
}
// DeleteOldSystemNotices deletes all old system notices from database.
func DeleteOldSystemNotices(olderThan time.Duration) (err error) {
func DeleteOldSystemNotices(ctx context.Context, olderThan time.Duration) (err error) {
if olderThan <= 0 {
return nil
}
_, err = db.GetEngine(db.DefaultContext).Where("created_unix < ?", time.Now().Add(-olderThan).Unix()).Delete(&Notice{})
_, err = db.GetEngine(ctx).Where("created_unix < ?", time.Now().Add(-olderThan).Unix()).Delete(&Notice{})
return err
}

View File

@ -55,14 +55,14 @@ func TestCountNotices(t *testing.T) {
func TestNotices(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase())
notices, err := system.Notices(1, 2)
notices, err := system.Notices(db.DefaultContext, 1, 2)
assert.NoError(t, err)
if assert.Len(t, notices, 2) {
assert.Equal(t, int64(3), notices[0].ID)
assert.Equal(t, int64(2), notices[1].ID)
}
notices, err = system.Notices(2, 2)
notices, err = system.Notices(db.DefaultContext, 2, 2)
assert.NoError(t, err)
if assert.Len(t, notices, 1) {
assert.Equal(t, int64(1), notices[0].ID)
@ -73,7 +73,7 @@ func TestDeleteNotice(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase())
unittest.AssertExistsAndLoadBean(t, &system.Notice{ID: 3})
assert.NoError(t, system.DeleteNotice(3))
assert.NoError(t, system.DeleteNotice(db.DefaultContext, 3))
unittest.AssertNotExistsBean(t, &system.Notice{ID: 3})
}
@ -84,7 +84,7 @@ func TestDeleteNotices(t *testing.T) {
unittest.AssertExistsAndLoadBean(t, &system.Notice{ID: 1})
unittest.AssertExistsAndLoadBean(t, &system.Notice{ID: 2})
unittest.AssertExistsAndLoadBean(t, &system.Notice{ID: 3})
assert.NoError(t, system.DeleteNotices(1, 2))
assert.NoError(t, system.DeleteNotices(db.DefaultContext, 1, 2))
unittest.AssertNotExistsBean(t, &system.Notice{ID: 1})
unittest.AssertNotExistsBean(t, &system.Notice{ID: 2})
unittest.AssertExistsAndLoadBean(t, &system.Notice{ID: 3})
@ -97,7 +97,7 @@ func TestDeleteNotices2(t *testing.T) {
unittest.AssertExistsAndLoadBean(t, &system.Notice{ID: 1})
unittest.AssertExistsAndLoadBean(t, &system.Notice{ID: 2})
unittest.AssertExistsAndLoadBean(t, &system.Notice{ID: 3})
assert.NoError(t, system.DeleteNotices(3, 2))
assert.NoError(t, system.DeleteNotices(db.DefaultContext, 3, 2))
unittest.AssertExistsAndLoadBean(t, &system.Notice{ID: 1})
unittest.AssertExistsAndLoadBean(t, &system.Notice{ID: 2})
unittest.AssertExistsAndLoadBean(t, &system.Notice{ID: 3})
@ -109,7 +109,7 @@ func TestDeleteNoticesByIDs(t *testing.T) {
unittest.AssertExistsAndLoadBean(t, &system.Notice{ID: 1})
unittest.AssertExistsAndLoadBean(t, &system.Notice{ID: 2})
unittest.AssertExistsAndLoadBean(t, &system.Notice{ID: 3})
assert.NoError(t, system.DeleteNoticesByIDs([]int64{1, 3}))
assert.NoError(t, system.DeleteNoticesByIDs(db.DefaultContext, []int64{1, 3}))
unittest.AssertNotExistsBean(t, &system.Notice{ID: 1})
unittest.AssertExistsAndLoadBean(t, &system.Notice{ID: 2})
unittest.AssertNotExistsBean(t, &system.Notice{ID: 3})

View File

@ -48,10 +48,10 @@ func init() {
}
// LookupUserRedirect look up userID if a user has a redirect name
func LookupUserRedirect(userName string) (int64, error) {
func LookupUserRedirect(ctx context.Context, userName string) (int64, error) {
userName = strings.ToLower(userName)
redirect := &Redirect{LowerName: userName}
if has, err := db.GetEngine(db.DefaultContext).Get(redirect); err != nil {
if has, err := db.GetEngine(ctx).Get(redirect); err != nil {
return 0, err
} else if !has {
return 0, ErrUserRedirectNotExist{Name: userName}

View File

@ -6,6 +6,7 @@ package user_test
import (
"testing"
"code.gitea.io/gitea/models/db"
"code.gitea.io/gitea/models/unittest"
user_model "code.gitea.io/gitea/models/user"
@ -15,10 +16,10 @@ import (
func TestLookupUserRedirect(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase())
userID, err := user_model.LookupUserRedirect("olduser1")
userID, err := user_model.LookupUserRedirect(db.DefaultContext, "olduser1")
assert.NoError(t, err)
assert.EqualValues(t, 1, userID)
_, err = user_model.LookupUserRedirect("doesnotexist")
_, err = user_model.LookupUserRedirect(db.DefaultContext, "doesnotexist")
assert.True(t, user_model.IsErrUserRedirectNotExist(err))
}

View File

@ -46,7 +46,7 @@ func GetOrganizationByParams(ctx *Context) {
ctx.Org.Organization, err = organization.GetOrgByName(ctx, orgName)
if err != nil {
if organization.IsErrOrgNotExist(err) {
redirectUserID, err := user_model.LookupUserRedirect(orgName)
redirectUserID, err := user_model.LookupUserRedirect(ctx, orgName)
if err == nil {
RedirectToUser(ctx.Base, orgName, redirectUserID)
} else if user_model.IsErrUserRedirectNotExist(err) {

View File

@ -456,7 +456,7 @@ func RepoAssignment(ctx *Context) context.CancelFunc {
return nil
}
if redirectUserID, err := user_model.LookupUserRedirect(userName); err == nil {
if redirectUserID, err := user_model.LookupUserRedirect(ctx, userName); err == nil {
RedirectToUser(ctx.Base, userName, redirectUserID)
} else if user_model.IsErrUserRedirectNotExist(err) {
ctx.NotFound("GetUserByName", nil)

View File

@ -33,7 +33,7 @@ func checkAuthorizedKeys(ctx context.Context, logger log.Logger, autofix bool) e
return fmt.Errorf("Unable to open authorized_keys file. ERROR: %w", err)
}
logger.Warn("Unable to open authorized_keys. (ERROR: %v). Attempting to rewrite...", err)
if err = asymkey_model.RewriteAllPublicKeys(); err != nil {
if err = asymkey_model.RewriteAllPublicKeys(ctx); err != nil {
logger.Critical("Unable to rewrite authorized_keys file. ERROR: %v", err)
return fmt.Errorf("Unable to rewrite authorized_keys file. ERROR: %w", err)
}
@ -76,7 +76,7 @@ func checkAuthorizedKeys(ctx context.Context, logger log.Logger, autofix bool) e
return fmt.Errorf(`authorized_keys is out of date and should be regenerated with "gitea admin regenerate keys" or "gitea doctor --run authorized-keys --fix"`)
}
logger.Warn("authorized_keys is out of date. Attempting rewrite...")
err = asymkey_model.RewriteAllPublicKeys()
err = asymkey_model.RewriteAllPublicKeys(ctx)
if err != nil {
logger.Critical("Unable to rewrite authorized_keys file. ERROR: %v", err)
return fmt.Errorf("Unable to rewrite authorized_keys file. ERROR: %w", err)

View File

@ -119,7 +119,7 @@ func (graph *Graph) LoadAndProcessCommits(ctx context.Context, repository *repo_
return repo_model.IsOwnerMemberCollaborator(repository, user.ID)
}, &keyMap)
statuses, _, err := git_model.GetLatestCommitStatus(db.DefaultContext, repository.ID, c.Commit.ID.String(), db.ListOptions{})
statuses, _, err := git_model.GetLatestCommitStatus(ctx, repository.ID, c.Commit.ID.String(), db.ListOptions{})
if err != nil {
log.Error("GetLatestCommitStatus: %v", err)
} else {

View File

@ -4,19 +4,20 @@
package repository
import (
"code.gitea.io/gitea/models/db"
"context"
"code.gitea.io/gitea/models/organization"
repo_model "code.gitea.io/gitea/models/repo"
user_model "code.gitea.io/gitea/models/user"
)
// CanUserDelete returns true if user could delete the repository
func CanUserDelete(repo *repo_model.Repository, user *user_model.User) (bool, error) {
func CanUserDelete(ctx context.Context, repo *repo_model.Repository, user *user_model.User) (bool, error) {
if user.IsAdmin || user.ID == repo.OwnerID {
return true, nil
}
if err := repo.LoadOwner(db.DefaultContext); err != nil {
if err := repo.LoadOwner(ctx); err != nil {
return false, err
}

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