Debian Codegraph @

tests/transaction_test.go

raw
1 package tests_test
2
3 import (
4 "context"
5 "errors"
6 "testing"
7 "time"
8
9 "gorm.io/gorm"
10 . "gorm.io/gorm/utils/tests"
11 )
12
13 func TestTransaction(t *testing.T) {
14 tx := DB.Begin()
15 user := *GetUser("transaction", Config{})
16
17 if err := tx.Save(&user).Error; err != nil {
18 t.Fatalf("No error should raise, but got %v", err)
19 }
20
21 if err := tx.First(&User{}, "name = ?", "transaction").Error; err != nil {
22 t.Fatalf("Should find saved record, but got %v", err)
23 }
24
25 user1 := *GetUser("transaction1-1", Config{})
26
27 if err := tx.Save(&user1).Error; err != nil {
28 t.Fatalf("No error should raise, but got %v", err)
29 }
30
31 if err := tx.First(&User{}, "name = ?", user1.Name).Error; err != nil {
32 t.Fatalf("Should find saved record, but got %v", err)
33 }
34
35 if sqlTx, ok := tx.Statement.ConnPool.(gorm.TxCommitter); !ok || sqlTx == nil {
36 t.Fatalf("Should return the underlying sql.Tx")
37 }
38
39 tx.Rollback()
40
41 if err := DB.First(&User{}, "name = ?", "transaction").Error; err == nil {
42 t.Fatalf("Should not find record after rollback, but got %v", err)
43 }
44
45 txDB := DB.Where("fake_name = ?", "fake_name")
46 tx2 := txDB.Session(&gorm.Session{NewDB: true}).Begin()
47 user2 := *GetUser("transaction-2", Config{})
48 if err := tx2.Save(&user2).Error; err != nil {
49 t.Fatalf("No error should raise, but got %v", err)
50 }
51
52 if err := tx2.First(&User{}, "name = ?", "transaction-2").Error; err != nil {
53 t.Fatalf("Should find saved record, but got %v", err)
54 }
55
56 tx2.Commit()
57
58 if err := DB.First(&User{}, "name = ?", "transaction-2").Error; err != nil {
59 t.Fatalf("Should be able to find committed record, but got %v", err)
60 }
61
62 t.Run("this is test nested transaction and prepareStmt coexist case", func(t *testing.T) {
63 // enable prepare statement
64 tx3 := DB.Session(&gorm.Session{PrepareStmt: true})
65 if err := tx3.Transaction(func(tx4 *gorm.DB) error {
66 // nested transaction
67 return tx4.Transaction(func(tx5 *gorm.DB) error {
68 return tx5.First(&User{}, "name = ?", "transaction-2").Error
69 })
70 }); err != nil {
71 t.Fatalf("prepare statement and nested transaction coexist: %v", err)
72 }
73 })
74 }
75
76 func TestCancelTransaction(t *testing.T) {
77 ctx := context.Background()
78 ctx, cancelFunc := context.WithCancel(ctx)
79 cancelFunc()
80
81 user := *GetUser("cancel_transaction", Config{})
82 DB.Create(&user)
83
84 err := DB.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
85 var result User
86 tx.First(&result, user.ID)
87 return nil
88 })
89
90 if err == nil {
91 t.Fatalf("Transaction should get error when using cancelled context")
92 }
93 }
94
95 func TestTransactionWithBlock(t *testing.T) {
96 assertPanic := func(f func()) {
97 defer func() {
98 if r := recover(); r == nil {
99 t.Fatalf("The code did not panic")
100 }
101 }()
102 f()
103 }
104
105 // rollback
106 err := DB.Transaction(func(tx *gorm.DB) error {
107 user := *GetUser("transaction-block", Config{})
108 if err := tx.Save(&user).Error; err != nil {
109 t.Fatalf("No error should raise")
110 }
111
112 if err := tx.First(&User{}, "name = ?", user.Name).Error; err != nil {
113 t.Fatalf("Should find saved record")
114 }
115
116 return errors.New("the error message")
117 })
118
119 if err != nil && err.Error() != "the error message" {
120 t.Fatalf("Transaction return error will equal the block returns error")
121 }
122
123 if err := DB.First(&User{}, "name = ?", "transaction-block").Error; err == nil {
124 t.Fatalf("Should not find record after rollback")
125 }
126
127 // commit
128 DB.Transaction(func(tx *gorm.DB) error {
129 user := *GetUser("transaction-block-2", Config{})
130 if err := tx.Save(&user).Error; err != nil {
131 t.Fatalf("No error should raise")
132 }
133
134 if err := tx.First(&User{}, "name = ?", user.Name).Error; err != nil {
135 t.Fatalf("Should find saved record")
136 }
137 return nil
138 })
139
140 if err := DB.First(&User{}, "name = ?", "transaction-block-2").Error; err != nil {
141 t.Fatalf("Should be able to find committed record")
142 }
143
144 // panic will rollback
145 assertPanic(func() {
146 DB.Transaction(func(tx *gorm.DB) error {
147 user := *GetUser("transaction-block-3", Config{})
148 if err := tx.Save(&user).Error; err != nil {
149 t.Fatalf("No error should raise")
150 }
151
152 if err := tx.First(&User{}, "name = ?", user.Name).Error; err != nil {
153 t.Fatalf("Should find saved record")
154 }
155
156 panic("force panic")
157 })
158 })
159
160 if err := DB.First(&User{}, "name = ?", "transaction-block-3").Error; err == nil {
161 t.Fatalf("Should not find record after panic rollback")
162 }
163 }
164
165 func TestTransactionRaiseErrorOnRollbackAfterCommit(t *testing.T) {
166 tx := DB.Begin()
167 user := User{Name: "transaction"}
168 if err := tx.Save(&user).Error; err != nil {
169 t.Fatalf("No error should raise")
170 }
171
172 if err := tx.Commit().Error; err != nil {
173 t.Fatalf("Commit should not raise error")
174 }
175
176 if err := tx.Rollback().Error; err == nil {
177 t.Fatalf("Rollback after commit should raise error")
178 }
179 }
180
181 func TestTransactionWithSavePoint(t *testing.T) {
182 tx := DB.Begin()
183
184 user := *GetUser("transaction-save-point", Config{})
185 tx.Create(&user)
186
187 if err := tx.First(&User{}, "name = ?", user.Name).Error; err != nil {
188 t.Fatalf("Should find saved record")
189 }
190
191 if err := tx.SavePoint("save_point1").Error; err != nil {
192 t.Fatalf("Failed to save point, got error %v", err)
193 }
194
195 user1 := *GetUser("transaction-save-point-1", Config{})
196 tx.Create(&user1)
197
198 if err := tx.First(&User{}, "name = ?", user1.Name).Error; err != nil {
199 t.Fatalf("Should find saved record")
200 }
201
202 if err := tx.RollbackTo("save_point1").Error; err != nil {
203 t.Fatalf("Failed to save point, got error %v", err)
204 }
205
206 if err := tx.First(&User{}, "name = ?", user1.Name).Error; err == nil {
207 t.Fatalf("Should not find rollbacked record")
208 }
209
210 if err := tx.SavePoint("save_point2").Error; err != nil {
211 t.Fatalf("Failed to save point, got error %v", err)
212 }
213
214 user2 := *GetUser("transaction-save-point-2", Config{})
215 tx.Create(&user2)
216
217 if err := tx.First(&User{}, "name = ?", user2.Name).Error; err != nil {
218 t.Fatalf("Should find saved record")
219 }
220
221 if err := tx.Commit().Error; err != nil {
222 t.Fatalf("Failed to commit, got error %v", err)
223 }
224
225 if err := DB.First(&User{}, "name = ?", user.Name).Error; err != nil {
226 t.Fatalf("Should find saved record")
227 }
228
229 if err := DB.First(&User{}, "name = ?", user1.Name).Error; err == nil {
230 t.Fatalf("Should not find rollbacked record")
231 }
232
233 if err := DB.First(&User{}, "name = ?", user2.Name).Error; err != nil {
234 t.Fatalf("Should find saved record")
235 }
236 }
237
238 func TestNestedTransactionWithBlock(t *testing.T) {
239 var (
240 user = *GetUser("transaction-nested", Config{})
241 user1 = *GetUser("transaction-nested-1", Config{})
242 user2 = *GetUser("transaction-nested-2", Config{})
243 )
244
245 if err := DB.Transaction(func(tx *gorm.DB) error {
246 tx.Create(&user)
247
248 if err := tx.First(&User{}, "name = ?", user.Name).Error; err != nil {
249 t.Fatalf("Should find saved record")
250 }
251
252 if err := tx.Transaction(func(tx1 *gorm.DB) error {
253 tx1.Create(&user1)
254
255 if err := tx1.First(&User{}, "name = ?", user1.Name).Error; err != nil {
256 t.Fatalf("Should find saved record")
257 }
258
259 return errors.New("rollback")
260 }); err == nil {
261 t.Fatalf("nested transaction should returns error")
262 }
263
264 if err := tx.First(&User{}, "name = ?", user1.Name).Error; err == nil {
265 t.Fatalf("Should not find rollbacked record")
266 }
267
268 if err := tx.Transaction(func(tx2 *gorm.DB) error {
269 tx2.Create(&user2)
270
271 if err := tx2.First(&User{}, "name = ?", user2.Name).Error; err != nil {
272 t.Fatalf("Should find saved record")
273 }
274
275 return nil
276 }); err != nil {
277 t.Fatalf("nested transaction returns error: %v", err)
278 }
279
280 if err := tx.First(&User{}, "name = ?", user2.Name).Error; err != nil {
281 t.Fatalf("Should find saved record")
282 }
283 return nil
284 }); err != nil {
285 t.Fatalf("no error should return, but got %v", err)
286 }
287
288 if err := DB.First(&User{}, "name = ?", user.Name).Error; err != nil {
289 t.Fatalf("Should find saved record")
290 }
291
292 if err := DB.First(&User{}, "name = ?", user1.Name).Error; err == nil {
293 t.Fatalf("Should not find rollbacked record")
294 }
295
296 if err := DB.First(&User{}, "name = ?", user2.Name).Error; err != nil {
297 t.Fatalf("Should find saved record")
298 }
299 }
300
301 func TestDeeplyNestedTransactionWithBlockAndWrappedCallback(t *testing.T) {
302 transaction := func(ctx context.Context, db *gorm.DB, callback func(ctx context.Context, db *gorm.DB) error) error {
303 return db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
304 return callback(ctx, tx)
305 })
306 }
307 var (
308 user = *GetUser("transaction-nested", Config{})
309 user1 = *GetUser("transaction-nested-1", Config{})
310 user2 = *GetUser("transaction-nested-2", Config{})
311 )
312
313 if err := transaction(context.Background(), DB, func(ctx context.Context, tx *gorm.DB) error {
314 tx.Create(&user)
315
316 if err := tx.First(&User{}, "name = ?", user.Name).Error; err != nil {
317 t.Fatalf("Should find saved record")
318 }
319
320 if err := transaction(ctx, tx, func(ctx context.Context, tx1 *gorm.DB) error {
321 tx1.Create(&user1)
322
323 if err := tx1.First(&User{}, "name = ?", user1.Name).Error; err != nil {
324 t.Fatalf("Should find saved record")
325 }
326
327 if err := transaction(ctx, tx1, func(ctx context.Context, tx2 *gorm.DB) error {
328 tx2.Create(&user2)
329
330 if err := tx2.First(&User{}, "name = ?", user2.Name).Error; err != nil {
331 t.Fatalf("Should find saved record")
332 }
333
334 return errors.New("inner rollback")
335 }); err == nil {
336 t.Fatalf("nested transaction has no error")
337 }
338
339 return errors.New("rollback")
340 }); err == nil {
341 t.Fatalf("nested transaction should returns error")
342 }
343
344 if err := tx.First(&User{}, "name = ?", user1.Name).Error; err == nil {
345 t.Fatalf("Should not find rollbacked record")
346 }
347
348 if err := tx.First(&User{}, "name = ?", user2.Name).Error; err != nil {
349 t.Fatalf("Should find saved record")
350 }
351 return nil
352 }); err != nil {
353 t.Fatalf("no error should return, but got %v", err)
354 }
355
356 if err := DB.First(&User{}, "name = ?", user.Name).Error; err != nil {
357 t.Fatalf("Should find saved record")
358 }
359
360 if err := DB.First(&User{}, "name = ?", user1.Name).Error; err == nil {
361 t.Fatalf("Should not find rollbacked parent record")
362 }
363
364 if err := DB.First(&User{}, "name = ?", user2.Name).Error; err != nil {
365 t.Fatalf("Should not find rollbacked nested record")
366 }
367 }
368
369 func TestDisabledNestedTransaction(t *testing.T) {
370 var (
371 user = *GetUser("transaction-nested", Config{})
372 user1 = *GetUser("transaction-nested-1", Config{})
373 user2 = *GetUser("transaction-nested-2", Config{})
374 )
375
376 if err := DB.Session(&gorm.Session{DisableNestedTransaction: true}).Transaction(func(tx *gorm.DB) error {
377 tx.Create(&user)
378
379 if err := tx.First(&User{}, "name = ?", user.Name).Error; err != nil {
380 t.Fatalf("Should find saved record")
381 }
382
383 if err := tx.Transaction(func(tx1 *gorm.DB) error {
384 tx1.Create(&user1)
385
386 if err := tx1.First(&User{}, "name = ?", user1.Name).Error; err != nil {
387 t.Fatalf("Should find saved record")
388 }
389
390 return errors.New("rollback")
391 }); err == nil {
392 t.Fatalf("nested transaction should returns error")
393 }
394
395 if err := tx.First(&User{}, "name = ?", user1.Name).Error; err != nil {
396 t.Fatalf("Should not rollback record if disabled nested transaction support")
397 }
398
399 if err := tx.Transaction(func(tx2 *gorm.DB) error {
400 tx2.Create(&user2)
401
402 if err := tx2.First(&User{}, "name = ?", user2.Name).Error; err != nil {
403 t.Fatalf("Should find saved record")
404 }
405
406 return nil
407 }); err != nil {
408 t.Fatalf("nested transaction returns error: %v", err)
409 }
410
411 if err := tx.First(&User{}, "name = ?", user2.Name).Error; err != nil {
412 t.Fatalf("Should find saved record")
413 }
414 return nil
415 }); err != nil {
416 t.Fatalf("no error should return, but got %v", err)
417 }
418
419 if err := DB.First(&User{}, "name = ?", user.Name).Error; err != nil {
420 t.Fatalf("Should find saved record")
421 }
422
423 if err := DB.First(&User{}, "name = ?", user1.Name).Error; err != nil {
424 t.Fatalf("Should not rollback record if disabled nested transaction support")
425 }
426
427 if err := DB.First(&User{}, "name = ?", user2.Name).Error; err != nil {
428 t.Fatalf("Should find saved record")
429 }
430 }
431
432 func TestTransactionOnClosedConn(t *testing.T) {
433 DB, err := OpenTestConnection(&gorm.Config{})
434 if err != nil {
435 t.Fatalf("failed to connect database, got error %v", err)
436 }
437 rawDB, _ := DB.DB()
438 rawDB.Close()
439
440 if err := DB.Transaction(func(tx *gorm.DB) error {
441 return nil
442 }); err == nil {
443 t.Errorf("should returns error when commit with closed conn, got error %v", err)
444 }
445
446 if err := DB.Session(&gorm.Session{PrepareStmt: true}).Transaction(func(tx *gorm.DB) error {
447 return nil
448 }); err == nil {
449 t.Errorf("should returns error when commit with closed conn, got error %v", err)
450 }
451 }
452
453 func TestTransactionWithHooks(t *testing.T) {
454 user := GetUser("tTestTransactionWithHooks", Config{Account: true})
455 DB.Create(&user)
456
457 var err error
458 err = DB.Transaction(func(tx *gorm.DB) error {
459 return tx.Model(&User{}).Limit(1).Transaction(func(tx2 *gorm.DB) error {
460 return tx2.Scan(&User{}).Error
461 })
462 })
463 if err != nil {
464 t.Error(err)
465 }
466
467 // method with hooks
468 err = DB.Transaction(func(tx1 *gorm.DB) error {
469 // callMethod do
470 tx2 := tx1.Find(&User{}).Session(&gorm.Session{NewDB: true})
471 // trx in hooks
472 return tx2.Transaction(func(tx3 *gorm.DB) error {
473 return tx3.Where("user_id", user.ID).Delete(&Account{}).Error
474 })
475 })
476 if err != nil {
477 t.Error(err)
478 }
479 }
480
481 func TestTransactionWithDefaultTimeout(t *testing.T) {
482 db, err := OpenTestConnection(&gorm.Config{DefaultTransactionTimeout: 2 * time.Second})
483 if err != nil {
484 t.Fatalf("failed to connect database, got error %v", err)
485 }
486
487 tx := db.Begin()
488 time.Sleep(3 * time.Second)
489 if err = tx.Find(&User{}).Error; err == nil {
490 t.Errorf("should return error when transaction timeout, got error %v", err)
491 }
492 }