Skip to content

Commit 76a85a4

Browse files
authored
Final round of db.DefaultContext refactor (#27587)
Last part of #27065
1 parent ae419fa commit 76a85a4

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

64 files changed

+250
-242
lines changed

cmd/admin_auth.go

+1-1
Original file line numberDiff line numberDiff line change
@@ -105,5 +105,5 @@ func runDeleteAuth(c *cli.Context) error {
105105
return err
106106
}
107107

108-
return auth_service.DeleteSource(source)
108+
return auth_service.DeleteSource(ctx, source)
109109
}

models/asymkey/gpg_key.go

+2-2
Original file line numberDiff line numberDiff line change
@@ -111,8 +111,8 @@ func GetGPGKeysByKeyID(ctx context.Context, keyID string) ([]*GPGKey, error) {
111111
}
112112

113113
// GPGKeyToEntity retrieve the imported key and the traducted entity
114-
func GPGKeyToEntity(k *GPGKey) (*openpgp.Entity, error) {
115-
impKey, err := GetGPGImportByKeyID(k.KeyID)
114+
func GPGKeyToEntity(ctx context.Context, k *GPGKey) (*openpgp.Entity, error) {
115+
impKey, err := GetGPGImportByKeyID(ctx, k.KeyID)
116116
if err != nil {
117117
return nil, err
118118
}

models/asymkey/gpg_key_import.go

+7-3
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,11 @@
33

44
package asymkey
55

6-
import "code.gitea.io/gitea/models/db"
6+
import (
7+
"context"
8+
9+
"code.gitea.io/gitea/models/db"
10+
)
711

812
// __________________ ________ ____ __.
913
// / _____/\______ \/ _____/ | |/ _|____ ___.__.
@@ -31,9 +35,9 @@ func init() {
3135
}
3236

3337
// GetGPGImportByKeyID returns the import public armored key by given KeyID.
34-
func GetGPGImportByKeyID(keyID string) (*GPGKeyImport, error) {
38+
func GetGPGImportByKeyID(ctx context.Context, keyID string) (*GPGKeyImport, error) {
3539
key := new(GPGKeyImport)
36-
has, err := db.GetEngine(db.DefaultContext).ID(keyID).Get(key)
40+
has, err := db.GetEngine(ctx).ID(keyID).Get(key)
3741
if err != nil {
3842
return nil, err
3943
} else if !has {

models/asymkey/gpg_key_verify.go

+3-2
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44
package asymkey
55

66
import (
7+
"context"
78
"strconv"
89
"time"
910

@@ -29,8 +30,8 @@ import (
2930
// This file provides functions relating verifying gpg keys
3031

3132
// VerifyGPGKey marks a GPG key as verified
32-
func VerifyGPGKey(ownerID int64, keyID, token, signature string) (string, error) {
33-
ctx, committer, err := db.TxContext(db.DefaultContext)
33+
func VerifyGPGKey(ctx context.Context, ownerID int64, keyID, token, signature string) (string, error) {
34+
ctx, committer, err := db.TxContext(ctx)
3435
if err != nil {
3536
return "", err
3637
}

models/asymkey/ssh_key_deploy.go

+8-8
Original file line numberDiff line numberDiff line change
@@ -106,15 +106,15 @@ func addDeployKey(ctx context.Context, keyID, repoID int64, name, fingerprint st
106106
}
107107

108108
// HasDeployKey returns true if public key is a deploy key of given repository.
109-
func HasDeployKey(keyID, repoID int64) bool {
110-
has, _ := db.GetEngine(db.DefaultContext).
109+
func HasDeployKey(ctx context.Context, keyID, repoID int64) bool {
110+
has, _ := db.GetEngine(ctx).
111111
Where("key_id = ? AND repo_id = ?", keyID, repoID).
112112
Get(new(DeployKey))
113113
return has
114114
}
115115

116116
// AddDeployKey add new deploy key to database and authorized_keys file.
117-
func AddDeployKey(repoID int64, name, content string, readOnly bool) (*DeployKey, error) {
117+
func AddDeployKey(ctx context.Context, repoID int64, name, content string, readOnly bool) (*DeployKey, error) {
118118
fingerprint, err := CalcFingerprint(content)
119119
if err != nil {
120120
return nil, err
@@ -125,7 +125,7 @@ func AddDeployKey(repoID int64, name, content string, readOnly bool) (*DeployKey
125125
accessMode = perm.AccessModeWrite
126126
}
127127

128-
ctx, committer, err := db.TxContext(db.DefaultContext)
128+
ctx, committer, err := db.TxContext(ctx)
129129
if err != nil {
130130
return nil, err
131131
}
@@ -197,8 +197,8 @@ func IsDeployKeyExistByKeyID(ctx context.Context, keyID int64) (bool, error) {
197197
}
198198

199199
// UpdateDeployKeyCols updates deploy key information in the specified columns.
200-
func UpdateDeployKeyCols(key *DeployKey, cols ...string) error {
201-
_, err := db.GetEngine(db.DefaultContext).ID(key.ID).Cols(cols...).Update(key)
200+
func UpdateDeployKeyCols(ctx context.Context, key *DeployKey, cols ...string) error {
201+
_, err := db.GetEngine(ctx).ID(key.ID).Cols(cols...).Update(key)
202202
return err
203203
}
204204

@@ -240,6 +240,6 @@ func ListDeployKeys(ctx context.Context, opts *ListDeployKeysOptions) ([]*Deploy
240240
}
241241

242242
// CountDeployKeys returns count deploy keys matching the provided arguments.
243-
func CountDeployKeys(opts *ListDeployKeysOptions) (int64, error) {
244-
return db.GetEngine(db.DefaultContext).Where(opts.toCond()).Count(&DeployKey{})
243+
func CountDeployKeys(ctx context.Context, opts *ListDeployKeysOptions) (int64, error) {
244+
return db.GetEngine(ctx).Where(opts.toCond()).Count(&DeployKey{})
245245
}

models/asymkey/ssh_key_principals.go

+7-7
Original file line numberDiff line numberDiff line change
@@ -25,15 +25,15 @@ import (
2525
// This file contains functions related to principals
2626

2727
// AddPrincipalKey adds new principal to database and authorized_principals file.
28-
func AddPrincipalKey(ownerID int64, content string, authSourceID int64) (*PublicKey, error) {
29-
ctx, committer, err := db.TxContext(db.DefaultContext)
28+
func AddPrincipalKey(ctx context.Context, ownerID int64, content string, authSourceID int64) (*PublicKey, error) {
29+
dbCtx, committer, err := db.TxContext(ctx)
3030
if err != nil {
3131
return nil, err
3232
}
3333
defer committer.Close()
3434

3535
// Principals cannot be duplicated.
36-
has, err := db.GetEngine(ctx).
36+
has, err := db.GetEngine(dbCtx).
3737
Where("content = ? AND type = ?", content, KeyTypePrincipal).
3838
Get(new(PublicKey))
3939
if err != nil {
@@ -50,7 +50,7 @@ func AddPrincipalKey(ownerID int64, content string, authSourceID int64) (*Public
5050
Type: KeyTypePrincipal,
5151
LoginSourceID: authSourceID,
5252
}
53-
if err = db.Insert(ctx, key); err != nil {
53+
if err = db.Insert(dbCtx, key); err != nil {
5454
return nil, fmt.Errorf("addKey: %w", err)
5555
}
5656

@@ -60,7 +60,7 @@ func AddPrincipalKey(ownerID int64, content string, authSourceID int64) (*Public
6060

6161
committer.Close()
6262

63-
return key, RewriteAllPrincipalKeys(db.DefaultContext)
63+
return key, RewriteAllPrincipalKeys(ctx)
6464
}
6565

6666
// CheckPrincipalKeyString strips spaces and returns an error if the given principal contains newlines
@@ -105,8 +105,8 @@ func CheckPrincipalKeyString(ctx context.Context, user *user_model.User, content
105105
}
106106

107107
// ListPrincipalKeys returns a list of principals belongs to given user.
108-
func ListPrincipalKeys(uid int64, listOptions db.ListOptions) ([]*PublicKey, error) {
109-
sess := db.GetEngine(db.DefaultContext).Where("owner_id = ? AND type = ?", uid, KeyTypePrincipal)
108+
func ListPrincipalKeys(ctx context.Context, uid int64, listOptions db.ListOptions) ([]*PublicKey, error) {
109+
sess := db.GetEngine(ctx).Where("owner_id = ? AND type = ?", uid, KeyTypePrincipal)
110110
if listOptions.Page != 0 {
111111
sess = db.SetSessionPagination(sess, &listOptions)
112112

models/asymkey/ssh_key_verify.go

+3-2
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ package asymkey
55

66
import (
77
"bytes"
8+
"context"
89

910
"code.gitea.io/gitea/models/db"
1011
"code.gitea.io/gitea/modules/log"
@@ -13,8 +14,8 @@ import (
1314
)
1415

1516
// VerifySSHKey marks a SSH key as verified
16-
func VerifySSHKey(ownerID int64, fingerprint, token, signature string) (string, error) {
17-
ctx, committer, err := db.TxContext(db.DefaultContext)
17+
func VerifySSHKey(ctx context.Context, ownerID int64, fingerprint, token, signature string) (string, error) {
18+
ctx, committer, err := db.TxContext(ctx)
1819
if err != nil {
1920
return "", err
2021
}

models/auth/oauth2.go

+12-12
Original file line numberDiff line numberDiff line change
@@ -170,7 +170,7 @@ const lowerBase32Chars = "abcdefghijklmnopqrstuvwxyz234567"
170170
var base32Lower = base32.NewEncoding(lowerBase32Chars).WithPadding(base32.NoPadding)
171171

172172
// GenerateClientSecret will generate the client secret and returns the plaintext and saves the hash at the database
173-
func (app *OAuth2Application) GenerateClientSecret() (string, error) {
173+
func (app *OAuth2Application) GenerateClientSecret(ctx context.Context) (string, error) {
174174
rBytes, err := util.CryptoRandomBytes(32)
175175
if err != nil {
176176
return "", err
@@ -184,7 +184,7 @@ func (app *OAuth2Application) GenerateClientSecret() (string, error) {
184184
return "", err
185185
}
186186
app.ClientSecret = string(hashedSecret)
187-
if _, err := db.GetEngine(db.DefaultContext).ID(app.ID).Cols("client_secret").Update(app); err != nil {
187+
if _, err := db.GetEngine(ctx).ID(app.ID).Cols("client_secret").Update(app); err != nil {
188188
return "", err
189189
}
190190
return clientSecret, nil
@@ -284,8 +284,8 @@ type UpdateOAuth2ApplicationOptions struct {
284284
}
285285

286286
// UpdateOAuth2Application updates an oauth2 application
287-
func UpdateOAuth2Application(opts UpdateOAuth2ApplicationOptions) (*OAuth2Application, error) {
288-
ctx, committer, err := db.TxContext(db.DefaultContext)
287+
func UpdateOAuth2Application(ctx context.Context, opts UpdateOAuth2ApplicationOptions) (*OAuth2Application, error) {
288+
ctx, committer, err := db.TxContext(ctx)
289289
if err != nil {
290290
return nil, err
291291
}
@@ -352,8 +352,8 @@ func deleteOAuth2Application(ctx context.Context, id, userid int64) error {
352352
}
353353

354354
// DeleteOAuth2Application deletes the application with the given id and the grants and auth codes related to it. It checks if the userid was the creator of the app.
355-
func DeleteOAuth2Application(id, userid int64) error {
356-
ctx, committer, err := db.TxContext(db.DefaultContext)
355+
func DeleteOAuth2Application(ctx context.Context, id, userid int64) error {
356+
ctx, committer, err := db.TxContext(ctx)
357357
if err != nil {
358358
return err
359359
}
@@ -373,8 +373,8 @@ func DeleteOAuth2Application(id, userid int64) error {
373373
}
374374

375375
// ListOAuth2Applications returns a list of oauth2 applications belongs to given user.
376-
func ListOAuth2Applications(uid int64, listOptions db.ListOptions) ([]*OAuth2Application, int64, error) {
377-
sess := db.GetEngine(db.DefaultContext).
376+
func ListOAuth2Applications(ctx context.Context, uid int64, listOptions db.ListOptions) ([]*OAuth2Application, int64, error) {
377+
sess := db.GetEngine(ctx).
378378
Where("uid=?", uid).
379379
Desc("id")
380380

@@ -632,18 +632,18 @@ func (err ErrOAuthApplicationNotFound) Unwrap() error {
632632
}
633633

634634
// GetActiveOAuth2ProviderSources returns all actived LoginOAuth2 sources
635-
func GetActiveOAuth2ProviderSources() ([]*Source, error) {
635+
func GetActiveOAuth2ProviderSources(ctx context.Context) ([]*Source, error) {
636636
sources := make([]*Source, 0, 1)
637-
if err := db.GetEngine(db.DefaultContext).Where("is_active = ? and type = ?", true, OAuth2).Find(&sources); err != nil {
637+
if err := db.GetEngine(ctx).Where("is_active = ? and type = ?", true, OAuth2).Find(&sources); err != nil {
638638
return nil, err
639639
}
640640
return sources, nil
641641
}
642642

643643
// GetActiveOAuth2SourceByName returns a OAuth2 AuthSource based on the given name
644-
func GetActiveOAuth2SourceByName(name string) (*Source, error) {
644+
func GetActiveOAuth2SourceByName(ctx context.Context, name string) (*Source, error) {
645645
authSource := new(Source)
646-
has, err := db.GetEngine(db.DefaultContext).Where("name = ? and type = ? and is_active = ?", name, OAuth2, true).Get(authSource)
646+
has, err := db.GetEngine(ctx).Where("name = ? and type = ? and is_active = ?", name, OAuth2, true).Get(authSource)
647647
if err != nil {
648648
return nil, err
649649
}

models/auth/oauth2_test.go

+3-3
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,7 @@ import (
1818
func TestOAuth2Application_GenerateClientSecret(t *testing.T) {
1919
assert.NoError(t, unittest.PrepareTestDatabase())
2020
app := unittest.AssertExistsAndLoadBean(t, &auth_model.OAuth2Application{ID: 1})
21-
secret, err := app.GenerateClientSecret()
21+
secret, err := app.GenerateClientSecret(db.DefaultContext)
2222
assert.NoError(t, err)
2323
assert.True(t, len(secret) > 0)
2424
unittest.AssertExistsAndLoadBean(t, &auth_model.OAuth2Application{ID: 1, ClientSecret: app.ClientSecret})
@@ -28,7 +28,7 @@ func BenchmarkOAuth2Application_GenerateClientSecret(b *testing.B) {
2828
assert.NoError(b, unittest.PrepareTestDatabase())
2929
app := unittest.AssertExistsAndLoadBean(b, &auth_model.OAuth2Application{ID: 1})
3030
for i := 0; i < b.N; i++ {
31-
_, _ = app.GenerateClientSecret()
31+
_, _ = app.GenerateClientSecret(db.DefaultContext)
3232
}
3333
}
3434

@@ -78,7 +78,7 @@ func TestOAuth2Application_ContainsRedirect_Slash(t *testing.T) {
7878
func TestOAuth2Application_ValidateClientSecret(t *testing.T) {
7979
assert.NoError(t, unittest.PrepareTestDatabase())
8080
app := unittest.AssertExistsAndLoadBean(t, &auth_model.OAuth2Application{ID: 1})
81-
secret, err := app.GenerateClientSecret()
81+
secret, err := app.GenerateClientSecret(db.DefaultContext)
8282
assert.NoError(t, err)
8383
assert.True(t, app.ValidateClientSecret([]byte(secret)))
8484
assert.False(t, app.ValidateClientSecret([]byte("fewijfowejgfiowjeoifew")))

models/avatars/avatar.go

+5-5
Original file line numberDiff line numberDiff line change
@@ -94,13 +94,13 @@ func HashEmail(email string) string {
9494
}
9595

9696
// GetEmailForHash converts a provided md5sum to the email
97-
func GetEmailForHash(md5Sum string) (string, error) {
97+
func GetEmailForHash(ctx context.Context, md5Sum string) (string, error) {
9898
return cache.GetString("Avatar:"+md5Sum, func() (string, error) {
9999
emailHash := EmailHash{
100100
Hash: strings.ToLower(strings.TrimSpace(md5Sum)),
101101
}
102102

103-
_, err := db.GetEngine(db.DefaultContext).Get(&emailHash)
103+
_, err := db.GetEngine(ctx).Get(&emailHash)
104104
return emailHash.Email, err
105105
})
106106
}
@@ -127,7 +127,7 @@ func LibravatarURL(email string) (*url.URL, error) {
127127

128128
// saveEmailHash returns an avatar link for a provided email,
129129
// the email and hash are saved into database, which will be used by GetEmailForHash later
130-
func saveEmailHash(email string) string {
130+
func saveEmailHash(ctx context.Context, email string) string {
131131
lowerEmail := strings.ToLower(strings.TrimSpace(email))
132132
emailHash := HashEmail(lowerEmail)
133133
_, _ = cache.GetString("Avatar:"+emailHash, func() (string, error) {
@@ -136,7 +136,7 @@ func saveEmailHash(email string) string {
136136
Hash: emailHash,
137137
}
138138
// OK we're going to open a session just because I think that that might hide away any problems with postgres reporting errors
139-
if err := db.WithTx(db.DefaultContext, func(ctx context.Context) error {
139+
if err := db.WithTx(ctx, func(ctx context.Context) error {
140140
has, err := db.GetEngine(ctx).Where("email = ? AND hash = ?", emailHash.Email, emailHash.Hash).Get(new(EmailHash))
141141
if has || err != nil {
142142
// Seriously we don't care about any DB problems just return the lowerEmail - we expect the transaction to fail most of the time
@@ -196,7 +196,7 @@ func generateEmailAvatarLink(ctx context.Context, email string, size int, final
196196

197197
enableFederatedAvatar := setting.Config().Picture.EnableFederatedAvatar.Value(ctx)
198198
if enableFederatedAvatar {
199-
emailHash := saveEmailHash(email)
199+
emailHash := saveEmailHash(ctx, email)
200200
if final {
201201
// for final link, we can spend more time on slow external query
202202
var avatarURL *url.URL

models/repo/redirect.go

+2-2
Original file line numberDiff line numberDiff line change
@@ -50,10 +50,10 @@ func init() {
5050
}
5151

5252
// LookupRedirect look up if a repository has a redirect name
53-
func LookupRedirect(ownerID int64, repoName string) (int64, error) {
53+
func LookupRedirect(ctx context.Context, ownerID int64, repoName string) (int64, error) {
5454
repoName = strings.ToLower(repoName)
5555
redirect := &Redirect{OwnerID: ownerID, LowerName: repoName}
56-
if has, err := db.GetEngine(db.DefaultContext).Get(redirect); err != nil {
56+
if has, err := db.GetEngine(ctx).Get(redirect); err != nil {
5757
return 0, err
5858
} else if !has {
5959
return 0, ErrRedirectNotExist{OwnerID: ownerID, RepoName: repoName}

models/repo/redirect_test.go

+2-2
Original file line numberDiff line numberDiff line change
@@ -16,11 +16,11 @@ import (
1616
func TestLookupRedirect(t *testing.T) {
1717
assert.NoError(t, unittest.PrepareTestDatabase())
1818

19-
repoID, err := repo_model.LookupRedirect(2, "oldrepo1")
19+
repoID, err := repo_model.LookupRedirect(db.DefaultContext, 2, "oldrepo1")
2020
assert.NoError(t, err)
2121
assert.EqualValues(t, 1, repoID)
2222

23-
_, err = repo_model.LookupRedirect(unittest.NonexistentID, "doesnotexist")
23+
_, err = repo_model.LookupRedirect(db.DefaultContext, unittest.NonexistentID, "doesnotexist")
2424
assert.True(t, repo_model.IsErrRedirectNotExist(err))
2525
}
2626

0 commit comments

Comments
 (0)