Skip to content

Commit c6c4d66

Browse files
authored
Fix misuse of TxContext (#30061)
Help #29999, or its tests cannot pass. Also, add some comments to clarify the usage of `TxContext`. I don't check all usages of `TxContext` because there are too many (almost 140+). It's a better idea to replace them with `WithTx` instead of checking them one by one. However, that may be another refactoring PR.
1 parent 2e31a28 commit c6c4d66

File tree

2 files changed

+11
-1
lines changed

2 files changed

+11
-1
lines changed

models/db/context.go

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -120,6 +120,16 @@ func (c *halfCommitter) Close() error {
120120

121121
// TxContext represents a transaction Context,
122122
// it will reuse the existing transaction in the parent context or create a new one.
123+
// Some tips to use:
124+
//
125+
// 1 It's always recommended to use `WithTx` in new code instead of `TxContext`, since `WithTx` will handle the transaction automatically.
126+
// 2. To maintain the old code which uses `TxContext`:
127+
// a. Always call `Close()` before returning regardless of whether `Commit()` has been called.
128+
// b. Always call `Commit()` before returning if there are no errors, even if the code did not change any data.
129+
// c. Remember the `Committer` will be a halfCommitter when a transaction is being reused.
130+
// So calling `Commit()` will do nothing, but calling `Close()` without calling `Commit()` will rollback the transaction.
131+
// And all operations submitted by the caller stack will be rollbacked as well, not only the operations in the current function.
132+
// d. It doesn't mean rollback is forbidden, but always do it only when there is an error, and you do want to rollback.
123133
func TxContext(parentCtx context.Context) (*Context, Committer, error) {
124134
if sess, ok := inTransaction(parentCtx); ok {
125135
return newContext(parentCtx, sess, true), &halfCommitter{committer: sess}, nil

models/issues/review.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -620,7 +620,7 @@ func AddReviewRequest(ctx context.Context, issue *Issue, reviewer, doer *user_mo
620620

621621
// skip it when reviewer hase been request to review
622622
if review != nil && review.Type == ReviewTypeRequest {
623-
return nil, nil
623+
return nil, committer.Commit() // still commit the transaction, or committer.Close() will rollback it, even if it's a reused transaction.
624624
}
625625

626626
// if the reviewer is an official reviewer,

0 commit comments

Comments
 (0)