1
1
mirror of https://github.com/go-gitea/gitea synced 2025-09-13 12:18:13 +00:00

Use db.WithTx/WithTx2 instead of TxContext when possible (#35428)

This commit is contained in:
Lunny Xiao
2025-09-09 20:15:01 -07:00
committed by GitHub
parent fb247f640e
commit e35e724e42
13 changed files with 601 additions and 694 deletions

View File

@@ -72,12 +72,7 @@ func AddGPGKey(ctx context.Context, ownerID int64, content, token, signature str
return nil, err return nil, err
} }
ctx, committer, err := db.TxContext(ctx) return db.WithTx2(ctx, func(ctx context.Context) ([]*GPGKey, error) {
if err != nil {
return nil, err
}
defer committer.Close()
keys := make([]*GPGKey, 0, len(ekeys)) keys := make([]*GPGKey, 0, len(ekeys))
verified := false verified := false
@@ -151,8 +146,6 @@ func AddGPGKey(ctx context.Context, ownerID int64, content, token, signature str
return nil, ErrGPGKeyIDAlreadyUsed{ekey.PrimaryKey.KeyIdString()} return nil, ErrGPGKeyIDAlreadyUsed{ekey.PrimaryKey.KeyIdString()}
} }
// Get DB session
key, err := parseGPGKey(ctx, ownerID, ekey, verified) key, err := parseGPGKey(ctx, ownerID, ekey, verified)
if err != nil { if err != nil {
return nil, err return nil, err
@@ -163,5 +156,6 @@ func AddGPGKey(ctx context.Context, ownerID int64, content, token, signature str
} }
keys = append(keys, key) keys = append(keys, key)
} }
return keys, committer.Commit() return keys, nil
})
} }

View File

@@ -334,12 +334,7 @@ func FindRenamedBranch(ctx context.Context, repoID int64, from string) (branch *
// RenameBranch rename a branch // RenameBranch rename a branch
func RenameBranch(ctx context.Context, repo *repo_model.Repository, from, to string, gitAction func(ctx context.Context, isDefault bool) error) (err error) { func RenameBranch(ctx context.Context, repo *repo_model.Repository, from, to string, gitAction func(ctx context.Context, isDefault bool) error) (err error) {
ctx, committer, err := db.TxContext(ctx) return db.WithTx(ctx, func(ctx context.Context) error {
if err != nil {
return err
}
defer committer.Close()
sess := db.GetEngine(ctx) sess := db.GetEngine(ctx)
// check whether from branch exist // check whether from branch exist
@@ -403,8 +398,7 @@ func RenameBranch(ctx context.Context, repo *repo_model.Repository, from, to str
if protectedBranch != nil { if protectedBranch != nil {
// there is a protect rule for this branch // there is a protect rule for this branch
protectedBranch.RuleName = to protectedBranch.RuleName = to
_, err = sess.ID(protectedBranch.ID).Cols("branch_name").Update(protectedBranch) if _, err = sess.ID(protectedBranch.ID).Cols("branch_name").Update(protectedBranch); err != nil {
if err != nil {
return err return err
} }
} else { } else {
@@ -434,22 +428,17 @@ func RenameBranch(ctx context.Context, repo *repo_model.Repository, from, to str
} }
// 5. insert renamed branch record // 5. insert renamed branch record
renamedBranch := &RenamedBranch{ if err = db.Insert(ctx, &RenamedBranch{
RepoID: repo.ID, RepoID: repo.ID,
From: from, From: from,
To: to, To: to,
} }); err != nil {
err = db.Insert(ctx, renamedBranch)
if err != nil {
return err return err
} }
// 6. do git action // 6. do git action
if err = gitAction(ctx, isDefault); err != nil { return gitAction(ctx, isDefault)
return err })
}
return committer.Commit()
} }
type FindRecentlyPushedNewBranchesOptions struct { type FindRecentlyPushedNewBranchesOptions struct {

View File

@@ -180,12 +180,7 @@ func RemoveLFSMetaObjectByOidFn(ctx context.Context, repoID int64, oid string, f
return 0, ErrLFSObjectNotExist return 0, ErrLFSObjectNotExist
} }
ctx, committer, err := db.TxContext(ctx) return db.WithTx2(ctx, func(ctx context.Context) (int64, error) {
if err != nil {
return 0, err
}
defer committer.Close()
m := &LFSMetaObject{Pointer: lfs.Pointer{Oid: oid}, RepositoryID: repoID} m := &LFSMetaObject{Pointer: lfs.Pointer{Oid: oid}, RepositoryID: repoID}
if _, err := db.DeleteByBean(ctx, m); err != nil { if _, err := db.DeleteByBean(ctx, m); err != nil {
return -1, err return -1, err
@@ -202,7 +197,8 @@ func RemoveLFSMetaObjectByOidFn(ctx context.Context, repoID int64, oid string, f
} }
} }
return count, committer.Commit() return count, nil
})
} }
// GetLFSMetaObjects returns all LFSMetaObjects associated with a repository // GetLFSMetaObjects returns all LFSMetaObjects associated with a repository
@@ -243,14 +239,7 @@ func ExistsLFSObject(ctx context.Context, oid string) (bool, error) {
// LFSAutoAssociate auto associates accessible LFSMetaObjects // LFSAutoAssociate auto associates accessible LFSMetaObjects
func LFSAutoAssociate(ctx context.Context, metas []*LFSMetaObject, user *user_model.User, repoID int64) error { func LFSAutoAssociate(ctx context.Context, metas []*LFSMetaObject, user *user_model.User, repoID int64) error {
ctx, committer, err := db.TxContext(ctx) return db.WithTx(ctx, func(ctx context.Context) error {
if err != nil {
return err
}
defer committer.Close()
sess := db.GetEngine(ctx)
oids := make([]any, len(metas)) oids := make([]any, len(metas))
oidMap := make(map[string]*LFSMetaObject, len(metas)) oidMap := make(map[string]*LFSMetaObject, len(metas))
for i, meta := range metas { for i, meta := range metas {
@@ -264,8 +253,7 @@ func LFSAutoAssociate(ctx context.Context, metas []*LFSMetaObject, user *user_mo
"`lfs_meta_object`.repository_id", "`lfs_meta_object`.repository_id",
builder.Select("`repository`.id").From("repository").Where(repo_model.AccessibleRepositoryCondition(user, unit.TypeInvalid)), builder.Select("`repository`.id").From("repository").Where(repo_model.AccessibleRepositoryCondition(user, unit.TypeInvalid)),
) )
err = sess.Cols("oid").Where(cond).In("oid", oids...).GroupBy("oid").Find(&newMetas) if err := db.GetEngine(ctx).Cols("oid").Where(cond).In("oid", oids...).GroupBy("oid").Find(&newMetas); err != nil {
if err != nil {
return err return err
} }
if len(newMetas) != len(oidMap) { if len(newMetas) != len(oidMap) {
@@ -275,24 +263,22 @@ func LFSAutoAssociate(ctx context.Context, metas []*LFSMetaObject, user *user_mo
newMetas[i].Size = oidMap[newMetas[i].Oid].Size newMetas[i].Size = oidMap[newMetas[i].Oid].Size
newMetas[i].RepositoryID = repoID newMetas[i].RepositoryID = repoID
} }
if err = db.Insert(ctx, newMetas); err != nil { return db.Insert(ctx, newMetas)
return err
} }
} else {
// admin can associate any LFS object to any repository, and we do not care about errors (eg: duplicated unique key), // admin can associate any LFS object to any repository, and we do not care about errors (eg: duplicated unique key),
// even if error occurs, it won't hurt users and won't make things worse // even if error occurs, it won't hurt users and won't make things worse
for i := range metas { for i := range metas {
p := lfs.Pointer{Oid: metas[i].Oid, Size: metas[i].Size} p := lfs.Pointer{Oid: metas[i].Oid, Size: metas[i].Size}
_, err = sess.Insert(&LFSMetaObject{ if err := db.Insert(ctx, &LFSMetaObject{
Pointer: p, Pointer: p,
RepositoryID: repoID, RepositoryID: repoID,
}) }); err != nil {
if err != nil {
log.Warn("failed to insert LFS meta object %-v for repo_id: %d into database, err=%v", p, repoID, err) log.Warn("failed to insert LFS meta object %-v for repo_id: %d into database, err=%v", p, repoID, err)
} }
} }
} return nil
return committer.Commit() })
} }
// CopyLFS copies LFS data from one repo to another // CopyLFS copies LFS data from one repo to another

View File

@@ -91,18 +91,10 @@ func GetAssignedIssues(ctx context.Context, opts *AssignedIssuesOptions) ([]*Iss
// ToggleIssueAssignee changes a user between assigned and not assigned for this issue, and make issue comment for it. // ToggleIssueAssignee changes a user between assigned and not assigned for this issue, and make issue comment for it.
func ToggleIssueAssignee(ctx context.Context, issue *Issue, doer *user_model.User, assigneeID int64) (removed bool, comment *Comment, err error) { func ToggleIssueAssignee(ctx context.Context, issue *Issue, doer *user_model.User, assigneeID int64) (removed bool, comment *Comment, err error) {
ctx, committer, err := db.TxContext(ctx) if err := db.WithTx(ctx, func(ctx context.Context) error {
if err != nil {
return false, nil, err
}
defer committer.Close()
removed, comment, err = toggleIssueAssignee(ctx, issue, doer, assigneeID, false) removed, comment, err = toggleIssueAssignee(ctx, issue, doer, assigneeID, false)
if err != nil { return err
return false, nil, err }); err != nil {
}
if err := committer.Commit(); err != nil {
return false, nil, err return false, nil, err
} }

View File

@@ -415,12 +415,7 @@ func NewIssueWithIndex(ctx context.Context, doer *user_model.User, opts NewIssue
// NewIssue creates new issue with labels for repository. // NewIssue creates new issue with labels for repository.
// The title will be cut off at 255 characters if it's longer than 255 characters. // The title will be cut off at 255 characters if it's longer than 255 characters.
func NewIssue(ctx context.Context, repo *repo_model.Repository, issue *Issue, labelIDs []int64, uuids []string) (err error) { func NewIssue(ctx context.Context, repo *repo_model.Repository, issue *Issue, labelIDs []int64, uuids []string) (err error) {
ctx, committer, err := db.TxContext(ctx) return db.WithTx(ctx, func(ctx context.Context) error {
if err != nil {
return err
}
defer committer.Close()
idx, err := db.GetNextResourceIndex(ctx, "issue_index", repo.ID) idx, err := db.GetNextResourceIndex(ctx, "issue_index", repo.ID)
if err != nil { if err != nil {
return fmt.Errorf("generate issue index failed: %w", err) return fmt.Errorf("generate issue index failed: %w", err)
@@ -440,12 +435,8 @@ func NewIssue(ctx context.Context, repo *repo_model.Repository, issue *Issue, la
} }
return fmt.Errorf("newIssue: %w", err) return fmt.Errorf("newIssue: %w", err)
} }
if err = committer.Commit(); err != nil {
return fmt.Errorf("Commit: %w", err)
}
return nil return nil
})
} }
// UpdateIssueMentions updates issue-user relations for mentioned users. // UpdateIssueMentions updates issue-user relations for mentioned users.

View File

@@ -442,12 +442,7 @@ func SearchEmails(ctx context.Context, opts *SearchEmailOptions) ([]*SearchEmail
// ActivateUserEmail will change the activated state of an email address, // ActivateUserEmail will change the activated state of an email address,
// either primary or secondary (all in the email_address table) // either primary or secondary (all in the email_address table)
func ActivateUserEmail(ctx context.Context, userID int64, email string, activate bool) (err error) { func ActivateUserEmail(ctx context.Context, userID int64, email string, activate bool) (err error) {
ctx, committer, err := db.TxContext(ctx) return db.WithTx(ctx, func(ctx context.Context) error {
if err != nil {
return err
}
defer committer.Close()
// Activate/deactivate a user's secondary email address // Activate/deactivate a user's secondary email address
// First check if there's another user active with the same address // First check if there's another user active with the same address
addr, exist, err := db.Get[EmailAddress](ctx, builder.Eq{"uid": userID, "lower_email": strings.ToLower(email)}) addr, exist, err := db.Get[EmailAddress](ctx, builder.Eq{"uid": userID, "lower_email": strings.ToLower(email)})
@@ -492,8 +487,8 @@ func ActivateUserEmail(ctx context.Context, userID int64, email string, activate
} }
} }
} }
return nil
return committer.Commit() })
} }
// validateEmailBasic checks whether the email complies with the rules // validateEmailBasic checks whether the email complies with the rules

View File

@@ -716,12 +716,7 @@ func createUser(ctx context.Context, u *User, meta *Meta, createdByAdmin bool, o
} }
} }
ctx, committer, err := db.TxContext(ctx) return db.WithTx(ctx, func(ctx context.Context) error {
if err != nil {
return err
}
defer committer.Close()
isExist, err := IsUserExist(ctx, 0, u.Name) isExist, err := IsUserExist(ctx, 0, u.Name)
if err != nil { if err != nil {
return err return err
@@ -789,17 +784,14 @@ func createUser(ctx context.Context, u *User, meta *Meta, createdByAdmin bool, o
} }
// insert email address // insert email address
if err := db.Insert(ctx, &EmailAddress{ return db.Insert(ctx, &EmailAddress{
UID: u.ID, UID: u.ID,
Email: u.Email, Email: u.Email,
LowerEmail: strings.ToLower(u.Email), LowerEmail: strings.ToLower(u.Email),
IsActivated: u.IsActive, IsActivated: u.IsActive,
IsPrimary: true, IsPrimary: true,
}); err != nil { })
return err })
}
return committer.Commit()
} }
// ErrDeleteLastAdminUser represents a "DeleteLastAdminUser" kind of error. // ErrDeleteLastAdminUser represents a "DeleteLastAdminUser" kind of error.

View File

@@ -261,12 +261,7 @@ func GetRefEndNamesAndURLs(issues []*issues_model.Issue, repoLink string) (map[i
// deleteIssue deletes the issue // deleteIssue deletes the issue
func deleteIssue(ctx context.Context, issue *issues_model.Issue) ([]string, error) { func deleteIssue(ctx context.Context, issue *issues_model.Issue) ([]string, error) {
ctx, committer, err := db.TxContext(ctx) return db.WithTx2(ctx, func(ctx context.Context) ([]string, error) {
if err != nil {
return nil, err
}
defer committer.Close()
if _, err := db.GetEngine(ctx).ID(issue.ID).NoAutoCondition().Delete(issue); err != nil { if _, err := db.GetEngine(ctx).ID(issue.ID).NoAutoCondition().Delete(issue); err != nil {
return nil, err return nil, err
} }
@@ -325,10 +320,8 @@ func deleteIssue(ctx context.Context, issue *issues_model.Issue) ([]string, erro
return nil, err return nil, err
} }
if err := committer.Commit(); err != nil {
return nil, err
}
return attachmentPaths, nil return attachmentPaths, nil
})
} }
// DeleteOrphanedIssues delete issues without a repo // DeleteOrphanedIssues delete issues without a repo

View File

@@ -52,12 +52,7 @@ func deleteOrganization(ctx context.Context, org *org_model.Organization) error
// DeleteOrganization completely and permanently deletes everything of organization. // DeleteOrganization completely and permanently deletes everything of organization.
func DeleteOrganization(ctx context.Context, org *org_model.Organization, purge bool) error { func DeleteOrganization(ctx context.Context, org *org_model.Organization, purge bool) error {
ctx, committer, err := db.TxContext(ctx) if err := db.WithTx(ctx, func(ctx context.Context) error {
if err != nil {
return err
}
defer committer.Close()
if purge { if purge {
err := repo_service.DeleteOwnerRepositoriesDirectly(ctx, org.AsUser()) err := repo_service.DeleteOwnerRepositoriesDirectly(ctx, org.AsUser())
if err != nil { if err != nil {
@@ -83,8 +78,8 @@ func DeleteOrganization(ctx context.Context, org *org_model.Organization, purge
if err := deleteOrganization(ctx, org); err != nil { if err := deleteOrganization(ctx, org); err != nil {
return fmt.Errorf("DeleteOrganization: %w", err) return fmt.Errorf("DeleteOrganization: %w", err)
} }
return nil
if err := committer.Commit(); err != nil { }); err != nil {
return err return err
} }

View File

@@ -47,12 +47,7 @@ func RemoveOrgUser(ctx context.Context, org *organization.Organization, user *us
} }
} }
ctx, committer, err := db.TxContext(ctx) return db.WithTx(ctx, func(ctx context.Context) error {
if err != nil {
return err
}
defer committer.Close()
if _, err := db.DeleteByID[organization.OrgUser](ctx, ou.ID); err != nil { if _, err := db.DeleteByID[organization.OrgUser](ctx, ou.ID); err != nil {
return err return err
} else if _, err = db.Exec(ctx, "UPDATE `user` SET num_members=num_members-1 WHERE id=?", org.ID); err != nil { } else if _, err = db.Exec(ctx, "UPDATE `user` SET num_members=num_members-1 WHERE id=?", org.ID); err != nil {
@@ -98,6 +93,6 @@ func RemoveOrgUser(ctx context.Context, org *organization.Organization, user *us
return err return err
} }
} }
return nil
return committer.Commit() })
} }

View File

@@ -267,18 +267,13 @@ func UpdateRelease(ctx context.Context, doer *user_model.User, gitRepo *git.Repo
} }
rel.LowerTagName = strings.ToLower(rel.TagName) rel.LowerTagName = strings.ToLower(rel.TagName)
ctx, committer, err := db.TxContext(ctx)
if err != nil {
return err
}
defer committer.Close()
oldRelease, err := repo_model.GetReleaseByID(ctx, rel.ID) oldRelease, err := repo_model.GetReleaseByID(ctx, rel.ID)
if err != nil { if err != nil {
return err return err
} }
isConvertedFromTag := oldRelease.IsTag && !rel.IsTag isConvertedFromTag := oldRelease.IsTag && !rel.IsTag
if err := db.WithTx(ctx, func(ctx context.Context) error {
if err = repo_model.UpdateRelease(ctx, rel); err != nil { if err = repo_model.UpdateRelease(ctx, rel); err != nil {
return err return err
} }
@@ -333,8 +328,8 @@ func UpdateRelease(ctx context.Context, doer *user_model.User, gitRepo *git.Repo
} }
} }
} }
return nil
if err := committer.Commit(); err != nil { }); err != nil {
return err return err
} }

View File

@@ -173,12 +173,7 @@ func MigrateRepositoryGitData(ctx context.Context, u *user_model.User,
} }
} }
ctx, committer, err := db.TxContext(ctx) return db.WithTx2(ctx, func(ctx context.Context) (*repo_model.Repository, error) {
if err != nil {
return nil, err
}
defer committer.Close()
if opts.Mirror { if opts.Mirror {
remoteAddress, err := util.SanitizeURL(opts.CloneAddr) remoteAddress, err := util.SanitizeURL(opts.CloneAddr)
if err != nil { if err != nil {
@@ -258,7 +253,8 @@ func MigrateRepositoryGitData(ctx context.Context, u *user_model.User,
return nil, err return nil, err
} }
} }
return repo, committer.Commit() return repo, nil
})
} }
// CleanUpMigrateInfo finishes migrating repository and/or wiki with things that don't need to be done for mirrors. // CleanUpMigrateInfo finishes migrating repository and/or wiki with things that don't need to be done for mirrors.

View File

@@ -210,12 +210,7 @@ func DeleteUser(ctx context.Context, u *user_model.User, purge bool) error {
} }
} }
ctx, committer, err := db.TxContext(ctx) if err := db.WithTx(ctx, func(ctx context.Context) error {
if err != nil {
return err
}
defer committer.Close()
// Note: A user owns any repository or belongs to any organization // Note: A user owns any repository or belongs to any organization
// cannot perform delete operation. This causes a race with the purge above // cannot perform delete operation. This causes a race with the purge above
// however consistency requires that we ensure that this is the case // however consistency requires that we ensure that this is the case
@@ -246,29 +241,28 @@ func DeleteUser(ctx context.Context, u *user_model.User, purge bool) error {
if err := deleteUser(ctx, u, purge); err != nil { if err := deleteUser(ctx, u, purge); err != nil {
return fmt.Errorf("DeleteUser: %w", err) return fmt.Errorf("DeleteUser: %w", err)
} }
return nil
if err := committer.Commit(); err != nil { }); err != nil {
return err return err
} }
_ = committer.Close()
if err = asymkey_service.RewriteAllPublicKeys(ctx); err != nil { if err := asymkey_service.RewriteAllPublicKeys(ctx); err != nil {
return err return err
} }
if err = asymkey_service.RewriteAllPrincipalKeys(ctx); err != nil { if err := asymkey_service.RewriteAllPrincipalKeys(ctx); err != nil {
return err return err
} }
// Note: There are something just cannot be roll back, so just keep error logs of those operations. // Note: There are something just cannot be roll back, so just keep error logs of those operations.
path := user_model.UserPath(u.Name) path := user_model.UserPath(u.Name)
if err = util.RemoveAll(path); err != nil { if err := util.RemoveAll(path); err != nil {
err = fmt.Errorf("failed to RemoveAll %s: %w", path, err) err = fmt.Errorf("failed to RemoveAll %s: %w", path, err)
_ = system_model.CreateNotice(ctx, system_model.NoticeTask, fmt.Sprintf("delete user '%s': %v", u.Name, err)) _ = system_model.CreateNotice(ctx, system_model.NoticeTask, fmt.Sprintf("delete user '%s': %v", u.Name, err))
} }
if u.Avatar != "" { if u.Avatar != "" {
avatarPath := u.CustomAvatarRelativePath() avatarPath := u.CustomAvatarRelativePath()
if err = storage.Avatars.Delete(avatarPath); err != nil { if err := storage.Avatars.Delete(avatarPath); err != nil {
err = fmt.Errorf("failed to remove %s: %w", avatarPath, err) err = fmt.Errorf("failed to remove %s: %w", avatarPath, err)
_ = system_model.CreateNotice(ctx, system_model.NoticeTask, fmt.Sprintf("delete user '%s': %v", u.Name, err)) _ = system_model.CreateNotice(ctx, system_model.NoticeTask, fmt.Sprintf("delete user '%s': %v", u.Name, err))
} }