go-gorm / playground

GORM Playground (Please Create PR for this project to report issues)
MIT License
89 stars 678 forks source link

unexpected unscoped behavior #697

Closed ksrnnb closed 6 months ago

ksrnnb commented 6 months ago

Explain your user case and expected results

When I want to hard delete records and use Unscoped to reassign the gorm.DB structure, the first Delete statement works correctly, but the second Delete statement does not. Why is this happening? What can I do to avoid this?

code

if tc.shouldHardDelete {
    tx = tx.Unscoped()
}

// delete pets separately to delete pets' association
if err := tx.Select(clause.Associations).Delete(&user.Pets).Error; err != nil {
    t.Errorf("Failed, got error: %v", err)
}

if err := tx.Select(clause.Associations).Delete(&user).Error; err != nil {
    t.Errorf("Failed, got error: %v", err)
}

SQL Log

$ DEBUG=true ./test.sh

2024/02/23 07:36:17 /Users/kyota/programing/playground/main_test.go:59
[0.055ms] [rows:1] DELETE FROM `toys` WHERE `toys`.`owner_type` = "pets" AND `toys`.`owner_id` = 1

2024/02/23 07:36:17 /Users/kyota/programing/playground/main_test.go:59
[0.162ms] [rows:1] DELETE FROM `pets` WHERE `pets`.`id` = 1

2024/02/23 07:36:17 /Users/kyota/programing/playground/main_test.go:63
[0.048ms] [rows:0] DELETE FROM `toys` WHERE `toys`.`owner_type` = "pets" AND `toys`.`owner_id` = 1

2024/02/23 07:36:17 /Users/kyota/programing/playground/main_test.go:63
[0.171ms] [rows:0] DELETE FROM `pets` WHERE `pets`.`id` = 1 AND `pets`.`id` = 1 AND `pets`.`id` = 1

2024/02/23 07:36:17 /Users/kyota/programing/playground/main_test.go:68 near "as": syntax error
[0.041ms] [rows:0] SELECT ~~~as~~~ FROM `pets` WHERE `pets`.`id` = 1 AND `pets`.`id` = 1 AND `pets`.`id` = 1 ORDER BY `pets`.`id` LIMIT 1
    main_test.go:72: Failed, got error: near "as": syntax error
--- FAIL: TestGORM (0.01s)
    --- PASS: TestGORM/soft_delete (0.00s)
    --- FAIL: TestGORM/hard_delete (0.00s)
FAIL
FAIL    gorm.io/playground      0.439s
FAIL