Debian Codegraph @

tests/association_generics_test.go

raw
1 package tests_test
2
3 import (
4 "context"
5 "testing"
6
7 "gorm.io/gorm"
8 "gorm.io/gorm/clause"
9 . "gorm.io/gorm/utils/tests"
10 )
11
12 // BelongsToCompany and BelongsToUser models for belongs to tests - using existing User and Company models
13
14 // Test Set + Create with Association OpCreate operation using real database
15 func TestClauseAssociationSetCreateWithOpCreate(t *testing.T) {
16 ctx := context.Background()
17
18 // First create a user with Set + Create
19 err := gorm.G[User](DB).Set(
20 clause.Assignment{Column: clause.Column{Name: "name"}, Value: "TestClauseAssociationSetCreateWithOpCreate"},
21 clause.Assignment{Column: clause.Column{Name: "age"}, Value: 25},
22 ).Create(ctx)
23 if err != nil {
24 t.Fatalf("Set Create failed: %v", err)
25 }
26
27 // Find the created user
28 var user User
29 if err := DB.Where("name = ?", "TestClauseAssociationSetCreateWithOpCreate").First(&user).Error; err != nil {
30 t.Fatalf("failed to find created user: %v", err)
31 }
32
33 // Test Set + Update with Association OpCreate
34 assocOp := clause.Association{
35 Association: "Pets",
36 Type: clause.OpCreate,
37 Set: []clause.Assignment{
38 {Column: clause.Column{Name: "name"}, Value: "test-pet"},
39 },
40 }
41
42 rows, err := gorm.G[User](DB).Where("id = ?", user.ID).Set(assocOp).Update(ctx)
43 if err != nil {
44 t.Fatalf("Set Update with association failed: %v", err)
45 }
46 // Only association operations were executed; no row update is expected
47 if rows != 0 {
48 t.Fatalf("expected 0 rows affected for association-only update, got %d", rows)
49 }
50
51 // Verify the association was created using real database query
52 AssertAssociationCount(t, &user, "Pets", 1, "after Set Update with association")
53 }
54
55 // Test Set + Update with Association OpCreate operation using real database
56 func TestClauseAssociationSetUpdateWithOpCreate(t *testing.T) {
57 ctx := context.Background()
58
59 // Create a user with a pet first using real database
60 user := User{Name: "TestClauseAssociationSetUpdateWithOpCreate", Age: 25}
61 user.Pets = []*Pet{{Name: "original-pet"}}
62 if err := DB.Create(&user).Error; err != nil {
63 t.Fatalf("failed to create user with pet: %v", err)
64 }
65
66 // Verify initial state using real database query
67 AssertAssociationCount(t, user, "Pets", 1, "before update")
68
69 // Test Set + Update with Association OpCreate
70 assocOp := clause.Association{
71 Association: "Pets",
72 Type: clause.OpCreate,
73 Set: []clause.Assignment{
74 {Column: clause.Column{Name: "name"}, Value: "new-pet"},
75 },
76 }
77
78 rows, err := gorm.G[User](DB).Where("id = ?", user.ID).Set(assocOp).Update(ctx)
79 if err != nil {
80 t.Fatalf("Set Update with association failed: %v", err)
81 }
82 // Only association operations were executed; no row update is expected
83 if rows != 0 {
84 t.Fatalf("expected 0 rows affected for association-only update, got %d", rows)
85 }
86
87 // Verify the association was updated using real database query
88 var updatedUser User
89 if err := DB.Preload("Pets").Where("id = ?", user.ID).First(&updatedUser).Error; err != nil {
90 t.Fatalf("failed to find updated user: %v", err)
91 }
92
93 if len(updatedUser.Pets) != 2 {
94 t.Fatalf("expected 2 pets, got %d", len(updatedUser.Pets))
95 }
96
97 petNames := make(map[string]bool)
98 for _, pet := range updatedUser.Pets {
99 petNames[pet.Name] = true
100 }
101
102 if !petNames["original-pet"] {
103 t.Error("original pet not found")
104 }
105
106 if !petNames["new-pet"] {
107 t.Error("new pet not found")
108 }
109 }
110
111 // Test Set + Create with multiple associations using real database
112 func TestClauseAssociationSetCreateWithMultipleAssociations(t *testing.T) {
113 ctx := context.Background()
114
115 // First create a user with Set + Create using real database
116 err := gorm.G[User](DB).Set(
117 clause.Assignment{Column: clause.Column{Name: "name"}, Value: "TestClauseAssociationSetCreateWithMultipleAssociations"},
118 clause.Assignment{Column: clause.Column{Name: "age"}, Value: 25},
119 ).Create(ctx)
120 if err != nil {
121 t.Fatalf("Set Create failed: %v", err)
122 }
123
124 // Find the created user using real database query
125 var user User
126 if err := DB.Where("name = ?", "TestClauseAssociationSetCreateWithMultipleAssociations").First(&user).Error; err != nil {
127 t.Fatalf("failed to find created user: %v", err)
128 }
129
130 // Test Set + Update with multiple association operations
131 assocOp1 := clause.Association{
132 Association: "Pets",
133 Type: clause.OpCreate,
134 Set: []clause.Assignment{
135 {Column: clause.Column{Name: "name"}, Value: "test-pet-1"},
136 },
137 }
138
139 assocOp2 := clause.Association{
140 Association: "Toys",
141 Type: clause.OpCreate,
142 Set: []clause.Assignment{
143 {Column: clause.Column{Name: "name"}, Value: "test-toy-1"},
144 },
145 }
146
147 rows, err := gorm.G[User](DB).Where("id = ?", user.ID).Set(assocOp1, assocOp2).Update(ctx)
148 if err != nil {
149 t.Fatalf("Set Update with multiple associations failed: %v", err)
150 }
151 // Only association operations were executed; no row update is expected
152 if rows != 0 {
153 t.Fatalf("expected 0 rows affected for association-only update, got %d", rows)
154 }
155
156 // Verify both associations were created using real database queries
157 AssertAssociationCount(t, &user, "Pets", 1, "after Set Update with multiple associations")
158 AssertAssociationCount(t, &user, "Toys", 1, "after Set Update with multiple associations")
159 }
160
161 // Test Set + Update with multiple associations using real database
162 func TestClauseAssociationSetUpdateWithMultipleAssociations(t *testing.T) {
163 ctx := context.Background()
164
165 // Create a user with initial associations using real database
166 user := User{Name: "TestClauseAssociationSetUpdateWithMultipleAssociations", Age: 25}
167 user.Pets = []*Pet{{Name: "original-pet"}}
168 user.Toys = []Toy{{Name: "original-toy"}}
169 if err := DB.Create(&user).Error; err != nil {
170 t.Fatalf("failed to create user with associations: %v", err)
171 }
172
173 // Verify initial state using real database queries
174 AssertAssociationCount(t, user, "Pets", 1, "before update")
175 AssertAssociationCount(t, user, "Toys", 1, "before update")
176
177 // Test Set + Update with multiple association operations
178 assocOp1 := clause.Association{
179 Association: "Pets",
180 Type: clause.OpCreate,
181 Set: []clause.Assignment{
182 {Column: clause.Column{Name: "name"}, Value: "new-pet"},
183 },
184 }
185
186 assocOp2 := clause.Association{
187 Association: "Toys",
188 Type: clause.OpCreate,
189 Set: []clause.Assignment{
190 {Column: clause.Column{Name: "name"}, Value: "new-toy"},
191 },
192 }
193
194 rows, err := gorm.G[User](DB).Where("id = ?", user.ID).Set(assocOp1, assocOp2).Update(ctx)
195 if err != nil {
196 t.Fatalf("Set Update with multiple associations failed: %v", err)
197 }
198 // Only association operations were executed; no row update is expected
199 if rows != 0 {
200 t.Fatalf("expected 0 rows affected for association-only update, got %d", rows)
201 }
202
203 // Verify both associations were updated using real database queries
204 var updatedUser User
205 if err := DB.Preload("Pets").Preload("Toys").Where("id = ?", user.ID).First(&updatedUser).Error; err != nil {
206 t.Fatalf("failed to find updated user: %v", err)
207 }
208
209 if len(updatedUser.Pets) != 2 {
210 t.Fatalf("expected 2 pets, got %d", len(updatedUser.Pets))
211 }
212
213 if len(updatedUser.Toys) != 2 {
214 t.Fatalf("expected 2 toys, got %d", len(updatedUser.Toys))
215 }
216 }
217
218 // Test Set + Update with Association OpUnlink operation using real database
219 func TestClauseAssociationSetUpdateWithOpUnlink(t *testing.T) {
220 ctx := context.Background()
221
222 // Create a user with pets using real database
223 user := User{Name: "TestClauseAssociationSetUpdateWithOpUnlink", Age: 25}
224 user.Pets = []*Pet{{Name: "pet-to-unlink"}, {Name: "pet-to-keep"}}
225 if err := DB.Create(&user).Error; err != nil {
226 t.Fatalf("failed to create user with pets: %v", err)
227 }
228
229 // Verify initial state using real database query
230 AssertAssociationCount(t, user, "Pets", 2, "before unlink")
231
232 // Get the pet to unlink using real database query
233 var petToUnlink Pet
234 if err := DB.Where("name = ?", "pet-to-unlink").First(&petToUnlink).Error; err != nil {
235 t.Fatalf("failed to find pet to unlink: %v", err)
236 }
237
238 // Test Set + Update with Association OpUnlink
239 assocOp := clause.Association{
240 Association: "Pets",
241 Type: clause.OpUnlink,
242 Conditions: []clause.Expression{
243 clause.Eq{Column: clause.Column{Name: "id"}, Value: petToUnlink.ID},
244 },
245 }
246
247 rows, err := gorm.G[User](DB).Where("id = ?", user.ID).Set(assocOp).Update(ctx)
248 if err != nil {
249 t.Fatalf("Set Update with association unlink failed: %v", err)
250 }
251 // Only association operations were executed; no row update is expected
252 if rows != 0 {
253 t.Fatalf("expected 0 rows affected for association-only update, got %d", rows)
254 }
255
256 // Verify only one pet remains using real database query
257 var updatedUser User
258 if err := DB.Preload("Pets").Where("id = ?", user.ID).First(&updatedUser).Error; err != nil {
259 t.Fatalf("failed to find updated user: %v", err)
260 }
261
262 if len(updatedUser.Pets) != 1 {
263 t.Fatalf("expected 1 pet after unlink, got %d", len(updatedUser.Pets))
264 }
265
266 if updatedUser.Pets[0].Name != "pet-to-keep" {
267 t.Errorf("expected pet-to-keep, got %s", updatedUser.Pets[0].Name)
268 }
269
270 // Verify the unlinked pet still exists in the database using real database query
271 var count int64
272 if err := DB.Model(&Pet{}).Where("id = ?", petToUnlink.ID).Count(&count).Error; err != nil {
273 t.Fatalf("failed to count pet: %v", err)
274 }
275 if count != 1 {
276 t.Error("unlinked pet should still exist in database")
277 }
278 }
279
280 // Test Set + Update with Association OpCreate operation using real database
281 func TestClauseAssociationSetUpdateWithOpCreateValues(t *testing.T) {
282 ctx := context.Background()
283
284 // Create a user first using real database
285 user := User{Name: "TestClauseAssociationSetUpdateWithOpCreate", Age: 25}
286 if err := DB.Create(&user).Error; err != nil {
287 t.Fatalf("failed to create user: %v", err)
288 }
289
290 // Create a pet object
291 newPet := Pet{Name: "created-pet"}
292
293 // Test Set + Update with Association OpCreate
294 assocOp := clause.Association{
295 Association: "Pets",
296 Type: clause.OpCreate,
297 Values: []interface{}{&newPet},
298 }
299
300 rows, err := gorm.G[User](DB).Where("id = ?", user.ID).Set(assocOp).Update(ctx)
301 if err != nil {
302 t.Fatalf("Set Update with association create values failed: %v", err)
303 }
304 // Only association operations were executed; no row update is expected
305 if rows != 0 {
306 t.Fatalf("expected 0 rows affected for association-only update, got %d", rows)
307 }
308
309 // Verify the pet was created and associated using real database query
310 var updatedUser User
311 if err := DB.Preload("Pets").Where("id = ?", user.ID).First(&updatedUser).Error; err != nil {
312 t.Fatalf("failed to find updated user: %v", err)
313 }
314
315 if len(updatedUser.Pets) != 1 {
316 t.Fatalf("expected 1 pet, got %d", len(updatedUser.Pets))
317 }
318
319 if updatedUser.Pets[0].Name != "created-pet" {
320 t.Errorf("expected created-pet, got %s", updatedUser.Pets[0].Name)
321 }
322 }
323
324 // Test Set + Create with many-to-many associations using real database
325 func TestClauseAssociationSetCreateWithManyToMany(t *testing.T) {
326 ctx := context.Background()
327
328 // Create a user first using real database
329 user := User{Name: "TestClauseAssociationSetCreateWithManyToMany", Age: 25}
330 if err := DB.Create(&user).Error; err != nil {
331 t.Fatalf("failed to create user: %v", err)
332 }
333
334 // Create languages using real database
335 langs := []Language{
336 {Code: "en", Name: "English"},
337 {Code: "fr", Name: "French"},
338 }
339 for _, lang := range langs {
340 DB.FirstOrCreate(&lang, "code = ?", lang.Code)
341 }
342
343 // Test Set + Update with many-to-many association
344 assocOp := clause.Association{
345 Association: "Languages",
346 Type: clause.OpCreate,
347 Values: []interface{}{langs[0], langs[1]},
348 }
349
350 rows, err := gorm.G[User](DB).Where("id = ?", user.ID).Set(assocOp).Update(ctx)
351 if err != nil {
352 t.Fatalf("Set Update with many-to-many association failed: %v", err)
353 }
354 // Only association operations were executed; no row update is expected
355 if rows != 0 {
356 t.Fatalf("expected 0 rows affected for association-only update, got %d", rows)
357 }
358
359 // Verify the languages were associated using real database query
360 var updatedUser User
361 if err := DB.Preload("Languages").Where("id = ?", user.ID).First(&updatedUser).Error; err != nil {
362 t.Fatalf("failed to find updated user: %v", err)
363 }
364
365 if len(updatedUser.Languages) != 2 {
366 t.Fatalf("expected 2 languages, got %d", len(updatedUser.Languages))
367 }
368 }
369
370 // Test Set + Create with belongs-to associations using real database
371 func TestClauseAssociationSetCreateWithBelongsTo(t *testing.T) {
372 ctx := context.Background()
373
374 // Create a company first using real database
375 company := Company{Name: "Test Company"}
376 if err := DB.Create(&company).Error; err != nil {
377 t.Fatalf("failed to create company: %v", err)
378 }
379
380 // Test Set + Create with belongs-to association using field assignment
381 err := gorm.G[User](DB).Set(
382 clause.Assignment{Column: clause.Column{Name: "name"}, Value: "TestClauseAssociationSetCreateWithBelongsTo"},
383 clause.Assignment{Column: clause.Column{Name: "age"}, Value: 25},
384 clause.Assignment{Column: clause.Column{Name: "company_id"}, Value: company.ID},
385 ).Create(ctx)
386 if err != nil {
387 t.Fatalf("Set Create with belongs-to association failed: %v", err)
388 }
389
390 // Verify the user was created with company association using real database query
391 var newUser User
392 if err := DB.Preload("Company").Where("name = ?", "TestClauseAssociationSetCreateWithBelongsTo").First(&newUser).Error; err != nil {
393 t.Fatalf("failed to find created user: %v", err)
394 }
395
396 if newUser.Company.ID != company.ID {
397 t.Errorf("expected company ID %d, got %d", company.ID, newUser.Company.ID)
398 }
399
400 if newUser.Company.Name != company.Name {
401 t.Errorf("expected company name %s, got %s", company.Name, newUser.Company.Name)
402 }
403 }
404
405 // BelongsTo: create and assign company via OpCreate
406 func TestClauseAssociationSetUpdateBelongsToCreateValues(t *testing.T) {
407 ctx := context.Background()
408
409 user := User{Name: "TestClauseAssociationSetUpdateBelongsToCreateValues", Age: 26}
410 if err := DB.Create(&user).Error; err != nil {
411 t.Fatalf("failed to create user: %v", err)
412 }
413
414 assocOp := clause.Association{Association: "Company", Type: clause.OpCreate, Values: []interface{}{Company{Name: "Belongs-To-Co"}}}
415 if rows, err := gorm.G[User](DB).Where("id = ?", user.ID).Set(assocOp).Update(ctx); err != nil {
416 t.Fatalf("Set Update belongs-to create values failed: %v", err)
417 } else if rows != 0 {
418 t.Fatalf("expected 0 rows affected for association-only update, got %d", rows)
419 }
420
421 var got User
422 if err := DB.Preload("Company").First(&got, user.ID).Error; err != nil {
423 t.Fatalf("failed preload company: %v", err)
424 }
425 if got.Company.ID == 0 || got.Company.Name != "Belongs-To-Co" {
426 t.Fatalf("expected Company assigned, got %+v", got.Company)
427 }
428 }
429
430 // Mixed fields + association: update Age and create a pet together
431 func TestClauseAssociationSetUpdateMixedFieldAndAssociation(t *testing.T) {
432 ctx := context.Background()
433 user := User{Name: "TestClauseAssociationSetUpdateMixed", Age: 20}
434 if err := DB.Create(&user).Error; err != nil {
435 t.Fatalf("create user: %v", err)
436 }
437
438 assocOp := clause.Association{Association: "Pets", Type: clause.OpCreate, Set: []clause.Assignment{{Column: clause.Column{Name: "name"}, Value: "mix-pet"}}}
439 rows, err := gorm.G[User](DB).Where("id = ?", user.ID).Set(
440 assocOp,
441 clause.Assignment{Column: clause.Column{Name: "age"}, Value: 30},
442 ).Update(ctx)
443 if err != nil {
444 t.Fatalf("Set Update mixed failed: %v", err)
445 }
446 if rows != 1 {
447 t.Fatalf("expected 1 row affected for field update, got %d", rows)
448 }
449
450 var got User
451 if err := DB.Preload("Pets").First(&got, user.ID).Error; err != nil {
452 t.Fatalf("load user: %v", err)
453 }
454 if got.Age != 30 {
455 t.Fatalf("expected age 30, got %d", got.Age)
456 }
457 if len(got.Pets) != 1 || got.Pets[0].Name != "mix-pet" {
458 t.Fatalf("expected pet created, got %+v", got.Pets)
459 }
460 }
461
462 // HasOne unlink clears NamedPet
463 func TestClauseAssociationSetUpdateHasOneUnlink(t *testing.T) {
464 ctx := context.Background()
465 user := User{Name: "TestClauseAssociationSetUpdateHasOneUnlink", Age: 25}
466 user.NamedPet = &Pet{Name: "np"}
467 if err := DB.Create(&user).Error; err != nil {
468 t.Fatalf("create: %v", err)
469 }
470
471 assocOp := clause.Association{Association: "NamedPet", Type: clause.OpUnlink}
472 if rows, err := gorm.G[User](DB).Where("id = ?", user.ID).Set(assocOp).Update(ctx); err != nil {
473 t.Fatalf("Set Update has-one unlink failed: %v", err)
474 } else if rows != 0 {
475 t.Fatalf("expected 0 rows affected for association-only update, got %d", rows)
476 }
477
478 var got User
479 if err := DB.Preload("NamedPet").First(&got, user.ID).Error; err != nil {
480 t.Fatalf("load user: %v", err)
481 }
482 if got.NamedPet != nil {
483 t.Fatalf("expected NamedPet cleared, got %+v", got.NamedPet)
484 }
485 }
486
487 // Many-to-Many create with Set
488 func TestClauseAssociationSetUpdateManyToManyCreateWithSet(t *testing.T) {
489 ctx := context.Background()
490 user := User{Name: "TestClauseAssociationSetUpdateMany2ManyCreateWithSet", Age: 25}
491 if err := DB.Create(&user).Error; err != nil {
492 t.Fatalf("create user: %v", err)
493 }
494
495 assocOp := clause.Association{
496 Association: "Languages", Type: clause.OpCreate,
497 Set: []clause.Assignment{{Column: clause.Column{Name: "code"}, Value: "it"}, {Column: clause.Column{Name: "name"}, Value: "Italian"}},
498 }
499 if rows, err := gorm.G[User](DB).Where("id = ?", user.ID).Set(assocOp).Update(ctx); err != nil {
500 t.Fatalf("Set Update many2many create with set failed: %v", err)
501 } else if rows != 0 {
502 t.Fatalf("expected 0 rows affected, got %d", rows)
503 }
504
505 AssertAssociationCount(t, user, "Languages", 1, "after create language")
506 }
507
508 // Many-to-Many clear
509 func TestClauseAssociationSetUpdateManyToManyClear(t *testing.T) {
510 ctx := context.Background()
511 user := User{Name: "TestClauseAssociationSetUpdateMany2ManyClear", Age: 25}
512 if err := DB.Create(&user).Error; err != nil {
513 t.Fatalf("create user: %v", err)
514 }
515 langs := []Language{{Code: "pt", Name: "Portuguese"}, {Code: "ru", Name: "Russian"}}
516 for _, l := range langs {
517 DB.FirstOrCreate(&l, "code = ?", l.Code)
518 }
519 if err := DB.Model(&user).Association("Languages").Append(&langs); err != nil {
520 t.Fatalf("append: %v", err)
521 }
522 AssertAssociationCount(t, user, "Languages", 2, "before clear")
523
524 assocOp := clause.Association{Association: "Languages", Type: clause.OpUnlink}
525 if rows, err := gorm.G[User](DB).Where("id = ?", user.ID).Set(assocOp).Update(ctx); err != nil {
526 t.Fatalf("Set Update many2many clear failed: %v", err)
527 } else if rows != 0 {
528 t.Fatalf("expected 0 rows affected, got %d", rows)
529 }
530 AssertAssociationCount(t, user, "Languages", 0, "after clear")
531 }
532
533 // Polymorphic Tools create and unlink
534 func TestClauseAssociationSetUpdatePolymorphicTools(t *testing.T) {
535 ctx := context.Background()
536 user := User{Name: "TestClauseAssociationSetUpdatePolymorphicTools", Age: 25}
537 if err := DB.Create(&user).Error; err != nil {
538 t.Fatalf("create user: %v", err)
539 }
540
541 createOp := clause.Association{Association: "Tools", Type: clause.OpCreate, Values: []interface{}{Tools{Name: "wrench"}}}
542 if rows, err := gorm.G[User](DB).Where("id = ?", user.ID).Set(createOp).Update(ctx); err != nil {
543 t.Fatalf("create tools: %v", err)
544 } else if rows != 0 {
545 t.Fatalf("rows %d", rows)
546 }
547 AssertAssociationCount(t, user, "Tools", 1, "after create tool")
548
549 unlinkOp := clause.Association{Association: "Tools", Type: clause.OpUnlink}
550 if rows, err := gorm.G[User](DB).Where("id = ?", user.ID).Set(unlinkOp).Update(ctx); err != nil {
551 t.Fatalf("unlink tools: %v", err)
552 } else if rows != 0 {
553 t.Fatalf("rows %d", rows)
554 }
555 AssertAssociationCount(t, user, "Tools", 0, "after clear tools")
556 }
557
558 // Invalid association should return error
559 func TestClauseAssociationSetUpdateInvalidAssociation(t *testing.T) {
560 ctx := context.Background()
561 user := User{Name: "TestClauseAssociationSetUpdateInvalidAssociation", Age: 25}
562 if err := DB.Create(&user).Error; err != nil {
563 t.Fatalf("create user: %v", err)
564 }
565
566 assocOp := clause.Association{Association: "Invalid", Type: clause.OpCreate}
567 if _, err := gorm.G[User](DB).Where("id = ?", user.ID).Set(assocOp).Update(ctx); err == nil {
568 t.Fatalf("expected error for invalid association, got nil")
569 }
570 }
571
572 // No owner matched; should be no-op
573 func TestClauseAssociationSetUpdateNoOwnerMatch(t *testing.T) {
574 ctx := context.Background()
575 assocOp := clause.Association{Association: "Pets", Type: clause.OpCreate, Set: []clause.Assignment{{Column: clause.Column{Name: "name"}, Value: "won't-create"}}}
576 if rows, err := gorm.G[User](DB).Where("id = ?", -1).Set(assocOp).Update(ctx); err != nil {
577 t.Fatalf("unexpected error: %v", err)
578 } else if rows != 0 {
579 t.Fatalf("expected 0 rows, got %d", rows)
580 }
581 }
582
583 // OpDelete/OpUpdate should work for associations
584 func TestClauseAssociationSetUpdateAndDelete(t *testing.T) {
585 ctx := context.Background()
586 user := User{Name: "TestClauseAssociationSetUpdateAndDelete", Age: 25}
587 user.Pets = []*Pet{{Name: "before"}}
588 if err := DB.Create(&user).Error; err != nil {
589 t.Fatalf("create user: %v", err)
590 }
591 AssertAssociationCount(t, user, "Pets", 1, "before update/delete")
592
593 // Update pet name via OpUpdate
594 updOp := clause.Association{Association: "Pets", Type: clause.OpUpdate, Set: []clause.Assignment{{Column: clause.Column{Name: "name"}, Value: "x"}}}
595 if _, err := gorm.G[User](DB).Where("id = ?", user.ID).Set(updOp).Update(ctx); err != nil {
596 t.Fatalf("OpUpdate failed: %v", err)
597 }
598 var got User
599 if err := DB.Preload("Pets").First(&got, user.ID).Error; err != nil {
600 t.Fatalf("load user: %v", err)
601 }
602 if len(got.Pets) != 1 || got.Pets[0].Name != "x" {
603 t.Fatalf("expected updated pet name, got %+v", got.Pets)
604 }
605
606 // Delete pets via OpDelete
607 delOp := clause.Association{Association: "Pets", Type: clause.OpDelete}
608 if _, err := gorm.G[User](DB).Where("id = ?", user.ID).Set(delOp).Update(ctx); err != nil {
609 t.Fatalf("OpDelete failed: %v", err)
610 }
611 AssertAssociationCount(t, user, "Pets", 0, "after delete")
612 }
613
614 // HasOne: update and delete NamedPet via OpUpdate/OpDelete
615 func TestClauseAssociationSetUpdateAndDeleteHasOne(t *testing.T) {
616 ctx := context.Background()
617 user := User{Name: "TestClauseAssociationSetUpdateAndDeleteHasOne", Age: 25}
618 user.NamedPet = &Pet{Name: "np-before"}
619 if err := DB.Create(&user).Error; err != nil {
620 t.Fatalf("create user: %v", err)
621 }
622 AssertAssociationCount(t, user, "NamedPet", 1, "before")
623
624 upd := clause.Association{Association: "NamedPet", Type: clause.OpUpdate, Set: []clause.Assignment{{Column: clause.Column{Name: "name"}, Value: "np-after"}}}
625 if _, err := gorm.G[User](DB).Where("id = ?", user.ID).Set(upd).Update(ctx); err != nil {
626 t.Fatalf("OpUpdate has-one failed: %v", err)
627 }
628 var u1 User
629 if err := DB.Preload("NamedPet").First(&u1, user.ID).Error; err != nil {
630 t.Fatalf("load: %v", err)
631 }
632 if u1.NamedPet == nil || u1.NamedPet.Name != "np-after" {
633 t.Fatalf("expected name updated, got %+v", u1.NamedPet)
634 }
635
636 del := clause.Association{Association: "NamedPet", Type: clause.OpDelete}
637 if _, err := gorm.G[User](DB).Where("id = ?", user.ID).Set(del).Update(ctx); err != nil {
638 t.Fatalf("OpDelete has-one failed: %v", err)
639 }
640 AssertAssociationCount(t, user, "NamedPet", 0, "after delete")
641 }
642
643 // Many2Many append with map using Association API (regression for map support)
644 func TestAssociationMany2ManyAppendMap_GenericFile(t *testing.T) {
645 user := User{Name: "AssocM2MAppendMapGeneric", Age: 28}
646 if err := DB.Create(&user).Error; err != nil {
647 t.Fatalf("create user: %v", err)
648 }
649
650 if err := DB.Model(&user).Association("Languages").Append(map[string]interface{}{
651 "code": "gm2m_map_1", "name": "GMap1",
652 }); err != nil {
653 t.Fatalf("append map: %v", err)
654 }
655 AssertAssociationCount(t, user, "Languages", 1, "after append 1 map (generic file)")
656
657 // Append more maps individually
658 if err := DB.Model(&user).Association("Languages").Append(map[string]interface{}{"code": "gm2m_map_2", "name": "GMap2"}); err != nil {
659 t.Fatalf("append map 2: %v", err)
660 }
661 if err := DB.Model(&user).Association("Languages").Append(map[string]interface{}{"code": "gm2m_map_3", "name": "GMap3"}); err != nil {
662 t.Fatalf("append map 3: %v", err)
663 }
664 AssertAssociationCount(t, user, "Languages", 3, "after append 3 maps total (generic file)")
665 }
666
667 // BelongsTo: update and delete Company via OpUpdate/OpDelete
668 func TestClauseAssociationSetUpdateAndDeleteBelongsTo(t *testing.T) {
669 ctx := context.Background()
670
671 // Create company and user with company
672 company := Company{Name: "Electronics"}
673 if err := DB.Create(&company).Error; err != nil {
674 t.Fatalf("create company: %v", err)
675 }
676
677 user := User{Name: "John", Age: 25, CompanyID: &company.ID}
678 if err := DB.Create(&user).Error; err != nil {
679 t.Fatalf("create user: %v", err)
680 }
681
682 // Verify association exists
683 AssertAssociationCount(t, &user, "Company", 1, "before")
684
685 // Update company name via OpUpdate
686 upd := clause.Association{Association: "Company", Type: clause.OpUpdate, Set: []clause.Assignment{{Column: clause.Column{Name: "name"}, Value: "Electronics-New"}}}
687 if _, err := gorm.G[User](DB).Where("id = ?", user.ID).Set(upd).Update(ctx); err != nil {
688 t.Fatalf("OpUpdate belongs-to failed: %v", err)
689 }
690
691 var u1 User
692 if err := DB.Preload("Company").First(&u1, user.ID).Error; err != nil {
693 t.Fatalf("load: %v", err)
694 }
695
696 if u1.Company.ID == 0 || u1.Company.Name != "Electronics-New" {
697 t.Fatalf("expected company updated, got %+v", u1.Company)
698 }
699
700 // Unlink company association via OpUnlink (instead of OpDelete which would try to delete the company record)
701 unlink := clause.Association{Association: "Company", Type: clause.OpUnlink}
702 if _, err := gorm.G[User](DB).Where("id = ?", user.ID).Set(unlink).Update(ctx); err != nil {
703 t.Fatalf("OpUnlink belongs-to failed: %v", err)
704 }
705
706 var u2 User
707 if err := DB.Preload("Company").First(&u2, user.ID).Error; err != nil {
708 t.Fatalf("load: %v", err)
709 }
710
711 if u2.Company.ID != 0 {
712 t.Fatalf("expected company association cleared due to unlink, got %+v", u2.Company)
713 }
714 }
715
716 // Many2Many: update and delete via Set
717 func TestClauseAssociationSetUpdateAndDeleteMany2Many(t *testing.T) {
718 ctx := context.Background()
719 user := User{Name: "TestClauseAssociationSetUpdateAndDeleteMany2Many", Age: 25}
720 if err := DB.Create(&user).Error; err != nil {
721 t.Fatalf("create user: %v", err)
722 }
723 langs := []Language{{Code: "es", Name: "Spanish"}, {Code: "de", Name: "German"}}
724 for _, l := range langs {
725 DB.FirstOrCreate(&l, "code = ?", l.Code)
726 }
727 if err := DB.Model(&user).Association("Languages").Append(&langs); err != nil {
728 t.Fatalf("append: %v", err)
729 }
730 AssertAssociationCount(t, user, "Languages", 2, "before")
731
732 upd := clause.Association{Association: "Languages", Type: clause.OpUpdate, Set: []clause.Assignment{{Column: clause.Column{Name: "name"}, Value: "Espanol"}}, Conditions: []clause.Expression{clause.Eq{Column: clause.Column{Name: "code"}, Value: "es"}}}
733 if _, err := gorm.G[User](DB).Where("id = ?", user.ID).Set(upd).Update(ctx); err != nil {
734 t.Fatalf("OpUpdate m2m failed: %v", err)
735 }
736 var es Language
737 if err := DB.First(&es, "code = ?", "es").Error; err != nil {
738 t.Fatalf("load lang: %v", err)
739 }
740 if es.Name != "Espanol" {
741 t.Fatalf("expected updated language name, got %s", es.Name)
742 }
743
744 del := clause.Association{Association: "Languages", Type: clause.OpDelete, Conditions: []clause.Expression{clause.Eq{Column: clause.Column{Name: "code"}, Value: "es"}}}
745 if _, err := gorm.G[User](DB).Where("id = ?", user.ID).Set(del).Update(ctx); err != nil {
746 t.Fatalf("OpDelete m2m failed: %v", err)
747 }
748 AssertAssociationCount(t, user, "Languages", 1, "after delete one")
749 // language row remains
750 var count int64
751 if err := DB.Model(&Language{}).Where("code = ?", "es").Count(&count).Error; err != nil {
752 t.Fatalf("count lang: %v", err)
753 }
754 if count != 1 {
755 t.Fatalf("expected language row still exists, got %d", count)
756 }
757 }
758
759 // Multi-owners: HasMany update and delete
760 func TestClauseAssociationSetUpdateAndDeleteManyOwnersHasMany(t *testing.T) {
761 ctx := context.Background()
762 u1 := User{Name: "MultiOwners-HasMany-1", Age: 21}
763 u1.Pets = []*Pet{{Name: "p1"}}
764 u2 := User{Name: "MultiOwners-HasMany-2", Age: 22}
765 u2.Pets = []*Pet{{Name: "p2"}}
766 if err := DB.Create(&u1).Error; err != nil {
767 t.Fatalf("create u1: %v", err)
768 }
769 if err := DB.Create(&u2).Error; err != nil {
770 t.Fatalf("create u2: %v", err)
771 }
772 AssertAssociationCount(t, u1, "Pets", 1, "before")
773 AssertAssociationCount(t, u2, "Pets", 1, "before")
774
775 upd := clause.Association{Association: "Pets", Type: clause.OpUpdate, Set: []clause.Assignment{{Column: clause.Column{Name: "name"}, Value: "x"}}}
776 if _, err := gorm.G[User](DB).Where("id IN ?", []uint{u1.ID, u2.ID}).Set(upd).Update(ctx); err != nil {
777 t.Fatalf("OpUpdate has-many failed: %v", err)
778 }
779 var got1, got2 User
780 if err := DB.Preload("Pets").First(&got1, u1.ID).Error; err != nil {
781 t.Fatalf("load u1: %v", err)
782 }
783 if err := DB.Preload("Pets").First(&got2, u2.ID).Error; err != nil {
784 t.Fatalf("load u2: %v", err)
785 }
786 if len(got1.Pets) != 1 || got1.Pets[0].Name != "x" {
787 t.Fatalf("u1 pet not updated: %+v", got1.Pets)
788 }
789 if len(got2.Pets) != 1 || got2.Pets[0].Name != "x" {
790 t.Fatalf("u2 pet not updated: %+v", got2.Pets)
791 }
792
793 del := clause.Association{Association: "Pets", Type: clause.OpDelete}
794 if _, err := gorm.G[User](DB).Where("id IN ?", []uint{u1.ID, u2.ID}).Set(del).Update(ctx); err != nil {
795 t.Fatalf("OpDelete has-many failed: %v", err)
796 }
797 AssertAssociationCount(t, u1, "Pets", 0, "after delete")
798 AssertAssociationCount(t, u2, "Pets", 0, "after delete")
799 }
800
801 // Multi-owners: BelongsTo update and delete
802
803 func TestClauseAssociationSetUpdateAndDeleteManyOwnersBelongsTo(t *testing.T) {
804 ctx := context.Background()
805
806 // Create companies
807 c1 := Company{Name: "Electronics"}
808 c2 := Company{Name: "Books"}
809 if err := DB.Create(&c1).Error; err != nil {
810 t.Fatalf("create c1: %v", err)
811 }
812 if err := DB.Create(&c2).Error; err != nil {
813 t.Fatalf("create c2: %v", err)
814 }
815
816 // Create users with companies
817 u1 := User{Name: "John", Age: 25, CompanyID: &c1.ID}
818 u2 := User{Name: "Jane", Age: 30, CompanyID: &c2.ID}
819 if err := DB.Create(&u1).Error; err != nil {
820 t.Fatalf("create u1: %v", err)
821 }
822 if err := DB.Create(&u2).Error; err != nil {
823 t.Fatalf("create u2: %v", err)
824 }
825
826 // Verify associations exist
827 AssertAssociationCount(t, &u1, "Company", 1, "before")
828 AssertAssociationCount(t, &u2, "Company", 1, "before")
829
830 // Update companies via OpUpdate for multiple users
831 upd := clause.Association{Association: "Company", Type: clause.OpUpdate, Set: []clause.Assignment{{Column: clause.Column{Name: "name"}, Value: "Category-New"}}}
832 if _, err := gorm.G[User](DB).Where("id IN ?", []uint{u1.ID, u2.ID}).Set(upd).Update(ctx); err != nil {
833 t.Fatalf("OpUpdate belongs-to failed: %v", err)
834 }
835
836 // Check if companies were updated
837 var g1, g2 User
838 if err := DB.Preload("Company").First(&g1, u1.ID).Error; err != nil {
839 t.Fatalf("load u1: %v", err)
840 }
841 if err := DB.Preload("Company").First(&g2, u2.ID).Error; err != nil {
842 t.Fatalf("load u2: %v", err)
843 }
844
845 if (g1.Company.ID == 0 || g1.Company.Name != "Category-New") || (g2.Company.ID == 0 || g2.Company.Name != "Category-New") {
846 t.Fatalf("company names not updated: %+v, %+v", g1.Company, g2.Company)
847 }
848
849 // Unlink companies via OpUnlink for multiple users (instead of OpDelete which would try to delete the company records)
850 unlink := clause.Association{Association: "Company", Type: clause.OpUnlink}
851 if _, err := gorm.G[User](DB).Where("id IN ?", []uint{u1.ID, u2.ID}).Set(unlink).Update(ctx); err != nil {
852 t.Fatalf("OpUnlink belongs-to failed: %v", err)
853 }
854
855 // Reload users to reflect the changes in the database
856 if err := DB.First(&u1, u1.ID).Error; err != nil {
857 t.Fatalf("reload u1: %v", err)
858 }
859 if err := DB.First(&u2, u2.ID).Error; err != nil {
860 t.Fatalf("reload u2: %v", err)
861 }
862
863 // Check if company associations were cleared
864 AssertAssociationCount(t, &u1, "Company", 0, "after unlink")
865 AssertAssociationCount(t, &u2, "Company", 0, "after unlink")
866 }
867
868 // Multi-owners: Many2Many update and delete
869 func TestClauseAssociationSetUpdateAndDeleteManyOwnersMany2Many(t *testing.T) {
870 ctx := context.Background()
871 u1 := User{Name: "MultiOwners-M2M-1", Age: 21}
872 u2 := User{Name: "MultiOwners-M2M-2", Age: 22}
873 if err := DB.Create(&u1).Error; err != nil {
874 t.Fatalf("create u1: %v", err)
875 }
876 if err := DB.Create(&u2).Error; err != nil {
877 t.Fatalf("create u2: %v", err)
878 }
879 l1 := Language{Code: "zz", Name: "ZZ"}
880 l2 := Language{Code: "yy", Name: "YY"}
881 DB.FirstOrCreate(&l1, "code = ?", l1.Code)
882 DB.FirstOrCreate(&l2, "code = ?", l2.Code)
883 if err := DB.Model(&u1).Association("Languages").Append(&l1, &l2); err != nil {
884 t.Fatalf("append u1: %v", err)
885 }
886 if err := DB.Model(&u2).Association("Languages").Append(&l1, &l2); err != nil {
887 t.Fatalf("append u2: %v", err)
888 }
889 AssertAssociationCount(t, u1, "Languages", 2, "before")
890 AssertAssociationCount(t, u2, "Languages", 2, "before")
891
892 upd := clause.Association{Association: "Languages", Type: clause.OpUpdate, Set: []clause.Assignment{{Column: clause.Column{Name: "name"}, Value: "ZZZ"}}, Conditions: []clause.Expression{clause.Eq{Column: clause.Column{Name: "code"}, Value: "zz"}}}
893 if _, err := gorm.G[User](DB).Where("id IN ?", []uint{u1.ID, u2.ID}).Set(upd).Update(ctx); err != nil {
894 t.Fatalf("OpUpdate m2m failed: %v", err)
895 }
896 var l Language
897 if err := DB.First(&l, "code = ?", "zz").Error; err != nil {
898 t.Fatalf("load lang: %v", err)
899 }
900 if l.Name != "ZZZ" {
901 t.Fatalf("expected lang updated, got %s", l.Name)
902 }
903
904 del := clause.Association{Association: "Languages", Type: clause.OpDelete, Conditions: []clause.Expression{clause.Eq{Column: clause.Column{Name: "code"}, Value: "zz"}}}
905 if _, err := gorm.G[User](DB).Where("id IN ?", []uint{u1.ID, u2.ID}).Set(del).Update(ctx); err != nil {
906 t.Fatalf("OpDelete m2m failed: %v", err)
907 }
908 AssertAssociationCount(t, u1, "Languages", 1, "after delete")
909 AssertAssociationCount(t, u2, "Languages", 1, "after delete")
910 }
911
912 // Test Set + Update with has-one (NamedPet) using OpCreate
913 func TestClauseAssociationSetUpdateHasOneCreateValues(t *testing.T) {
914 ctx := context.Background()
915
916 user := User{Name: "TestClauseAssociationSetUpdateHasOneCreateValues", Age: 25}
917 if err := DB.Create(&user).Error; err != nil {
918 t.Fatalf("failed to create user: %v", err)
919 }
920
921 assocOp := clause.Association{
922 Association: "NamedPet",
923 Type: clause.OpCreate,
924 Values: []interface{}{Pet{Name: "named-pet"}},
925 }
926
927 rows, err := gorm.G[User](DB).Where("id = ?", user.ID).Set(assocOp).Update(ctx)
928 if err != nil {
929 t.Fatalf("Set Update has-one create values failed: %v", err)
930 }
931 if rows != 0 {
932 t.Fatalf("expected 0 rows affected for association-only update, got %d", rows)
933 }
934
935 var updated User
936 if err := DB.Preload("NamedPet").First(&updated, user.ID).Error; err != nil {
937 t.Fatalf("failed to load user: %v", err)
938 }
939 if updated.NamedPet == nil || updated.NamedPet.Name != "named-pet" {
940 t.Fatalf("expected named-pet created, got %+v", updated.NamedPet)
941 }
942 }
943
944 // Test Set + Update to clear all has-many (Pets) via OpUnlink without conditions
945 func TestClauseAssociationSetUpdateHasManyClear(t *testing.T) {
946 ctx := context.Background()
947
948 user := User{Name: "TestClauseAssociationSetUpdateHasManyClear", Age: 25}
949 user.Pets = []*Pet{{Name: "p1"}, {Name: "p2"}}
950 if err := DB.Create(&user).Error; err != nil {
951 t.Fatalf("failed to create user: %v", err)
952 }
953 AssertAssociationCount(t, user, "Pets", 2, "before clear")
954
955 assocOp := clause.Association{Association: "Pets", Type: clause.OpUnlink}
956 if rows, err := gorm.G[User](DB).Where("id = ?", user.ID).Set(assocOp).Update(ctx); err != nil {
957 t.Fatalf("Set Update has-many clear failed: %v", err)
958 } else if rows != 0 {
959 t.Fatalf("expected 0 rows affected for association-only update, got %d", rows)
960 }
961
962 AssertAssociationCount(t, user, "Pets", 0, "after clear")
963 }
964
965 // Test Set + Update with many-to-many unlink specific records using conditions
966 func TestClauseAssociationSetUpdateManyToManyUnlink(t *testing.T) {
967 ctx := context.Background()
968
969 user := User{Name: "TestClauseAssociationSetUpdateManyToManyUnlink", Age: 25}
970 if err := DB.Create(&user).Error; err != nil {
971 t.Fatalf("failed to create user: %v", err)
972 }
973
974 langs := []Language{{Code: "es", Name: "Spanish"}, {Code: "de", Name: "German"}}
975 for _, l := range langs {
976 DB.FirstOrCreate(&l, "code = ?", l.Code)
977 }
978
979 // Associate both
980 if err := DB.Model(&user).Association("Languages").Append(&langs); err != nil {
981 t.Fatalf("failed to append languages: %v", err)
982 }
983 AssertAssociationCount(t, user, "Languages", 2, "before unlink")
984
985 assocOp := clause.Association{
986 Association: "Languages",
987 Type: clause.OpUnlink,
988 Conditions: []clause.Expression{clause.Eq{Column: clause.Column{Name: "code"}, Value: "es"}},
989 }
990 if rows, err := gorm.G[User](DB).Where("id = ?", user.ID).Set(assocOp).Update(ctx); err != nil {
991 t.Fatalf("Set Update many-to-many unlink failed: %v", err)
992 } else if rows != 0 {
993 t.Fatalf("expected 0 rows affected for association-only update, got %d", rows)
994 }
995 AssertAssociationCount(t, user, "Languages", 1, "after unlink one")
996 }
997
998 // Test Set + Update with polymorphic has-many (Toys) using OpCreate
999 func TestClauseAssociationSetUpdatePolymorphicCreate(t *testing.T) {
1000 ctx := context.Background()
1001 user := User{Name: "TestClauseAssociationSetUpdatePolymorphicCreate", Age: 25}
1002 if err := DB.Create(&user).Error; err != nil {
1003 t.Fatalf("failed to create user: %v", err)
1004 }
1005
1006 assocOp := clause.Association{
1007 Association: "Toys",
1008 Type: clause.OpCreate,
1009 Set: []clause.Assignment{{Column: clause.Column{Name: "name"}, Value: "yo-yo"}},
1010 }
1011 if rows, err := gorm.G[User](DB).Where("id = ?", user.ID).Set(assocOp).Update(ctx); err != nil {
1012 t.Fatalf("Set Update polymorphic create failed: %v", err)
1013 } else if rows != 0 {
1014 t.Fatalf("expected 0 rows affected for association-only update, got %d", rows)
1015 }
1016
1017 AssertAssociationCount(t, user, "Toys", 1, "after create toy")
1018 }
1019
1020 // Test Set + Update across multiple owners
1021 func TestClauseAssociationSetUpdateMultipleOwners(t *testing.T) {
1022 ctx := context.Background()
1023
1024 u1 := User{Name: "SetUpdateMultipleOwners-1", Age: 20}
1025 u2 := User{Name: "SetUpdateMultipleOwners-2", Age: 21}
1026 if err := DB.Create(&u1).Error; err != nil {
1027 t.Fatalf("create u1: %v", err)
1028 }
1029 if err := DB.Create(&u2).Error; err != nil {
1030 t.Fatalf("create u2: %v", err)
1031 }
1032
1033 assocOp := clause.Association{Association: "Pets", Type: clause.OpCreate, Set: []clause.Assignment{{Column: clause.Column{Name: "name"}, Value: "multi-pet"}}}
1034 if rows, err := gorm.G[User](DB).Where("name IN ?", []string{u1.Name, u2.Name}).Set(assocOp).Update(ctx); err != nil {
1035 t.Fatalf("Set Update multi owners failed: %v", err)
1036 } else if rows != 0 {
1037 t.Fatalf("expected 0 rows affected for association-only update, got %d", rows)
1038 }
1039
1040 AssertAssociationCount(t, u1, "Pets", 1, "u1 after create")
1041 AssertAssociationCount(t, u2, "Pets", 1, "u2 after create")
1042 }