Skip to content

Commit 363d978

Browse files
Merge pull request #456 from rchowinfoblox/cherrypick0.19
Rearrange lock in Commit/Rollback to eliminate race condition (cherry-pick into v0.19 branch)
2 parents bb6e885 + dc6eed7 commit 363d978

File tree

1 file changed

+6
-5
lines changed

1 file changed

+6
-5
lines changed

gorm/transaction.go

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -133,15 +133,15 @@ func (t *Transaction) beginWithContextAndOptions(ctx context.Context, opts *sql.
133133
// Rollback terminates transaction by calling `*gorm.DB.Rollback()`
134134
// Reset current transaction and returns an error if any.
135135
func (t *Transaction) Rollback() error {
136+
t.mu.Lock()
137+
defer t.mu.Unlock()
138+
136139
if t.current == nil {
137140
return nil
138141
}
139142
if reflect.ValueOf(t.current.CommonDB()).IsNil() {
140143
return status.Error(codes.Unavailable, "Database connection not available")
141144
}
142-
t.mu.Lock()
143-
defer t.mu.Unlock()
144-
145145
t.current.Rollback()
146146
err := t.current.Error
147147
t.current = nil
@@ -151,11 +151,12 @@ func (t *Transaction) Rollback() error {
151151
// Commit finishes transaction by calling `*gorm.DB.Commit()`
152152
// Reset current transaction and returns an error if any.
153153
func (t *Transaction) Commit(ctx context.Context) error {
154+
t.mu.Lock()
155+
defer t.mu.Unlock()
156+
154157
if t.current == nil || reflect.ValueOf(t.current.CommonDB()).IsNil() {
155158
return nil
156159
}
157-
t.mu.Lock()
158-
defer t.mu.Unlock()
159160
t.current.Commit()
160161
err := t.current.Error
161162
if err == nil {

0 commit comments

Comments
 (0)