From ebe803e514acb4eedc884226be2489ee6b4acd28 Mon Sep 17 00:00:00 2001
From: JakobDev <jakobdev@gmx.de>
Date: Wed, 11 Oct 2023 06:24:07 +0200
Subject: [PATCH] Penultimate round of `db.DefaultContext` refactor (#27414)

Part of #27065

---------

Co-authored-by: Lunny Xiao <xiaolunwen@gmail.com>
---
 cmd/admin_auth.go                             |  4 +-
 cmd/admin_auth_ldap.go                        | 22 ++++----
 cmd/admin_auth_ldap_test.go                   | 24 ++++----
 cmd/admin_auth_oauth.go                       |  6 +-
 cmd/admin_auth_stmp.go                        |  6 +-
 models/actions/run_job_list.go                |  2 +-
 models/actions/run_list.go                    |  4 +-
 models/actions/schedule_list.go               |  4 +-
 models/actions/schedule_spec_list.go          |  4 +-
 models/activities/statistic.go                |  2 +-
 models/asymkey/ssh_key.go                     | 56 +++++++++----------
 models/asymkey/ssh_key_commit_verification.go |  2 +-
 models/asymkey/ssh_key_deploy.go              |  4 +-
 models/auth/source.go                         | 47 ++++++++--------
 models/auth/source_test.go                    |  2 +-
 models/issues/comment_code.go                 |  2 +-
 models/issues/dependency.go                   |  8 +--
 models/issues/dependency_test.go              |  8 +--
 models/issues/issue_label.go                  | 18 +++---
 models/issues/issue_label_test.go             |  3 +-
 models/issues/issue_lock.go                   | 14 +++--
 models/issues/issue_project.go                | 14 ++---
 models/issues/issue_search.go                 |  4 +-
 models/issues/issue_test.go                   |  6 +-
 models/issues/label_test.go                   | 16 +++---
 models/issues/milestone_list.go               |  4 +-
 models/issues/milestone_test.go               |  8 +--
 models/issues/pull.go                         | 42 +++++++-------
 models/issues/pull_test.go                    | 12 ++--
 models/repo.go                                | 10 ++--
 models/repo/avatar.go                         |  4 +-
 models/repo/language_stats.go                 | 12 ++--
 models/repo/repo.go                           | 28 +++++-----
 models/repo/repo_indexer.go                   |  4 +-
 models/repo/repo_list.go                      |  8 +--
 models/repo/repo_test.go                      |  6 +-
 models/repo_test.go                           |  2 +-
 modules/context/repo.go                       |  6 +-
 modules/doctor/mergebase.go                   |  2 +-
 modules/doctor/misc.go                        |  2 +-
 modules/indexer/code/indexer.go               |  2 +-
 modules/indexer/issues/util.go                |  2 +-
 modules/indexer/stats/db.go                   |  2 +-
 modules/indexer/stats/indexer.go              |  8 ++-
 modules/indexer/stats/indexer_test.go         |  2 +-
 routers/api/v1/admin/user.go                  |  2 +-
 routers/api/v1/api.go                         |  5 +-
 routers/api/v1/org/avatar.go                  |  4 +-
 routers/api/v1/org/team.go                    |  2 +-
 routers/api/v1/repo/issue.go                  |  4 +-
 routers/api/v1/repo/issue_dependency.go       |  4 +-
 routers/api/v1/repo/key.go                    |  4 +-
 routers/api/v1/repo/milestone.go              |  2 +-
 routers/api/v1/repo/pull.go                   |  4 +-
 routers/api/v1/user/avatar.go                 |  4 +-
 routers/api/v1/user/key.go                    | 14 ++---
 routers/common/markup.go                      |  4 +-
 routers/init.go                               |  2 +-
 routers/private/actions.go                    |  2 +-
 routers/private/hook_post_receive.go          | 10 ++--
 routers/private/key.go                        |  2 +-
 routers/private/serv.go                       |  6 +-
 routers/web/admin/auths.go                    | 16 +++---
 routers/web/admin/users.go                    | 10 ++--
 routers/web/auth/auth.go                      |  4 +-
 routers/web/auth/linkaccount.go               |  2 +-
 routers/web/auth/oauth.go                     |  6 +-
 routers/web/explore/code.go                   |  2 +-
 routers/web/feed/convert.go                   |  2 +-
 routers/web/org/projects.go                   |  2 +-
 routers/web/org/setting.go                    |  2 +-
 routers/web/org/teams.go                      |  2 +-
 routers/web/repo/branch.go                    |  2 +-
 routers/web/repo/http.go                      |  2 +-
 routers/web/repo/issue.go                     | 26 ++++-----
 routers/web/repo/issue_dependency.go          |  4 +-
 routers/web/repo/issue_lock.go                |  4 +-
 routers/web/repo/milestone.go                 |  6 +-
 routers/web/repo/projects.go                  |  6 +-
 routers/web/repo/pull.go                      |  6 +-
 routers/web/repo/release.go                   |  4 +-
 routers/web/repo/render.go                    |  2 +-
 routers/web/repo/view.go                      |  8 +--
 routers/web/repo/wiki.go                      |  2 +-
 routers/web/shared/user/header.go             |  2 +-
 routers/web/user/code.go                      |  2 +-
 routers/web/user/home.go                      | 14 ++---
 routers/web/user/setting/keys.go              |  8 +--
 routers/web/user/setting/profile.go           |  4 +-
 routers/web/user/setting/security/security.go |  2 +-
 routers/web/web.go                            |  3 +-
 services/actions/schedule_tasks.go            |  2 +-
 services/agit/agit.go                         |  2 +-
 services/asymkey/ssh_key.go                   |  2 +-
 services/asymkey/ssh_key_test.go              |  4 +-
 services/auth/httpsign.go                     |  2 +-
 services/auth/signin.go                       |  4 +-
 .../auth/source/ldap/source_authenticate.go   |  6 +-
 services/auth/source/ldap/source_sync.go      |  8 +--
 services/auth/sspi.go                         |  6 +-
 services/auth/sync.go                         |  2 +-
 services/convert/pull.go                      |  2 +-
 services/issue/issue_test.go                  |  2 +-
 services/issue/label.go                       |  8 +--
 services/issue/milestone.go                   |  8 +--
 services/issue/milestone_test.go              |  3 +-
 services/mailer/mail.go                       |  2 +-
 services/mailer/mail_issue.go                 |  2 +-
 services/mailer/mail_release.go               |  2 +-
 services/mailer/notify.go                     |  2 +-
 services/migrations/gitea_uploader.go         |  2 +-
 services/migrations/gitea_uploader_test.go    |  4 +-
 services/pull/check.go                        |  4 +-
 services/pull/pull.go                         |  2 +-
 services/repository/archiver/archiver.go      | 12 ++--
 services/repository/archiver/archiver_test.go | 13 +++--
 services/repository/branch.go                 |  2 +-
 services/repository/fork.go                   |  2 +-
 services/uinotification/notify.go             |  2 +-
 services/user/avatar.go                       |  9 +--
 services/user/user.go                         |  2 +-
 templates/repo/branch/list.tmpl               |  4 +-
 templates/repo/commit_page.tmpl               |  6 +-
 templates/repo/commits_list.tmpl              |  4 +-
 templates/repo/commits_list_small.tmpl        |  4 +-
 templates/repo/diff/compare.tmpl              |  4 +-
 templates/repo/graph/commits.tmpl             |  2 +-
 templates/repo/header.tmpl                    |  2 +-
 templates/repo/icon.tmpl                      |  2 +-
 templates/repo/issue/view_content/pull.tmpl   |  2 +-
 templates/repo/issue/view_title.tmpl          |  2 +-
 templates/repo/view_list.tmpl                 |  6 +-
 templates/shared/issueicon.tmpl               |  4 +-
 templates/user/dashboard/feeds.tmpl           |  2 +-
 tests/integration/auth_ldap_test.go           |  2 +-
 tests/integration/pull_merge_test.go          |  2 +-
 136 files changed, 428 insertions(+), 421 deletions(-)

diff --git a/cmd/admin_auth.go b/cmd/admin_auth.go
index ef826a4893..0c931e74eb 100644
--- a/cmd/admin_auth.go
+++ b/cmd/admin_auth.go
@@ -62,7 +62,7 @@ func runListAuth(c *cli.Context) error {
 		return err
 	}
 
-	authSources, err := auth_model.Sources()
+	authSources, err := auth_model.Sources(ctx)
 	if err != nil {
 		return err
 	}
@@ -100,7 +100,7 @@ func runDeleteAuth(c *cli.Context) error {
 		return err
 	}
 
-	source, err := auth_model.GetSourceByID(c.Int64("id"))
+	source, err := auth_model.GetSourceByID(ctx, c.Int64("id"))
 	if err != nil {
 		return err
 	}
diff --git a/cmd/admin_auth_ldap.go b/cmd/admin_auth_ldap.go
index 111bc7955c..e3c81809f8 100644
--- a/cmd/admin_auth_ldap.go
+++ b/cmd/admin_auth_ldap.go
@@ -17,9 +17,9 @@ import (
 type (
 	authService struct {
 		initDB            func(ctx context.Context) error
-		createAuthSource  func(*auth.Source) error
-		updateAuthSource  func(*auth.Source) error
-		getAuthSourceByID func(id int64) (*auth.Source, error)
+		createAuthSource  func(context.Context, *auth.Source) error
+		updateAuthSource  func(context.Context, *auth.Source) error
+		getAuthSourceByID func(ctx context.Context, id int64) (*auth.Source, error)
 	}
 )
 
@@ -289,12 +289,12 @@ func findLdapSecurityProtocolByName(name string) (ldap.SecurityProtocol, bool) {
 
 // getAuthSource gets the login source by its id defined in the command line flags.
 // It returns an error if the id is not set, does not match any source or if the source is not of expected type.
-func (a *authService) getAuthSource(c *cli.Context, authType auth.Type) (*auth.Source, error) {
+func (a *authService) getAuthSource(ctx context.Context, c *cli.Context, authType auth.Type) (*auth.Source, error) {
 	if err := argsSet(c, "id"); err != nil {
 		return nil, err
 	}
 
-	authSource, err := a.getAuthSourceByID(c.Int64("id"))
+	authSource, err := a.getAuthSourceByID(ctx, c.Int64("id"))
 	if err != nil {
 		return nil, err
 	}
@@ -332,7 +332,7 @@ func (a *authService) addLdapBindDn(c *cli.Context) error {
 		return err
 	}
 
-	return a.createAuthSource(authSource)
+	return a.createAuthSource(ctx, authSource)
 }
 
 // updateLdapBindDn updates a new LDAP via Bind DN authentication source.
@@ -344,7 +344,7 @@ func (a *authService) updateLdapBindDn(c *cli.Context) error {
 		return err
 	}
 
-	authSource, err := a.getAuthSource(c, auth.LDAP)
+	authSource, err := a.getAuthSource(ctx, c, auth.LDAP)
 	if err != nil {
 		return err
 	}
@@ -354,7 +354,7 @@ func (a *authService) updateLdapBindDn(c *cli.Context) error {
 		return err
 	}
 
-	return a.updateAuthSource(authSource)
+	return a.updateAuthSource(ctx, authSource)
 }
 
 // addLdapSimpleAuth adds a new LDAP (simple auth) authentication source.
@@ -383,7 +383,7 @@ func (a *authService) addLdapSimpleAuth(c *cli.Context) error {
 		return err
 	}
 
-	return a.createAuthSource(authSource)
+	return a.createAuthSource(ctx, authSource)
 }
 
 // updateLdapBindDn updates a new LDAP (simple auth) authentication source.
@@ -395,7 +395,7 @@ func (a *authService) updateLdapSimpleAuth(c *cli.Context) error {
 		return err
 	}
 
-	authSource, err := a.getAuthSource(c, auth.DLDAP)
+	authSource, err := a.getAuthSource(ctx, c, auth.DLDAP)
 	if err != nil {
 		return err
 	}
@@ -405,5 +405,5 @@ func (a *authService) updateLdapSimpleAuth(c *cli.Context) error {
 		return err
 	}
 
-	return a.updateAuthSource(authSource)
+	return a.updateAuthSource(ctx, authSource)
 }
diff --git a/cmd/admin_auth_ldap_test.go b/cmd/admin_auth_ldap_test.go
index 228c9dd3ed..7791f3a9cc 100644
--- a/cmd/admin_auth_ldap_test.go
+++ b/cmd/admin_auth_ldap_test.go
@@ -210,15 +210,15 @@ func TestAddLdapBindDn(t *testing.T) {
 			initDB: func(context.Context) error {
 				return nil
 			},
-			createAuthSource: func(authSource *auth.Source) error {
+			createAuthSource: func(ctx context.Context, authSource *auth.Source) error {
 				createdAuthSource = authSource
 				return nil
 			},
-			updateAuthSource: func(authSource *auth.Source) error {
+			updateAuthSource: func(ctx context.Context, authSource *auth.Source) error {
 				assert.FailNow(t, "case %d: should not call updateAuthSource", n)
 				return nil
 			},
-			getAuthSourceByID: func(id int64) (*auth.Source, error) {
+			getAuthSourceByID: func(ctx context.Context, id int64) (*auth.Source, error) {
 				assert.FailNow(t, "case %d: should not call getAuthSourceByID", n)
 				return nil, nil
 			},
@@ -441,15 +441,15 @@ func TestAddLdapSimpleAuth(t *testing.T) {
 			initDB: func(context.Context) error {
 				return nil
 			},
-			createAuthSource: func(authSource *auth.Source) error {
+			createAuthSource: func(ctx context.Context, authSource *auth.Source) error {
 				createdAuthSource = authSource
 				return nil
 			},
-			updateAuthSource: func(authSource *auth.Source) error {
+			updateAuthSource: func(ctx context.Context, authSource *auth.Source) error {
 				assert.FailNow(t, "case %d: should not call updateAuthSource", n)
 				return nil
 			},
-			getAuthSourceByID: func(id int64) (*auth.Source, error) {
+			getAuthSourceByID: func(ctx context.Context, id int64) (*auth.Source, error) {
 				assert.FailNow(t, "case %d: should not call getAuthSourceByID", n)
 				return nil, nil
 			},
@@ -896,15 +896,15 @@ func TestUpdateLdapBindDn(t *testing.T) {
 			initDB: func(context.Context) error {
 				return nil
 			},
-			createAuthSource: func(authSource *auth.Source) error {
+			createAuthSource: func(ctx context.Context, authSource *auth.Source) error {
 				assert.FailNow(t, "case %d: should not call createAuthSource", n)
 				return nil
 			},
-			updateAuthSource: func(authSource *auth.Source) error {
+			updateAuthSource: func(ctx context.Context, authSource *auth.Source) error {
 				updatedAuthSource = authSource
 				return nil
 			},
-			getAuthSourceByID: func(id int64) (*auth.Source, error) {
+			getAuthSourceByID: func(ctx context.Context, id int64) (*auth.Source, error) {
 				if c.id != 0 {
 					assert.Equal(t, c.id, id, "case %d: wrong id", n)
 				}
@@ -1286,15 +1286,15 @@ func TestUpdateLdapSimpleAuth(t *testing.T) {
 			initDB: func(context.Context) error {
 				return nil
 			},
-			createAuthSource: func(authSource *auth.Source) error {
+			createAuthSource: func(ctx context.Context, authSource *auth.Source) error {
 				assert.FailNow(t, "case %d: should not call createAuthSource", n)
 				return nil
 			},
-			updateAuthSource: func(authSource *auth.Source) error {
+			updateAuthSource: func(ctx context.Context, authSource *auth.Source) error {
 				updatedAuthSource = authSource
 				return nil
 			},
-			getAuthSourceByID: func(id int64) (*auth.Source, error) {
+			getAuthSourceByID: func(ctx context.Context, id int64) (*auth.Source, error) {
 				if c.id != 0 {
 					assert.Equal(t, c.id, id, "case %d: wrong id", n)
 				}
diff --git a/cmd/admin_auth_oauth.go b/cmd/admin_auth_oauth.go
index cc54ac9454..c151c0af27 100644
--- a/cmd/admin_auth_oauth.go
+++ b/cmd/admin_auth_oauth.go
@@ -183,7 +183,7 @@ func runAddOauth(c *cli.Context) error {
 		}
 	}
 
-	return auth_model.CreateSource(&auth_model.Source{
+	return auth_model.CreateSource(ctx, &auth_model.Source{
 		Type:     auth_model.OAuth2,
 		Name:     c.String("name"),
 		IsActive: true,
@@ -203,7 +203,7 @@ func runUpdateOauth(c *cli.Context) error {
 		return err
 	}
 
-	source, err := auth_model.GetSourceByID(c.Int64("id"))
+	source, err := auth_model.GetSourceByID(ctx, c.Int64("id"))
 	if err != nil {
 		return err
 	}
@@ -294,5 +294,5 @@ func runUpdateOauth(c *cli.Context) error {
 	oAuth2Config.CustomURLMapping = customURLMapping
 	source.Cfg = oAuth2Config
 
-	return auth_model.UpdateSource(source)
+	return auth_model.UpdateSource(ctx, source)
 }
diff --git a/cmd/admin_auth_stmp.go b/cmd/admin_auth_stmp.go
index 8c65de8a1b..58a6e2ac22 100644
--- a/cmd/admin_auth_stmp.go
+++ b/cmd/admin_auth_stmp.go
@@ -156,7 +156,7 @@ func runAddSMTP(c *cli.Context) error {
 		smtpConfig.Auth = "PLAIN"
 	}
 
-	return auth_model.CreateSource(&auth_model.Source{
+	return auth_model.CreateSource(ctx, &auth_model.Source{
 		Type:     auth_model.SMTP,
 		Name:     c.String("name"),
 		IsActive: active,
@@ -176,7 +176,7 @@ func runUpdateSMTP(c *cli.Context) error {
 		return err
 	}
 
-	source, err := auth_model.GetSourceByID(c.Int64("id"))
+	source, err := auth_model.GetSourceByID(ctx, c.Int64("id"))
 	if err != nil {
 		return err
 	}
@@ -197,5 +197,5 @@ func runUpdateSMTP(c *cli.Context) error {
 
 	source.Cfg = smtpConfig
 
-	return auth_model.UpdateSource(source)
+	return auth_model.UpdateSource(ctx, source)
 }
diff --git a/models/actions/run_job_list.go b/models/actions/run_job_list.go
index 047bf64410..a166396694 100644
--- a/models/actions/run_job_list.go
+++ b/models/actions/run_job_list.go
@@ -42,7 +42,7 @@ func (jobs ActionJobList) LoadRuns(ctx context.Context, withRepo bool) error {
 		for _, r := range runs {
 			runsList = append(runsList, r)
 		}
-		return runsList.LoadRepos()
+		return runsList.LoadRepos(ctx)
 	}
 	return nil
 }
diff --git a/models/actions/run_list.go b/models/actions/run_list.go
index db36f6df98..cd053ea7b5 100644
--- a/models/actions/run_list.go
+++ b/models/actions/run_list.go
@@ -52,9 +52,9 @@ func (runs RunList) LoadTriggerUser(ctx context.Context) error {
 	return nil
 }
 
-func (runs RunList) LoadRepos() error {
+func (runs RunList) LoadRepos(ctx context.Context) error {
 	repoIDs := runs.GetRepoIDs()
-	repos, err := repo_model.GetRepositoriesMapByIDs(repoIDs)
+	repos, err := repo_model.GetRepositoriesMapByIDs(ctx, repoIDs)
 	if err != nil {
 		return err
 	}
diff --git a/models/actions/schedule_list.go b/models/actions/schedule_list.go
index e873c05ec3..ddd9a1321e 100644
--- a/models/actions/schedule_list.go
+++ b/models/actions/schedule_list.go
@@ -49,9 +49,9 @@ func (schedules ScheduleList) LoadTriggerUser(ctx context.Context) error {
 	return nil
 }
 
-func (schedules ScheduleList) LoadRepos() error {
+func (schedules ScheduleList) LoadRepos(ctx context.Context) error {
 	repoIDs := schedules.GetRepoIDs()
-	repos, err := repo_model.GetRepositoriesMapByIDs(repoIDs)
+	repos, err := repo_model.GetRepositoriesMapByIDs(ctx, repoIDs)
 	if err != nil {
 		return err
 	}
diff --git a/models/actions/schedule_spec_list.go b/models/actions/schedule_spec_list.go
index 2c017fdabc..6bf91cf819 100644
--- a/models/actions/schedule_spec_list.go
+++ b/models/actions/schedule_spec_list.go
@@ -53,9 +53,9 @@ func (specs SpecList) GetRepoIDs() []int64 {
 	return ids.Values()
 }
 
-func (specs SpecList) LoadRepos() error {
+func (specs SpecList) LoadRepos(ctx context.Context) error {
 	repoIDs := specs.GetRepoIDs()
-	repos, err := repo_model.GetRepositoriesMapByIDs(repoIDs)
+	repos, err := repo_model.GetRepositoriesMapByIDs(ctx, repoIDs)
 	if err != nil {
 		return err
 	}
diff --git a/models/activities/statistic.go b/models/activities/statistic.go
index ea13f3ed5c..009c8c5ab4 100644
--- a/models/activities/statistic.go
+++ b/models/activities/statistic.go
@@ -102,7 +102,7 @@ func GetStatistic(ctx context.Context) (stats Statistic) {
 	stats.Counter.Follow, _ = e.Count(new(user_model.Follow))
 	stats.Counter.Mirror, _ = e.Count(new(repo_model.Mirror))
 	stats.Counter.Release, _ = e.Count(new(repo_model.Release))
-	stats.Counter.AuthSource = auth.CountSources()
+	stats.Counter.AuthSource = auth.CountSources(ctx)
 	stats.Counter.Webhook, _ = e.Count(new(webhook.Webhook))
 	stats.Counter.Milestone, _ = e.Count(new(issues_model.Milestone))
 	stats.Counter.Label, _ = e.Count(new(issues_model.Label))
diff --git a/models/asymkey/ssh_key.go b/models/asymkey/ssh_key.go
index 8d84c2f7dc..f36738fb3d 100644
--- a/models/asymkey/ssh_key.go
+++ b/models/asymkey/ssh_key.go
@@ -91,7 +91,7 @@ func addKey(ctx context.Context, key *PublicKey) (err error) {
 }
 
 // AddPublicKey adds new public key to database and authorized_keys file.
-func AddPublicKey(ownerID int64, name, content string, authSourceID int64) (*PublicKey, error) {
+func AddPublicKey(ctx context.Context, ownerID int64, name, content string, authSourceID int64) (*PublicKey, error) {
 	log.Trace(content)
 
 	fingerprint, err := CalcFingerprint(content)
@@ -99,7 +99,7 @@ func AddPublicKey(ownerID int64, name, content string, authSourceID int64) (*Pub
 		return nil, err
 	}
 
-	ctx, committer, err := db.TxContext(db.DefaultContext)
+	ctx, committer, err := db.TxContext(ctx)
 	if err != nil {
 		return nil, err
 	}
@@ -136,9 +136,9 @@ func AddPublicKey(ownerID int64, name, content string, authSourceID int64) (*Pub
 }
 
 // GetPublicKeyByID returns public key by given ID.
-func GetPublicKeyByID(keyID int64) (*PublicKey, error) {
+func GetPublicKeyByID(ctx context.Context, keyID int64) (*PublicKey, error) {
 	key := new(PublicKey)
-	has, err := db.GetEngine(db.DefaultContext).
+	has, err := db.GetEngine(ctx).
 		ID(keyID).
 		Get(key)
 	if err != nil {
@@ -180,7 +180,7 @@ func SearchPublicKeyByContentExact(ctx context.Context, content string) (*Public
 }
 
 // SearchPublicKey returns a list of public keys matching the provided arguments.
-func SearchPublicKey(uid int64, fingerprint string) ([]*PublicKey, error) {
+func SearchPublicKey(ctx context.Context, uid int64, fingerprint string) ([]*PublicKey, error) {
 	keys := make([]*PublicKey, 0, 5)
 	cond := builder.NewCond()
 	if uid != 0 {
@@ -189,12 +189,12 @@ func SearchPublicKey(uid int64, fingerprint string) ([]*PublicKey, error) {
 	if fingerprint != "" {
 		cond = cond.And(builder.Eq{"fingerprint": fingerprint})
 	}
-	return keys, db.GetEngine(db.DefaultContext).Where(cond).Find(&keys)
+	return keys, db.GetEngine(ctx).Where(cond).Find(&keys)
 }
 
 // ListPublicKeys returns a list of public keys belongs to given user.
-func ListPublicKeys(uid int64, listOptions db.ListOptions) ([]*PublicKey, error) {
-	sess := db.GetEngine(db.DefaultContext).Where("owner_id = ? AND type != ?", uid, KeyTypePrincipal)
+func ListPublicKeys(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)
 
@@ -207,30 +207,30 @@ func ListPublicKeys(uid int64, listOptions db.ListOptions) ([]*PublicKey, error)
 }
 
 // CountPublicKeys count public keys a user has
-func CountPublicKeys(userID int64) (int64, error) {
-	sess := db.GetEngine(db.DefaultContext).Where("owner_id = ? AND type != ?", userID, KeyTypePrincipal)
+func CountPublicKeys(ctx context.Context, userID int64) (int64, error) {
+	sess := db.GetEngine(ctx).Where("owner_id = ? AND type != ?", userID, KeyTypePrincipal)
 	return sess.Count(&PublicKey{})
 }
 
 // ListPublicKeysBySource returns a list of synchronized public keys for a given user and login source.
-func ListPublicKeysBySource(uid, authSourceID int64) ([]*PublicKey, error) {
+func ListPublicKeysBySource(ctx context.Context, uid, authSourceID int64) ([]*PublicKey, error) {
 	keys := make([]*PublicKey, 0, 5)
-	return keys, db.GetEngine(db.DefaultContext).
+	return keys, db.GetEngine(ctx).
 		Where("owner_id = ? AND login_source_id = ?", uid, authSourceID).
 		Find(&keys)
 }
 
 // UpdatePublicKeyUpdated updates public key use time.
-func UpdatePublicKeyUpdated(id int64) error {
+func UpdatePublicKeyUpdated(ctx context.Context, id int64) error {
 	// Check if key exists before update as affected rows count is unreliable
 	//    and will return 0 affected rows if two updates are made at the same time
-	if cnt, err := db.GetEngine(db.DefaultContext).ID(id).Count(&PublicKey{}); err != nil {
+	if cnt, err := db.GetEngine(ctx).ID(id).Count(&PublicKey{}); err != nil {
 		return err
 	} else if cnt != 1 {
 		return ErrKeyNotExist{id}
 	}
 
-	_, err := db.GetEngine(db.DefaultContext).ID(id).Cols("updated_unix").Update(&PublicKey{
+	_, err := db.GetEngine(ctx).ID(id).Cols("updated_unix").Update(&PublicKey{
 		UpdatedUnix: timeutil.TimeStampNow(),
 	})
 	if err != nil {
@@ -250,7 +250,7 @@ func DeletePublicKeys(ctx context.Context, keyIDs ...int64) error {
 }
 
 // PublicKeysAreExternallyManaged returns whether the provided KeyID represents an externally managed Key
-func PublicKeysAreExternallyManaged(keys []*PublicKey) ([]bool, error) {
+func PublicKeysAreExternallyManaged(ctx context.Context, keys []*PublicKey) ([]bool, error) {
 	sources := make([]*auth.Source, 0, 5)
 	externals := make([]bool, len(keys))
 keyloop:
@@ -272,7 +272,7 @@ keyloop:
 
 		if source == nil {
 			var err error
-			source, err = auth.GetSourceByID(key.LoginSourceID)
+			source, err = auth.GetSourceByID(ctx, key.LoginSourceID)
 			if err != nil {
 				if auth.IsErrSourceNotExist(err) {
 					externals[i] = false
@@ -295,15 +295,15 @@ keyloop:
 }
 
 // PublicKeyIsExternallyManaged returns whether the provided KeyID represents an externally managed Key
-func PublicKeyIsExternallyManaged(id int64) (bool, error) {
-	key, err := GetPublicKeyByID(id)
+func PublicKeyIsExternallyManaged(ctx context.Context, id int64) (bool, error) {
+	key, err := GetPublicKeyByID(ctx, id)
 	if err != nil {
 		return false, err
 	}
 	if key.LoginSourceID == 0 {
 		return false, nil
 	}
-	source, err := auth.GetSourceByID(key.LoginSourceID)
+	source, err := auth.GetSourceByID(ctx, key.LoginSourceID)
 	if err != nil {
 		if auth.IsErrSourceNotExist(err) {
 			return false, nil
@@ -318,9 +318,9 @@ func PublicKeyIsExternallyManaged(id int64) (bool, error) {
 }
 
 // deleteKeysMarkedForDeletion returns true if ssh keys needs update
-func deleteKeysMarkedForDeletion(keys []string) (bool, error) {
+func deleteKeysMarkedForDeletion(ctx context.Context, keys []string) (bool, error) {
 	// Start session
-	ctx, committer, err := db.TxContext(db.DefaultContext)
+	ctx, committer, err := db.TxContext(ctx)
 	if err != nil {
 		return false, err
 	}
@@ -349,7 +349,7 @@ func deleteKeysMarkedForDeletion(keys []string) (bool, error) {
 }
 
 // AddPublicKeysBySource add a users public keys. Returns true if there are changes.
-func AddPublicKeysBySource(usr *user_model.User, s *auth.Source, sshPublicKeys []string) bool {
+func AddPublicKeysBySource(ctx context.Context, usr *user_model.User, s *auth.Source, sshPublicKeys []string) bool {
 	var sshKeysNeedUpdate bool
 	for _, sshKey := range sshPublicKeys {
 		var err error
@@ -368,7 +368,7 @@ func AddPublicKeysBySource(usr *user_model.User, s *auth.Source, sshPublicKeys [
 			marshalled = marshalled[:len(marshalled)-1]
 			sshKeyName := fmt.Sprintf("%s-%s", s.Name, ssh.FingerprintSHA256(out))
 
-			if _, err := AddPublicKey(usr.ID, sshKeyName, marshalled, s.ID); err != nil {
+			if _, err := AddPublicKey(ctx, usr.ID, sshKeyName, marshalled, s.ID); err != nil {
 				if IsErrKeyAlreadyExist(err) {
 					log.Trace("AddPublicKeysBySource[%s]: Public SSH Key %s already exists for user", sshKeyName, usr.Name)
 				} else {
@@ -387,14 +387,14 @@ func AddPublicKeysBySource(usr *user_model.User, s *auth.Source, sshPublicKeys [
 }
 
 // SynchronizePublicKeys updates a users public keys. Returns true if there are changes.
-func SynchronizePublicKeys(usr *user_model.User, s *auth.Source, sshPublicKeys []string) bool {
+func SynchronizePublicKeys(ctx context.Context, usr *user_model.User, s *auth.Source, sshPublicKeys []string) bool {
 	var sshKeysNeedUpdate bool
 
 	log.Trace("synchronizePublicKeys[%s]: Handling Public SSH Key synchronization for user %s", s.Name, usr.Name)
 
 	// Get Public Keys from DB with current LDAP source
 	var giteaKeys []string
-	keys, err := ListPublicKeysBySource(usr.ID, s.ID)
+	keys, err := ListPublicKeysBySource(ctx, usr.ID, s.ID)
 	if err != nil {
 		log.Error("synchronizePublicKeys[%s]: Error listing Public SSH Keys for user %s: %v", s.Name, usr.Name, err)
 	}
@@ -429,7 +429,7 @@ func SynchronizePublicKeys(usr *user_model.User, s *auth.Source, sshPublicKeys [
 			newKeys = append(newKeys, key)
 		}
 	}
-	if AddPublicKeysBySource(usr, s, newKeys) {
+	if AddPublicKeysBySource(ctx, usr, s, newKeys) {
 		sshKeysNeedUpdate = true
 	}
 
@@ -443,7 +443,7 @@ func SynchronizePublicKeys(usr *user_model.User, s *auth.Source, sshPublicKeys [
 	}
 
 	// Delete keys from DB that no longer exist in the source
-	needUpd, err := deleteKeysMarkedForDeletion(giteaKeysToDelete)
+	needUpd, err := deleteKeysMarkedForDeletion(ctx, giteaKeysToDelete)
 	if err != nil {
 		log.Error("synchronizePublicKeys[%s]: Error deleting Public Keys marked for deletion for user %s: %v", s.Name, usr.Name, err)
 	}
diff --git a/models/asymkey/ssh_key_commit_verification.go b/models/asymkey/ssh_key_commit_verification.go
index 80931c9af4..a61f0663b1 100644
--- a/models/asymkey/ssh_key_commit_verification.go
+++ b/models/asymkey/ssh_key_commit_verification.go
@@ -21,7 +21,7 @@ import (
 func ParseCommitWithSSHSignature(ctx context.Context, c *git.Commit, committer *user_model.User) *CommitVerification {
 	// Now try to associate the signature with the committer, if present
 	if committer.ID != 0 {
-		keys, err := ListPublicKeys(committer.ID, db.ListOptions{})
+		keys, err := ListPublicKeys(ctx, committer.ID, db.ListOptions{})
 		if err != nil { // Skipping failed to get ssh keys of user
 			log.Error("ListPublicKeys: %v", err)
 			return &CommitVerification{
diff --git a/models/asymkey/ssh_key_deploy.go b/models/asymkey/ssh_key_deploy.go
index cc84392117..25d95291fa 100644
--- a/models/asymkey/ssh_key_deploy.go
+++ b/models/asymkey/ssh_key_deploy.go
@@ -48,8 +48,8 @@ func (key *DeployKey) AfterLoad() {
 }
 
 // GetContent gets associated public key content.
-func (key *DeployKey) GetContent() error {
-	pkey, err := GetPublicKeyByID(key.KeyID)
+func (key *DeployKey) GetContent(ctx context.Context) error {
+	pkey, err := GetPublicKeyByID(ctx, key.KeyID)
 	if err != nil {
 		return err
 	}
diff --git a/models/auth/source.go b/models/auth/source.go
index 0a904b7772..0f57d1702a 100644
--- a/models/auth/source.go
+++ b/models/auth/source.go
@@ -5,6 +5,7 @@
 package auth
 
 import (
+	"context"
 	"fmt"
 	"reflect"
 
@@ -199,8 +200,8 @@ func (source *Source) SkipVerify() bool {
 
 // CreateSource inserts a AuthSource in the DB if not already
 // existing with the given name.
-func CreateSource(source *Source) error {
-	has, err := db.GetEngine(db.DefaultContext).Where("name=?", source.Name).Exist(new(Source))
+func CreateSource(ctx context.Context, source *Source) error {
+	has, err := db.GetEngine(ctx).Where("name=?", source.Name).Exist(new(Source))
 	if err != nil {
 		return err
 	} else if has {
@@ -211,7 +212,7 @@ func CreateSource(source *Source) error {
 		source.IsSyncEnabled = false
 	}
 
-	_, err = db.GetEngine(db.DefaultContext).Insert(source)
+	_, err = db.GetEngine(ctx).Insert(source)
 	if err != nil {
 		return err
 	}
@@ -232,7 +233,7 @@ func CreateSource(source *Source) error {
 	err = registerableSource.RegisterSource()
 	if err != nil {
 		// remove the AuthSource in case of errors while registering configuration
-		if _, err := db.GetEngine(db.DefaultContext).Delete(source); err != nil {
+		if _, err := db.GetEngine(ctx).Delete(source); err != nil {
 			log.Error("CreateSource: Error while wrapOpenIDConnectInitializeError: %v", err)
 		}
 	}
@@ -240,33 +241,33 @@ func CreateSource(source *Source) error {
 }
 
 // Sources returns a slice of all login sources found in DB.
-func Sources() ([]*Source, error) {
+func Sources(ctx context.Context) ([]*Source, error) {
 	auths := make([]*Source, 0, 6)
-	return auths, db.GetEngine(db.DefaultContext).Find(&auths)
+	return auths, db.GetEngine(ctx).Find(&auths)
 }
 
 // SourcesByType returns all sources of the specified type
-func SourcesByType(loginType Type) ([]*Source, error) {
+func SourcesByType(ctx context.Context, loginType Type) ([]*Source, error) {
 	sources := make([]*Source, 0, 1)
-	if err := db.GetEngine(db.DefaultContext).Where("type = ?", loginType).Find(&sources); err != nil {
+	if err := db.GetEngine(ctx).Where("type = ?", loginType).Find(&sources); err != nil {
 		return nil, err
 	}
 	return sources, nil
 }
 
 // AllActiveSources returns all active sources
-func AllActiveSources() ([]*Source, error) {
+func AllActiveSources(ctx context.Context) ([]*Source, error) {
 	sources := make([]*Source, 0, 5)
-	if err := db.GetEngine(db.DefaultContext).Where("is_active = ?", true).Find(&sources); err != nil {
+	if err := db.GetEngine(ctx).Where("is_active = ?", true).Find(&sources); err != nil {
 		return nil, err
 	}
 	return sources, nil
 }
 
 // ActiveSources returns all active sources of the specified type
-func ActiveSources(tp Type) ([]*Source, error) {
+func ActiveSources(ctx context.Context, tp Type) ([]*Source, error) {
 	sources := make([]*Source, 0, 1)
-	if err := db.GetEngine(db.DefaultContext).Where("is_active = ? and type = ?", true, tp).Find(&sources); err != nil {
+	if err := db.GetEngine(ctx).Where("is_active = ? and type = ?", true, tp).Find(&sources); err != nil {
 		return nil, err
 	}
 	return sources, nil
@@ -274,11 +275,11 @@ func ActiveSources(tp Type) ([]*Source, error) {
 
 // IsSSPIEnabled returns true if there is at least one activated login
 // source of type LoginSSPI
-func IsSSPIEnabled() bool {
+func IsSSPIEnabled(ctx context.Context) bool {
 	if !db.HasEngine {
 		return false
 	}
-	sources, err := ActiveSources(SSPI)
+	sources, err := ActiveSources(ctx, SSPI)
 	if err != nil {
 		log.Error("ActiveSources: %v", err)
 		return false
@@ -287,7 +288,7 @@ func IsSSPIEnabled() bool {
 }
 
 // GetSourceByID returns login source by given ID.
-func GetSourceByID(id int64) (*Source, error) {
+func GetSourceByID(ctx context.Context, id int64) (*Source, error) {
 	source := new(Source)
 	if id == 0 {
 		source.Cfg = registeredConfigs[NoType]()
@@ -297,7 +298,7 @@ func GetSourceByID(id int64) (*Source, error) {
 		return source, nil
 	}
 
-	has, err := db.GetEngine(db.DefaultContext).ID(id).Get(source)
+	has, err := db.GetEngine(ctx).ID(id).Get(source)
 	if err != nil {
 		return nil, err
 	} else if !has {
@@ -307,24 +308,24 @@ func GetSourceByID(id int64) (*Source, error) {
 }
 
 // UpdateSource updates a Source record in DB.
-func UpdateSource(source *Source) error {
+func UpdateSource(ctx context.Context, source *Source) error {
 	var originalSource *Source
 	if source.IsOAuth2() {
 		// keep track of the original values so we can restore in case of errors while registering OAuth2 providers
 		var err error
-		if originalSource, err = GetSourceByID(source.ID); err != nil {
+		if originalSource, err = GetSourceByID(ctx, source.ID); err != nil {
 			return err
 		}
 	}
 
-	has, err := db.GetEngine(db.DefaultContext).Where("name=? AND id!=?", source.Name, source.ID).Exist(new(Source))
+	has, err := db.GetEngine(ctx).Where("name=? AND id!=?", source.Name, source.ID).Exist(new(Source))
 	if err != nil {
 		return err
 	} else if has {
 		return ErrSourceAlreadyExist{source.Name}
 	}
 
-	_, err = db.GetEngine(db.DefaultContext).ID(source.ID).AllCols().Update(source)
+	_, err = db.GetEngine(ctx).ID(source.ID).AllCols().Update(source)
 	if err != nil {
 		return err
 	}
@@ -345,7 +346,7 @@ func UpdateSource(source *Source) error {
 	err = registerableSource.RegisterSource()
 	if err != nil {
 		// restore original values since we cannot update the provider it self
-		if _, err := db.GetEngine(db.DefaultContext).ID(source.ID).AllCols().Update(originalSource); err != nil {
+		if _, err := db.GetEngine(ctx).ID(source.ID).AllCols().Update(originalSource); err != nil {
 			log.Error("UpdateSource: Error while wrapOpenIDConnectInitializeError: %v", err)
 		}
 	}
@@ -353,8 +354,8 @@ func UpdateSource(source *Source) error {
 }
 
 // CountSources returns number of login sources.
-func CountSources() int64 {
-	count, _ := db.GetEngine(db.DefaultContext).Count(new(Source))
+func CountSources(ctx context.Context) int64 {
+	count, _ := db.GetEngine(ctx).Count(new(Source))
 	return count
 }
 
diff --git a/models/auth/source_test.go b/models/auth/source_test.go
index 31216cca8e..36e76d5e28 100644
--- a/models/auth/source_test.go
+++ b/models/auth/source_test.go
@@ -42,7 +42,7 @@ func TestDumpAuthSource(t *testing.T) {
 
 	auth_model.RegisterTypeConfig(auth_model.OAuth2, new(TestSource))
 
-	auth_model.CreateSource(&auth_model.Source{
+	auth_model.CreateSource(db.DefaultContext, &auth_model.Source{
 		Type:     auth_model.OAuth2,
 		Name:     "TestSource",
 		IsActive: false,
diff --git a/models/issues/comment_code.go b/models/issues/comment_code.go
index 49927fbbe2..25e606f092 100644
--- a/models/issues/comment_code.go
+++ b/models/issues/comment_code.go
@@ -111,7 +111,7 @@ func findCodeComments(ctx context.Context, opts FindCommentsOptions, issue *Issu
 		if comment.RenderedContent, err = markdown.RenderString(&markup.RenderContext{
 			Ctx:       ctx,
 			URLPrefix: issue.Repo.Link(),
-			Metas:     issue.Repo.ComposeMetas(),
+			Metas:     issue.Repo.ComposeMetas(ctx),
 		}, comment.Content); err != nil {
 			return nil, err
 		}
diff --git a/models/issues/dependency.go b/models/issues/dependency.go
index 4dc5a4aec7..146dd1887d 100644
--- a/models/issues/dependency.go
+++ b/models/issues/dependency.go
@@ -127,8 +127,8 @@ const (
 )
 
 // CreateIssueDependency creates a new dependency for an issue
-func CreateIssueDependency(user *user_model.User, issue, dep *Issue) error {
-	ctx, committer, err := db.TxContext(db.DefaultContext)
+func CreateIssueDependency(ctx context.Context, user *user_model.User, issue, dep *Issue) error {
+	ctx, committer, err := db.TxContext(ctx)
 	if err != nil {
 		return err
 	}
@@ -168,8 +168,8 @@ func CreateIssueDependency(user *user_model.User, issue, dep *Issue) error {
 }
 
 // RemoveIssueDependency removes a dependency from an issue
-func RemoveIssueDependency(user *user_model.User, issue, dep *Issue, depType DependencyType) (err error) {
-	ctx, committer, err := db.TxContext(db.DefaultContext)
+func RemoveIssueDependency(ctx context.Context, user *user_model.User, issue, dep *Issue, depType DependencyType) (err error) {
+	ctx, committer, err := db.TxContext(ctx)
 	if err != nil {
 		return err
 	}
diff --git a/models/issues/dependency_test.go b/models/issues/dependency_test.go
index cdc8e3182d..6eed483cc9 100644
--- a/models/issues/dependency_test.go
+++ b/models/issues/dependency_test.go
@@ -28,16 +28,16 @@ func TestCreateIssueDependency(t *testing.T) {
 	assert.NoError(t, err)
 
 	// Create a dependency and check if it was successful
-	err = issues_model.CreateIssueDependency(user1, issue1, issue2)
+	err = issues_model.CreateIssueDependency(db.DefaultContext, user1, issue1, issue2)
 	assert.NoError(t, err)
 
 	// Do it again to see if it will check if the dependency already exists
-	err = issues_model.CreateIssueDependency(user1, issue1, issue2)
+	err = issues_model.CreateIssueDependency(db.DefaultContext, user1, issue1, issue2)
 	assert.Error(t, err)
 	assert.True(t, issues_model.IsErrDependencyExists(err))
 
 	// Check for circular dependencies
-	err = issues_model.CreateIssueDependency(user1, issue2, issue1)
+	err = issues_model.CreateIssueDependency(db.DefaultContext, user1, issue2, issue1)
 	assert.Error(t, err)
 	assert.True(t, issues_model.IsErrCircularDependency(err))
 
@@ -57,6 +57,6 @@ func TestCreateIssueDependency(t *testing.T) {
 	assert.True(t, left)
 
 	// Test removing the dependency
-	err = issues_model.RemoveIssueDependency(user1, issue1, issue2, issues_model.DependencyTypeBlockedBy)
+	err = issues_model.RemoveIssueDependency(db.DefaultContext, user1, issue1, issue2, issues_model.DependencyTypeBlockedBy)
 	assert.NoError(t, err)
 }
diff --git a/models/issues/issue_label.go b/models/issues/issue_label.go
index 0a2ffdb35f..733f1043b0 100644
--- a/models/issues/issue_label.go
+++ b/models/issues/issue_label.go
@@ -83,12 +83,12 @@ func RemoveDuplicateExclusiveIssueLabels(ctx context.Context, issue *Issue, labe
 }
 
 // NewIssueLabel creates a new issue-label relation.
-func NewIssueLabel(issue *Issue, label *Label, doer *user_model.User) (err error) {
-	if HasIssueLabel(db.DefaultContext, issue.ID, label.ID) {
+func NewIssueLabel(ctx context.Context, issue *Issue, label *Label, doer *user_model.User) (err error) {
+	if HasIssueLabel(ctx, issue.ID, label.ID) {
 		return nil
 	}
 
-	ctx, committer, err := db.TxContext(db.DefaultContext)
+	ctx, committer, err := db.TxContext(ctx)
 	if err != nil {
 		return err
 	}
@@ -149,8 +149,8 @@ func newIssueLabels(ctx context.Context, issue *Issue, labels []*Label, doer *us
 }
 
 // NewIssueLabels creates a list of issue-label relations.
-func NewIssueLabels(issue *Issue, labels []*Label, doer *user_model.User) (err error) {
-	ctx, committer, err := db.TxContext(db.DefaultContext)
+func NewIssueLabels(ctx context.Context, issue *Issue, labels []*Label, doer *user_model.User) (err error) {
+	ctx, committer, err := db.TxContext(ctx)
 	if err != nil {
 		return err
 	}
@@ -359,8 +359,8 @@ func clearIssueLabels(ctx context.Context, issue *Issue, doer *user_model.User)
 
 // ClearIssueLabels removes all issue labels as the given user.
 // Triggers appropriate WebHooks, if any.
-func ClearIssueLabels(issue *Issue, doer *user_model.User) (err error) {
-	ctx, committer, err := db.TxContext(db.DefaultContext)
+func ClearIssueLabels(ctx context.Context, issue *Issue, doer *user_model.User) (err error) {
+	ctx, committer, err := db.TxContext(ctx)
 	if err != nil {
 		return err
 	}
@@ -432,8 +432,8 @@ func RemoveDuplicateExclusiveLabels(labels []*Label) []*Label {
 
 // ReplaceIssueLabels removes all current labels and add new labels to the issue.
 // Triggers appropriate WebHooks, if any.
-func ReplaceIssueLabels(issue *Issue, labels []*Label, doer *user_model.User) (err error) {
-	ctx, committer, err := db.TxContext(db.DefaultContext)
+func ReplaceIssueLabels(ctx context.Context, issue *Issue, labels []*Label, doer *user_model.User) (err error) {
+	ctx, committer, err := db.TxContext(ctx)
 	if err != nil {
 		return err
 	}
diff --git a/models/issues/issue_label_test.go b/models/issues/issue_label_test.go
index 0d991b7c4f..0470b99e24 100644
--- a/models/issues/issue_label_test.go
+++ b/models/issues/issue_label_test.go
@@ -6,6 +6,7 @@ package issues_test
 import (
 	"testing"
 
+	"code.gitea.io/gitea/models/db"
 	issues_model "code.gitea.io/gitea/models/issues"
 	"code.gitea.io/gitea/models/unittest"
 	user_model "code.gitea.io/gitea/models/user"
@@ -21,7 +22,7 @@ func TestNewIssueLabelsScope(t *testing.T) {
 	label2 := unittest.AssertExistsAndLoadBean(t, &issues_model.Label{ID: 8})
 	doer := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2})
 
-	assert.NoError(t, issues_model.NewIssueLabels(issue, []*issues_model.Label{label1, label2}, doer))
+	assert.NoError(t, issues_model.NewIssueLabels(db.DefaultContext, issue, []*issues_model.Label{label1, label2}, doer))
 
 	assert.Len(t, issue.Labels, 1)
 	assert.Equal(t, label2.ID, issue.Labels[0].ID)
diff --git a/models/issues/issue_lock.go b/models/issues/issue_lock.go
index 19cd6d3167..b21629b529 100644
--- a/models/issues/issue_lock.go
+++ b/models/issues/issue_lock.go
@@ -4,6 +4,8 @@
 package issues
 
 import (
+	"context"
+
 	"code.gitea.io/gitea/models/db"
 	user_model "code.gitea.io/gitea/models/user"
 )
@@ -17,16 +19,16 @@ type IssueLockOptions struct {
 
 // LockIssue locks an issue. This would limit commenting abilities to
 // users with write access to the repo
-func LockIssue(opts *IssueLockOptions) error {
-	return updateIssueLock(opts, true)
+func LockIssue(ctx context.Context, opts *IssueLockOptions) error {
+	return updateIssueLock(ctx, opts, true)
 }
 
 // UnlockIssue unlocks a previously locked issue.
-func UnlockIssue(opts *IssueLockOptions) error {
-	return updateIssueLock(opts, false)
+func UnlockIssue(ctx context.Context, opts *IssueLockOptions) error {
+	return updateIssueLock(ctx, opts, false)
 }
 
-func updateIssueLock(opts *IssueLockOptions, lock bool) error {
+func updateIssueLock(ctx context.Context, opts *IssueLockOptions, lock bool) error {
 	if opts.Issue.IsLocked == lock {
 		return nil
 	}
@@ -39,7 +41,7 @@ func updateIssueLock(opts *IssueLockOptions, lock bool) error {
 		commentType = CommentTypeUnlock
 	}
 
-	ctx, committer, err := db.TxContext(db.DefaultContext)
+	ctx, committer, err := db.TxContext(ctx)
 	if err != nil {
 		return err
 	}
diff --git a/models/issues/issue_project.go b/models/issues/issue_project.go
index ed249527bf..7906c3eace 100644
--- a/models/issues/issue_project.go
+++ b/models/issues/issue_project.go
@@ -38,11 +38,7 @@ func (issue *Issue) projectID(ctx context.Context) int64 {
 }
 
 // ProjectBoardID return project board id if issue was assigned to one
-func (issue *Issue) ProjectBoardID() int64 {
-	return issue.projectBoardID(db.DefaultContext)
-}
-
-func (issue *Issue) projectBoardID(ctx context.Context) int64 {
+func (issue *Issue) ProjectBoardID(ctx context.Context) int64 {
 	var ip project_model.ProjectIssue
 	has, err := db.GetEngine(ctx).Where("issue_id=?", issue.ID).Get(&ip)
 	if err != nil || !has {
@@ -100,8 +96,8 @@ func LoadIssuesFromBoardList(ctx context.Context, bs project_model.BoardList) (m
 }
 
 // ChangeProjectAssign changes the project associated with an issue
-func ChangeProjectAssign(issue *Issue, doer *user_model.User, newProjectID int64) error {
-	ctx, committer, err := db.TxContext(db.DefaultContext)
+func ChangeProjectAssign(ctx context.Context, issue *Issue, doer *user_model.User, newProjectID int64) error {
+	ctx, committer, err := db.TxContext(ctx)
 	if err != nil {
 		return err
 	}
@@ -156,8 +152,8 @@ func addUpdateIssueProject(ctx context.Context, issue *Issue, doer *user_model.U
 }
 
 // MoveIssueAcrossProjectBoards move a card from one board to another
-func MoveIssueAcrossProjectBoards(issue *Issue, board *project_model.Board) error {
-	ctx, committer, err := db.TxContext(db.DefaultContext)
+func MoveIssueAcrossProjectBoards(ctx context.Context, issue *Issue, board *project_model.Board) error {
+	ctx, committer, err := db.TxContext(ctx)
 	if err != nil {
 		return err
 	}
diff --git a/models/issues/issue_search.go b/models/issues/issue_search.go
index 5c05ead687..3e878ff1e7 100644
--- a/models/issues/issue_search.go
+++ b/models/issues/issue_search.go
@@ -444,9 +444,9 @@ func applySubscribedCondition(sess *xorm.Session, subscriberID int64) *xorm.Sess
 }
 
 // GetRepoIDsForIssuesOptions find all repo ids for the given options
-func GetRepoIDsForIssuesOptions(opts *IssuesOptions, user *user_model.User) ([]int64, error) {
+func GetRepoIDsForIssuesOptions(ctx context.Context, opts *IssuesOptions, user *user_model.User) ([]int64, error) {
 	repoIDs := make([]int64, 0, 5)
-	e := db.GetEngine(db.DefaultContext)
+	e := db.GetEngine(ctx)
 
 	sess := e.Join("INNER", "repository", "`issue`.repo_id = `repository`.id")
 
diff --git a/models/issues/issue_test.go b/models/issues/issue_test.go
index 4e98442c11..f554820964 100644
--- a/models/issues/issue_test.go
+++ b/models/issues/issue_test.go
@@ -34,7 +34,7 @@ func TestIssue_ReplaceLabels(t *testing.T) {
 		for i, labelID := range labelIDs {
 			labels[i] = unittest.AssertExistsAndLoadBean(t, &issues_model.Label{ID: labelID, RepoID: repo.ID})
 		}
-		assert.NoError(t, issues_model.ReplaceIssueLabels(issue, labels, doer))
+		assert.NoError(t, issues_model.ReplaceIssueLabels(db.DefaultContext, issue, labels, doer))
 		unittest.AssertCount(t, &issues_model.IssueLabel{IssueID: issueID}, len(expectedLabelIDs))
 		for _, labelID := range expectedLabelIDs {
 			unittest.AssertExistsAndLoadBean(t, &issues_model.IssueLabel{IssueID: issueID, LabelID: labelID})
@@ -122,7 +122,7 @@ func TestIssue_ClearLabels(t *testing.T) {
 		assert.NoError(t, unittest.PrepareTestDatabase())
 		issue := unittest.AssertExistsAndLoadBean(t, &issues_model.Issue{ID: test.issueID})
 		doer := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: test.doerID})
-		assert.NoError(t, issues_model.ClearIssueLabels(issue, doer))
+		assert.NoError(t, issues_model.ClearIssueLabels(db.DefaultContext, issue, doer))
 		unittest.AssertNotExistsBean(t, &issues_model.IssueLabel{IssueID: test.issueID})
 	}
 }
@@ -230,7 +230,7 @@ func TestGetRepoIDsForIssuesOptions(t *testing.T) {
 			[]int64{1, 2},
 		},
 	} {
-		repoIDs, err := issues_model.GetRepoIDsForIssuesOptions(&test.Opts, user)
+		repoIDs, err := issues_model.GetRepoIDsForIssuesOptions(db.DefaultContext, &test.Opts, user)
 		assert.NoError(t, err)
 		if assert.Len(t, repoIDs, len(test.ExpectedRepoIDs)) {
 			for i, repoID := range repoIDs {
diff --git a/models/issues/label_test.go b/models/issues/label_test.go
index 9f44cd3e03..3a8db6ceec 100644
--- a/models/issues/label_test.go
+++ b/models/issues/label_test.go
@@ -307,7 +307,7 @@ func TestNewIssueLabel(t *testing.T) {
 
 	// add new IssueLabel
 	prevNumIssues := label.NumIssues
-	assert.NoError(t, issues_model.NewIssueLabel(issue, label, doer))
+	assert.NoError(t, issues_model.NewIssueLabel(db.DefaultContext, issue, label, doer))
 	unittest.AssertExistsAndLoadBean(t, &issues_model.IssueLabel{IssueID: issue.ID, LabelID: label.ID})
 	unittest.AssertExistsAndLoadBean(t, &issues_model.Comment{
 		Type:     issues_model.CommentTypeLabel,
@@ -320,7 +320,7 @@ func TestNewIssueLabel(t *testing.T) {
 	assert.EqualValues(t, prevNumIssues+1, label.NumIssues)
 
 	// re-add existing IssueLabel
-	assert.NoError(t, issues_model.NewIssueLabel(issue, label, doer))
+	assert.NoError(t, issues_model.NewIssueLabel(db.DefaultContext, issue, label, doer))
 	unittest.CheckConsistencyFor(t, &issues_model.Issue{}, &issues_model.Label{})
 }
 
@@ -334,19 +334,19 @@ func TestNewIssueExclusiveLabel(t *testing.T) {
 	exclusiveLabelB := unittest.AssertExistsAndLoadBean(t, &issues_model.Label{ID: 8})
 
 	// coexisting regular and exclusive label
-	assert.NoError(t, issues_model.NewIssueLabel(issue, otherLabel, doer))
-	assert.NoError(t, issues_model.NewIssueLabel(issue, exclusiveLabelA, doer))
+	assert.NoError(t, issues_model.NewIssueLabel(db.DefaultContext, issue, otherLabel, doer))
+	assert.NoError(t, issues_model.NewIssueLabel(db.DefaultContext, issue, exclusiveLabelA, doer))
 	unittest.AssertExistsAndLoadBean(t, &issues_model.IssueLabel{IssueID: issue.ID, LabelID: otherLabel.ID})
 	unittest.AssertExistsAndLoadBean(t, &issues_model.IssueLabel{IssueID: issue.ID, LabelID: exclusiveLabelA.ID})
 
 	// exclusive label replaces existing one
-	assert.NoError(t, issues_model.NewIssueLabel(issue, exclusiveLabelB, doer))
+	assert.NoError(t, issues_model.NewIssueLabel(db.DefaultContext, issue, exclusiveLabelB, doer))
 	unittest.AssertExistsAndLoadBean(t, &issues_model.IssueLabel{IssueID: issue.ID, LabelID: otherLabel.ID})
 	unittest.AssertExistsAndLoadBean(t, &issues_model.IssueLabel{IssueID: issue.ID, LabelID: exclusiveLabelB.ID})
 	unittest.AssertNotExistsBean(t, &issues_model.IssueLabel{IssueID: issue.ID, LabelID: exclusiveLabelA.ID})
 
 	// exclusive label replaces existing one again
-	assert.NoError(t, issues_model.NewIssueLabel(issue, exclusiveLabelA, doer))
+	assert.NoError(t, issues_model.NewIssueLabel(db.DefaultContext, issue, exclusiveLabelA, doer))
 	unittest.AssertExistsAndLoadBean(t, &issues_model.IssueLabel{IssueID: issue.ID, LabelID: otherLabel.ID})
 	unittest.AssertExistsAndLoadBean(t, &issues_model.IssueLabel{IssueID: issue.ID, LabelID: exclusiveLabelA.ID})
 	unittest.AssertNotExistsBean(t, &issues_model.IssueLabel{IssueID: issue.ID, LabelID: exclusiveLabelB.ID})
@@ -359,7 +359,7 @@ func TestNewIssueLabels(t *testing.T) {
 	issue := unittest.AssertExistsAndLoadBean(t, &issues_model.Issue{ID: 5})
 	doer := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2})
 
-	assert.NoError(t, issues_model.NewIssueLabels(issue, []*issues_model.Label{label1, label2}, doer))
+	assert.NoError(t, issues_model.NewIssueLabels(db.DefaultContext, issue, []*issues_model.Label{label1, label2}, doer))
 	unittest.AssertExistsAndLoadBean(t, &issues_model.IssueLabel{IssueID: issue.ID, LabelID: label1.ID})
 	unittest.AssertExistsAndLoadBean(t, &issues_model.Comment{
 		Type:     issues_model.CommentTypeLabel,
@@ -377,7 +377,7 @@ func TestNewIssueLabels(t *testing.T) {
 	assert.EqualValues(t, 1, label2.NumClosedIssues)
 
 	// corner case: test empty slice
-	assert.NoError(t, issues_model.NewIssueLabels(issue, []*issues_model.Label{}, doer))
+	assert.NoError(t, issues_model.NewIssueLabels(db.DefaultContext, issue, []*issues_model.Label{}, doer))
 
 	unittest.CheckConsistencyFor(t, &issues_model.Issue{}, &issues_model.Label{})
 }
diff --git a/models/issues/milestone_list.go b/models/issues/milestone_list.go
index d5c9b1358c..d55c18a995 100644
--- a/models/issues/milestone_list.go
+++ b/models/issues/milestone_list.go
@@ -58,8 +58,8 @@ func (opts GetMilestonesOption) toCond() builder.Cond {
 }
 
 // GetMilestones returns milestones filtered by GetMilestonesOption's
-func GetMilestones(opts GetMilestonesOption) (MilestoneList, int64, error) {
-	sess := db.GetEngine(db.DefaultContext).Where(opts.toCond())
+func GetMilestones(ctx context.Context, opts GetMilestonesOption) (MilestoneList, int64, error) {
+	sess := db.GetEngine(ctx).Where(opts.toCond())
 
 	if opts.Page != 0 {
 		sess = db.SetSessionPagination(sess, &opts)
diff --git a/models/issues/milestone_test.go b/models/issues/milestone_test.go
index 403eeaadb3..ecfccf6ddb 100644
--- a/models/issues/milestone_test.go
+++ b/models/issues/milestone_test.go
@@ -40,7 +40,7 @@ func TestGetMilestonesByRepoID(t *testing.T) {
 	assert.NoError(t, unittest.PrepareTestDatabase())
 	test := func(repoID int64, state api.StateType) {
 		repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: repoID})
-		milestones, _, err := issues_model.GetMilestones(issues_model.GetMilestonesOption{
+		milestones, _, err := issues_model.GetMilestones(db.DefaultContext, issues_model.GetMilestonesOption{
 			RepoID: repo.ID,
 			State:  state,
 		})
@@ -77,7 +77,7 @@ func TestGetMilestonesByRepoID(t *testing.T) {
 	test(3, api.StateClosed)
 	test(3, api.StateAll)
 
-	milestones, _, err := issues_model.GetMilestones(issues_model.GetMilestonesOption{
+	milestones, _, err := issues_model.GetMilestones(db.DefaultContext, issues_model.GetMilestonesOption{
 		RepoID: unittest.NonexistentID,
 		State:  api.StateOpen,
 	})
@@ -90,7 +90,7 @@ func TestGetMilestones(t *testing.T) {
 	repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1})
 	test := func(sortType string, sortCond func(*issues_model.Milestone) int) {
 		for _, page := range []int{0, 1} {
-			milestones, _, err := issues_model.GetMilestones(issues_model.GetMilestonesOption{
+			milestones, _, err := issues_model.GetMilestones(db.DefaultContext, issues_model.GetMilestonesOption{
 				ListOptions: db.ListOptions{
 					Page:     page,
 					PageSize: setting.UI.IssuePagingNum,
@@ -107,7 +107,7 @@ func TestGetMilestones(t *testing.T) {
 			}
 			assert.True(t, sort.IntsAreSorted(values))
 
-			milestones, _, err = issues_model.GetMilestones(issues_model.GetMilestonesOption{
+			milestones, _, err = issues_model.GetMilestones(db.DefaultContext, issues_model.GetMilestonesOption{
 				ListOptions: db.ListOptions{
 					Page:     page,
 					PageSize: setting.UI.IssuePagingNum,
diff --git a/models/issues/pull.go b/models/issues/pull.go
index 9adcaee1a1..971ce049c3 100644
--- a/models/issues/pull.go
+++ b/models/issues/pull.go
@@ -378,9 +378,9 @@ func (pr *PullRequest) GetApprovalCounts(ctx context.Context) ([]*ReviewCount, e
 }
 
 // GetApprovers returns the approvers of the pull request
-func (pr *PullRequest) GetApprovers() string {
+func (pr *PullRequest) GetApprovers(ctx context.Context) string {
 	stringBuilder := strings.Builder{}
-	if err := pr.getReviewedByLines(&stringBuilder); err != nil {
+	if err := pr.getReviewedByLines(ctx, &stringBuilder); err != nil {
 		log.Error("Unable to getReviewedByLines: Error: %v", err)
 		return ""
 	}
@@ -388,14 +388,14 @@ func (pr *PullRequest) GetApprovers() string {
 	return stringBuilder.String()
 }
 
-func (pr *PullRequest) getReviewedByLines(writer io.Writer) error {
+func (pr *PullRequest) getReviewedByLines(ctx context.Context, writer io.Writer) error {
 	maxReviewers := setting.Repository.PullRequest.DefaultMergeMessageMaxApprovers
 
 	if maxReviewers == 0 {
 		return nil
 	}
 
-	ctx, committer, err := db.TxContext(db.DefaultContext)
+	ctx, committer, err := db.TxContext(ctx)
 	if err != nil {
 		return err
 	}
@@ -594,9 +594,9 @@ func GetUnmergedPullRequest(ctx context.Context, headRepoID, baseRepoID int64, h
 
 // GetLatestPullRequestByHeadInfo returns the latest pull request (regardless of its status)
 // by given head information (repo and branch).
-func GetLatestPullRequestByHeadInfo(repoID int64, branch string) (*PullRequest, error) {
+func GetLatestPullRequestByHeadInfo(ctx context.Context, repoID int64, branch string) (*PullRequest, error) {
 	pr := new(PullRequest)
-	has, err := db.GetEngine(db.DefaultContext).
+	has, err := db.GetEngine(ctx).
 		Where("head_repo_id = ? AND head_branch = ? AND flow = ?", repoID, branch, PullRequestFlowGithub).
 		OrderBy("id DESC").
 		Get(pr)
@@ -646,9 +646,9 @@ func GetPullRequestByID(ctx context.Context, id int64) (*PullRequest, error) {
 }
 
 // GetPullRequestByIssueIDWithNoAttributes returns pull request with no attributes loaded by given issue ID.
-func GetPullRequestByIssueIDWithNoAttributes(issueID int64) (*PullRequest, error) {
+func GetPullRequestByIssueIDWithNoAttributes(ctx context.Context, issueID int64) (*PullRequest, error) {
 	var pr PullRequest
-	has, err := db.GetEngine(db.DefaultContext).Where("issue_id = ?", issueID).Get(&pr)
+	has, err := db.GetEngine(ctx).Where("issue_id = ?", issueID).Get(&pr)
 	if err != nil {
 		return nil, err
 	}
@@ -687,14 +687,14 @@ func GetAllUnmergedAgitPullRequestByPoster(ctx context.Context, uid int64) ([]*P
 }
 
 // Update updates all fields of pull request.
-func (pr *PullRequest) Update() error {
-	_, err := db.GetEngine(db.DefaultContext).ID(pr.ID).AllCols().Update(pr)
+func (pr *PullRequest) Update(ctx context.Context) error {
+	_, err := db.GetEngine(ctx).ID(pr.ID).AllCols().Update(pr)
 	return err
 }
 
 // UpdateCols updates specific fields of pull request.
-func (pr *PullRequest) UpdateCols(cols ...string) error {
-	_, err := db.GetEngine(db.DefaultContext).ID(pr.ID).Cols(cols...).Update(pr)
+func (pr *PullRequest) UpdateCols(ctx context.Context, cols ...string) error {
+	_, err := db.GetEngine(ctx).ID(pr.ID).Cols(cols...).Update(pr)
 	return err
 }
 
@@ -706,8 +706,8 @@ func (pr *PullRequest) UpdateColsIfNotMerged(ctx context.Context, cols ...string
 
 // IsWorkInProgress determine if the Pull Request is a Work In Progress by its title
 // Issue must be set before this method can be called.
-func (pr *PullRequest) IsWorkInProgress() bool {
-	if err := pr.LoadIssue(db.DefaultContext); err != nil {
+func (pr *PullRequest) IsWorkInProgress(ctx context.Context) bool {
+	if err := pr.LoadIssue(ctx); err != nil {
 		log.Error("LoadIssue: %v", err)
 		return false
 	}
@@ -774,8 +774,8 @@ func GetPullRequestsByHeadBranch(ctx context.Context, headBranch string, headRep
 }
 
 // GetBaseBranchLink returns the relative URL of the base branch
-func (pr *PullRequest) GetBaseBranchLink() string {
-	if err := pr.LoadBaseRepo(db.DefaultContext); err != nil {
+func (pr *PullRequest) GetBaseBranchLink(ctx context.Context) string {
+	if err := pr.LoadBaseRepo(ctx); err != nil {
 		log.Error("LoadBaseRepo: %v", err)
 		return ""
 	}
@@ -786,12 +786,12 @@ func (pr *PullRequest) GetBaseBranchLink() string {
 }
 
 // GetHeadBranchLink returns the relative URL of the head branch
-func (pr *PullRequest) GetHeadBranchLink() string {
+func (pr *PullRequest) GetHeadBranchLink(ctx context.Context) string {
 	if pr.Flow == PullRequestFlowAGit {
 		return ""
 	}
 
-	if err := pr.LoadHeadRepo(db.DefaultContext); err != nil {
+	if err := pr.LoadHeadRepo(ctx); err != nil {
 		log.Error("LoadHeadRepo: %v", err)
 		return ""
 	}
@@ -810,14 +810,14 @@ func UpdateAllowEdits(ctx context.Context, pr *PullRequest) error {
 }
 
 // Mergeable returns if the pullrequest is mergeable.
-func (pr *PullRequest) Mergeable() bool {
+func (pr *PullRequest) Mergeable(ctx context.Context) bool {
 	// If a pull request isn't mergable if it's:
 	// - Being conflict checked.
 	// - Has a conflict.
 	// - Received a error while being conflict checked.
 	// - Is a work-in-progress pull request.
 	return pr.Status != PullRequestStatusChecking && pr.Status != PullRequestStatusConflict &&
-		pr.Status != PullRequestStatusError && !pr.IsWorkInProgress()
+		pr.Status != PullRequestStatusError && !pr.IsWorkInProgress(ctx)
 }
 
 // HasEnoughApprovals returns true if pr has enough granted approvals.
@@ -890,7 +890,7 @@ func MergeBlockedByOutdatedBranch(protectBranch *git_model.ProtectedBranch, pr *
 func PullRequestCodeOwnersReview(ctx context.Context, pull *Issue, pr *PullRequest) error {
 	files := []string{"CODEOWNERS", "docs/CODEOWNERS", ".gitea/CODEOWNERS"}
 
-	if pr.IsWorkInProgress() {
+	if pr.IsWorkInProgress(ctx) {
 		return nil
 	}
 
diff --git a/models/issues/pull_test.go b/models/issues/pull_test.go
index 3636263c46..173417136c 100644
--- a/models/issues/pull_test.go
+++ b/models/issues/pull_test.go
@@ -213,7 +213,7 @@ func TestPullRequest_Update(t *testing.T) {
 	pr := unittest.AssertExistsAndLoadBean(t, &issues_model.PullRequest{ID: 1})
 	pr.BaseBranch = "baseBranch"
 	pr.HeadBranch = "headBranch"
-	pr.Update()
+	pr.Update(db.DefaultContext)
 
 	pr = unittest.AssertExistsAndLoadBean(t, &issues_model.PullRequest{ID: pr.ID})
 	assert.Equal(t, "baseBranch", pr.BaseBranch)
@@ -228,7 +228,7 @@ func TestPullRequest_UpdateCols(t *testing.T) {
 		BaseBranch: "baseBranch",
 		HeadBranch: "headBranch",
 	}
-	assert.NoError(t, pr.UpdateCols("head_branch"))
+	assert.NoError(t, pr.UpdateCols(db.DefaultContext, "head_branch"))
 
 	pr = unittest.AssertExistsAndLoadBean(t, &issues_model.PullRequest{ID: 1})
 	assert.Equal(t, "master", pr.BaseBranch)
@@ -260,13 +260,13 @@ func TestPullRequest_IsWorkInProgress(t *testing.T) {
 	pr := unittest.AssertExistsAndLoadBean(t, &issues_model.PullRequest{ID: 2})
 	pr.LoadIssue(db.DefaultContext)
 
-	assert.False(t, pr.IsWorkInProgress())
+	assert.False(t, pr.IsWorkInProgress(db.DefaultContext))
 
 	pr.Issue.Title = "WIP: " + pr.Issue.Title
-	assert.True(t, pr.IsWorkInProgress())
+	assert.True(t, pr.IsWorkInProgress(db.DefaultContext))
 
 	pr.Issue.Title = "[wip]: " + pr.Issue.Title
-	assert.True(t, pr.IsWorkInProgress())
+	assert.True(t, pr.IsWorkInProgress(db.DefaultContext))
 }
 
 func TestPullRequest_GetWorkInProgressPrefixWorkInProgress(t *testing.T) {
@@ -334,7 +334,7 @@ func TestGetApprovers(t *testing.T) {
 	// Official reviews are already deduplicated. Allow unofficial reviews
 	// to assert that there are no duplicated approvers.
 	setting.Repository.PullRequest.DefaultMergeMessageOfficialApproversOnly = false
-	approvers := pr.GetApprovers()
+	approvers := pr.GetApprovers(db.DefaultContext)
 	expected := "Reviewed-by: User Five <user5@example.com>\nReviewed-by: Org Six <org6@example.com>\n"
 	assert.EqualValues(t, expected, approvers)
 }
diff --git a/models/repo.go b/models/repo.go
index 82433ca055..d525264b3b 100644
--- a/models/repo.go
+++ b/models/repo.go
@@ -277,8 +277,8 @@ func UpdateRepoStats(ctx context.Context, id int64) error {
 	return nil
 }
 
-func updateUserStarNumbers(users []user_model.User) error {
-	ctx, committer, err := db.TxContext(db.DefaultContext)
+func updateUserStarNumbers(ctx context.Context, users []user_model.User) error {
+	ctx, committer, err := db.TxContext(ctx)
 	if err != nil {
 		return err
 	}
@@ -294,19 +294,19 @@ func updateUserStarNumbers(users []user_model.User) error {
 }
 
 // DoctorUserStarNum recalculate Stars number for all user
-func DoctorUserStarNum() (err error) {
+func DoctorUserStarNum(ctx context.Context) (err error) {
 	const batchSize = 100
 
 	for start := 0; ; start += batchSize {
 		users := make([]user_model.User, 0, batchSize)
-		if err = db.GetEngine(db.DefaultContext).Limit(batchSize, start).Where("type = ?", 0).Cols("id").Find(&users); err != nil {
+		if err = db.GetEngine(ctx).Limit(batchSize, start).Where("type = ?", 0).Cols("id").Find(&users); err != nil {
 			return err
 		}
 		if len(users) == 0 {
 			break
 		}
 
-		if err = updateUserStarNumbers(users); err != nil {
+		if err = updateUserStarNumbers(ctx, users); err != nil {
 			return err
 		}
 	}
diff --git a/models/repo/avatar.go b/models/repo/avatar.go
index a76a949267..72ee938ada 100644
--- a/models/repo/avatar.go
+++ b/models/repo/avatar.go
@@ -31,8 +31,8 @@ func ExistsWithAvatarAtStoragePath(ctx context.Context, storagePath string) (boo
 }
 
 // RelAvatarLink returns a relative link to the repository's avatar.
-func (repo *Repository) RelAvatarLink() string {
-	return repo.relAvatarLink(db.DefaultContext)
+func (repo *Repository) RelAvatarLink(ctx context.Context) string {
+	return repo.relAvatarLink(ctx)
 }
 
 // generateRandomAvatar generates a random avatar for repository.
diff --git a/models/repo/language_stats.go b/models/repo/language_stats.go
index 2da16814bd..0bc0f1fb40 100644
--- a/models/repo/language_stats.go
+++ b/models/repo/language_stats.go
@@ -108,8 +108,8 @@ func GetLanguageStats(ctx context.Context, repo *Repository) (LanguageStatList,
 }
 
 // GetTopLanguageStats returns the top language statistics for a repository
-func GetTopLanguageStats(repo *Repository, limit int) (LanguageStatList, error) {
-	stats, err := GetLanguageStats(db.DefaultContext, repo)
+func GetTopLanguageStats(ctx context.Context, repo *Repository, limit int) (LanguageStatList, error) {
+	stats, err := GetLanguageStats(ctx, repo)
 	if err != nil {
 		return nil, err
 	}
@@ -140,8 +140,8 @@ func GetTopLanguageStats(repo *Repository, limit int) (LanguageStatList, error)
 }
 
 // UpdateLanguageStats updates the language statistics for repository
-func UpdateLanguageStats(repo *Repository, commitID string, stats map[string]int64) error {
-	ctx, committer, err := db.TxContext(db.DefaultContext)
+func UpdateLanguageStats(ctx context.Context, repo *Repository, commitID string, stats map[string]int64) error {
+	ctx, committer, err := db.TxContext(ctx)
 	if err != nil {
 		return err
 	}
@@ -212,8 +212,8 @@ func UpdateLanguageStats(repo *Repository, commitID string, stats map[string]int
 }
 
 // CopyLanguageStat Copy originalRepo language stat information to destRepo (use for forked repo)
-func CopyLanguageStat(originalRepo, destRepo *Repository) error {
-	ctx, committer, err := db.TxContext(db.DefaultContext)
+func CopyLanguageStat(ctx context.Context, originalRepo, destRepo *Repository) error {
+	ctx, committer, err := db.TxContext(ctx)
 	if err != nil {
 		return err
 	}
diff --git a/models/repo/repo.go b/models/repo/repo.go
index 0b0c029993..c4b215e074 100644
--- a/models/repo/repo.go
+++ b/models/repo/repo.go
@@ -447,7 +447,7 @@ func (repo *Repository) MustOwner(ctx context.Context) *user_model.User {
 }
 
 // ComposeMetas composes a map of metas for properly rendering issue links and external issue trackers.
-func (repo *Repository) ComposeMetas() map[string]string {
+func (repo *Repository) ComposeMetas(ctx context.Context) map[string]string {
 	if len(repo.RenderingMetas) == 0 {
 		metas := map[string]string{
 			"user":     repo.OwnerName,
@@ -456,7 +456,7 @@ func (repo *Repository) ComposeMetas() map[string]string {
 			"mode":     "comment",
 		}
 
-		unit, err := repo.GetUnit(db.DefaultContext, unit.TypeExternalTracker)
+		unit, err := repo.GetUnit(ctx, unit.TypeExternalTracker)
 		if err == nil {
 			metas["format"] = unit.ExternalTrackerConfig().ExternalTrackerFormat
 			switch unit.ExternalTrackerConfig().ExternalTrackerStyle {
@@ -470,10 +470,10 @@ func (repo *Repository) ComposeMetas() map[string]string {
 			}
 		}
 
-		repo.MustOwner(db.DefaultContext)
+		repo.MustOwner(ctx)
 		if repo.Owner.IsOrganization() {
 			teams := make([]string, 0, 5)
-			_ = db.GetEngine(db.DefaultContext).Table("team_repo").
+			_ = db.GetEngine(ctx).Table("team_repo").
 				Join("INNER", "team", "team.id = team_repo.team_id").
 				Where("team_repo.repo_id = ?", repo.ID).
 				Select("team.lower_name").
@@ -489,10 +489,10 @@ func (repo *Repository) ComposeMetas() map[string]string {
 }
 
 // ComposeDocumentMetas composes a map of metas for properly rendering documents
-func (repo *Repository) ComposeDocumentMetas() map[string]string {
+func (repo *Repository) ComposeDocumentMetas(ctx context.Context) map[string]string {
 	if len(repo.DocumentRenderingMetas) == 0 {
 		metas := map[string]string{}
-		for k, v := range repo.ComposeMetas() {
+		for k, v := range repo.ComposeMetas(ctx) {
 			metas[k] = v
 		}
 		metas["mode"] = "document"
@@ -566,8 +566,8 @@ func (repo *Repository) CanEnablePulls() bool {
 }
 
 // AllowsPulls returns true if repository meets the requirements of accepting pulls and has them enabled.
-func (repo *Repository) AllowsPulls() bool {
-	return repo.CanEnablePulls() && repo.UnitEnabled(db.DefaultContext, unit.TypePullRequests)
+func (repo *Repository) AllowsPulls(ctx context.Context) bool {
+	return repo.CanEnablePulls() && repo.UnitEnabled(ctx, unit.TypePullRequests)
 }
 
 // CanEnableEditor returns true if repository meets the requirements of web editor.
@@ -718,12 +718,12 @@ func GetRepositoryByOwnerAndName(ctx context.Context, ownerName, repoName string
 }
 
 // GetRepositoryByName returns the repository by given name under user if exists.
-func GetRepositoryByName(ownerID int64, name string) (*Repository, error) {
+func GetRepositoryByName(ctx context.Context, ownerID int64, name string) (*Repository, error) {
 	repo := &Repository{
 		OwnerID:   ownerID,
 		LowerName: strings.ToLower(name),
 	}
-	has, err := db.GetEngine(db.DefaultContext).Get(repo)
+	has, err := db.GetEngine(ctx).Get(repo)
 	if err != nil {
 		return nil, err
 	} else if !has {
@@ -788,9 +788,9 @@ func GetRepositoryByID(ctx context.Context, id int64) (*Repository, error) {
 }
 
 // GetRepositoriesMapByIDs returns the repositories by given id slice.
-func GetRepositoriesMapByIDs(ids []int64) (map[int64]*Repository, error) {
+func GetRepositoriesMapByIDs(ctx context.Context, ids []int64) (map[int64]*Repository, error) {
 	repos := make(map[int64]*Repository, len(ids))
-	return repos, db.GetEngine(db.DefaultContext).In("id", ids).Find(&repos)
+	return repos, db.GetEngine(ctx).In("id", ids).Find(&repos)
 }
 
 // IsRepositoryModelOrDirExist returns true if the repository with given name under user has already existed.
@@ -822,8 +822,8 @@ func GetTemplateRepo(ctx context.Context, repo *Repository) (*Repository, error)
 }
 
 // TemplateRepo returns the repository, which is template of this repository
-func (repo *Repository) TemplateRepo() *Repository {
-	repo, err := GetTemplateRepo(db.DefaultContext, repo)
+func (repo *Repository) TemplateRepo(ctx context.Context) *Repository {
+	repo, err := GetTemplateRepo(ctx, repo)
 	if err != nil {
 		log.Error("TemplateRepo: %v", err)
 		return nil
diff --git a/models/repo/repo_indexer.go b/models/repo/repo_indexer.go
index 9667c56244..bad1248b40 100644
--- a/models/repo/repo_indexer.go
+++ b/models/repo/repo_indexer.go
@@ -36,14 +36,14 @@ func init() {
 }
 
 // GetUnindexedRepos returns repos which do not have an indexer status
-func GetUnindexedRepos(indexerType RepoIndexerType, maxRepoID int64, page, pageSize int) ([]int64, error) {
+func GetUnindexedRepos(ctx context.Context, indexerType RepoIndexerType, maxRepoID int64, page, pageSize int) ([]int64, error) {
 	ids := make([]int64, 0, 50)
 	cond := builder.Cond(builder.IsNull{
 		"repo_indexer_status.id",
 	}).And(builder.Eq{
 		"repository.is_empty": false,
 	})
-	sess := db.GetEngine(db.DefaultContext).Table("repository").Join("LEFT OUTER", "repo_indexer_status", "repository.id = repo_indexer_status.repo_id AND repo_indexer_status.indexer_type = ?", indexerType)
+	sess := db.GetEngine(ctx).Table("repository").Join("LEFT OUTER", "repo_indexer_status", "repository.id = repo_indexer_status.repo_id AND repo_indexer_status.indexer_type = ?", indexerType)
 	if maxRepoID > 0 {
 		cond = builder.And(cond, builder.Lte{
 			"repository.id": maxRepoID,
diff --git a/models/repo/repo_list.go b/models/repo/repo_list.go
index a0485ed8d4..4a703dc584 100644
--- a/models/repo/repo_list.go
+++ b/models/repo/repo_list.go
@@ -21,8 +21,8 @@ import (
 )
 
 // FindReposMapByIDs find repos as map
-func FindReposMapByIDs(repoIDs []int64, res map[int64]*Repository) error {
-	return db.GetEngine(db.DefaultContext).In("id", repoIDs).Find(&res)
+func FindReposMapByIDs(ctx context.Context, repoIDs []int64, res map[int64]*Repository) error {
+	return db.GetEngine(ctx).In("id", repoIDs).Find(&res)
 }
 
 // RepositoryListDefaultPageSize is the default number of repositories
@@ -672,12 +672,12 @@ func SearchRepositoryByName(ctx context.Context, opts *SearchRepoOptions) (Repos
 
 // SearchRepositoryIDs takes keyword and part of repository name to search,
 // it returns results in given range and number of total results.
-func SearchRepositoryIDs(opts *SearchRepoOptions) ([]int64, int64, error) {
+func SearchRepositoryIDs(ctx context.Context, opts *SearchRepoOptions) ([]int64, int64, error) {
 	opts.IncludeDescription = false
 
 	cond := SearchRepositoryCondition(opts)
 
-	sess, count, err := searchRepositoryByCondition(db.DefaultContext, opts, cond)
+	sess, count, err := searchRepositoryByCondition(ctx, opts, cond)
 	if err != nil {
 		return nil, 0, err
 	}
diff --git a/models/repo/repo_test.go b/models/repo/repo_test.go
index fb021561c3..4bbfeb634a 100644
--- a/models/repo/repo_test.go
+++ b/models/repo/repo_test.go
@@ -83,7 +83,7 @@ func TestMetas(t *testing.T) {
 
 	repo.Units = nil
 
-	metas := repo.ComposeMetas()
+	metas := repo.ComposeMetas(db.DefaultContext)
 	assert.Equal(t, "testRepo", metas["repo"])
 	assert.Equal(t, "testOwner", metas["user"])
 
@@ -97,7 +97,7 @@ func TestMetas(t *testing.T) {
 	testSuccess := func(expectedStyle string) {
 		repo.Units = []*repo_model.RepoUnit{&externalTracker}
 		repo.RenderingMetas = nil
-		metas := repo.ComposeMetas()
+		metas := repo.ComposeMetas(db.DefaultContext)
 		assert.Equal(t, expectedStyle, metas["style"])
 		assert.Equal(t, "testRepo", metas["repo"])
 		assert.Equal(t, "testOwner", metas["user"])
@@ -118,7 +118,7 @@ func TestMetas(t *testing.T) {
 	repo, err := repo_model.GetRepositoryByID(db.DefaultContext, 3)
 	assert.NoError(t, err)
 
-	metas = repo.ComposeMetas()
+	metas = repo.ComposeMetas(db.DefaultContext)
 	assert.Contains(t, metas, "org")
 	assert.Contains(t, metas, "teams")
 	assert.Equal(t, "org3", metas["org"])
diff --git a/models/repo_test.go b/models/repo_test.go
index da66b16136..2a8a4a743e 100644
--- a/models/repo_test.go
+++ b/models/repo_test.go
@@ -20,5 +20,5 @@ func TestCheckRepoStats(t *testing.T) {
 func TestDoctorUserStarNum(t *testing.T) {
 	assert.NoError(t, unittest.PrepareTestDatabase())
 
-	assert.NoError(t, DoctorUserStarNum())
+	assert.NoError(t, DoctorUserStarNum(db.DefaultContext))
 }
diff --git a/modules/context/repo.go b/modules/context/repo.go
index 18b6650b6e..b340a6e230 100644
--- a/modules/context/repo.go
+++ b/modules/context/repo.go
@@ -495,7 +495,7 @@ func RepoAssignment(ctx *Context) context.CancelFunc {
 	}
 
 	// Get repository.
-	repo, err := repo_model.GetRepositoryByName(owner.ID, repoName)
+	repo, err := repo_model.GetRepositoryByName(ctx, owner.ID, repoName)
 	if err != nil {
 		if repo_model.IsErrRepoNotExist(err) {
 			redirectRepoID, err := repo_model.LookupRedirect(owner.ID, repoName)
@@ -711,13 +711,13 @@ func RepoAssignment(ctx *Context) context.CancelFunc {
 
 	// Pull request is allowed if this is a fork repository
 	// and base repository accepts pull requests.
-	if repo.BaseRepo != nil && repo.BaseRepo.AllowsPulls() {
+	if repo.BaseRepo != nil && repo.BaseRepo.AllowsPulls(ctx) {
 		canCompare = true
 		ctx.Data["BaseRepo"] = repo.BaseRepo
 		ctx.Repo.PullRequest.BaseRepo = repo.BaseRepo
 		ctx.Repo.PullRequest.Allowed = canPush
 		ctx.Repo.PullRequest.HeadInfoSubURL = url.PathEscape(ctx.Repo.Owner.Name) + ":" + util.PathEscapeSegments(ctx.Repo.BranchName)
-	} else if repo.AllowsPulls() {
+	} else if repo.AllowsPulls(ctx) {
 		// Or, this is repository accepts pull requests between branches.
 		canCompare = true
 		ctx.Data["BaseRepo"] = repo
diff --git a/modules/doctor/mergebase.go b/modules/doctor/mergebase.go
index e79369e581..de460c4190 100644
--- a/modules/doctor/mergebase.go
+++ b/modules/doctor/mergebase.go
@@ -74,7 +74,7 @@ func checkPRMergeBase(ctx context.Context, logger log.Logger, autofix bool) erro
 			pr.MergeBase = strings.TrimSpace(pr.MergeBase)
 			if pr.MergeBase != oldMergeBase {
 				if autofix {
-					if err := pr.UpdateCols("merge_base"); err != nil {
+					if err := pr.UpdateCols(ctx, "merge_base"); err != nil {
 						logger.Critical("Failed to update merge_base. ERROR: %v", err)
 						return fmt.Errorf("Failed to update merge_base. ERROR: %w", err)
 					}
diff --git a/modules/doctor/misc.go b/modules/doctor/misc.go
index e01c3e109b..f0b5966b54 100644
--- a/modules/doctor/misc.go
+++ b/modules/doctor/misc.go
@@ -74,7 +74,7 @@ func checkHooks(ctx context.Context, logger log.Logger, autofix bool) error {
 
 func checkUserStarNum(ctx context.Context, logger log.Logger, autofix bool) error {
 	if autofix {
-		if err := models.DoctorUserStarNum(); err != nil {
+		if err := models.DoctorUserStarNum(ctx); err != nil {
 			logger.Critical("Unable update User Stars numbers")
 			return err
 		}
diff --git a/modules/indexer/code/indexer.go b/modules/indexer/code/indexer.go
index 019773fe51..ebebf6ba8a 100644
--- a/modules/indexer/code/indexer.go
+++ b/modules/indexer/code/indexer.go
@@ -288,7 +288,7 @@ func populateRepoIndexer(ctx context.Context) {
 			return
 		default:
 		}
-		ids, err := repo_model.GetUnindexedRepos(repo_model.RepoIndexerTypeCode, maxRepoID, 0, 50)
+		ids, err := repo_model.GetUnindexedRepos(ctx, repo_model.RepoIndexerTypeCode, maxRepoID, 0, 50)
 		if err != nil {
 			log.Error("populateRepoIndexer: %v", err)
 			return
diff --git a/modules/indexer/issues/util.go b/modules/indexer/issues/util.go
index 2dec3b71db..ca4ff6d42f 100644
--- a/modules/indexer/issues/util.go
+++ b/modules/indexer/issues/util.go
@@ -107,7 +107,7 @@ func getIssueIndexerData(ctx context.Context, issueID int64) (*internal.IndexerD
 		NoLabel:            len(labels) == 0,
 		MilestoneID:        issue.MilestoneID,
 		ProjectID:          projectID,
-		ProjectBoardID:     issue.ProjectBoardID(),
+		ProjectBoardID:     issue.ProjectBoardID(ctx),
 		PosterID:           issue.PosterID,
 		AssigneeID:         issue.AssigneeID,
 		MentionIDs:         mentionIDs,
diff --git a/modules/indexer/stats/db.go b/modules/indexer/stats/db.go
index 2a0475dea6..163843b47f 100644
--- a/modules/indexer/stats/db.go
+++ b/modules/indexer/stats/db.go
@@ -68,7 +68,7 @@ func (db *DBIndexer) Index(id int64) error {
 		}
 		return err
 	}
-	err = repo_model.UpdateLanguageStats(repo, commitID, stats)
+	err = repo_model.UpdateLanguageStats(ctx, repo, commitID, stats)
 	if err != nil {
 		log.Error("Unable to update language stats for ID %s for default branch %s in %s. Error: %v", commitID, repo.DefaultBranch, repo.RepoPath(), err)
 		return err
diff --git a/modules/indexer/stats/indexer.go b/modules/indexer/stats/indexer.go
index 6bfa8bdedb..7ec89e2afb 100644
--- a/modules/indexer/stats/indexer.go
+++ b/modules/indexer/stats/indexer.go
@@ -4,6 +4,8 @@
 package stats
 
 import (
+	"context"
+
 	"code.gitea.io/gitea/models/db"
 	repo_model "code.gitea.io/gitea/models/repo"
 	"code.gitea.io/gitea/modules/graceful"
@@ -28,14 +30,14 @@ func Init() error {
 		return err
 	}
 
-	go populateRepoIndexer()
+	go populateRepoIndexer(db.DefaultContext)
 
 	return nil
 }
 
 // populateRepoIndexer populate the repo indexer with pre-existing data. This
 // should only be run when the indexer is created for the first time.
-func populateRepoIndexer() {
+func populateRepoIndexer(ctx context.Context) {
 	log.Info("Populating the repo stats indexer with existing repositories")
 
 	isShutdown := graceful.GetManager().IsShutdown()
@@ -62,7 +64,7 @@ func populateRepoIndexer() {
 			return
 		default:
 		}
-		ids, err := repo_model.GetUnindexedRepos(repo_model.RepoIndexerTypeStats, maxRepoID, 0, 50)
+		ids, err := repo_model.GetUnindexedRepos(ctx, repo_model.RepoIndexerTypeStats, maxRepoID, 0, 50)
 		if err != nil {
 			log.Error("populateRepoIndexer: %v", err)
 			return
diff --git a/modules/indexer/stats/indexer_test.go b/modules/indexer/stats/indexer_test.go
index 6f935a20de..5be45d7a3b 100644
--- a/modules/indexer/stats/indexer_test.go
+++ b/modules/indexer/stats/indexer_test.go
@@ -45,7 +45,7 @@ func TestRepoStatsIndex(t *testing.T) {
 	status, err := repo_model.GetIndexerStatus(db.DefaultContext, repo, repo_model.RepoIndexerTypeStats)
 	assert.NoError(t, err)
 	assert.Equal(t, "65f1bf27bc3bf70f64657658635e66094edbcb4d", status.CommitSha)
-	langs, err := repo_model.GetTopLanguageStats(repo, 5)
+	langs, err := repo_model.GetTopLanguageStats(db.DefaultContext, repo, 5)
 	assert.NoError(t, err)
 	assert.Empty(t, langs)
 }
diff --git a/routers/api/v1/admin/user.go b/routers/api/v1/admin/user.go
index 610eba1749..09d7c1a940 100644
--- a/routers/api/v1/admin/user.go
+++ b/routers/api/v1/admin/user.go
@@ -36,7 +36,7 @@ func parseAuthSource(ctx *context.APIContext, u *user_model.User, sourceID int64
 		return
 	}
 
-	source, err := auth.GetSourceByID(sourceID)
+	source, err := auth.GetSourceByID(ctx, sourceID)
 	if err != nil {
 		if auth.IsErrSourceNotExist(err) {
 			ctx.Error(http.StatusUnprocessableEntity, "", err)
diff --git a/routers/api/v1/api.go b/routers/api/v1/api.go
index 441801885f..8abe51ea4f 100644
--- a/routers/api/v1/api.go
+++ b/routers/api/v1/api.go
@@ -70,6 +70,7 @@ import (
 
 	actions_model "code.gitea.io/gitea/models/actions"
 	auth_model "code.gitea.io/gitea/models/auth"
+	"code.gitea.io/gitea/models/db"
 	"code.gitea.io/gitea/models/organization"
 	"code.gitea.io/gitea/models/perm"
 	access_model "code.gitea.io/gitea/models/perm/access"
@@ -165,7 +166,7 @@ func repoAssignment() func(ctx *context.APIContext) {
 		ctx.ContextUser = owner
 
 		// Get repository.
-		repo, err := repo_model.GetRepositoryByName(owner.ID, repoName)
+		repo, err := repo_model.GetRepositoryByName(ctx, owner.ID, repoName)
 		if err != nil {
 			if repo_model.IsErrRepoNotExist(err) {
 				redirectRepoID, err := repo_model.LookupRedirect(owner.ID, repoName)
@@ -716,7 +717,7 @@ func buildAuthGroup() *auth.Group {
 		group.Add(&auth.ReverseProxy{})
 	}
 
-	if setting.IsWindows && auth_model.IsSSPIEnabled() {
+	if setting.IsWindows && auth_model.IsSSPIEnabled(db.DefaultContext) {
 		group.Add(&auth.SSPI{}) // it MUST be the last, see the comment of SSPI
 	}
 
diff --git a/routers/api/v1/org/avatar.go b/routers/api/v1/org/avatar.go
index a7b5008525..7b621a50c3 100644
--- a/routers/api/v1/org/avatar.go
+++ b/routers/api/v1/org/avatar.go
@@ -43,7 +43,7 @@ func UpdateAvatar(ctx *context.APIContext) {
 		return
 	}
 
-	err = user_service.UploadAvatar(ctx.Org.Organization.AsUser(), content)
+	err = user_service.UploadAvatar(ctx, ctx.Org.Organization.AsUser(), content)
 	if err != nil {
 		ctx.Error(http.StatusInternalServerError, "UploadAvatar", err)
 	}
@@ -69,7 +69,7 @@ func DeleteAvatar(ctx *context.APIContext) {
 	//     "$ref": "#/responses/empty"
 	//   "404":
 	//     "$ref": "#/responses/notFound"
-	err := user_service.DeleteAvatar(ctx.Org.Organization.AsUser())
+	err := user_service.DeleteAvatar(ctx, ctx.Org.Organization.AsUser())
 	if err != nil {
 		ctx.Error(http.StatusInternalServerError, "DeleteAvatar", err)
 	}
diff --git a/routers/api/v1/org/team.go b/routers/api/v1/org/team.go
index 9b68253623..f129c66230 100644
--- a/routers/api/v1/org/team.go
+++ b/routers/api/v1/org/team.go
@@ -638,7 +638,7 @@ func GetTeamRepo(ctx *context.APIContext) {
 
 // getRepositoryByParams get repository by a team's organization ID and repo name
 func getRepositoryByParams(ctx *context.APIContext) *repo_model.Repository {
-	repo, err := repo_model.GetRepositoryByName(ctx.Org.Team.OrgID, ctx.Params(":reponame"))
+	repo, err := repo_model.GetRepositoryByName(ctx, ctx.Org.Team.OrgID, ctx.Params(":reponame"))
 	if err != nil {
 		if repo_model.IsErrRepoNotExist(err) {
 			ctx.NotFound()
diff --git a/routers/api/v1/repo/issue.go b/routers/api/v1/repo/issue.go
index 58689b72a6..74e6361f6c 100644
--- a/routers/api/v1/repo/issue.go
+++ b/routers/api/v1/repo/issue.go
@@ -188,7 +188,7 @@ func SearchIssues(ctx *context.APIContext) {
 			allPublic = true
 			opts.AllPublic = false // set it false to avoid returning too many repos, we could filter by indexer
 		}
-		repoIDs, _, err = repo_model.SearchRepositoryIDs(opts)
+		repoIDs, _, err = repo_model.SearchRepositoryIDs(ctx, opts)
 		if err != nil {
 			ctx.Error(http.StatusInternalServerError, "SearchRepositoryIDs", err)
 			return
@@ -837,7 +837,7 @@ func EditIssue(ctx *context.APIContext) {
 		issue.MilestoneID != *form.Milestone {
 		oldMilestoneID := issue.MilestoneID
 		issue.MilestoneID = *form.Milestone
-		if err = issue_service.ChangeMilestoneAssign(issue, ctx.Doer, oldMilestoneID); err != nil {
+		if err = issue_service.ChangeMilestoneAssign(ctx, issue, ctx.Doer, oldMilestoneID); err != nil {
 			ctx.Error(http.StatusInternalServerError, "ChangeMilestoneAssign", err)
 			return
 		}
diff --git a/routers/api/v1/repo/issue_dependency.go b/routers/api/v1/repo/issue_dependency.go
index 9571532800..0e3bcd93ef 100644
--- a/routers/api/v1/repo/issue_dependency.go
+++ b/routers/api/v1/repo/issue_dependency.go
@@ -576,7 +576,7 @@ func createIssueDependency(ctx *context.APIContext, target, dependency *issues_m
 		return
 	}
 
-	err := issues_model.CreateIssueDependency(ctx.Doer, target, dependency)
+	err := issues_model.CreateIssueDependency(ctx, ctx.Doer, target, dependency)
 	if err != nil {
 		ctx.Error(http.StatusInternalServerError, "CreateIssueDependency", err)
 		return
@@ -602,7 +602,7 @@ func removeIssueDependency(ctx *context.APIContext, target, dependency *issues_m
 		return
 	}
 
-	err := issues_model.RemoveIssueDependency(ctx.Doer, target, dependency, issues_model.DependencyTypeBlockedBy)
+	err := issues_model.RemoveIssueDependency(ctx, ctx.Doer, target, dependency, issues_model.DependencyTypeBlockedBy)
 	if err != nil {
 		ctx.Error(http.StatusInternalServerError, "CreateIssueDependency", err)
 		return
diff --git a/routers/api/v1/repo/key.go b/routers/api/v1/repo/key.go
index 7d97f5f5e2..e2b7b49438 100644
--- a/routers/api/v1/repo/key.go
+++ b/routers/api/v1/repo/key.go
@@ -105,7 +105,7 @@ func ListDeployKeys(ctx *context.APIContext) {
 	apiLink := composeDeployKeysAPILink(ctx.Repo.Owner.Name, ctx.Repo.Repository.Name)
 	apiKeys := make([]*api.DeployKey, len(keys))
 	for i := range keys {
-		if err := keys[i].GetContent(); err != nil {
+		if err := keys[i].GetContent(ctx); err != nil {
 			ctx.Error(http.StatusInternalServerError, "GetContent", err)
 			return
 		}
@@ -159,7 +159,7 @@ func GetDeployKey(ctx *context.APIContext) {
 		return
 	}
 
-	if err = key.GetContent(); err != nil {
+	if err = key.GetContent(ctx); err != nil {
 		ctx.Error(http.StatusInternalServerError, "GetContent", err)
 		return
 	}
diff --git a/routers/api/v1/repo/milestone.go b/routers/api/v1/repo/milestone.go
index 1a86444660..da470dfa74 100644
--- a/routers/api/v1/repo/milestone.go
+++ b/routers/api/v1/repo/milestone.go
@@ -58,7 +58,7 @@ func ListMilestones(ctx *context.APIContext) {
 	//   "404":
 	//     "$ref": "#/responses/notFound"
 
-	milestones, total, err := issues_model.GetMilestones(issues_model.GetMilestonesOption{
+	milestones, total, err := issues_model.GetMilestones(ctx, issues_model.GetMilestonesOption{
 		ListOptions: utils.GetListOptions(ctx),
 		RepoID:      ctx.Repo.Repository.ID,
 		State:       api.StateType(ctx.FormString("state")),
diff --git a/routers/api/v1/repo/pull.go b/routers/api/v1/repo/pull.go
index 6fcc5267cf..df9e7217bb 100644
--- a/routers/api/v1/repo/pull.go
+++ b/routers/api/v1/repo/pull.go
@@ -555,7 +555,7 @@ func EditPullRequest(ctx *context.APIContext) {
 		issue.MilestoneID != form.Milestone {
 		oldMilestoneID := issue.MilestoneID
 		issue.MilestoneID = form.Milestone
-		if err = issue_service.ChangeMilestoneAssign(issue, ctx.Doer, oldMilestoneID); err != nil {
+		if err = issue_service.ChangeMilestoneAssign(ctx, issue, ctx.Doer, oldMilestoneID); err != nil {
 			ctx.Error(http.StatusInternalServerError, "ChangeMilestoneAssign", err)
 			return
 		}
@@ -578,7 +578,7 @@ func EditPullRequest(ctx *context.APIContext) {
 			labels = append(labels, orgLabels...)
 		}
 
-		if err = issues_model.ReplaceIssueLabels(issue, labels, ctx.Doer); err != nil {
+		if err = issues_model.ReplaceIssueLabels(ctx, issue, labels, ctx.Doer); err != nil {
 			ctx.Error(http.StatusInternalServerError, "ReplaceLabelsError", err)
 			return
 		}
diff --git a/routers/api/v1/user/avatar.go b/routers/api/v1/user/avatar.go
index 84fa129b13..1c1bb6181a 100644
--- a/routers/api/v1/user/avatar.go
+++ b/routers/api/v1/user/avatar.go
@@ -36,7 +36,7 @@ func UpdateAvatar(ctx *context.APIContext) {
 		return
 	}
 
-	err = user_service.UploadAvatar(ctx.Doer, content)
+	err = user_service.UploadAvatar(ctx, ctx.Doer, content)
 	if err != nil {
 		ctx.Error(http.StatusInternalServerError, "UploadAvatar", err)
 	}
@@ -54,7 +54,7 @@ func DeleteAvatar(ctx *context.APIContext) {
 	// responses:
 	//   "204":
 	//     "$ref": "#/responses/empty"
-	err := user_service.DeleteAvatar(ctx.Doer)
+	err := user_service.DeleteAvatar(ctx, ctx.Doer)
 	if err != nil {
 		ctx.Error(http.StatusInternalServerError, "DeleteAvatar", err)
 	}
diff --git a/routers/api/v1/user/key.go b/routers/api/v1/user/key.go
index 7fc10e82f2..fd891699ce 100644
--- a/routers/api/v1/user/key.go
+++ b/routers/api/v1/user/key.go
@@ -59,14 +59,14 @@ func listPublicKeys(ctx *context.APIContext, user *user_model.User) {
 		// Querying not just listing
 		if username != "" {
 			// Restrict to provided uid
-			keys, err = asymkey_model.SearchPublicKey(user.ID, fingerprint)
+			keys, err = asymkey_model.SearchPublicKey(ctx, user.ID, fingerprint)
 		} else {
 			// Unrestricted
-			keys, err = asymkey_model.SearchPublicKey(0, fingerprint)
+			keys, err = asymkey_model.SearchPublicKey(ctx, 0, fingerprint)
 		}
 		count = len(keys)
 	} else {
-		total, err2 := asymkey_model.CountPublicKeys(user.ID)
+		total, err2 := asymkey_model.CountPublicKeys(ctx, user.ID)
 		if err2 != nil {
 			ctx.InternalServerError(err)
 			return
@@ -74,7 +74,7 @@ func listPublicKeys(ctx *context.APIContext, user *user_model.User) {
 		count = int(total)
 
 		// Use ListPublicKeys
-		keys, err = asymkey_model.ListPublicKeys(user.ID, utils.GetListOptions(ctx))
+		keys, err = asymkey_model.ListPublicKeys(ctx, user.ID, utils.GetListOptions(ctx))
 	}
 
 	if err != nil {
@@ -176,7 +176,7 @@ func GetPublicKey(ctx *context.APIContext) {
 	//   "404":
 	//     "$ref": "#/responses/notFound"
 
-	key, err := asymkey_model.GetPublicKeyByID(ctx.ParamsInt64(":id"))
+	key, err := asymkey_model.GetPublicKeyByID(ctx, ctx.ParamsInt64(":id"))
 	if err != nil {
 		if asymkey_model.IsErrKeyNotExist(err) {
 			ctx.NotFound()
@@ -202,7 +202,7 @@ func CreateUserPublicKey(ctx *context.APIContext, form api.CreateKeyOption, uid
 		return
 	}
 
-	key, err := asymkey_model.AddPublicKey(uid, form.Title, content, 0)
+	key, err := asymkey_model.AddPublicKey(ctx, uid, form.Title, content, 0)
 	if err != nil {
 		repo.HandleAddKeyError(ctx, err)
 		return
@@ -262,7 +262,7 @@ func DeletePublicKey(ctx *context.APIContext) {
 	//     "$ref": "#/responses/notFound"
 
 	id := ctx.ParamsInt64(":id")
-	externallyManaged, err := asymkey_model.PublicKeyIsExternallyManaged(id)
+	externallyManaged, err := asymkey_model.PublicKeyIsExternallyManaged(ctx, id)
 	if err != nil {
 		if asymkey_model.IsErrKeyNotExist(err) {
 			ctx.NotFound()
diff --git a/routers/common/markup.go b/routers/common/markup.go
index 5f412014d7..aaedc13de9 100644
--- a/routers/common/markup.go
+++ b/routers/common/markup.go
@@ -65,9 +65,9 @@ func RenderMarkup(ctx *context.Base, repo *context.Repository, mode, text, urlPr
 	meta := map[string]string{}
 	if repo != nil && repo.Repository != nil {
 		if mode == "comment" {
-			meta = repo.Repository.ComposeMetas()
+			meta = repo.Repository.ComposeMetas(ctx)
 		} else {
-			meta = repo.Repository.ComposeDocumentMetas()
+			meta = repo.Repository.ComposeDocumentMetas(ctx)
 		}
 	}
 	if mode != "comment" {
diff --git a/routers/init.go b/routers/init.go
index 3cd63eb9ae..0da510cc59 100644
--- a/routers/init.go
+++ b/routers/init.go
@@ -121,7 +121,7 @@ func InitWebInstalled(ctx context.Context) {
 	mustInit(cache.NewContext)
 	mustInit(feed_service.Init)
 	mustInit(uinotification.Init)
-	mustInit(archiver.Init)
+	mustInitCtx(ctx, archiver.Init)
 
 	highlight.NewContext()
 	external.RegisterRenderers()
diff --git a/routers/private/actions.go b/routers/private/actions.go
index 74515256da..025a6a2c39 100644
--- a/routers/private/actions.go
+++ b/routers/private/actions.go
@@ -83,7 +83,7 @@ func parseScope(ctx *context.PrivateContext, scope string) (ownerID, repoID int6
 		return ownerID, repoID, nil
 	}
 
-	r, err := repo_model.GetRepositoryByName(u.ID, repoName)
+	r, err := repo_model.GetRepositoryByName(ctx, u.ID, repoName)
 	if err != nil {
 		return ownerID, repoID, err
 	}
diff --git a/routers/private/hook_post_receive.go b/routers/private/hook_post_receive.go
index 0c9a2a10fa..d5a46e4e7f 100644
--- a/routers/private/hook_post_receive.go
+++ b/routers/private/hook_post_receive.go
@@ -150,7 +150,7 @@ func HookPostReceive(ctx *gitea_context.PrivateContext) {
 			}
 
 			results = append(results, private.HookPostReceiveBranchResult{
-				Message: setting.Git.PullRequestPushMessage && repo.AllowsPulls(),
+				Message: setting.Git.PullRequestPushMessage && repo.AllowsPulls(ctx),
 				Create:  false,
 				Branch:  "",
 				URL:     fmt.Sprintf("%s/pulls/%d", repo.HTMLURL(), pr.Index),
@@ -179,12 +179,12 @@ func HookPostReceive(ctx *gitea_context.PrivateContext) {
 						})
 						return
 					}
-					if repo.BaseRepo.AllowsPulls() {
+					if repo.BaseRepo.AllowsPulls(ctx) {
 						baseRepo = repo.BaseRepo
 					}
 				}
 
-				if !baseRepo.AllowsPulls() {
+				if !baseRepo.AllowsPulls(ctx) {
 					// We can stop there's no need to go any further
 					ctx.JSON(http.StatusOK, private.HookPostReceiveResult{
 						RepoWasEmpty: wasEmpty,
@@ -217,14 +217,14 @@ func HookPostReceive(ctx *gitea_context.PrivateContext) {
 					branch = fmt.Sprintf("%s:%s", repo.OwnerName, branch)
 				}
 				results = append(results, private.HookPostReceiveBranchResult{
-					Message: setting.Git.PullRequestPushMessage && baseRepo.AllowsPulls(),
+					Message: setting.Git.PullRequestPushMessage && baseRepo.AllowsPulls(ctx),
 					Create:  true,
 					Branch:  branch,
 					URL:     fmt.Sprintf("%s/compare/%s...%s", baseRepo.HTMLURL(), util.PathEscapeSegments(baseRepo.DefaultBranch), util.PathEscapeSegments(branch)),
 				})
 			} else {
 				results = append(results, private.HookPostReceiveBranchResult{
-					Message: setting.Git.PullRequestPushMessage && baseRepo.AllowsPulls(),
+					Message: setting.Git.PullRequestPushMessage && baseRepo.AllowsPulls(ctx),
 					Create:  false,
 					Branch:  branch,
 					URL:     fmt.Sprintf("%s/pulls/%d", baseRepo.HTMLURL(), pr.Index),
diff --git a/routers/private/key.go b/routers/private/key.go
index a13b4c12ae..176e5ffcc8 100644
--- a/routers/private/key.go
+++ b/routers/private/key.go
@@ -16,7 +16,7 @@ import (
 func UpdatePublicKeyInRepo(ctx *context.PrivateContext) {
 	keyID := ctx.ParamsInt64(":id")
 	repoID := ctx.ParamsInt64(":repoid")
-	if err := asymkey_model.UpdatePublicKeyUpdated(keyID); err != nil {
+	if err := asymkey_model.UpdatePublicKeyUpdated(ctx, keyID); err != nil {
 		ctx.JSON(http.StatusInternalServerError, private.Response{
 			Err: err.Error(),
 		})
diff --git a/routers/private/serv.go b/routers/private/serv.go
index b1efc58800..00731947a5 100644
--- a/routers/private/serv.go
+++ b/routers/private/serv.go
@@ -33,7 +33,7 @@ func ServNoCommand(ctx *context.PrivateContext) {
 	}
 	results := private.KeyAndOwner{}
 
-	key, err := asymkey_model.GetPublicKeyByID(keyID)
+	key, err := asymkey_model.GetPublicKeyByID(ctx, keyID)
 	if err != nil {
 		if asymkey_model.IsErrKeyNotExist(err) {
 			ctx.JSON(http.StatusUnauthorized, private.Response{
@@ -132,7 +132,7 @@ func ServCommand(ctx *context.PrivateContext) {
 
 	// Now get the Repository and set the results section
 	repoExist := true
-	repo, err := repo_model.GetRepositoryByName(owner.ID, results.RepoName)
+	repo, err := repo_model.GetRepositoryByName(ctx, owner.ID, results.RepoName)
 	if err != nil {
 		if repo_model.IsErrRepoNotExist(err) {
 			repoExist = false
@@ -184,7 +184,7 @@ func ServCommand(ctx *context.PrivateContext) {
 	}
 
 	// Get the Public Key represented by the keyID
-	key, err := asymkey_model.GetPublicKeyByID(keyID)
+	key, err := asymkey_model.GetPublicKeyByID(ctx, keyID)
 	if err != nil {
 		if asymkey_model.IsErrKeyNotExist(err) {
 			ctx.JSON(http.StatusNotFound, private.Response{
diff --git a/routers/web/admin/auths.go b/routers/web/admin/auths.go
index b743d1b0a5..22de15036c 100644
--- a/routers/web/admin/auths.go
+++ b/routers/web/admin/auths.go
@@ -48,13 +48,13 @@ func Authentications(ctx *context.Context) {
 	ctx.Data["PageIsAdminAuthentications"] = true
 
 	var err error
-	ctx.Data["Sources"], err = auth.Sources()
+	ctx.Data["Sources"], err = auth.Sources(ctx)
 	if err != nil {
 		ctx.ServerError("auth.Sources", err)
 		return
 	}
 
-	ctx.Data["Total"] = auth.CountSources()
+	ctx.Data["Total"] = auth.CountSources(ctx)
 	ctx.HTML(http.StatusOK, tplAuths)
 }
 
@@ -284,7 +284,7 @@ func NewAuthSourcePost(ctx *context.Context) {
 			ctx.RenderWithErr(err.Error(), tplAuthNew, form)
 			return
 		}
-		existing, err := auth.SourcesByType(auth.SSPI)
+		existing, err := auth.SourcesByType(ctx, auth.SSPI)
 		if err != nil || len(existing) > 0 {
 			ctx.Data["Err_Type"] = true
 			ctx.RenderWithErr(ctx.Tr("admin.auths.login_source_of_type_exist"), tplAuthNew, form)
@@ -301,7 +301,7 @@ func NewAuthSourcePost(ctx *context.Context) {
 		return
 	}
 
-	if err := auth.CreateSource(&auth.Source{
+	if err := auth.CreateSource(ctx, &auth.Source{
 		Type:          auth.Type(form.Type),
 		Name:          form.Name,
 		IsActive:      form.IsActive,
@@ -337,7 +337,7 @@ func EditAuthSource(ctx *context.Context) {
 	oauth2providers := oauth2.GetOAuth2Providers()
 	ctx.Data["OAuth2Providers"] = oauth2providers
 
-	source, err := auth.GetSourceByID(ctx.ParamsInt64(":authid"))
+	source, err := auth.GetSourceByID(ctx, ctx.ParamsInt64(":authid"))
 	if err != nil {
 		ctx.ServerError("auth.GetSourceByID", err)
 		return
@@ -371,7 +371,7 @@ func EditAuthSourcePost(ctx *context.Context) {
 	oauth2providers := oauth2.GetOAuth2Providers()
 	ctx.Data["OAuth2Providers"] = oauth2providers
 
-	source, err := auth.GetSourceByID(ctx.ParamsInt64(":authid"))
+	source, err := auth.GetSourceByID(ctx, ctx.ParamsInt64(":authid"))
 	if err != nil {
 		ctx.ServerError("auth.GetSourceByID", err)
 		return
@@ -421,7 +421,7 @@ func EditAuthSourcePost(ctx *context.Context) {
 	source.IsActive = form.IsActive
 	source.IsSyncEnabled = form.IsSyncEnabled
 	source.Cfg = config
-	if err := auth.UpdateSource(source); err != nil {
+	if err := auth.UpdateSource(ctx, source); err != nil {
 		if auth.IsErrSourceAlreadyExist(err) {
 			ctx.Data["Err_Name"] = true
 			ctx.RenderWithErr(ctx.Tr("admin.auths.login_source_exist", err.(auth.ErrSourceAlreadyExist).Name), tplAuthEdit, form)
@@ -442,7 +442,7 @@ func EditAuthSourcePost(ctx *context.Context) {
 
 // DeleteAuthSource response for deleting an auth source
 func DeleteAuthSource(ctx *context.Context) {
-	source, err := auth.GetSourceByID(ctx.ParamsInt64(":authid"))
+	source, err := auth.GetSourceByID(ctx, ctx.ParamsInt64(":authid"))
 	if err != nil {
 		ctx.ServerError("auth.GetSourceByID", err)
 		return
diff --git a/routers/web/admin/users.go b/routers/web/admin/users.go
index 18d7313e72..91a578fb55 100644
--- a/routers/web/admin/users.go
+++ b/routers/web/admin/users.go
@@ -90,7 +90,7 @@ func NewUser(ctx *context.Context) {
 
 	ctx.Data["login_type"] = "0-0"
 
-	sources, err := auth.Sources()
+	sources, err := auth.Sources(ctx)
 	if err != nil {
 		ctx.ServerError("auth.Sources", err)
 		return
@@ -109,7 +109,7 @@ func NewUserPost(ctx *context.Context) {
 	ctx.Data["DefaultUserVisibilityMode"] = setting.Service.DefaultUserVisibilityMode
 	ctx.Data["AllowedUserVisibilityModes"] = setting.Service.AllowedUserVisibilityModesSlice.ToVisibleTypeSlice()
 
-	sources, err := auth.Sources()
+	sources, err := auth.Sources(ctx)
 	if err != nil {
 		ctx.ServerError("auth.Sources", err)
 		return
@@ -221,7 +221,7 @@ func prepareUserInfo(ctx *context.Context) *user_model.User {
 	ctx.Data["User"] = u
 
 	if u.LoginSource > 0 {
-		ctx.Data["LoginSource"], err = auth.GetSourceByID(u.LoginSource)
+		ctx.Data["LoginSource"], err = auth.GetSourceByID(ctx, u.LoginSource)
 		if err != nil {
 			ctx.ServerError("auth.GetSourceByID", err)
 			return nil
@@ -230,7 +230,7 @@ func prepareUserInfo(ctx *context.Context) *user_model.User {
 		ctx.Data["LoginSource"] = &auth.Source{}
 	}
 
-	sources, err := auth.Sources()
+	sources, err := auth.Sources(ctx)
 	if err != nil {
 		ctx.ServerError("auth.Sources", err)
 		return nil
@@ -532,7 +532,7 @@ func DeleteAvatar(ctx *context.Context) {
 		return
 	}
 
-	if err := user_service.DeleteAvatar(u); err != nil {
+	if err := user_service.DeleteAvatar(ctx, u); err != nil {
 		ctx.Flash.Error(err.Error())
 	}
 
diff --git a/routers/web/auth/auth.go b/routers/web/auth/auth.go
index 8017602d99..df835a2fa1 100644
--- a/routers/web/auth/auth.go
+++ b/routers/web/auth/auth.go
@@ -157,7 +157,7 @@ func SignIn(ctx *context.Context) {
 	ctx.Data["SignInLink"] = setting.AppSubURL + "/user/login"
 	ctx.Data["PageIsSignIn"] = true
 	ctx.Data["PageIsLogin"] = true
-	ctx.Data["EnableSSPI"] = auth.IsSSPIEnabled()
+	ctx.Data["EnableSSPI"] = auth.IsSSPIEnabled(ctx)
 
 	if setting.Service.EnableCaptcha && setting.Service.RequireCaptchaForLogin {
 		context.SetCaptchaData(ctx)
@@ -181,7 +181,7 @@ func SignInPost(ctx *context.Context) {
 	ctx.Data["SignInLink"] = setting.AppSubURL + "/user/login"
 	ctx.Data["PageIsSignIn"] = true
 	ctx.Data["PageIsLogin"] = true
-	ctx.Data["EnableSSPI"] = auth.IsSSPIEnabled()
+	ctx.Data["EnableSSPI"] = auth.IsSSPIEnabled(ctx)
 
 	if ctx.HasError() {
 		ctx.HTML(http.StatusOK, tplSignIn)
diff --git a/routers/web/auth/linkaccount.go b/routers/web/auth/linkaccount.go
index 42d846180d..1e70d85cee 100644
--- a/routers/web/auth/linkaccount.go
+++ b/routers/web/auth/linkaccount.go
@@ -152,7 +152,7 @@ func LinkAccountPostSignIn(ctx *context.Context) {
 }
 
 func linkAccount(ctx *context.Context, u *user_model.User, gothUser goth.User, remember bool) {
-	updateAvatarIfNeed(gothUser.AvatarURL, u)
+	updateAvatarIfNeed(ctx, gothUser.AvatarURL, u)
 
 	// If this user is enrolled in 2FA, we can't sign the user in just yet.
 	// Instead, redirect them to the 2FA authentication page.
diff --git a/routers/web/auth/oauth.go b/routers/web/auth/oauth.go
index ce58cbdef9..64106e1ab6 100644
--- a/routers/web/auth/oauth.go
+++ b/routers/web/auth/oauth.go
@@ -1074,7 +1074,7 @@ func showLinkingLogin(ctx *context.Context, gothUser goth.User) {
 	ctx.Redirect(setting.AppSubURL + "/user/link_account")
 }
 
-func updateAvatarIfNeed(url string, u *user_model.User) {
+func updateAvatarIfNeed(ctx *context.Context, url string, u *user_model.User) {
 	if setting.OAuth2Client.UpdateAvatar && len(url) > 0 {
 		resp, err := http.Get(url)
 		if err == nil {
@@ -1086,14 +1086,14 @@ func updateAvatarIfNeed(url string, u *user_model.User) {
 		if err == nil && resp.StatusCode == http.StatusOK {
 			data, err := io.ReadAll(io.LimitReader(resp.Body, setting.Avatar.MaxFileSize+1))
 			if err == nil && int64(len(data)) <= setting.Avatar.MaxFileSize {
-				_ = user_service.UploadAvatar(u, data)
+				_ = user_service.UploadAvatar(ctx, u, data)
 			}
 		}
 	}
 }
 
 func handleOAuth2SignIn(ctx *context.Context, source *auth.Source, u *user_model.User, gothUser goth.User) {
-	updateAvatarIfNeed(gothUser.AvatarURL, u)
+	updateAvatarIfNeed(ctx, gothUser.AvatarURL, u)
 
 	needs2FA := false
 	if !source.Cfg.(*oauth2.Source).SkipLocalTwoFA {
diff --git a/routers/web/explore/code.go b/routers/web/explore/code.go
index 94d83818fc..d81884ec62 100644
--- a/routers/web/explore/code.go
+++ b/routers/web/explore/code.go
@@ -102,7 +102,7 @@ func Code(ctx *context.Context) {
 			}
 		}
 
-		repoMaps, err := repo_model.GetRepositoriesMapByIDs(loadRepoIDs)
+		repoMaps, err := repo_model.GetRepositoriesMapByIDs(ctx, loadRepoIDs)
 		if err != nil {
 			ctx.ServerError("GetRepositoriesMapByIDs", err)
 			return
diff --git a/routers/web/feed/convert.go b/routers/web/feed/convert.go
index 04078955bb..4d4918a8fd 100644
--- a/routers/web/feed/convert.go
+++ b/routers/web/feed/convert.go
@@ -290,7 +290,7 @@ func releasesToFeedItems(ctx *context.Context, releases []*repo_model.Release, i
 		content, err = markdown.RenderString(&markup.RenderContext{
 			Ctx:       ctx,
 			URLPrefix: rel.Repo.Link(),
-			Metas:     rel.Repo.ComposeMetas(),
+			Metas:     rel.Repo.ComposeMetas(ctx),
 		}, rel.Note)
 
 		if err != nil {
diff --git a/routers/web/org/projects.go b/routers/web/org/projects.go
index 19d3682f51..439fdf644b 100644
--- a/routers/web/org/projects.go
+++ b/routers/web/org/projects.go
@@ -468,7 +468,7 @@ func UpdateIssueProject(ctx *context.Context) {
 			}
 		}
 
-		if err := issues_model.ChangeProjectAssign(issue, ctx.Doer, projectID); err != nil {
+		if err := issues_model.ChangeProjectAssign(ctx, issue, ctx.Doer, projectID); err != nil {
 			ctx.ServerError("ChangeProjectAssign", err)
 			return
 		}
diff --git a/routers/web/org/setting.go b/routers/web/org/setting.go
index 0f082a70df..a8e1bc1c83 100644
--- a/routers/web/org/setting.go
+++ b/routers/web/org/setting.go
@@ -160,7 +160,7 @@ func SettingsAvatar(ctx *context.Context) {
 
 // SettingsDeleteAvatar response for delete avatar on settings page
 func SettingsDeleteAvatar(ctx *context.Context) {
-	if err := user_service.DeleteAvatar(ctx.Org.Organization.AsUser()); err != nil {
+	if err := user_service.DeleteAvatar(ctx, ctx.Org.Organization.AsUser()); err != nil {
 		ctx.Flash.Error(err.Error())
 	}
 
diff --git a/routers/web/org/teams.go b/routers/web/org/teams.go
index 98014d99a6..183b7dd266 100644
--- a/routers/web/org/teams.go
+++ b/routers/web/org/teams.go
@@ -237,7 +237,7 @@ func TeamsRepoAction(ctx *context.Context) {
 	case "add":
 		repoName := path.Base(ctx.FormString("repo_name"))
 		var repo *repo_model.Repository
-		repo, err = repo_model.GetRepositoryByName(ctx.Org.Organization.ID, repoName)
+		repo, err = repo_model.GetRepositoryByName(ctx, ctx.Org.Organization.ID, repoName)
 		if err != nil {
 			if repo_model.IsErrRepoNotExist(err) {
 				ctx.Flash.Error(ctx.Tr("org.teams.add_nonexistent_repo"))
diff --git a/routers/web/repo/branch.go b/routers/web/repo/branch.go
index e0e27fd482..bc72d5f2ec 100644
--- a/routers/web/repo/branch.go
+++ b/routers/web/repo/branch.go
@@ -37,7 +37,7 @@ const (
 func Branches(ctx *context.Context) {
 	ctx.Data["Title"] = "Branches"
 	ctx.Data["IsRepoToolbarBranches"] = true
-	ctx.Data["AllowsPulls"] = ctx.Repo.Repository.AllowsPulls()
+	ctx.Data["AllowsPulls"] = ctx.Repo.Repository.AllowsPulls(ctx)
 	ctx.Data["IsWriter"] = ctx.Repo.CanWrite(unit.TypeCode)
 	ctx.Data["IsMirror"] = ctx.Repo.Repository.IsMirror
 	ctx.Data["CanPull"] = ctx.Repo.CanWrite(unit.TypeCode) ||
diff --git a/routers/web/repo/http.go b/routers/web/repo/http.go
index 1fd784a40a..9e11d7a8c0 100644
--- a/routers/web/repo/http.go
+++ b/routers/web/repo/http.go
@@ -105,7 +105,7 @@ func httpBase(ctx *context.Context) *serviceHandler {
 	}
 
 	repoExist := true
-	repo, err := repo_model.GetRepositoryByName(owner.ID, reponame)
+	repo, err := repo_model.GetRepositoryByName(ctx, owner.ID, reponame)
 	if err != nil {
 		if repo_model.IsErrRepoNotExist(err) {
 			if redirectRepoID, err := repo_model.LookupRedirect(owner.ID, reponame); err == nil {
diff --git a/routers/web/repo/issue.go b/routers/web/repo/issue.go
index 5bee8c76a9..bb5f6e7ef5 100644
--- a/routers/web/repo/issue.go
+++ b/routers/web/repo/issue.go
@@ -495,7 +495,7 @@ func Issues(ctx *context.Context) {
 
 func renderMilestones(ctx *context.Context) {
 	// Get milestones
-	milestones, _, err := issues_model.GetMilestones(issues_model.GetMilestonesOption{
+	milestones, _, err := issues_model.GetMilestones(ctx, issues_model.GetMilestonesOption{
 		RepoID: ctx.Repo.Repository.ID,
 		State:  api.StateAll,
 	})
@@ -519,7 +519,7 @@ func renderMilestones(ctx *context.Context) {
 // RetrieveRepoMilestonesAndAssignees find all the milestones and assignees of a repository
 func RetrieveRepoMilestonesAndAssignees(ctx *context.Context, repo *repo_model.Repository) {
 	var err error
-	ctx.Data["OpenMilestones"], _, err = issues_model.GetMilestones(issues_model.GetMilestonesOption{
+	ctx.Data["OpenMilestones"], _, err = issues_model.GetMilestones(ctx, issues_model.GetMilestonesOption{
 		RepoID: repo.ID,
 		State:  api.StateOpen,
 	})
@@ -527,7 +527,7 @@ func RetrieveRepoMilestonesAndAssignees(ctx *context.Context, repo *repo_model.R
 		ctx.ServerError("GetMilestones", err)
 		return
 	}
-	ctx.Data["ClosedMilestones"], _, err = issues_model.GetMilestones(issues_model.GetMilestonesOption{
+	ctx.Data["ClosedMilestones"], _, err = issues_model.GetMilestones(ctx, issues_model.GetMilestonesOption{
 		RepoID: repo.ID,
 		State:  api.StateClosed,
 	})
@@ -1229,7 +1229,7 @@ func NewIssuePost(ctx *context.Context) {
 			ctx.Error(http.StatusBadRequest, "user hasn't permissions to read projects")
 			return
 		}
-		if err := issues_model.ChangeProjectAssign(issue, ctx.Doer, projectID); err != nil {
+		if err := issues_model.ChangeProjectAssign(ctx, issue, ctx.Doer, projectID); err != nil {
 			ctx.ServerError("ChangeProjectAssign", err)
 			return
 		}
@@ -1332,7 +1332,7 @@ func ViewIssue(ctx *context.Context) {
 		extIssueUnit, err := ctx.Repo.Repository.GetUnit(ctx, unit.TypeExternalTracker)
 		if err == nil && extIssueUnit != nil {
 			if extIssueUnit.ExternalTrackerConfig().ExternalTrackerStyle == markup.IssueNameStyleNumeric || extIssueUnit.ExternalTrackerConfig().ExternalTrackerStyle == "" {
-				metas := ctx.Repo.Repository.ComposeMetas()
+				metas := ctx.Repo.Repository.ComposeMetas(ctx)
 				metas["index"] = ctx.Params(":index")
 				res, err := vars.Expand(extIssueUnit.ExternalTrackerConfig().ExternalTrackerFormat, metas)
 				if err != nil {
@@ -1425,7 +1425,7 @@ func ViewIssue(ctx *context.Context) {
 
 	issue.RenderedContent, err = markdown.RenderString(&markup.RenderContext{
 		URLPrefix: ctx.Repo.RepoLink,
-		Metas:     ctx.Repo.Repository.ComposeMetas(),
+		Metas:     ctx.Repo.Repository.ComposeMetas(ctx),
 		GitRepo:   ctx.Repo.GitRepo,
 		Ctx:       ctx,
 	}, issue.Content)
@@ -1588,7 +1588,7 @@ func ViewIssue(ctx *context.Context) {
 
 			comment.RenderedContent, err = markdown.RenderString(&markup.RenderContext{
 				URLPrefix: ctx.Repo.RepoLink,
-				Metas:     ctx.Repo.Repository.ComposeMetas(),
+				Metas:     ctx.Repo.Repository.ComposeMetas(ctx),
 				GitRepo:   ctx.Repo.GitRepo,
 				Ctx:       ctx,
 			}, comment.Content)
@@ -1665,7 +1665,7 @@ func ViewIssue(ctx *context.Context) {
 		} else if comment.Type.HasContentSupport() {
 			comment.RenderedContent, err = markdown.RenderString(&markup.RenderContext{
 				URLPrefix: ctx.Repo.RepoLink,
-				Metas:     ctx.Repo.Repository.ComposeMetas(),
+				Metas:     ctx.Repo.Repository.ComposeMetas(ctx),
 				GitRepo:   ctx.Repo.GitRepo,
 				Ctx:       ctx,
 			}, comment.Content)
@@ -1909,7 +1909,7 @@ func ViewIssue(ctx *context.Context) {
 			if pull.HasMerged || issue.IsClosed || !ctx.IsSigned {
 				return false
 			}
-			if pull.CanAutoMerge() || pull.IsWorkInProgress() || pull.IsChecking() {
+			if pull.CanAutoMerge() || pull.IsWorkInProgress(ctx) || pull.IsChecking() {
 				return false
 			}
 			if (ctx.Doer.IsAdmin || ctx.Repo.IsAdmin()) && prConfig.AllowManualMerge {
@@ -2223,7 +2223,7 @@ func UpdateIssueContent(ctx *context.Context) {
 
 	content, err := markdown.RenderString(&markup.RenderContext{
 		URLPrefix: ctx.FormString("context"), // FIXME: <- IS THIS SAFE ?
-		Metas:     ctx.Repo.Repository.ComposeMetas(),
+		Metas:     ctx.Repo.Repository.ComposeMetas(ctx),
 		GitRepo:   ctx.Repo.GitRepo,
 		Ctx:       ctx,
 	}, issue.Content)
@@ -2286,7 +2286,7 @@ func UpdateIssueMilestone(ctx *context.Context) {
 			continue
 		}
 		issue.MilestoneID = milestoneID
-		if err := issue_service.ChangeMilestoneAssign(issue, ctx.Doer, oldMilestoneID); err != nil {
+		if err := issue_service.ChangeMilestoneAssign(ctx, issue, ctx.Doer, oldMilestoneID); err != nil {
 			ctx.ServerError("ChangeMilestoneAssign", err)
 			return
 		}
@@ -2536,7 +2536,7 @@ func SearchIssues(ctx *context.Context) {
 			allPublic = true
 			opts.AllPublic = false // set it false to avoid returning too many repos, we could filter by indexer
 		}
-		repoIDs, _, err = repo_model.SearchRepositoryIDs(opts)
+		repoIDs, _, err = repo_model.SearchRepositoryIDs(ctx, opts)
 		if err != nil {
 			ctx.Error(http.StatusInternalServerError, "SearchRepositoryIDs", err.Error())
 			return
@@ -3127,7 +3127,7 @@ func UpdateCommentContent(ctx *context.Context) {
 
 	content, err := markdown.RenderString(&markup.RenderContext{
 		URLPrefix: ctx.FormString("context"), // FIXME: <- IS THIS SAFE ?
-		Metas:     ctx.Repo.Repository.ComposeMetas(),
+		Metas:     ctx.Repo.Repository.ComposeMetas(ctx),
 		GitRepo:   ctx.Repo.GitRepo,
 		Ctx:       ctx,
 	}, comment.Content)
diff --git a/routers/web/repo/issue_dependency.go b/routers/web/repo/issue_dependency.go
index 5b9c570b74..716a02ab6c 100644
--- a/routers/web/repo/issue_dependency.go
+++ b/routers/web/repo/issue_dependency.go
@@ -72,7 +72,7 @@ func AddDependency(ctx *context.Context) {
 		return
 	}
 
-	err = issues_model.CreateIssueDependency(ctx.Doer, issue, dep)
+	err = issues_model.CreateIssueDependency(ctx, ctx.Doer, issue, dep)
 	if err != nil {
 		if issues_model.IsErrDependencyExists(err) {
 			ctx.Flash.Error(ctx.Tr("repo.issues.dependency.add_error_dep_exists"))
@@ -131,7 +131,7 @@ func RemoveDependency(ctx *context.Context) {
 		return
 	}
 
-	if err = issues_model.RemoveIssueDependency(ctx.Doer, issue, dep, depType); err != nil {
+	if err = issues_model.RemoveIssueDependency(ctx, ctx.Doer, issue, dep, depType); err != nil {
 		if issues_model.IsErrDependencyNotExists(err) {
 			ctx.Flash.Error(ctx.Tr("repo.issues.dependency.add_error_dep_not_exist"))
 			return
diff --git a/routers/web/repo/issue_lock.go b/routers/web/repo/issue_lock.go
index 93f5a588d9..f83109d9b3 100644
--- a/routers/web/repo/issue_lock.go
+++ b/routers/web/repo/issue_lock.go
@@ -29,7 +29,7 @@ func LockIssue(ctx *context.Context) {
 		return
 	}
 
-	if err := issues_model.LockIssue(&issues_model.IssueLockOptions{
+	if err := issues_model.LockIssue(ctx, &issues_model.IssueLockOptions{
 		Doer:   ctx.Doer,
 		Issue:  issue,
 		Reason: form.Reason,
@@ -53,7 +53,7 @@ func UnlockIssue(ctx *context.Context) {
 		return
 	}
 
-	if err := issues_model.UnlockIssue(&issues_model.IssueLockOptions{
+	if err := issues_model.UnlockIssue(ctx, &issues_model.IssueLockOptions{
 		Doer:  ctx.Doer,
 		Issue: issue,
 	}); err != nil {
diff --git a/routers/web/repo/milestone.go b/routers/web/repo/milestone.go
index df52ca3528..32cbc29c67 100644
--- a/routers/web/repo/milestone.go
+++ b/routers/web/repo/milestone.go
@@ -50,7 +50,7 @@ func Milestones(ctx *context.Context) {
 		state = structs.StateClosed
 	}
 
-	miles, total, err := issues_model.GetMilestones(issues_model.GetMilestonesOption{
+	miles, total, err := issues_model.GetMilestones(ctx, issues_model.GetMilestonesOption{
 		ListOptions: db.ListOptions{
 			Page:     page,
 			PageSize: setting.UI.IssuePagingNum,
@@ -82,7 +82,7 @@ func Milestones(ctx *context.Context) {
 	for _, m := range miles {
 		m.RenderedContent, err = markdown.RenderString(&markup.RenderContext{
 			URLPrefix: ctx.Repo.RepoLink,
-			Metas:     ctx.Repo.Repository.ComposeMetas(),
+			Metas:     ctx.Repo.Repository.ComposeMetas(ctx),
 			GitRepo:   ctx.Repo.GitRepo,
 			Ctx:       ctx,
 		}, m.Content)
@@ -275,7 +275,7 @@ func MilestoneIssuesAndPulls(ctx *context.Context) {
 
 	milestone.RenderedContent, err = markdown.RenderString(&markup.RenderContext{
 		URLPrefix: ctx.Repo.RepoLink,
-		Metas:     ctx.Repo.Repository.ComposeMetas(),
+		Metas:     ctx.Repo.Repository.ComposeMetas(ctx),
 		GitRepo:   ctx.Repo.GitRepo,
 		Ctx:       ctx,
 	}, milestone.Content)
diff --git a/routers/web/repo/projects.go b/routers/web/repo/projects.go
index 33bc79d96d..ada398fdc8 100644
--- a/routers/web/repo/projects.go
+++ b/routers/web/repo/projects.go
@@ -87,7 +87,7 @@ func Projects(ctx *context.Context) {
 	for i := range projects {
 		projects[i].RenderedContent, err = markdown.RenderString(&markup.RenderContext{
 			URLPrefix: ctx.Repo.RepoLink,
-			Metas:     ctx.Repo.Repository.ComposeMetas(),
+			Metas:     ctx.Repo.Repository.ComposeMetas(ctx),
 			GitRepo:   ctx.Repo.GitRepo,
 			Ctx:       ctx,
 		}, projects[i].Description)
@@ -353,7 +353,7 @@ func ViewProject(ctx *context.Context) {
 
 	project.RenderedContent, err = markdown.RenderString(&markup.RenderContext{
 		URLPrefix: ctx.Repo.RepoLink,
-		Metas:     ctx.Repo.Repository.ComposeMetas(),
+		Metas:     ctx.Repo.Repository.ComposeMetas(ctx),
 		GitRepo:   ctx.Repo.GitRepo,
 		Ctx:       ctx,
 	}, project.Description)
@@ -391,7 +391,7 @@ func UpdateIssueProject(ctx *context.Context) {
 			}
 		}
 
-		if err := issues_model.ChangeProjectAssign(issue, ctx.Doer, projectID); err != nil {
+		if err := issues_model.ChangeProjectAssign(ctx, issue, ctx.Doer, projectID); err != nil {
 			ctx.ServerError("ChangeProjectAssign", err)
 			return
 		}
diff --git a/routers/web/repo/pull.go b/routers/web/repo/pull.go
index 639c0c74d0..c8a0a04fe5 100644
--- a/routers/web/repo/pull.go
+++ b/routers/web/repo/pull.go
@@ -371,8 +371,8 @@ func setMergeTarget(ctx *context.Context, pull *issues_model.PullRequest) {
 		ctx.Data["HeadTarget"] = pull.MustHeadUserName(ctx) + "/" + pull.HeadRepo.Name + ":" + pull.HeadBranch
 	}
 	ctx.Data["BaseTarget"] = pull.BaseBranch
-	ctx.Data["HeadBranchLink"] = pull.GetHeadBranchLink()
-	ctx.Data["BaseBranchLink"] = pull.GetBaseBranchLink()
+	ctx.Data["HeadBranchLink"] = pull.GetHeadBranchLink(ctx)
+	ctx.Data["BaseBranchLink"] = pull.GetBaseBranchLink(ctx)
 }
 
 // GetPullDiffStats get Pull Requests diff stats
@@ -696,7 +696,7 @@ func PrepareViewPullInfo(ctx *context.Context, issue *issues_model.Issue) *git.C
 		ctx.Data["IsNothingToCompare"] = true
 	}
 
-	if pull.IsWorkInProgress() {
+	if pull.IsWorkInProgress(ctx) {
 		ctx.Data["IsPullWorkInProgress"] = true
 		ctx.Data["WorkInProgressPrefix"] = pull.GetWorkInProgressPrefix(ctx)
 	}
diff --git a/routers/web/repo/release.go b/routers/web/repo/release.go
index 61f1973125..5cbd6b3d51 100644
--- a/routers/web/repo/release.go
+++ b/routers/web/repo/release.go
@@ -136,7 +136,7 @@ func Releases(ctx *context.Context) {
 
 		r.Note, err = markdown.RenderString(&markup.RenderContext{
 			URLPrefix: ctx.Repo.RepoLink,
-			Metas:     ctx.Repo.Repository.ComposeMetas(),
+			Metas:     ctx.Repo.Repository.ComposeMetas(ctx),
 			GitRepo:   ctx.Repo.GitRepo,
 			Ctx:       ctx,
 		}, r.Note)
@@ -285,7 +285,7 @@ func SingleRelease(ctx *context.Context) {
 	}
 	release.Note, err = markdown.RenderString(&markup.RenderContext{
 		URLPrefix: ctx.Repo.RepoLink,
-		Metas:     ctx.Repo.Repository.ComposeMetas(),
+		Metas:     ctx.Repo.Repository.ComposeMetas(ctx),
 		GitRepo:   ctx.Repo.GitRepo,
 		Ctx:       ctx,
 	}, release.Note)
diff --git a/routers/web/repo/render.go b/routers/web/repo/render.go
index f07b4e8c11..33476c1d2c 100644
--- a/routers/web/repo/render.go
+++ b/routers/web/repo/render.go
@@ -67,7 +67,7 @@ func RenderFile(ctx *context.Context) {
 		Ctx:              ctx,
 		RelativePath:     ctx.Repo.TreePath,
 		URLPrefix:        path.Dir(treeLink),
-		Metas:            ctx.Repo.Repository.ComposeDocumentMetas(),
+		Metas:            ctx.Repo.Repository.ComposeDocumentMetas(ctx),
 		GitRepo:          ctx.Repo.GitRepo,
 		InStandalonePage: true,
 	}, rd, ctx.Resp)
diff --git a/routers/web/repo/view.go b/routers/web/repo/view.go
index 6571790627..4dfa01d8e2 100644
--- a/routers/web/repo/view.go
+++ b/routers/web/repo/view.go
@@ -312,7 +312,7 @@ func renderReadmeFile(ctx *context.Context, subfolder string, readmeFile *git.Tr
 			Ctx:          ctx,
 			RelativePath: path.Join(ctx.Repo.TreePath, readmeFile.Name()), // ctx.Repo.TreePath is the directory not the Readme so we must append the Readme filename (and path).
 			URLPrefix:    path.Join(readmeTreelink, subfolder),
-			Metas:        ctx.Repo.Repository.ComposeDocumentMetas(),
+			Metas:        ctx.Repo.Repository.ComposeDocumentMetas(ctx),
 			GitRepo:      ctx.Repo.GitRepo,
 		}, rd)
 		if err != nil {
@@ -469,7 +469,7 @@ func renderFile(ctx *context.Context, entry *git.TreeEntry, treeLink, rawLink st
 			if !detected {
 				markupType = ""
 			}
-			metas := ctx.Repo.Repository.ComposeDocumentMetas()
+			metas := ctx.Repo.Repository.ComposeDocumentMetas(ctx)
 			metas["BranchNameSubURL"] = ctx.Repo.BranchNameSubURL()
 			ctx.Data["EscapeStatus"], ctx.Data["FileContent"], err = markupRender(ctx, &markup.RenderContext{
 				Ctx:          ctx,
@@ -582,7 +582,7 @@ func renderFile(ctx *context.Context, entry *git.TreeEntry, treeLink, rawLink st
 				Ctx:          ctx,
 				RelativePath: ctx.Repo.TreePath,
 				URLPrefix:    path.Dir(treeLink),
-				Metas:        ctx.Repo.Repository.ComposeDocumentMetas(),
+				Metas:        ctx.Repo.Repository.ComposeDocumentMetas(ctx),
 				GitRepo:      ctx.Repo.GitRepo,
 			}, rd)
 			if err != nil {
@@ -879,7 +879,7 @@ func renderDirectoryFiles(ctx *context.Context, timeout time.Duration) git.Entri
 }
 
 func renderLanguageStats(ctx *context.Context) {
-	langs, err := repo_model.GetTopLanguageStats(ctx.Repo.Repository, 5)
+	langs, err := repo_model.GetTopLanguageStats(ctx, ctx.Repo.Repository, 5)
 	if err != nil {
 		ctx.ServerError("Repo.GetTopLanguageStats", err)
 		return
diff --git a/routers/web/repo/wiki.go b/routers/web/repo/wiki.go
index c9cec0313d..8ea18a186c 100644
--- a/routers/web/repo/wiki.go
+++ b/routers/web/repo/wiki.go
@@ -240,7 +240,7 @@ func renderViewPage(ctx *context.Context) (*git.Repository, *git.TreeEntry) {
 	rctx := &markup.RenderContext{
 		Ctx:       ctx,
 		URLPrefix: ctx.Repo.RepoLink,
-		Metas:     ctx.Repo.Repository.ComposeDocumentMetas(),
+		Metas:     ctx.Repo.Repository.ComposeDocumentMetas(ctx),
 		IsWiki:    true,
 	}
 	buf := &strings.Builder{}
diff --git a/routers/web/shared/user/header.go b/routers/web/shared/user/header.go
index 355f2ddeff..6d1901dd2b 100644
--- a/routers/web/shared/user/header.go
+++ b/routers/web/shared/user/header.go
@@ -85,7 +85,7 @@ func PrepareContextForProfileBigAvatar(ctx *context.Context) {
 }
 
 func FindUserProfileReadme(ctx *context.Context) (profileGitRepo *git.Repository, profileReadmeBlob *git.Blob, profileClose func()) {
-	profileDbRepo, err := repo_model.GetRepositoryByName(ctx.ContextUser.ID, ".profile")
+	profileDbRepo, err := repo_model.GetRepositoryByName(ctx, ctx.ContextUser.ID, ".profile")
 	if err == nil && !profileDbRepo.IsEmpty && !profileDbRepo.IsPrivate {
 		if profileGitRepo, err = git.OpenRepository(ctx, profileDbRepo.RepoPath()); err != nil {
 			log.Error("FindUserProfileReadme failed to OpenRepository: %v", err)
diff --git a/routers/web/user/code.go b/routers/web/user/code.go
index 42d7284189..ee514a7cfe 100644
--- a/routers/web/user/code.go
+++ b/routers/web/user/code.go
@@ -100,7 +100,7 @@ func CodeSearch(ctx *context.Context) {
 			}
 		}
 
-		repoMaps, err := repo_model.GetRepositoriesMapByIDs(loadRepoIDs)
+		repoMaps, err := repo_model.GetRepositoriesMapByIDs(ctx, loadRepoIDs)
 		if err != nil {
 			ctx.ServerError("GetRepositoriesMapByIDs", err)
 			return
diff --git a/routers/web/user/home.go b/routers/web/user/home.go
index 76b9262ead..9364ce80dc 100644
--- a/routers/web/user/home.go
+++ b/routers/web/user/home.go
@@ -247,7 +247,7 @@ func Milestones(ctx *context.Context) {
 
 		milestones[i].RenderedContent, err = markdown.RenderString(&markup.RenderContext{
 			URLPrefix: milestones[i].Repo.Link(),
-			Metas:     milestones[i].Repo.ComposeMetas(),
+			Metas:     milestones[i].Repo.ComposeMetas(ctx),
 			Ctx:       ctx,
 		}, milestones[i].Content)
 		if err != nil {
@@ -463,7 +463,7 @@ func buildIssueOverview(ctx *context.Context, unitType unit.Type) {
 	}
 	accessibleRepos := container.Set[int64]{}
 	{
-		ids, _, err := repo_model.SearchRepositoryIDs(repoOpts)
+		ids, _, err := repo_model.SearchRepositoryIDs(ctx, repoOpts)
 		if err != nil {
 			ctx.ServerError("SearchRepositoryIDs", err)
 			return
@@ -576,7 +576,7 @@ func buildIssueOverview(ctx *context.Context, unitType unit.Type) {
 	}
 
 	// showReposMap maps repository IDs to their Repository pointers.
-	showReposMap, err := loadRepoByIDs(ctxUser, issueCountByRepo, unitType)
+	showReposMap, err := loadRepoByIDs(ctx, ctxUser, issueCountByRepo, unitType)
 	if err != nil {
 		if repo_model.IsErrRepoNotExist(err) {
 			ctx.NotFound("GetRepositoryByID", err)
@@ -734,7 +734,7 @@ func getRepoIDs(reposQuery string) []int64 {
 	return repoIDs
 }
 
-func loadRepoByIDs(ctxUser *user_model.User, issueCountByRepo map[int64]int64, unitType unit.Type) (map[int64]*repo_model.Repository, error) {
+func loadRepoByIDs(ctx *context.Context, ctxUser *user_model.User, issueCountByRepo map[int64]int64, unitType unit.Type) (map[int64]*repo_model.Repository, error) {
 	totalRes := make(map[int64]*repo_model.Repository, len(issueCountByRepo))
 	repoIDs := make([]int64, 0, 500)
 	for id := range issueCountByRepo {
@@ -743,14 +743,14 @@ func loadRepoByIDs(ctxUser *user_model.User, issueCountByRepo map[int64]int64, u
 		}
 		repoIDs = append(repoIDs, id)
 		if len(repoIDs) == 500 {
-			if err := repo_model.FindReposMapByIDs(repoIDs, totalRes); err != nil {
+			if err := repo_model.FindReposMapByIDs(ctx, repoIDs, totalRes); err != nil {
 				return nil, err
 			}
 			repoIDs = repoIDs[:0]
 		}
 	}
 	if len(repoIDs) > 0 {
-		if err := repo_model.FindReposMapByIDs(repoIDs, totalRes); err != nil {
+		if err := repo_model.FindReposMapByIDs(ctx, repoIDs, totalRes); err != nil {
 			return nil, err
 		}
 	}
@@ -759,7 +759,7 @@ func loadRepoByIDs(ctxUser *user_model.User, issueCountByRepo map[int64]int64, u
 
 // ShowSSHKeys output all the ssh keys of user by uid
 func ShowSSHKeys(ctx *context.Context) {
-	keys, err := asymkey_model.ListPublicKeys(ctx.ContextUser.ID, db.ListOptions{})
+	keys, err := asymkey_model.ListPublicKeys(ctx, ctx.ContextUser.ID, db.ListOptions{})
 	if err != nil {
 		ctx.ServerError("ListPublicKeys", err)
 		return
diff --git a/routers/web/user/setting/keys.go b/routers/web/user/setting/keys.go
index 160c5ee0c0..227c1d3a75 100644
--- a/routers/web/user/setting/keys.go
+++ b/routers/web/user/setting/keys.go
@@ -168,7 +168,7 @@ func KeysPost(ctx *context.Context) {
 			return
 		}
 
-		if _, err = asymkey_model.AddPublicKey(ctx.Doer.ID, form.Title, content, 0); err != nil {
+		if _, err = asymkey_model.AddPublicKey(ctx, ctx.Doer.ID, form.Title, content, 0); err != nil {
 			ctx.Data["HasSSHError"] = true
 			switch {
 			case asymkey_model.IsErrKeyAlreadyExist(err):
@@ -231,7 +231,7 @@ func DeleteKey(ctx *context.Context) {
 		}
 	case "ssh":
 		keyID := ctx.FormInt64("id")
-		external, err := asymkey_model.PublicKeyIsExternallyManaged(keyID)
+		external, err := asymkey_model.PublicKeyIsExternallyManaged(ctx, keyID)
 		if err != nil {
 			ctx.ServerError("sshKeysExternalManaged", err)
 			return
@@ -260,14 +260,14 @@ func DeleteKey(ctx *context.Context) {
 }
 
 func loadKeysData(ctx *context.Context) {
-	keys, err := asymkey_model.ListPublicKeys(ctx.Doer.ID, db.ListOptions{})
+	keys, err := asymkey_model.ListPublicKeys(ctx, ctx.Doer.ID, db.ListOptions{})
 	if err != nil {
 		ctx.ServerError("ListPublicKeys", err)
 		return
 	}
 	ctx.Data["Keys"] = keys
 
-	externalKeys, err := asymkey_model.PublicKeysAreExternallyManaged(keys)
+	externalKeys, err := asymkey_model.PublicKeysAreExternallyManaged(ctx, keys)
 	if err != nil {
 		ctx.ServerError("ListPublicKeys", err)
 		return
diff --git a/routers/web/user/setting/profile.go b/routers/web/user/setting/profile.go
index 72e60bda58..c97e66574e 100644
--- a/routers/web/user/setting/profile.go
+++ b/routers/web/user/setting/profile.go
@@ -157,7 +157,7 @@ func UpdateAvatarSetting(ctx *context.Context, form *forms.AvatarForm, ctxUser *
 		if !(st.IsImage() && !st.IsSvgImage()) {
 			return errors.New(ctx.Tr("settings.uploaded_avatar_not_a_image"))
 		}
-		if err = user_service.UploadAvatar(ctxUser, data); err != nil {
+		if err = user_service.UploadAvatar(ctx, ctxUser, data); err != nil {
 			return fmt.Errorf("UploadAvatar: %w", err)
 		}
 	} else if ctxUser.UseCustomAvatar && ctxUser.Avatar == "" {
@@ -189,7 +189,7 @@ func AvatarPost(ctx *context.Context) {
 
 // DeleteAvatar render delete avatar page
 func DeleteAvatar(ctx *context.Context) {
-	if err := user_service.DeleteAvatar(ctx.Doer); err != nil {
+	if err := user_service.DeleteAvatar(ctx, ctx.Doer); err != nil {
 		ctx.Flash.Error(err.Error())
 	}
 
diff --git a/routers/web/user/setting/security/security.go b/routers/web/user/setting/security/security.go
index 5a17c161fe..833940d928 100644
--- a/routers/web/user/setting/security/security.go
+++ b/routers/web/user/setting/security/security.go
@@ -82,7 +82,7 @@ func loadSecurityData(ctx *context.Context) {
 	// map the provider display name with the AuthSource
 	sources := make(map[*auth_model.Source]string)
 	for _, externalAccount := range accountLinks {
-		if authSource, err := auth_model.GetSourceByID(externalAccount.LoginSourceID); err == nil {
+		if authSource, err := auth_model.GetSourceByID(ctx, externalAccount.LoginSourceID); err == nil {
 			var providerDisplayName string
 
 			type DisplayNamed interface {
diff --git a/routers/web/web.go b/routers/web/web.go
index 2154838726..d2179a0008 100644
--- a/routers/web/web.go
+++ b/routers/web/web.go
@@ -9,6 +9,7 @@ import (
 	"strings"
 
 	auth_model "code.gitea.io/gitea/models/auth"
+	"code.gitea.io/gitea/models/db"
 	"code.gitea.io/gitea/models/perm"
 	"code.gitea.io/gitea/models/unit"
 	"code.gitea.io/gitea/modules/context"
@@ -94,7 +95,7 @@ func buildAuthGroup() *auth_service.Group {
 		group.Add(&auth_service.ReverseProxy{})
 	}
 
-	if setting.IsWindows && auth_model.IsSSPIEnabled() {
+	if setting.IsWindows && auth_model.IsSSPIEnabled(db.DefaultContext) {
 		group.Add(&auth_service.SSPI{}) // it MUST be the last, see the comment of SSPI
 	}
 
diff --git a/services/actions/schedule_tasks.go b/services/actions/schedule_tasks.go
index 40b606c777..8eef2b67bd 100644
--- a/services/actions/schedule_tasks.go
+++ b/services/actions/schedule_tasks.go
@@ -45,7 +45,7 @@ func startTasks(ctx context.Context) error {
 			return fmt.Errorf("find specs: %w", err)
 		}
 
-		if err := specs.LoadRepos(); err != nil {
+		if err := specs.LoadRepos(ctx); err != nil {
 			return fmt.Errorf("LoadRepos: %w", err)
 		}
 
diff --git a/services/agit/agit.go b/services/agit/agit.go
index a39034b025..acfedf09d4 100644
--- a/services/agit/agit.go
+++ b/services/agit/agit.go
@@ -237,7 +237,7 @@ func UserNameChanged(ctx context.Context, user *user_model.User, newName string)
 	for _, pull := range pulls {
 		pull.HeadBranch = strings.TrimPrefix(pull.HeadBranch, user.LowerName+"/")
 		pull.HeadBranch = newName + "/" + pull.HeadBranch
-		if err = pull.UpdateCols("head_branch"); err != nil {
+		if err = pull.UpdateCols(ctx, "head_branch"); err != nil {
 			return err
 		}
 	}
diff --git a/services/asymkey/ssh_key.go b/services/asymkey/ssh_key.go
index 204d9c58f3..1c3bf09b08 100644
--- a/services/asymkey/ssh_key.go
+++ b/services/asymkey/ssh_key.go
@@ -13,7 +13,7 @@ import (
 
 // DeletePublicKey deletes SSH key information both in database and authorized_keys file.
 func DeletePublicKey(ctx context.Context, doer *user_model.User, id int64) (err error) {
-	key, err := asymkey_model.GetPublicKeyByID(id)
+	key, err := asymkey_model.GetPublicKeyByID(ctx, id)
 	if err != nil {
 		return err
 	}
diff --git a/services/asymkey/ssh_key_test.go b/services/asymkey/ssh_key_test.go
index 2395b2dadf..3a39a9a1db 100644
--- a/services/asymkey/ssh_key_test.go
+++ b/services/asymkey/ssh_key_test.go
@@ -66,8 +66,8 @@ ssh-dss AAAAB3NzaC1kc3MAAACBAOChCC7lf6Uo9n7BmZ6M8St19PZf4Tn59NriyboW2x/DZuYAz3ib
 
 	for i, kase := range testCases {
 		s.ID = int64(i) + 20
-		asymkey_model.AddPublicKeysBySource(user, s, []string{kase.keyString})
-		keys, err := asymkey_model.ListPublicKeysBySource(user.ID, s.ID)
+		asymkey_model.AddPublicKeysBySource(db.DefaultContext, user, s, []string{kase.keyString})
+		keys, err := asymkey_model.ListPublicKeysBySource(db.DefaultContext, user.ID, s.ID)
 		assert.NoError(t, err)
 		if err != nil {
 			continue
diff --git a/services/auth/httpsign.go b/services/auth/httpsign.go
index d6a64c6fc4..d5c8ea33aa 100644
--- a/services/auth/httpsign.go
+++ b/services/auth/httpsign.go
@@ -92,7 +92,7 @@ func VerifyPubKey(r *http.Request) (*asymkey_model.PublicKey, error) {
 
 	keyID := verifier.KeyId()
 
-	publicKeys, err := asymkey_model.SearchPublicKey(0, keyID)
+	publicKeys, err := asymkey_model.SearchPublicKey(r.Context(), 0, keyID)
 	if err != nil {
 		return nil, err
 	}
diff --git a/services/auth/signin.go b/services/auth/signin.go
index 6d515ac628..5fdf6d2bd7 100644
--- a/services/auth/signin.go
+++ b/services/auth/signin.go
@@ -56,7 +56,7 @@ func UserSignIn(ctx context.Context, username, password string) (*user_model.Use
 		}
 
 		if hasUser {
-			source, err := auth.GetSourceByID(user.LoginSource)
+			source, err := auth.GetSourceByID(ctx, user.LoginSource)
 			if err != nil {
 				return nil, nil, err
 			}
@@ -85,7 +85,7 @@ func UserSignIn(ctx context.Context, username, password string) (*user_model.Use
 		}
 	}
 
-	sources, err := auth.AllActiveSources()
+	sources, err := auth.AllActiveSources(ctx)
 	if err != nil {
 		return nil, nil, err
 	}
diff --git a/services/auth/source/ldap/source_authenticate.go b/services/auth/source/ldap/source_authenticate.go
index 9f4d7ed68f..a7ea61b81c 100644
--- a/services/auth/source/ldap/source_authenticate.go
+++ b/services/auth/source/ldap/source_authenticate.go
@@ -70,7 +70,7 @@ func (source *Source) Authenticate(ctx context.Context, user *user_model.User, u
 	}
 
 	if user != nil {
-		if isAttributeSSHPublicKeySet && asymkey_model.SynchronizePublicKeys(user, source.authSource, sr.SSHPublicKey) {
+		if isAttributeSSHPublicKeySet && asymkey_model.SynchronizePublicKeys(ctx, user, source.authSource, sr.SSHPublicKey) {
 			if err := asymkey_model.RewriteAllPublicKeys(ctx); err != nil {
 				return user, err
 			}
@@ -96,13 +96,13 @@ func (source *Source) Authenticate(ctx context.Context, user *user_model.User, u
 			return user, err
 		}
 
-		if isAttributeSSHPublicKeySet && asymkey_model.AddPublicKeysBySource(user, source.authSource, sr.SSHPublicKey) {
+		if isAttributeSSHPublicKeySet && asymkey_model.AddPublicKeysBySource(ctx, user, source.authSource, sr.SSHPublicKey) {
 			if err := asymkey_model.RewriteAllPublicKeys(ctx); err != nil {
 				return user, err
 			}
 		}
 		if len(source.AttributeAvatar) > 0 {
-			if err := user_service.UploadAvatar(user, sr.Avatar); err != nil {
+			if err := user_service.UploadAvatar(ctx, user, sr.Avatar); err != nil {
 				return user, err
 			}
 		}
diff --git a/services/auth/source/ldap/source_sync.go b/services/auth/source/ldap/source_sync.go
index 261f2b8a95..5c65ca8dc2 100644
--- a/services/auth/source/ldap/source_sync.go
+++ b/services/auth/source/ldap/source_sync.go
@@ -135,17 +135,17 @@ func (source *Source) Sync(ctx context.Context, updateExisting bool) error {
 
 			if err == nil && isAttributeSSHPublicKeySet {
 				log.Trace("SyncExternalUsers[%s]: Adding LDAP Public SSH Keys for user %s", source.authSource.Name, usr.Name)
-				if asymkey_model.AddPublicKeysBySource(usr, source.authSource, su.SSHPublicKey) {
+				if asymkey_model.AddPublicKeysBySource(ctx, usr, source.authSource, su.SSHPublicKey) {
 					sshKeysNeedUpdate = true
 				}
 			}
 
 			if err == nil && len(source.AttributeAvatar) > 0 {
-				_ = user_service.UploadAvatar(usr, su.Avatar)
+				_ = user_service.UploadAvatar(ctx, usr, su.Avatar)
 			}
 		} else if updateExisting {
 			// Synchronize SSH Public Key if that attribute is set
-			if isAttributeSSHPublicKeySet && asymkey_model.SynchronizePublicKeys(usr, source.authSource, su.SSHPublicKey) {
+			if isAttributeSSHPublicKeySet && asymkey_model.SynchronizePublicKeys(ctx, usr, source.authSource, su.SSHPublicKey) {
 				sshKeysNeedUpdate = true
 			}
 
@@ -179,7 +179,7 @@ func (source *Source) Sync(ctx context.Context, updateExisting bool) error {
 
 			if usr.IsUploadAvatarChanged(su.Avatar) {
 				if err == nil && len(source.AttributeAvatar) > 0 {
-					_ = user_service.UploadAvatar(usr, su.Avatar)
+					_ = user_service.UploadAvatar(ctx, usr, su.Avatar)
 				}
 			}
 		}
diff --git a/services/auth/sspi.go b/services/auth/sspi.go
index d4f7e3ec60..573d94b42c 100644
--- a/services/auth/sspi.go
+++ b/services/auth/sspi.go
@@ -67,7 +67,7 @@ func (s *SSPI) Verify(req *http.Request, w http.ResponseWriter, store DataStore,
 		return nil, nil
 	}
 
-	cfg, err := s.getConfig()
+	cfg, err := s.getConfig(req.Context())
 	if err != nil {
 		log.Error("could not get SSPI config: %v", err)
 		return nil, err
@@ -129,8 +129,8 @@ func (s *SSPI) Verify(req *http.Request, w http.ResponseWriter, store DataStore,
 }
 
 // getConfig retrieves the SSPI configuration from login sources
-func (s *SSPI) getConfig() (*sspi.Source, error) {
-	sources, err := auth.ActiveSources(auth.SSPI)
+func (s *SSPI) getConfig(ctx context.Context) (*sspi.Source, error) {
+	sources, err := auth.ActiveSources(ctx, auth.SSPI)
 	if err != nil {
 		return nil, err
 	}
diff --git a/services/auth/sync.go b/services/auth/sync.go
index e42e8a51a7..25b9460b99 100644
--- a/services/auth/sync.go
+++ b/services/auth/sync.go
@@ -15,7 +15,7 @@ import (
 func SyncExternalUsers(ctx context.Context, updateExisting bool) error {
 	log.Trace("Doing: SyncExternalUsers")
 
-	ls, err := auth.Sources()
+	ls, err := auth.Sources(ctx)
 	if err != nil {
 		log.Error("SyncExternalUsers: %v", err)
 		return err
diff --git a/services/convert/pull.go b/services/convert/pull.go
index e4e3097056..7eebe20426 100644
--- a/services/convert/pull.go
+++ b/services/convert/pull.go
@@ -68,7 +68,7 @@ func ToAPIPullRequest(ctx context.Context, pr *issues_model.PullRequest, doer *u
 		PatchURL:  pr.Issue.PatchURL(),
 		HasMerged: pr.HasMerged,
 		MergeBase: pr.MergeBase,
-		Mergeable: pr.Mergeable(),
+		Mergeable: pr.Mergeable(ctx),
 		Deadline:  apiIssue.Deadline,
 		Created:   pr.Issue.CreatedUnix.AsTimePtr(),
 		Updated:   pr.Issue.UpdatedUnix.AsTimePtr(),
diff --git a/services/issue/issue_test.go b/services/issue/issue_test.go
index 1f6a77096e..8806cec0e7 100644
--- a/services/issue/issue_test.go
+++ b/services/issue/issue_test.go
@@ -72,7 +72,7 @@ func TestIssue_DeleteIssue(t *testing.T) {
 	assert.NoError(t, err)
 	issue2, err := issues_model.GetIssueByID(db.DefaultContext, 2)
 	assert.NoError(t, err)
-	err = issues_model.CreateIssueDependency(user, issue1, issue2)
+	err = issues_model.CreateIssueDependency(db.DefaultContext, user, issue1, issue2)
 	assert.NoError(t, err)
 	left, err := issues_model.IssueNoDependenciesLeft(db.DefaultContext, issue1)
 	assert.NoError(t, err)
diff --git a/services/issue/label.go b/services/issue/label.go
index 91f0308d9f..6b8070d8aa 100644
--- a/services/issue/label.go
+++ b/services/issue/label.go
@@ -15,7 +15,7 @@ import (
 
 // ClearLabels clears all of an issue's labels
 func ClearLabels(ctx context.Context, issue *issues_model.Issue, doer *user_model.User) error {
-	if err := issues_model.ClearIssueLabels(issue, doer); err != nil {
+	if err := issues_model.ClearIssueLabels(ctx, issue, doer); err != nil {
 		return err
 	}
 
@@ -26,7 +26,7 @@ func ClearLabels(ctx context.Context, issue *issues_model.Issue, doer *user_mode
 
 // AddLabel adds a new label to the issue.
 func AddLabel(ctx context.Context, issue *issues_model.Issue, doer *user_model.User, label *issues_model.Label) error {
-	if err := issues_model.NewIssueLabel(issue, label, doer); err != nil {
+	if err := issues_model.NewIssueLabel(ctx, issue, label, doer); err != nil {
 		return err
 	}
 
@@ -36,7 +36,7 @@ func AddLabel(ctx context.Context, issue *issues_model.Issue, doer *user_model.U
 
 // AddLabels adds a list of new labels to the issue.
 func AddLabels(ctx context.Context, issue *issues_model.Issue, doer *user_model.User, labels []*issues_model.Label) error {
-	if err := issues_model.NewIssueLabels(issue, labels, doer); err != nil {
+	if err := issues_model.NewIssueLabels(ctx, issue, labels, doer); err != nil {
 		return err
 	}
 
@@ -86,7 +86,7 @@ func ReplaceLabels(ctx context.Context, issue *issues_model.Issue, doer *user_mo
 		return err
 	}
 
-	if err := issues_model.ReplaceIssueLabels(issue, labels, doer); err != nil {
+	if err := issues_model.ReplaceIssueLabels(ctx, issue, labels, doer); err != nil {
 		return err
 	}
 
diff --git a/services/issue/milestone.go b/services/issue/milestone.go
index 5a07cfd2e5..ff645744a7 100644
--- a/services/issue/milestone.go
+++ b/services/issue/milestone.go
@@ -63,14 +63,14 @@ func changeMilestoneAssign(ctx context.Context, doer *user_model.User, issue *is
 }
 
 // ChangeMilestoneAssign changes assignment of milestone for issue.
-func ChangeMilestoneAssign(issue *issues_model.Issue, doer *user_model.User, oldMilestoneID int64) (err error) {
-	ctx, committer, err := db.TxContext(db.DefaultContext)
+func ChangeMilestoneAssign(ctx context.Context, issue *issues_model.Issue, doer *user_model.User, oldMilestoneID int64) (err error) {
+	dbCtx, committer, err := db.TxContext(ctx)
 	if err != nil {
 		return err
 	}
 	defer committer.Close()
 
-	if err = changeMilestoneAssign(ctx, doer, issue, oldMilestoneID); err != nil {
+	if err = changeMilestoneAssign(dbCtx, doer, issue, oldMilestoneID); err != nil {
 		return err
 	}
 
@@ -78,7 +78,7 @@ func ChangeMilestoneAssign(issue *issues_model.Issue, doer *user_model.User, old
 		return fmt.Errorf("Commit: %w", err)
 	}
 
-	notify_service.IssueChangeMilestone(db.DefaultContext, doer, issue, oldMilestoneID)
+	notify_service.IssueChangeMilestone(ctx, doer, issue, oldMilestoneID)
 
 	return nil
 }
diff --git a/services/issue/milestone_test.go b/services/issue/milestone_test.go
index 069117d1f1..42b910166f 100644
--- a/services/issue/milestone_test.go
+++ b/services/issue/milestone_test.go
@@ -6,6 +6,7 @@ package issue
 import (
 	"testing"
 
+	"code.gitea.io/gitea/models/db"
 	issues_model "code.gitea.io/gitea/models/issues"
 	"code.gitea.io/gitea/models/unittest"
 	user_model "code.gitea.io/gitea/models/user"
@@ -22,7 +23,7 @@ func TestChangeMilestoneAssign(t *testing.T) {
 
 	oldMilestoneID := issue.MilestoneID
 	issue.MilestoneID = 2
-	assert.NoError(t, ChangeMilestoneAssign(issue, doer, oldMilestoneID))
+	assert.NoError(t, ChangeMilestoneAssign(db.DefaultContext, issue, doer, oldMilestoneID))
 	unittest.AssertExistsAndLoadBean(t, &issues_model.Comment{
 		IssueID:        issue.ID,
 		Type:           issues_model.CommentTypeMilestone,
diff --git a/services/mailer/mail.go b/services/mailer/mail.go
index 50d59a4452..0210128046 100644
--- a/services/mailer/mail.go
+++ b/services/mailer/mail.go
@@ -235,7 +235,7 @@ func composeIssueCommentMessages(ctx *mailCommentContext, lang string, recipient
 	body, err := markdown.RenderString(&markup.RenderContext{
 		Ctx:       ctx,
 		URLPrefix: ctx.Issue.Repo.HTMLURL(),
-		Metas:     ctx.Issue.Repo.ComposeMetas(),
+		Metas:     ctx.Issue.Repo.ComposeMetas(ctx),
 	}, ctx.Content)
 	if err != nil {
 		return nil, err
diff --git a/services/mailer/mail_issue.go b/services/mailer/mail_issue.go
index be5279aac5..baa9f1d9ab 100644
--- a/services/mailer/mail_issue.go
+++ b/services/mailer/mail_issue.go
@@ -82,7 +82,7 @@ func mailIssueCommentToParticipants(ctx *mailCommentContext, mentions []*user_mo
 
 	// =========== Repo watchers ===========
 	// Make repo watchers last, since it's likely the list with the most users
-	if !(ctx.Issue.IsPull && ctx.Issue.PullRequest.IsWorkInProgress() && ctx.ActionType != activities_model.ActionCreatePullRequest) {
+	if !(ctx.Issue.IsPull && ctx.Issue.PullRequest.IsWorkInProgress(ctx) && ctx.ActionType != activities_model.ActionCreatePullRequest) {
 		ids, err = repo_model.GetRepoWatchersIDs(ctx, ctx.Issue.RepoID)
 		if err != nil {
 			return fmt.Errorf("GetRepoWatchersIDs(%d): %w", ctx.Issue.RepoID, err)
diff --git a/services/mailer/mail_release.go b/services/mailer/mail_release.go
index fb638ebd42..7bc3db3fe6 100644
--- a/services/mailer/mail_release.go
+++ b/services/mailer/mail_release.go
@@ -60,7 +60,7 @@ func mailNewRelease(ctx context.Context, lang string, tos []string, rel *repo_mo
 	rel.RenderedNote, err = markdown.RenderString(&markup.RenderContext{
 		Ctx:       ctx,
 		URLPrefix: rel.Repo.Link(),
-		Metas:     rel.Repo.ComposeMetas(),
+		Metas:     rel.Repo.ComposeMetas(ctx),
 	}, rel.Note)
 	if err != nil {
 		log.Error("markdown.RenderString(%d): %v", rel.RepoID, err)
diff --git a/services/mailer/notify.go b/services/mailer/notify.go
index 9eaf268d0a..cc4e6baf0b 100644
--- a/services/mailer/notify.go
+++ b/services/mailer/notify.go
@@ -79,7 +79,7 @@ func (m *mailNotifier) IssueChangeTitle(ctx context.Context, doer *user_model.Us
 		log.Error("issue.LoadPullRequest: %v", err)
 		return
 	}
-	if issue.IsPull && issues_model.HasWorkInProgressPrefix(oldTitle) && !issue.PullRequest.IsWorkInProgress() {
+	if issue.IsPull && issues_model.HasWorkInProgressPrefix(oldTitle) && !issue.PullRequest.IsWorkInProgress(ctx) {
 		if err := MailParticipants(ctx, issue, doer, activities_model.ActionPullRequestReadyForReview, nil); err != nil {
 			log.Error("MailParticipants: %v", err)
 		}
diff --git a/services/migrations/gitea_uploader.go b/services/migrations/gitea_uploader.go
index ebf22e0e40..36b5e15298 100644
--- a/services/migrations/gitea_uploader.go
+++ b/services/migrations/gitea_uploader.go
@@ -840,7 +840,7 @@ func (g *GiteaLocalUploader) CreateReviews(reviews ...*base.Review) error {
 		pr, ok := g.prCache[issue.ID]
 		if !ok {
 			var err error
-			pr, err = issues_model.GetPullRequestByIssueIDWithNoAttributes(issue.ID)
+			pr, err = issues_model.GetPullRequestByIssueIDWithNoAttributes(g.ctx, issue.ID)
 			if err != nil {
 				return err
 			}
diff --git a/services/migrations/gitea_uploader_test.go b/services/migrations/gitea_uploader_test.go
index 4c6dfddc08..847e76d9b1 100644
--- a/services/migrations/gitea_uploader_test.go
+++ b/services/migrations/gitea_uploader_test.go
@@ -65,14 +65,14 @@ func TestGiteaUploadRepo(t *testing.T) {
 	assert.True(t, repo.HasWiki())
 	assert.EqualValues(t, repo_model.RepositoryReady, repo.Status)
 
-	milestones, _, err := issues_model.GetMilestones(issues_model.GetMilestonesOption{
+	milestones, _, err := issues_model.GetMilestones(db.DefaultContext, issues_model.GetMilestonesOption{
 		RepoID: repo.ID,
 		State:  structs.StateOpen,
 	})
 	assert.NoError(t, err)
 	assert.Len(t, milestones, 1)
 
-	milestones, _, err = issues_model.GetMilestones(issues_model.GetMilestonesOption{
+	milestones, _, err = issues_model.GetMilestones(db.DefaultContext, issues_model.GetMilestonesOption{
 		RepoID: repo.ID,
 		State:  structs.StateClosed,
 	})
diff --git a/services/pull/check.go b/services/pull/check.go
index e4a0f6b27b..b51b58f480 100644
--- a/services/pull/check.go
+++ b/services/pull/check.go
@@ -91,7 +91,7 @@ func CheckPullMergable(stdCtx context.Context, doer *user_model.User, perm *acce
 			return nil
 		}
 
-		if pr.IsWorkInProgress() {
+		if pr.IsWorkInProgress(ctx) {
 			return ErrIsWorkInProgress
 		}
 
@@ -360,7 +360,7 @@ func testPR(id int64) {
 	if err := TestPatch(pr); err != nil {
 		log.Error("testPatch[%-v]: %v", pr, err)
 		pr.Status = issues_model.PullRequestStatusError
-		if err := pr.UpdateCols("status"); err != nil {
+		if err := pr.UpdateCols(ctx, "status"); err != nil {
 			log.Error("update pr [%-v] status to PullRequestStatusError failed: %v", pr, err)
 		}
 		return
diff --git a/services/pull/pull.go b/services/pull/pull.go
index 8ef7499ad5..e4096f8ac4 100644
--- a/services/pull/pull.go
+++ b/services/pull/pull.go
@@ -125,7 +125,7 @@ func NewPullRequest(ctx context.Context, repo *repo_model.Repository, issue *iss
 			return err
 		}
 
-		if !pr.IsWorkInProgress() {
+		if !pr.IsWorkInProgress(ctx) {
 			if err := issues_model.PullRequestCodeOwnersReview(ctx, issue, pr); err != nil {
 				return err
 			}
diff --git a/services/repository/archiver/archiver.go b/services/repository/archiver/archiver.go
index f6f03e75ae..9f1ea48dca 100644
--- a/services/repository/archiver/archiver.go
+++ b/services/repository/archiver/archiver.go
@@ -172,8 +172,8 @@ func (aReq *ArchiveRequest) Await(ctx context.Context) (*repo_model.RepoArchiver
 	}
 }
 
-func doArchive(r *ArchiveRequest) (*repo_model.RepoArchiver, error) {
-	txCtx, committer, err := db.TxContext(db.DefaultContext)
+func doArchive(ctx context.Context, r *ArchiveRequest) (*repo_model.RepoArchiver, error) {
+	txCtx, committer, err := db.TxContext(ctx)
 	if err != nil {
 		return nil, err
 	}
@@ -291,18 +291,18 @@ func doArchive(r *ArchiveRequest) (*repo_model.RepoArchiver, error) {
 // anything.  In all cases, the caller should be examining the *ArchiveRequest
 // being returned for completion, as it may be different than the one they passed
 // in.
-func ArchiveRepository(request *ArchiveRequest) (*repo_model.RepoArchiver, error) {
-	return doArchive(request)
+func ArchiveRepository(ctx context.Context, request *ArchiveRequest) (*repo_model.RepoArchiver, error) {
+	return doArchive(ctx, request)
 }
 
 var archiverQueue *queue.WorkerPoolQueue[*ArchiveRequest]
 
 // Init initializes archiver
-func Init() error {
+func Init(ctx context.Context) error {
 	handler := func(items ...*ArchiveRequest) []*ArchiveRequest {
 		for _, archiveReq := range items {
 			log.Trace("ArchiverData Process: %#v", archiveReq)
-			if _, err := doArchive(archiveReq); err != nil {
+			if _, err := doArchive(ctx, archiveReq); err != nil {
 				log.Error("Archive %v failed: %v", archiveReq, err)
 			}
 		}
diff --git a/services/repository/archiver/archiver_test.go b/services/repository/archiver/archiver_test.go
index ff8bb8ca7a..5deec259da 100644
--- a/services/repository/archiver/archiver_test.go
+++ b/services/repository/archiver/archiver_test.go
@@ -8,6 +8,7 @@ import (
 	"testing"
 	"time"
 
+	"code.gitea.io/gitea/models/db"
 	"code.gitea.io/gitea/models/unittest"
 	"code.gitea.io/gitea/modules/contexttest"
 
@@ -79,13 +80,13 @@ func TestArchive_Basic(t *testing.T) {
 	inFlight[1] = tgzReq
 	inFlight[2] = secondReq
 
-	ArchiveRepository(zipReq)
-	ArchiveRepository(tgzReq)
-	ArchiveRepository(secondReq)
+	ArchiveRepository(db.DefaultContext, zipReq)
+	ArchiveRepository(db.DefaultContext, tgzReq)
+	ArchiveRepository(db.DefaultContext, secondReq)
 
 	// Make sure sending an unprocessed request through doesn't affect the queue
 	// count.
-	ArchiveRepository(zipReq)
+	ArchiveRepository(db.DefaultContext, zipReq)
 
 	// Sleep two seconds to make sure the queue doesn't change.
 	time.Sleep(2 * time.Second)
@@ -100,7 +101,7 @@ func TestArchive_Basic(t *testing.T) {
 	// We still have the other three stalled at completion, waiting to remove
 	// from archiveInProgress.  Try to submit this new one before its
 	// predecessor has cleared out of the queue.
-	ArchiveRepository(zipReq2)
+	ArchiveRepository(db.DefaultContext, zipReq2)
 
 	// Now we'll submit a request and TimedWaitForCompletion twice, before and
 	// after we release it.  We should trigger both the timeout and non-timeout
@@ -108,7 +109,7 @@ func TestArchive_Basic(t *testing.T) {
 	timedReq, err := NewRequest(ctx.Repo.Repository.ID, ctx.Repo.GitRepo, secondCommit+".tar.gz")
 	assert.NoError(t, err)
 	assert.NotNil(t, timedReq)
-	ArchiveRepository(timedReq)
+	ArchiveRepository(db.DefaultContext, timedReq)
 
 	zipReq2, err = NewRequest(ctx.Repo.Repository.ID, ctx.Repo.GitRepo, firstCommit+".zip")
 	assert.NoError(t, err)
diff --git a/services/repository/branch.go b/services/repository/branch.go
index 3351252200..735fa1a756 100644
--- a/services/repository/branch.go
+++ b/services/repository/branch.go
@@ -161,7 +161,7 @@ func loadOneBranch(ctx context.Context, repo *repo_model.Repository, dbBranch *g
 		}
 	}
 
-	pr, err := issues_model.GetLatestPullRequestByHeadInfo(repo.ID, branchName)
+	pr, err := issues_model.GetLatestPullRequestByHeadInfo(ctx, repo.ID, branchName)
 	if err != nil {
 		return nil, fmt.Errorf("GetLatestPullRequestByHeadInfo: %v", err)
 	}
diff --git a/services/repository/fork.go b/services/repository/fork.go
index d5ab42badd..851a69c80f 100644
--- a/services/repository/fork.go
+++ b/services/repository/fork.go
@@ -185,7 +185,7 @@ func ForkRepository(ctx context.Context, doer, owner *user_model.User, opts Fork
 	if err := repo_module.UpdateRepoSize(ctx, repo); err != nil {
 		log.Error("Failed to update size for repository: %v", err)
 	}
-	if err := repo_model.CopyLanguageStat(opts.BaseRepo, repo); err != nil {
+	if err := repo_model.CopyLanguageStat(ctx, opts.BaseRepo, repo); err != nil {
 		log.Error("Copy language stat from oldRepo failed: %v", err)
 	}
 
diff --git a/services/uinotification/notify.go b/services/uinotification/notify.go
index 9230d1ee6c..be5f7019a2 100644
--- a/services/uinotification/notify.go
+++ b/services/uinotification/notify.go
@@ -114,7 +114,7 @@ func (ns *notificationService) IssueChangeTitle(ctx context.Context, doer *user_
 		log.Error("issue.LoadPullRequest: %v", err)
 		return
 	}
-	if issue.IsPull && issues_model.HasWorkInProgressPrefix(oldTitle) && !issue.PullRequest.IsWorkInProgress() {
+	if issue.IsPull && issues_model.HasWorkInProgressPrefix(oldTitle) && !issue.PullRequest.IsWorkInProgress(ctx) {
 		_ = ns.issueQueue.Push(issueNotificationOpts{
 			IssueID:              issue.ID,
 			NotificationAuthorID: doer.ID,
diff --git a/services/user/avatar.go b/services/user/avatar.go
index 26c100abdb..4130d07c38 100644
--- a/services/user/avatar.go
+++ b/services/user/avatar.go
@@ -4,6 +4,7 @@
 package user
 
 import (
+	"context"
 	"fmt"
 	"io"
 
@@ -15,13 +16,13 @@ import (
 )
 
 // UploadAvatar saves custom avatar for user.
-func UploadAvatar(u *user_model.User, data []byte) error {
+func UploadAvatar(ctx context.Context, u *user_model.User, data []byte) error {
 	avatarData, err := avatar.ProcessAvatarImage(data)
 	if err != nil {
 		return err
 	}
 
-	ctx, committer, err := db.TxContext(db.DefaultContext)
+	ctx, committer, err := db.TxContext(ctx)
 	if err != nil {
 		return err
 	}
@@ -44,7 +45,7 @@ func UploadAvatar(u *user_model.User, data []byte) error {
 }
 
 // DeleteAvatar deletes the user's custom avatar.
-func DeleteAvatar(u *user_model.User) error {
+func DeleteAvatar(ctx context.Context, u *user_model.User) error {
 	aPath := u.CustomAvatarRelativePath()
 	log.Trace("DeleteAvatar[%d]: %s", u.ID, aPath)
 	if len(u.Avatar) > 0 {
@@ -55,7 +56,7 @@ func DeleteAvatar(u *user_model.User) error {
 
 	u.UseCustomAvatar = false
 	u.Avatar = ""
-	if _, err := db.GetEngine(db.DefaultContext).ID(u.ID).Cols("avatar, use_custom_avatar").Update(u); err != nil {
+	if _, err := db.GetEngine(ctx).ID(u.ID).Cols("avatar, use_custom_avatar").Update(u); err != nil {
 		return fmt.Errorf("UpdateUser: %w", err)
 	}
 	return nil
diff --git a/services/user/user.go b/services/user/user.go
index 53cc361107..b95a7e0639 100644
--- a/services/user/user.go
+++ b/services/user/user.go
@@ -223,7 +223,7 @@ func DeleteUser(ctx context.Context, u *user_model.User, purge bool) error {
 		}
 	}
 
-	ctx, committer, err := db.TxContext(db.DefaultContext)
+	ctx, committer, err := db.TxContext(ctx)
 	if err != nil {
 		return err
 	}
diff --git a/templates/repo/branch/list.tmpl b/templates/repo/branch/list.tmpl
index 370a412efb..cec5b6fc3e 100644
--- a/templates/repo/branch/list.tmpl
+++ b/templates/repo/branch/list.tmpl
@@ -25,7 +25,7 @@
 									<button class="btn interact-fg gt-px-2" data-clipboard-text="{{.DefaultBranchBranch.DBBranch.Name}}">{{svg "octicon-copy" 14}}</button>
 									{{template "repo/commit_statuses" dict "Status" (index $.CommitStatus .DefaultBranchBranch.DBBranch.CommitID) "Statuses" (index $.CommitStatuses .DefaultBranchBranch.DBBranch.CommitID)}}
 								</div>
-								<p class="info gt-df gt-ac gt-my-2">{{svg "octicon-git-commit" 16 "gt-mr-2"}}<a href="{{.RepoLink}}/commit/{{PathEscape .DefaultBranchBranch.DBBranch.CommitID}}">{{ShortSha .DefaultBranchBranch.DBBranch.CommitID}}</a> · <span class="commit-message">{{RenderCommitMessage $.Context .DefaultBranchBranch.DBBranch.CommitMessage .RepoLink .Repository.ComposeMetas}}</span> · {{ctx.Locale.Tr "org.repo_updated"}} {{TimeSince .DefaultBranchBranch.DBBranch.CommitTime.AsTime ctx.Locale}}{{if .DefaultBranchBranch.DBBranch.Pusher}} &nbsp;{{template "shared/user/avatarlink" dict "user" .DefaultBranchBranch.DBBranch.Pusher}}{{template "shared/user/namelink" .DefaultBranchBranch.DBBranch.Pusher}}{{end}}</p>
+								<p class="info gt-df gt-ac gt-my-2">{{svg "octicon-git-commit" 16 "gt-mr-2"}}<a href="{{.RepoLink}}/commit/{{PathEscape .DefaultBranchBranch.DBBranch.CommitID}}">{{ShortSha .DefaultBranchBranch.DBBranch.CommitID}}</a> · <span class="commit-message">{{RenderCommitMessage $.Context .DefaultBranchBranch.DBBranch.CommitMessage .RepoLink (.Repository.ComposeMetas ctx)}}</span> · {{ctx.Locale.Tr "org.repo_updated"}} {{TimeSince .DefaultBranchBranch.DBBranch.CommitTime.AsTime ctx.Locale}}{{if .DefaultBranchBranch.DBBranch.Pusher}} &nbsp;{{template "shared/user/avatarlink" dict "user" .DefaultBranchBranch.DBBranch.Pusher}}{{template "shared/user/namelink" .DefaultBranchBranch.DBBranch.Pusher}}{{end}}</p>
 							</td>
 							<td class="right aligned middle aligned overflow-visible">
 								{{if and $.IsWriter (not $.Repository.IsArchived) (not .IsDeleted)}}
@@ -101,7 +101,7 @@
 										<button class="btn interact-fg gt-px-2" data-clipboard-text="{{.DBBranch.Name}}">{{svg "octicon-copy" 14}}</button>
 										{{template "repo/commit_statuses" dict "Status" (index $.CommitStatus .DBBranch.CommitID) "Statuses" (index $.CommitStatuses .DBBranch.CommitID)}}
 									</div>
-									<p class="info gt-df gt-ac gt-my-2">{{svg "octicon-git-commit" 16 "gt-mr-2"}}<a href="{{$.RepoLink}}/commit/{{PathEscape .DBBranch.CommitID}}">{{ShortSha .DBBranch.CommitID}}</a> · <span class="commit-message">{{RenderCommitMessage $.Context .DBBranch.CommitMessage $.RepoLink $.Repository.ComposeMetas}}</span> · {{ctx.Locale.Tr "org.repo_updated"}} {{TimeSince .DBBranch.CommitTime.AsTime ctx.Locale}}{{if .DBBranch.Pusher}} &nbsp;{{template "shared/user/avatarlink" dict "user" .DBBranch.Pusher}} &nbsp;{{template "shared/user/namelink" .DBBranch.Pusher}}{{end}}</p>
+									<p class="info gt-df gt-ac gt-my-2">{{svg "octicon-git-commit" 16 "gt-mr-2"}}<a href="{{$.RepoLink}}/commit/{{PathEscape .DBBranch.CommitID}}">{{ShortSha .DBBranch.CommitID}}</a> · <span class="commit-message">{{RenderCommitMessage $.Context .DBBranch.CommitMessage $.RepoLink ($.Repository.ComposeMetas ctx)}}</span> · {{ctx.Locale.Tr "org.repo_updated"}} {{TimeSince .DBBranch.CommitTime.AsTime ctx.Locale}}{{if .DBBranch.Pusher}} &nbsp;{{template "shared/user/avatarlink" dict "user" .DBBranch.Pusher}} &nbsp;{{template "shared/user/namelink" .DBBranch.Pusher}}{{end}}</p>
 								{{end}}
 								</td>
 								<td class="two wide ui">
diff --git a/templates/repo/commit_page.tmpl b/templates/repo/commit_page.tmpl
index e0a63f3041..c0dfc6e0ad 100644
--- a/templates/repo/commit_page.tmpl
+++ b/templates/repo/commit_page.tmpl
@@ -19,7 +19,7 @@
 		{{end}}
 		<div class="ui top attached header clearing segment gt-relative commit-header {{$class}}">
 			<div class="gt-df gt-mb-4 gt-fw">
-				<h3 class="gt-mb-0 gt-f1"><span class="commit-summary" title="{{.Commit.Summary}}">{{RenderCommitMessage $.Context .Commit.Message $.RepoLink $.Repository.ComposeMetas}}</span>{{template "repo/commit_statuses" dict "Status" .CommitStatus "Statuses" .CommitStatuses "root" $}}</h3>
+				<h3 class="gt-mb-0 gt-f1"><span class="commit-summary" title="{{.Commit.Summary}}">{{RenderCommitMessage $.Context .Commit.Message $.RepoLink ($.Repository.ComposeMetas ctx)}}</span>{{template "repo/commit_statuses" dict "Status" .CommitStatus "Statuses" .CommitStatuses "root" $}}</h3>
 				{{if not $.PageIsWiki}}
 					<div>
 						<a class="ui primary tiny button" href="{{.SourcePath}}">
@@ -135,7 +135,7 @@
 				{{end}}
 			</div>
 			{{if IsMultilineCommitMessage .Commit.Message}}
-				<pre class="commit-body">{{RenderCommitBody $.Context .Commit.Message $.RepoLink $.Repository.ComposeMetas}}</pre>
+				<pre class="commit-body">{{RenderCommitBody $.Context .Commit.Message $.RepoLink ($.Repository.ComposeMetas ctx)}}</pre>
 			{{end}}
 			{{template "repo/commit_load_branches_and_tags" .}}
 		</div>
@@ -276,7 +276,7 @@
 				<span class="text grey" id="note-authored-time">{{TimeSince .NoteCommit.Author.When ctx.Locale}}</span>
 			</div>
 			<div class="ui bottom attached info segment git-notes">
-				<pre class="commit-body">{{RenderNote $.Context .Note $.RepoLink $.Repository.ComposeMetas}}</pre>
+				<pre class="commit-body">{{RenderNote $.Context .Note $.RepoLink ($.Repository.ComposeMetas ctx)}}</pre>
 			</div>
 		{{end}}
 		{{template "repo/diff/box" .}}
diff --git a/templates/repo/commits_list.tmpl b/templates/repo/commits_list.tmpl
index d071fb90a1..cdb893f51f 100644
--- a/templates/repo/commits_list.tmpl
+++ b/templates/repo/commits_list.tmpl
@@ -60,7 +60,7 @@
 								<span class="commit-summary {{if gt .ParentCount 1}} grey text{{end}}" title="{{.Summary}}">{{.Summary | RenderEmoji $.Context}}</span>
 							{{else}}
 								{{$commitLink:= printf "%s/commit/%s" $commitRepoLink (PathEscape .ID.String)}}
-								<span class="commit-summary {{if gt .ParentCount 1}} grey text{{end}}" title="{{.Summary}}">{{RenderCommitMessageLinkSubject $.Context .Message $commitRepoLink $commitLink $.Repository.ComposeMetas}}</span>
+								<span class="commit-summary {{if gt .ParentCount 1}} grey text{{end}}" title="{{.Summary}}">{{RenderCommitMessageLinkSubject $.Context .Message $commitRepoLink $commitLink ($.Repository.ComposeMetas ctx)}}</span>
 							{{end}}
 							</span>
 							{{if IsMultilineCommitMessage .Message}}
@@ -68,7 +68,7 @@
 							{{end}}
 							{{template "repo/commit_statuses" dict "Status" .Status "Statuses" .Statuses "root" $}}
 							{{if IsMultilineCommitMessage .Message}}
-							<pre class="commit-body gt-hidden">{{RenderCommitBody $.Context .Message $commitRepoLink $.Repository.ComposeMetas}}</pre>
+							<pre class="commit-body gt-hidden">{{RenderCommitBody $.Context .Message $commitRepoLink ($.Repository.ComposeMetas ctx)}}</pre>
 							{{end}}
 						</td>
 						{{if .Committer}}
diff --git a/templates/repo/commits_list_small.tmpl b/templates/repo/commits_list_small.tmpl
index 645bd73bb8..5b715a71d4 100644
--- a/templates/repo/commits_list_small.tmpl
+++ b/templates/repo/commits_list_small.tmpl
@@ -38,12 +38,12 @@
 			</a>
 		</span>
 
-		<span class="gt-mono commit-summary {{if gt .ParentCount 1}} grey text{{end}}" title="{{.Summary}}">{{RenderCommitMessageLinkSubject $.root.Context .Message ($.comment.Issue.PullRequest.BaseRepo.Link|Escape) $commitLink $.comment.Issue.PullRequest.BaseRepo.ComposeMetas}}</span>
+		<span class="gt-mono commit-summary {{if gt .ParentCount 1}} grey text{{end}}" title="{{.Summary}}">{{RenderCommitMessageLinkSubject $.root.Context .Message ($.comment.Issue.PullRequest.BaseRepo.Link|Escape) $commitLink ($.comment.Issue.PullRequest.BaseRepo.ComposeMetas ctx)}}</span>
 		{{if IsMultilineCommitMessage .Message}}
 			<button class="ui button js-toggle-commit-body ellipsis-button" aria-expanded="false">...</button>
 		{{end}}
 		{{if IsMultilineCommitMessage .Message}}
-			<pre class="commit-body gt-hidden">{{RenderCommitBody $.root.Context .Message ($.comment.Issue.PullRequest.BaseRepo.Link|Escape) $.comment.Issue.PullRequest.BaseRepo.ComposeMetas}}</pre>
+			<pre class="commit-body gt-hidden">{{RenderCommitBody $.root.Context .Message ($.comment.Issue.PullRequest.BaseRepo.Link|Escape) ($.comment.Issue.PullRequest.BaseRepo.ComposeMetas ctx)}}</pre>
 		{{end}}
 	</div>
 {{end}}
diff --git a/templates/repo/diff/compare.tmpl b/templates/repo/diff/compare.tmpl
index ebeae39222..4ebf34ea84 100644
--- a/templates/repo/diff/compare.tmpl
+++ b/templates/repo/diff/compare.tmpl
@@ -77,7 +77,7 @@
 							<div class="item" data-url="{{$.OwnForkRepo.Link}}/compare/{{PathEscapeSegments .}}{{$.CompareSeparator}}{{PathEscape $.HeadUser.Name}}/{{PathEscape $.HeadRepo.Name}}:{{PathEscapeSegments $.HeadBranch}}">{{$OwnForkCompareName}}:{{.}}</div>
 						{{end}}
 					{{end}}
-					{{if and .RootRepo .RootRepo.AllowsPulls}}
+					{{if and .RootRepo (.RootRepo.AllowsPulls ctx)}}
 						{{range .RootRepoBranches}}
 							<div class="item" data-url="{{$.RootRepo.Link}}/compare/{{PathEscapeSegments .}}{{$.CompareSeparator}}{{PathEscape $.HeadUser.Name}}/{{PathEscape $.HeadRepo.Name}}:{{PathEscapeSegments $.HeadBranch}}">{{$RootRepoCompareName}}:{{.}}</div>
 						{{end}}
@@ -194,7 +194,7 @@
 				<div class="twelve wide column issue-title">
 					{{ctx.Locale.Tr "repo.pulls.has_pull_request" (print (Escape $.RepoLink) "/pulls/" .PullRequest.Issue.Index) (Escape $.RepoRelPath) .PullRequest.Index | Safe}}
 					<h1>
-						<span id="issue-title">{{RenderIssueTitle $.Context .PullRequest.Issue.Title $.RepoLink $.Repository.ComposeMetas}}</span>
+						<span id="issue-title">{{RenderIssueTitle $.Context .PullRequest.Issue.Title $.RepoLink ($.Repository.ComposeMetas ctx)}}</span>
 						<span class="index">#{{.PullRequest.Issue.Index}}</span>
 					</h1>
 				</div>
diff --git a/templates/repo/graph/commits.tmpl b/templates/repo/graph/commits.tmpl
index b8817f5c88..3c63046c6c 100644
--- a/templates/repo/graph/commits.tmpl
+++ b/templates/repo/graph/commits.tmpl
@@ -29,7 +29,7 @@
 						</a>
 					</span>
 					<span class="message gt-dib gt-ellipsis gt-mr-3">
-						<span>{{RenderCommitMessage $.Context $commit.Subject $.RepoLink $.Repository.ComposeMetas}}</span>
+						<span>{{RenderCommitMessage $.Context $commit.Subject $.RepoLink ($.Repository.ComposeMetas ctx)}}</span>
 					</span>
 					<span class="commit-refs gt-df gt-ac gt-mr-2">
 						{{range $commit.Refs}}
diff --git a/templates/repo/header.tmpl b/templates/repo/header.tmpl
index 5d4bc64734..2eb9014cdd 100644
--- a/templates/repo/header.tmpl
+++ b/templates/repo/header.tmpl
@@ -40,7 +40,7 @@
 					<div class="fork-flag">{{ctx.Locale.Tr "repo.mirror_from"}} <a target="_blank" rel="noopener noreferrer" href="{{$.PullMirror.RemoteAddress}}">{{$.PullMirror.RemoteAddress}}</a></div>
 				{{end}}
 				{{if .IsFork}}<div class="fork-flag">{{ctx.Locale.Tr "repo.forked_from"}} <a href="{{.BaseRepo.Link}}">{{.BaseRepo.FullName}}</a></div>{{end}}
-				{{if .IsGenerated}}<div class="fork-flag">{{ctx.Locale.Tr "repo.generated_from"}} <a href="{{.TemplateRepo.Link}}">{{.TemplateRepo.FullName}}</a></div>{{end}}
+				{{if .IsGenerated}}<div class="fork-flag">{{ctx.Locale.Tr "repo.generated_from"}} <a href="{{(.TemplateRepo ctx).Link}}">{{(.TemplateRepo ctx).FullName}}</a></div>{{end}}
 			</div>
 			{{if not (or .IsBeingCreated .IsBroken)}}
 				<div class="repo-buttons">
diff --git a/templates/repo/icon.tmpl b/templates/repo/icon.tmpl
index 0568b74f63..8ad9a77b19 100644
--- a/templates/repo/icon.tmpl
+++ b/templates/repo/icon.tmpl
@@ -1,4 +1,4 @@
-{{$avatarLink := .RelAvatarLink}}
+{{$avatarLink := (.RelAvatarLink ctx)}}
 {{if $avatarLink}}
 	<img class="ui avatar gt-vm" src="{{$avatarLink}}" width="32" height="32" alt="{{.FullName}}">
 {{else if $.IsTemplate}}
diff --git a/templates/repo/issue/view_content/pull.tmpl b/templates/repo/issue/view_content/pull.tmpl
index 409af3a5d5..a4f7ede74d 100644
--- a/templates/repo/issue/view_content/pull.tmpl
+++ b/templates/repo/issue/view_content/pull.tmpl
@@ -189,7 +189,7 @@
 
 				{{if .AllowMerge}} {{/* user is allowed to merge */}}
 					{{$prUnit := .Repository.MustGetUnit $.Context $.UnitTypePullRequests}}
-					{{$approvers := .Issue.PullRequest.GetApprovers}}
+					{{$approvers := (.Issue.PullRequest.GetApprovers ctx)}}
 					{{if or $prUnit.PullRequestsConfig.AllowMerge $prUnit.PullRequestsConfig.AllowRebase $prUnit.PullRequestsConfig.AllowRebaseMerge $prUnit.PullRequestsConfig.AllowSquash}}
 						{{$hasPendingPullRequestMergeTip := ""}}
 						{{if .HasPendingPullRequestMerge}}
diff --git a/templates/repo/issue/view_title.tmpl b/templates/repo/issue/view_title.tmpl
index c18825f204..d2c48ff275 100644
--- a/templates/repo/issue/view_title.tmpl
+++ b/templates/repo/issue/view_title.tmpl
@@ -6,7 +6,7 @@
 <div class="issue-title-header">
 	<div class="issue-title" id="issue-title-wrapper">
 		<h1 class="gt-word-break">
-			<span id="issue-title">{{RenderIssueTitle $.Context .Issue.Title $.RepoLink $.Repository.ComposeMetas | RenderCodeBlock}} <span class="index">#{{.Issue.Index}}</span>
+			<span id="issue-title">{{RenderIssueTitle $.Context .Issue.Title $.RepoLink ($.Repository.ComposeMetas ctx) | RenderCodeBlock}} <span class="index">#{{.Issue.Index}}</span>
 </span>
 			<div id="edit-title-input" class="ui input gt-f1 gt-hidden">
 				<input value="{{.Issue.Title}}" maxlength="255" autocomplete="off">
diff --git a/templates/repo/view_list.tmpl b/templates/repo/view_list.tmpl
index bfd59839f5..7e60f27291 100644
--- a/templates/repo/view_list.tmpl
+++ b/templates/repo/view_list.tmpl
@@ -26,10 +26,10 @@
 					</a>
 					{{template "repo/commit_statuses" dict "Status" .LatestCommitStatus "Statuses" .LatestCommitStatuses "root" $}}
 					{{$commitLink:= printf "%s/commit/%s" .RepoLink (PathEscape .LatestCommit.ID.String)}}
-					<span class="grey commit-summary" title="{{.LatestCommit.Summary}}"><span class="message-wrapper">{{RenderCommitMessageLinkSubject $.Context .LatestCommit.Message $.RepoLink $commitLink $.Repository.ComposeMetas}}</span>
+					<span class="grey commit-summary" title="{{.LatestCommit.Summary}}"><span class="message-wrapper">{{RenderCommitMessageLinkSubject $.Context .LatestCommit.Message $.RepoLink $commitLink ($.Repository.ComposeMetas ctx)}}</span>
 						{{if IsMultilineCommitMessage .LatestCommit.Message}}
 							<button class="ui button js-toggle-commit-body ellipsis-button" aria-expanded="false">...</button>
-							<pre class="commit-body gt-hidden">{{RenderCommitBody $.Context .LatestCommit.Message $.RepoLink $.Repository.ComposeMetas}}</pre>
+							<pre class="commit-body gt-hidden">{{RenderCommitBody $.Context .LatestCommit.Message $.RepoLink ($.Repository.ComposeMetas ctx)}}</pre>
 						{{end}}
 					</span>
 				{{end}}
@@ -83,7 +83,7 @@
 					<span class="truncate">
 						{{if $commit}}
 							{{$commitLink := printf "%s/commit/%s" $.RepoLink (PathEscape $commit.ID.String)}}
-							{{RenderCommitMessageLinkSubject $.Context $commit.Message $.RepoLink $commitLink $.Repository.ComposeMetas}}
+							{{RenderCommitMessageLinkSubject $.Context $commit.Message $.RepoLink $commitLink ($.Repository.ComposeMetas ctx)}}
 						{{else}}
 							<div class="ui active tiny slow centered inline">…</div>
 						{{end}}
diff --git a/templates/shared/issueicon.tmpl b/templates/shared/issueicon.tmpl
index 6e1c654818..089e80bd8b 100644
--- a/templates/shared/issueicon.tmpl
+++ b/templates/shared/issueicon.tmpl
@@ -7,9 +7,9 @@
 		{{if .IsClosed}}
 			{{svg "octicon-git-pull-request" 16 "text red"}}
 		{{else}}
-			{{if and .PullRequest .PullRequest.IsWorkInProgress}}
+			{{if and .PullRequest (.PullRequest.IsWorkInProgress ctx)}}
 				{{svg "octicon-git-pull-request-draft" 16 "text grey"}}
-			{{else if and (.GetPullRequest ctx) (.GetPullRequest ctx).IsWorkInProgress}}
+			{{else if and (.GetPullRequest ctx) ((.GetPullRequest ctx).IsWorkInProgress ctx)}}
 				{{svg "octicon-git-pull-request-draft" 16 "text grey"}}
 			{{else}}
 				{{svg "octicon-git-pull-request" 16 "text green"}}
diff --git a/templates/user/dashboard/feeds.tmpl b/templates/user/dashboard/feeds.tmpl
index c986dcfb44..7a2c4c7815 100644
--- a/templates/user/dashboard/feeds.tmpl
+++ b/templates/user/dashboard/feeds.tmpl
@@ -90,7 +90,7 @@
 								<img class="ui avatar" src="{{$push.AvatarLink $.Context .AuthorEmail}}" title="{{.AuthorName}}" width="16" height="16">
 								<a class="ui sha label" href="{{$commitLink}}">{{ShortSha .Sha1}}</a>
 								<span class="text truncate">
-									{{RenderCommitMessage $.Context .Message $repoLink $.ComposeMetas}}
+									{{RenderCommitMessage $.Context .Message $repoLink ($.ComposeMetas ctx)}}
 								</span>
 							</div>
 						{{end}}
diff --git a/tests/integration/auth_ldap_test.go b/tests/integration/auth_ldap_test.go
index ac4c41bf4d..dbd3bc9346 100644
--- a/tests/integration/auth_ldap_test.go
+++ b/tests/integration/auth_ldap_test.go
@@ -332,7 +332,7 @@ func TestLDAPUserSyncWithGroupFilter(t *testing.T) {
 	})
 	ldapConfig := ldapSource.Cfg.(*ldap.Source)
 	ldapConfig.GroupFilter = "(cn=ship_crew)"
-	auth_model.UpdateSource(ldapSource)
+	auth_model.UpdateSource(db.DefaultContext, ldapSource)
 
 	auth.SyncExternalUsers(context.Background(), true)
 
diff --git a/tests/integration/pull_merge_test.go b/tests/integration/pull_merge_test.go
index adb0e982c0..f94809e4b3 100644
--- a/tests/integration/pull_merge_test.go
+++ b/tests/integration/pull_merge_test.go
@@ -425,6 +425,6 @@ func TestConflictChecking(t *testing.T) {
 		// Check if status is correct.
 		assert.Equal(t, issues_model.PullRequestStatusConflict, conflictingPR.Status)
 		// Ensure that mergeable returns false
-		assert.False(t, conflictingPR.Mergeable())
+		assert.False(t, conflictingPR.Mergeable(db.DefaultContext))
 	})
 }