Skip to content

Commit bb98441

Browse files
Merge pull request #455 from rchowinfoblox/cherrypick0.25
Rearrange lock in Commit/Rollback to eliminate race condition (cherry-pick into v0.25 branch)
2 parents 2055506 + 1651772 commit bb98441

File tree

2 files changed

+8
-6
lines changed

2 files changed

+8
-6
lines changed

.github/workflows/pr.yaml

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -19,11 +19,12 @@ jobs:
1919
- uses: actions/setup-go@v2
2020
with:
2121
go-version: "1.x"
22-
- uses: actions/cache@v2
22+
- uses: actions/cache@v4
2323
with:
2424
path: ~/go/pkg/mod
2525
key: ${{ runner.os }}-go-${{ hashFiles('**/go.sum') }}
2626
restore-keys: |
27+
${{ runner.os }}-go-${{ env.GITHUB_JOB }}-
2728
${{ runner.os }}-go-
2829
- run: make test
2930
- name: uncommitted changes?

gorm/transaction.go

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -268,15 +268,15 @@ func (t *Transaction) beginWithContextAndOptions(ctx context.Context, opts *sql.
268268
// Rollback terminates transaction by calling `*gorm.DB.Rollback()`
269269
// Reset current transaction and returns an error if any.
270270
func (t *Transaction) Rollback() error {
271+
t.mu.Lock()
272+
defer t.mu.Unlock()
273+
271274
if t.current == nil {
272275
return nil
273276
}
274277
if reflect.ValueOf(t.current.CommonDB()).IsNil() {
275278
return status.Error(codes.Unavailable, "Database connection not available")
276279
}
277-
t.mu.Lock()
278-
defer t.mu.Unlock()
279-
280280
t.current.Rollback()
281281
err := t.current.Error
282282
t.current = nil
@@ -286,11 +286,12 @@ func (t *Transaction) Rollback() error {
286286
// Commit finishes transaction by calling `*gorm.DB.Commit()`
287287
// Reset current transaction and returns an error if any.
288288
func (t *Transaction) Commit(ctx context.Context) error {
289+
t.mu.Lock()
290+
defer t.mu.Unlock()
291+
289292
if t.current == nil || reflect.ValueOf(t.current.CommonDB()).IsNil() {
290293
return nil
291294
}
292-
t.mu.Lock()
293-
defer t.mu.Unlock()
294295
t.current.Commit()
295296
err := t.current.Error
296297
if err == nil {

0 commit comments

Comments
 (0)