Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Final round of db.DefaultContext refactor #27587

Merged
merged 3 commits into from
Oct 14, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion cmd/admin_auth.go
Original file line number Diff line number Diff line change
Expand Up @@ -105,5 +105,5 @@ func runDeleteAuth(c *cli.Context) error {
return err
}

return auth_service.DeleteSource(source)
return auth_service.DeleteSource(ctx, source)
}
4 changes: 2 additions & 2 deletions models/asymkey/gpg_key.go
Original file line number Diff line number Diff line change
Expand Up @@ -111,8 +111,8 @@ func GetGPGKeysByKeyID(ctx context.Context, keyID string) ([]*GPGKey, error) {
}

// GPGKeyToEntity retrieve the imported key and the traducted entity
func GPGKeyToEntity(k *GPGKey) (*openpgp.Entity, error) {
impKey, err := GetGPGImportByKeyID(k.KeyID)
func GPGKeyToEntity(ctx context.Context, k *GPGKey) (*openpgp.Entity, error) {
impKey, err := GetGPGImportByKeyID(ctx, k.KeyID)
if err != nil {
return nil, err
}
Expand Down
10 changes: 7 additions & 3 deletions models/asymkey/gpg_key_import.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,11 @@

package asymkey

import "code.gitea.io/gitea/models/db"
import (
"context"

"code.gitea.io/gitea/models/db"
)

// __________________ ________ ____ __.
// / _____/\______ \/ _____/ | |/ _|____ ___.__.
Expand Down Expand Up @@ -31,9 +35,9 @@ func init() {
}

// GetGPGImportByKeyID returns the import public armored key by given KeyID.
func GetGPGImportByKeyID(keyID string) (*GPGKeyImport, error) {
func GetGPGImportByKeyID(ctx context.Context, keyID string) (*GPGKeyImport, error) {
key := new(GPGKeyImport)
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 {
Expand Down
5 changes: 3 additions & 2 deletions models/asymkey/gpg_key_verify.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
package asymkey

import (
"context"
"strconv"
"time"

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

// VerifyGPGKey marks a GPG key as verified
func VerifyGPGKey(ownerID int64, keyID, token, signature string) (string, error) {
ctx, committer, err := db.TxContext(db.DefaultContext)
func VerifyGPGKey(ctx context.Context, ownerID int64, keyID, token, signature string) (string, error) {
ctx, committer, err := db.TxContext(ctx)
KN4CK3R marked this conversation as resolved.
Show resolved Hide resolved
if err != nil {
return "", err
}
Expand Down
16 changes: 8 additions & 8 deletions models/asymkey/ssh_key_deploy.go
Original file line number Diff line number Diff line change
Expand Up @@ -106,15 +106,15 @@ func addDeployKey(ctx context.Context, keyID, repoID int64, name, fingerprint st
}

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

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

ctx, committer, err := db.TxContext(db.DefaultContext)
ctx, committer, err := db.TxContext(ctx)
if err != nil {
return nil, err
}
Expand Down Expand Up @@ -197,8 +197,8 @@ func IsDeployKeyExistByKeyID(ctx context.Context, keyID int64) (bool, error) {
}

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

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

// CountDeployKeys returns count deploy keys matching the provided arguments.
func CountDeployKeys(opts *ListDeployKeysOptions) (int64, error) {
return db.GetEngine(db.DefaultContext).Where(opts.toCond()).Count(&DeployKey{})
func CountDeployKeys(ctx context.Context, opts *ListDeployKeysOptions) (int64, error) {
return db.GetEngine(ctx).Where(opts.toCond()).Count(&DeployKey{})
}
14 changes: 7 additions & 7 deletions models/asymkey/ssh_key_principals.go
Original file line number Diff line number Diff line change
Expand Up @@ -25,15 +25,15 @@ import (
// This file contains functions related to principals

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

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

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

committer.Close()

return key, RewriteAllPrincipalKeys(db.DefaultContext)
return key, RewriteAllPrincipalKeys(ctx)
}

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

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

Expand Down
5 changes: 3 additions & 2 deletions models/asymkey/ssh_key_verify.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ package asymkey

import (
"bytes"
"context"

"code.gitea.io/gitea/models/db"
"code.gitea.io/gitea/modules/log"
Expand All @@ -13,8 +14,8 @@ import (
)

// VerifySSHKey marks a SSH key as verified
func VerifySSHKey(ownerID int64, fingerprint, token, signature string) (string, error) {
ctx, committer, err := db.TxContext(db.DefaultContext)
func VerifySSHKey(ctx context.Context, ownerID int64, fingerprint, token, signature string) (string, error) {
ctx, committer, err := db.TxContext(ctx)
KN4CK3R marked this conversation as resolved.
Show resolved Hide resolved
if err != nil {
return "", err
}
Expand Down
24 changes: 12 additions & 12 deletions models/auth/oauth2.go
Original file line number Diff line number Diff line change
Expand Up @@ -170,7 +170,7 @@ const lowerBase32Chars = "abcdefghijklmnopqrstuvwxyz234567"
var base32Lower = base32.NewEncoding(lowerBase32Chars).WithPadding(base32.NoPadding)

// GenerateClientSecret will generate the client secret and returns the plaintext and saves the hash at the database
func (app *OAuth2Application) GenerateClientSecret() (string, error) {
func (app *OAuth2Application) GenerateClientSecret(ctx context.Context) (string, error) {
rBytes, err := util.CryptoRandomBytes(32)
if err != nil {
return "", err
Expand All @@ -184,7 +184,7 @@ func (app *OAuth2Application) GenerateClientSecret() (string, error) {
return "", err
}
app.ClientSecret = string(hashedSecret)
if _, err := db.GetEngine(db.DefaultContext).ID(app.ID).Cols("client_secret").Update(app); err != nil {
if _, err := db.GetEngine(ctx).ID(app.ID).Cols("client_secret").Update(app); err != nil {
return "", err
}
return clientSecret, nil
Expand Down Expand Up @@ -284,8 +284,8 @@ type UpdateOAuth2ApplicationOptions struct {
}

// UpdateOAuth2Application updates an oauth2 application
func UpdateOAuth2Application(opts UpdateOAuth2ApplicationOptions) (*OAuth2Application, error) {
ctx, committer, err := db.TxContext(db.DefaultContext)
func UpdateOAuth2Application(ctx context.Context, opts UpdateOAuth2ApplicationOptions) (*OAuth2Application, error) {
ctx, committer, err := db.TxContext(ctx)
KN4CK3R marked this conversation as resolved.
Show resolved Hide resolved
if err != nil {
return nil, err
}
Expand Down Expand Up @@ -352,8 +352,8 @@ func deleteOAuth2Application(ctx context.Context, id, userid int64) error {
}

// 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.
func DeleteOAuth2Application(id, userid int64) error {
ctx, committer, err := db.TxContext(db.DefaultContext)
func DeleteOAuth2Application(ctx context.Context, id, userid int64) error {
ctx, committer, err := db.TxContext(ctx)
KN4CK3R marked this conversation as resolved.
Show resolved Hide resolved
if err != nil {
return err
}
Expand All @@ -373,8 +373,8 @@ func DeleteOAuth2Application(id, userid int64) error {
}

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

Expand Down Expand Up @@ -632,18 +632,18 @@ func (err ErrOAuthApplicationNotFound) Unwrap() error {
}

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

// GetActiveOAuth2SourceByName returns a OAuth2 AuthSource based on the given name
func GetActiveOAuth2SourceByName(name string) (*Source, error) {
func GetActiveOAuth2SourceByName(ctx context.Context, name string) (*Source, error) {
authSource := new(Source)
has, err := db.GetEngine(db.DefaultContext).Where("name = ? and type = ? and is_active = ?", name, OAuth2, true).Get(authSource)
has, err := db.GetEngine(ctx).Where("name = ? and type = ? and is_active = ?", name, OAuth2, true).Get(authSource)
if err != nil {
return nil, err
}
Expand Down
6 changes: 3 additions & 3 deletions models/auth/oauth2_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ import (
func TestOAuth2Application_GenerateClientSecret(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase())
app := unittest.AssertExistsAndLoadBean(t, &auth_model.OAuth2Application{ID: 1})
secret, err := app.GenerateClientSecret()
secret, err := app.GenerateClientSecret(db.DefaultContext)
assert.NoError(t, err)
assert.True(t, len(secret) > 0)
unittest.AssertExistsAndLoadBean(t, &auth_model.OAuth2Application{ID: 1, ClientSecret: app.ClientSecret})
Expand All @@ -28,7 +28,7 @@ func BenchmarkOAuth2Application_GenerateClientSecret(b *testing.B) {
assert.NoError(b, unittest.PrepareTestDatabase())
app := unittest.AssertExistsAndLoadBean(b, &auth_model.OAuth2Application{ID: 1})
for i := 0; i < b.N; i++ {
_, _ = app.GenerateClientSecret()
_, _ = app.GenerateClientSecret(db.DefaultContext)
}
}

Expand Down Expand Up @@ -78,7 +78,7 @@ func TestOAuth2Application_ContainsRedirect_Slash(t *testing.T) {
func TestOAuth2Application_ValidateClientSecret(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase())
app := unittest.AssertExistsAndLoadBean(t, &auth_model.OAuth2Application{ID: 1})
secret, err := app.GenerateClientSecret()
secret, err := app.GenerateClientSecret(db.DefaultContext)
assert.NoError(t, err)
assert.True(t, app.ValidateClientSecret([]byte(secret)))
assert.False(t, app.ValidateClientSecret([]byte("fewijfowejgfiowjeoifew")))
Expand Down
10 changes: 5 additions & 5 deletions models/avatars/avatar.go
Original file line number Diff line number Diff line change
Expand Up @@ -94,13 +94,13 @@ func HashEmail(email string) string {
}

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

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

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

enableFederatedAvatar := setting.Config().Picture.EnableFederatedAvatar.Value(ctx)
if enableFederatedAvatar {
emailHash := saveEmailHash(email)
emailHash := saveEmailHash(ctx, email)
if final {
// for final link, we can spend more time on slow external query
var avatarURL *url.URL
Expand Down
4 changes: 2 additions & 2 deletions models/repo/redirect.go
Original file line number Diff line number Diff line change
Expand Up @@ -50,10 +50,10 @@ func init() {
}

// LookupRedirect look up if a repository has a redirect name
func LookupRedirect(ownerID int64, repoName string) (int64, error) {
func LookupRedirect(ctx context.Context, ownerID int64, repoName string) (int64, error) {
repoName = strings.ToLower(repoName)
redirect := &Redirect{OwnerID: ownerID, LowerName: repoName}
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, ErrRedirectNotExist{OwnerID: ownerID, RepoName: repoName}
Expand Down
4 changes: 2 additions & 2 deletions models/repo/redirect_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,11 +16,11 @@ import (
func TestLookupRedirect(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase())

repoID, err := repo_model.LookupRedirect(2, "oldrepo1")
repoID, err := repo_model.LookupRedirect(db.DefaultContext, 2, "oldrepo1")
assert.NoError(t, err)
assert.EqualValues(t, 1, repoID)

_, err = repo_model.LookupRedirect(unittest.NonexistentID, "doesnotexist")
_, err = repo_model.LookupRedirect(db.DefaultContext, unittest.NonexistentID, "doesnotexist")
assert.True(t, repo_model.IsErrRedirectNotExist(err))
}

Expand Down
Loading