Debian Codegraph @

schema/relationship_test.go

raw
1 package schema_test
2
3 import (
4 "sync"
5 "testing"
6 "time"
7
8 "gorm.io/gorm"
9 "gorm.io/gorm/schema"
10 "gorm.io/gorm/utils/tests"
11 )
12
13 func checkStructRelation(t *testing.T, data interface{}, relations ...Relation) {
14 if s, err := schema.Parse(data, &sync.Map{}, schema.NamingStrategy{}); err != nil {
15 t.Errorf("Failed to parse schema, got error %v", err)
16 } else {
17 for _, rel := range relations {
18 checkSchemaRelation(t, s, rel)
19 }
20 }
21 }
22
23 func TestBelongsToOverrideForeignKey(t *testing.T) {
24 type Profile struct {
25 gorm.Model
26 Name string
27 }
28
29 type User struct {
30 gorm.Model
31 Profile Profile `gorm:"ForeignKey:ProfileRefer"`
32 ProfileRefer int
33 }
34
35 checkStructRelation(t, &User{}, Relation{
36 Name: "Profile", Type: schema.BelongsTo, Schema: "User", FieldSchema: "Profile",
37 References: []Reference{{"ID", "Profile", "ProfileRefer", "User", "", false}},
38 })
39 }
40
41 func TestBelongsToOverrideReferences(t *testing.T) {
42 type Profile struct {
43 gorm.Model
44 Refer string
45 Name string
46 }
47
48 type User struct {
49 gorm.Model
50 Profile Profile `gorm:"ForeignKey:ProfileID;References:Refer"`
51 ProfileID int
52 }
53
54 checkStructRelation(t, &User{}, Relation{
55 Name: "Profile", Type: schema.BelongsTo, Schema: "User", FieldSchema: "Profile",
56 References: []Reference{{"Refer", "Profile", "ProfileID", "User", "", false}},
57 })
58 }
59
60 func TestBelongsToWithOnlyReferences(t *testing.T) {
61 type Profile struct {
62 gorm.Model
63 Refer string
64 Name string
65 }
66
67 type User struct {
68 gorm.Model
69 Profile Profile `gorm:"References:Refer"`
70 ProfileRefer int
71 }
72
73 checkStructRelation(t, &User{}, Relation{
74 Name: "Profile", Type: schema.BelongsTo, Schema: "User", FieldSchema: "Profile",
75 References: []Reference{{"Refer", "Profile", "ProfileRefer", "User", "", false}},
76 })
77 }
78
79 func TestBelongsToWithOnlyReferences2(t *testing.T) {
80 type Profile struct {
81 gorm.Model
82 Refer string
83 Name string
84 }
85
86 type User struct {
87 gorm.Model
88 Profile Profile `gorm:"References:Refer"`
89 ProfileID int
90 }
91
92 checkStructRelation(t, &User{}, Relation{
93 Name: "Profile", Type: schema.BelongsTo, Schema: "User", FieldSchema: "Profile",
94 References: []Reference{{"Refer", "Profile", "ProfileID", "User", "", false}},
95 })
96 }
97
98 func TestSelfReferentialBelongsTo(t *testing.T) {
99 type User struct {
100 ID int32 `gorm:"primaryKey"`
101 Name string
102 CreatorID *int32
103 Creator *User
104 }
105
106 checkStructRelation(t, &User{}, Relation{
107 Name: "Creator", Type: schema.BelongsTo, Schema: "User", FieldSchema: "User",
108 References: []Reference{{"ID", "User", "CreatorID", "User", "", false}},
109 })
110 }
111
112 func TestSelfReferentialBelongsToOverrideReferences(t *testing.T) {
113 type User struct {
114 ID int32 `gorm:"primaryKey"`
115 Name string
116 CreatedBy *int32
117 Creator *User `gorm:"foreignKey:CreatedBy;references:ID"`
118 }
119
120 checkStructRelation(t, &User{}, Relation{
121 Name: "Creator", Type: schema.BelongsTo, Schema: "User", FieldSchema: "User",
122 References: []Reference{{"ID", "User", "CreatedBy", "User", "", false}},
123 })
124 }
125
126 func TestBelongsToWithMixin(t *testing.T) {
127 type Profile struct {
128 gorm.Model
129 Refer string
130 Name string
131 }
132
133 type ProfileMixin struct {
134 Profile Profile `gorm:"References:Refer"`
135 ProfileRefer int
136 }
137
138 type User struct {
139 gorm.Model
140 ProfileMixin
141 }
142
143 checkStructRelation(t, &User{}, Relation{
144 Name: "Profile", Type: schema.BelongsTo, Schema: "User", FieldSchema: "Profile",
145 References: []Reference{{"Refer", "Profile", "ProfileRefer", "User", "", false}},
146 })
147 }
148
149 func TestHasOneOverrideForeignKey(t *testing.T) {
150 type Profile struct {
151 gorm.Model
152 Name string
153 UserRefer uint
154 }
155
156 type User struct {
157 gorm.Model
158 Profile Profile `gorm:"ForeignKey:UserRefer"`
159 }
160
161 checkStructRelation(t, &User{}, Relation{
162 Name: "Profile", Type: schema.HasOne, Schema: "User", FieldSchema: "Profile",
163 References: []Reference{{"ID", "User", "UserRefer", "Profile", "", true}},
164 })
165 }
166
167 func TestHasOneOverrideReferences(t *testing.T) {
168 type Profile struct {
169 gorm.Model
170 Name string
171 UserID uint
172 }
173
174 type User struct {
175 gorm.Model
176 Refer string
177 Profile Profile `gorm:"ForeignKey:UserID;References:Refer"`
178 }
179
180 checkStructRelation(t, &User{}, Relation{
181 Name: "Profile", Type: schema.HasOne, Schema: "User", FieldSchema: "Profile",
182 References: []Reference{{"Refer", "User", "UserID", "Profile", "", true}},
183 })
184 }
185
186 func TestHasOneOverrideReferences2(t *testing.T) {
187 type Profile struct {
188 gorm.Model
189 Name string
190 }
191
192 type User struct {
193 gorm.Model
194 ProfileID uint `gorm:"column:profile_id"`
195 Profile *Profile `gorm:"foreignKey:ID;references:ProfileID"`
196 }
197
198 checkStructRelation(t, &User{}, Relation{
199 Name: "Profile", Type: schema.HasOne, Schema: "User", FieldSchema: "Profile",
200 References: []Reference{{"ProfileID", "User", "ID", "Profile", "", true}},
201 })
202 }
203
204 func TestHasOneWithOnlyReferences(t *testing.T) {
205 type Profile struct {
206 gorm.Model
207 Name string
208 UserRefer uint
209 }
210
211 type User struct {
212 gorm.Model
213 Refer string
214 Profile Profile `gorm:"References:Refer"`
215 }
216
217 checkStructRelation(t, &User{}, Relation{
218 Name: "Profile", Type: schema.HasOne, Schema: "User", FieldSchema: "Profile",
219 References: []Reference{{"Refer", "User", "UserRefer", "Profile", "", true}},
220 })
221 }
222
223 func TestHasOneWithOnlyReferences2(t *testing.T) {
224 type Profile struct {
225 gorm.Model
226 Name string
227 UserID uint
228 }
229
230 type User struct {
231 gorm.Model
232 Refer string
233 Profile Profile `gorm:"References:Refer"`
234 }
235
236 checkStructRelation(t, &User{}, Relation{
237 Name: "Profile", Type: schema.HasOne, Schema: "User", FieldSchema: "Profile",
238 References: []Reference{{"Refer", "User", "UserID", "Profile", "", true}},
239 })
240 }
241
242 func TestHasManyOverrideForeignKey(t *testing.T) {
243 type Profile struct {
244 gorm.Model
245 Name string
246 UserRefer uint
247 }
248
249 type User struct {
250 gorm.Model
251 Profile []Profile `gorm:"ForeignKey:UserRefer"`
252 }
253
254 checkStructRelation(t, &User{}, Relation{
255 Name: "Profile", Type: schema.HasMany, Schema: "User", FieldSchema: "Profile",
256 References: []Reference{{"ID", "User", "UserRefer", "Profile", "", true}},
257 })
258 }
259
260 func TestHasManyOverrideReferences(t *testing.T) {
261 type Profile struct {
262 gorm.Model
263 Name string
264 UserID uint
265 }
266
267 type User struct {
268 gorm.Model
269 Refer string
270 Profile []Profile `gorm:"ForeignKey:UserID;References:Refer"`
271 }
272
273 checkStructRelation(t, &User{}, Relation{
274 Name: "Profile", Type: schema.HasMany, Schema: "User", FieldSchema: "Profile",
275 References: []Reference{{"Refer", "User", "UserID", "Profile", "", true}},
276 })
277 }
278
279 func TestMany2ManyOverrideForeignKeyAndReferences(t *testing.T) {
280 type Profile struct {
281 gorm.Model
282 Name string
283 UserRefer uint
284 }
285
286 type User struct {
287 gorm.Model
288 Profiles []Profile `gorm:"many2many:user_profiles;ForeignKey:Refer;JoinForeignKey:UserReferID;References:UserRefer;JoinReferences:ProfileRefer"`
289 Profiles2 []Profile `gorm:"many2many:user_profiles2;ForeignKey:refer;JoinForeignKey:user_refer_id;References:user_refer;JoinReferences:profile_refer"`
290 Refer uint
291 }
292
293 checkStructRelation(t, &User{}, Relation{
294 Name: "Profiles", Type: schema.Many2Many, Schema: "User", FieldSchema: "Profile",
295 JoinTable: JoinTable{Name: "user_profiles", Table: "user_profiles"},
296 References: []Reference{
297 {"Refer", "User", "UserReferID", "user_profiles", "", true},
298 {"UserRefer", "Profile", "ProfileRefer", "user_profiles", "", false},
299 },
300 }, Relation{
301 Name: "Profiles2", Type: schema.Many2Many, Schema: "User", FieldSchema: "Profile",
302 JoinTable: JoinTable{Name: "user_profiles2", Table: "user_profiles2"},
303 References: []Reference{
304 {"Refer", "User", "User_refer_id", "user_profiles2", "", true},
305 {"UserRefer", "Profile", "Profile_refer", "user_profiles2", "", false},
306 },
307 })
308 }
309
310 func TestMany2ManyOverrideForeignKey(t *testing.T) {
311 type Profile struct {
312 gorm.Model
313 Name string
314 UserRefer uint
315 }
316
317 type User struct {
318 gorm.Model
319 Profiles []Profile `gorm:"many2many:user_profiles;ForeignKey:Refer;References:UserRefer"`
320 Refer uint
321 }
322
323 checkStructRelation(t, &User{}, Relation{
324 Name: "Profiles", Type: schema.Many2Many, Schema: "User", FieldSchema: "Profile",
325 JoinTable: JoinTable{Name: "user_profiles", Table: "user_profiles"},
326 References: []Reference{
327 {"Refer", "User", "UserRefer", "user_profiles", "", true},
328 {"UserRefer", "Profile", "ProfileUserRefer", "user_profiles", "", false},
329 },
330 })
331 }
332
333 func TestMany2ManySharedForeignKey(t *testing.T) {
334 type Profile struct {
335 gorm.Model
336 Name string
337 Kind string
338 ProfileRefer uint
339 }
340
341 type User struct {
342 gorm.Model
343 Profiles []Profile `gorm:"many2many:user_profiles;foreignKey:Refer,Kind;joinForeignKey:UserRefer,Kind;References:ProfileRefer,Kind;joinReferences:ProfileR,Kind"`
344 Kind string
345 Refer uint
346 }
347
348 checkStructRelation(t, &User{}, Relation{
349 Name: "Profiles", Type: schema.Many2Many, Schema: "User", FieldSchema: "Profile",
350 JoinTable: JoinTable{Name: "user_profiles", Table: "user_profiles"},
351 References: []Reference{
352 {"Refer", "User", "UserRefer", "user_profiles", "", true},
353 {"Kind", "User", "Kind", "user_profiles", "", true},
354 {"ProfileRefer", "Profile", "ProfileR", "user_profiles", "", false},
355 {"Kind", "Profile", "Kind", "user_profiles", "", false},
356 },
357 })
358 }
359
360 func TestMany2ManyOverrideJoinForeignKey(t *testing.T) {
361 type Profile struct {
362 gorm.Model
363 Name string
364 UserRefer uint
365 }
366
367 type User struct {
368 gorm.Model
369 Profiles []Profile `gorm:"many2many:user_profile;JoinForeignKey:UserReferID;JoinReferences:ProfileRefer"`
370 Refer uint
371 }
372
373 checkStructRelation(t, &User{}, Relation{
374 Name: "Profiles", Type: schema.Many2Many, Schema: "User", FieldSchema: "Profile",
375 JoinTable: JoinTable{Name: "user_profile", Table: "user_profile"},
376 References: []Reference{
377 {"ID", "User", "UserReferID", "user_profile", "", true},
378 {"ID", "Profile", "ProfileRefer", "user_profile", "", false},
379 },
380 })
381 }
382
383 func TestBuildReadonlyMany2ManyRelation(t *testing.T) {
384 type Profile struct {
385 gorm.Model
386 Name string
387 UserRefer uint
388 }
389
390 type User struct {
391 gorm.Model
392 Profiles []Profile `gorm:"->;many2many:user_profile;JoinForeignKey:UserReferID;JoinReferences:ProfileRefer"`
393 Refer uint
394 }
395
396 checkStructRelation(t, &User{}, Relation{
397 Name: "Profiles", Type: schema.Many2Many, Schema: "User", FieldSchema: "Profile",
398 JoinTable: JoinTable{Name: "user_profile", Table: "user_profile"},
399 References: []Reference{
400 {"ID", "User", "UserReferID", "user_profile", "", true},
401 {"ID", "Profile", "ProfileRefer", "user_profile", "", false},
402 },
403 })
404 }
405
406 func TestMany2ManyWithMultiPrimaryKeys(t *testing.T) {
407 type Tag struct {
408 ID uint `gorm:"primary_key"`
409 Locale string `gorm:"primary_key"`
410 Value string
411 }
412
413 type Blog struct {
414 ID uint `gorm:"primary_key"`
415 Locale string `gorm:"primary_key"`
416 Subject string
417 Body string
418 Tags []Tag `gorm:"many2many:blog_tags;"`
419 SharedTags []Tag `gorm:"many2many:shared_blog_tags;ForeignKey:id;References:id"`
420 LocaleTags []Tag `gorm:"many2many:locale_blog_tags;ForeignKey:id,locale;References:id"`
421 }
422
423 checkStructRelation(t, &Blog{},
424 Relation{
425 Name: "Tags", Type: schema.Many2Many, Schema: "Blog", FieldSchema: "Tag",
426 JoinTable: JoinTable{Name: "blog_tags", Table: "blog_tags"},
427 References: []Reference{
428 {"ID", "Blog", "BlogID", "blog_tags", "", true},
429 {"Locale", "Blog", "BlogLocale", "blog_tags", "", true},
430 {"ID", "Tag", "TagID", "blog_tags", "", false},
431 {"Locale", "Tag", "TagLocale", "blog_tags", "", false},
432 },
433 },
434 Relation{
435 Name: "SharedTags", Type: schema.Many2Many, Schema: "Blog", FieldSchema: "Tag",
436 JoinTable: JoinTable{Name: "shared_blog_tags", Table: "shared_blog_tags"},
437 References: []Reference{
438 {"ID", "Blog", "BlogID", "shared_blog_tags", "", true},
439 {"ID", "Tag", "TagID", "shared_blog_tags", "", false},
440 },
441 },
442 Relation{
443 Name: "LocaleTags", Type: schema.Many2Many, Schema: "Blog", FieldSchema: "Tag",
444 JoinTable: JoinTable{Name: "locale_blog_tags", Table: "locale_blog_tags"},
445 References: []Reference{
446 {"ID", "Blog", "BlogID", "locale_blog_tags", "", true},
447 {"Locale", "Blog", "BlogLocale", "locale_blog_tags", "", true},
448 {"ID", "Tag", "TagID", "locale_blog_tags", "", false},
449 },
450 },
451 )
452 }
453
454 func TestMultipleMany2Many(t *testing.T) {
455 type Thing struct {
456 ID int
457 }
458
459 type Person struct {
460 ID int
461 Likes []Thing `gorm:"many2many:likes"`
462 Dislikes []Thing `gorm:"many2many:dislikes"`
463 }
464
465 checkStructRelation(t, &Person{},
466 Relation{
467 Name: "Likes", Type: schema.Many2Many, Schema: "Person", FieldSchema: "Thing",
468 JoinTable: JoinTable{Name: "likes", Table: "likes"},
469 References: []Reference{
470 {"ID", "Person", "PersonID", "likes", "", true},
471 {"ID", "Thing", "ThingID", "likes", "", false},
472 },
473 },
474 Relation{
475 Name: "Dislikes", Type: schema.Many2Many, Schema: "Person", FieldSchema: "Thing",
476 JoinTable: JoinTable{Name: "dislikes", Table: "dislikes"},
477 References: []Reference{
478 {"ID", "Person", "PersonID", "dislikes", "", true},
479 {"ID", "Thing", "ThingID", "dislikes", "", false},
480 },
481 },
482 )
483 }
484
485 func TestSelfReferentialMany2Many(t *testing.T) {
486 type User struct {
487 ID int32 `gorm:"primaryKey"`
488 Name string
489 CreatedBy int32
490 Creators []User `gorm:"foreignKey:CreatedBy"`
491 AnotherPro interface{} `gorm:"-"`
492 }
493
494 checkStructRelation(t, &User{}, Relation{
495 Name: "Creators", Type: schema.HasMany, Schema: "User", FieldSchema: "User",
496 References: []Reference{{"ID", "User", "CreatedBy", "User", "", true}},
497 })
498
499 user, err := schema.Parse(&User{}, &sync.Map{}, schema.NamingStrategy{})
500 if err != nil {
501 t.Fatalf("failed to parse schema")
502 }
503
504 relSchema := user.Relationships.Relations["Creators"].FieldSchema
505 if user != relSchema {
506 t.Fatalf("schema should be same, expects %p but got %p", user, relSchema)
507 }
508 }
509
510 type CreatedByModel struct {
511 CreatedByID uint
512 CreatedBy *CreatedUser
513 }
514
515 type CreatedUser struct {
516 gorm.Model
517 CreatedByModel
518 }
519
520 func TestEmbeddedRelation(t *testing.T) {
521 checkStructRelation(t, &CreatedUser{}, Relation{
522 Name: "CreatedBy", Type: schema.BelongsTo, Schema: "CreatedUser", FieldSchema: "CreatedUser",
523 References: []Reference{
524 {"ID", "CreatedUser", "CreatedByID", "CreatedUser", "", false},
525 },
526 })
527
528 userSchema, err := schema.Parse(&CreatedUser{}, &sync.Map{}, schema.NamingStrategy{})
529 if err != nil {
530 t.Fatalf("failed to parse schema, got error %v", err)
531 }
532
533 if len(userSchema.Relationships.Relations) != 1 {
534 t.Fatalf("expects 1 relations, but got %v", len(userSchema.Relationships.Relations))
535 }
536
537 if createdByRel, ok := userSchema.Relationships.Relations["CreatedBy"]; ok {
538 if createdByRel.FieldSchema != userSchema {
539 t.Fatalf("expects same field schema, but got new %p, old %p", createdByRel.FieldSchema, userSchema)
540 }
541 } else {
542 t.Fatalf("expects created by relations, but not found")
543 }
544 }
545
546 func TestEmbeddedHas(t *testing.T) {
547 type Toy struct {
548 ID int
549 Name string
550 OwnerID int
551 OwnerType string
552 }
553 type User struct {
554 ID int
555 Cat struct {
556 Name string
557 Toy Toy `gorm:"polymorphic:Owner;"`
558 Toys []Toy `gorm:"polymorphic:Owner;"`
559 } `gorm:"embedded;embeddedPrefix:cat_"`
560 Dog struct {
561 ID int
562 Name string
563 UserID int
564 Toy Toy `gorm:"polymorphic:Owner;"`
565 Toys []Toy `gorm:"polymorphic:Owner;"`
566 }
567 Toys []Toy `gorm:"polymorphic:Owner;"`
568 }
569
570 s, err := schema.Parse(&User{}, &sync.Map{}, schema.NamingStrategy{})
571 if err != nil {
572 t.Fatalf("Failed to parse schema, got error %v", err)
573 }
574
575 checkEmbeddedRelations(t, s.Relationships.EmbeddedRelations, map[string]EmbeddedRelations{
576 "Cat": {
577 Relations: map[string]Relation{
578 "Toy": {
579 Name: "Toy",
580 Type: schema.HasOne,
581 Schema: "User",
582 FieldSchema: "Toy",
583 Polymorphic: Polymorphic{ID: "OwnerID", Type: "OwnerType", Value: "users"},
584 References: []Reference{
585 {ForeignKey: "OwnerType", ForeignSchema: "Toy", PrimaryValue: "users"},
586 {ForeignKey: "OwnerType", ForeignSchema: "Toy", PrimaryValue: "users"},
587 },
588 },
589 "Toys": {
590 Name: "Toys",
591 Type: schema.HasMany,
592 Schema: "User",
593 FieldSchema: "Toy",
594 Polymorphic: Polymorphic{ID: "OwnerID", Type: "OwnerType", Value: "users"},
595 References: []Reference{
596 {ForeignKey: "OwnerType", ForeignSchema: "Toy", PrimaryValue: "users"},
597 {ForeignKey: "OwnerType", ForeignSchema: "Toy", PrimaryValue: "users"},
598 },
599 },
600 },
601 },
602 })
603 }
604
605 func TestPolymorphic(t *testing.T) {
606 t.Run("has one", func(t *testing.T) {
607 type Toy struct {
608 ID int
609 Name string
610 OwnerID int
611 OwnerType string
612 }
613
614 type Cat struct {
615 ID int
616 Name string
617 Toy Toy `gorm:"polymorphic:Owner;"`
618 }
619
620 s, err := schema.Parse(&Cat{}, &sync.Map{}, schema.NamingStrategy{})
621 if err != nil {
622 t.Fatalf("Failed to parse schema, got error %v", err)
623 }
624
625 checkEmbeddedRelations(t, s.Relationships.EmbeddedRelations, map[string]EmbeddedRelations{
626 "Cat": {
627 Relations: map[string]Relation{
628 "Toy": {
629 Name: "Toy",
630 Type: schema.HasOne,
631 Schema: "User",
632 FieldSchema: "Toy",
633 Polymorphic: Polymorphic{ID: "OwnerID", Type: "OwnerType", Value: "users"},
634 References: []Reference{
635 {ForeignKey: "OwnerType", ForeignSchema: "Toy", PrimaryValue: "users"},
636 },
637 },
638 },
639 },
640 })
641 })
642
643 t.Run("has one with custom polymorphic type and id", func(t *testing.T) {
644 type Toy struct {
645 ID int
646 Name string
647 RefId int
648 Type string
649 }
650
651 type Cat struct {
652 ID int
653 Name string
654 Toy Toy `gorm:"polymorphic:Owner;polymorphicType:Type;polymorphicId:RefId"`
655 }
656
657 s, err := schema.Parse(&Cat{}, &sync.Map{}, schema.NamingStrategy{})
658 if err != nil {
659 t.Fatalf("Failed to parse schema, got error %v", err)
660 }
661
662 checkEmbeddedRelations(t, s.Relationships.EmbeddedRelations, map[string]EmbeddedRelations{
663 "Cat": {
664 Relations: map[string]Relation{
665 "Toy": {
666 Name: "Toy",
667 Type: schema.HasOne,
668 Schema: "User",
669 FieldSchema: "Toy",
670 Polymorphic: Polymorphic{ID: "ref_id", Type: "Type", Value: "users"},
671 References: []Reference{
672 {ForeignKey: "Type", ForeignSchema: "Toy", PrimaryValue: "users"},
673 },
674 },
675 },
676 },
677 })
678 })
679
680 t.Run("has one with only polymorphic type", func(t *testing.T) {
681 type Toy struct {
682 ID int
683 Name string
684 OwnerID int
685 Type string
686 }
687
688 type Cat struct {
689 ID int
690 Name string
691 Toy Toy `gorm:"polymorphic:Owner;polymorphicType:Type"`
692 }
693
694 s, err := schema.Parse(&Cat{}, &sync.Map{}, schema.NamingStrategy{})
695 if err != nil {
696 t.Fatalf("Failed to parse schema, got error %v", err)
697 }
698
699 checkEmbeddedRelations(t, s.Relationships.EmbeddedRelations, map[string]EmbeddedRelations{
700 "Cat": {
701 Relations: map[string]Relation{
702 "Toy": {
703 Name: "Toy",
704 Type: schema.HasOne,
705 Schema: "User",
706 FieldSchema: "Toy",
707 Polymorphic: Polymorphic{ID: "owner_id", Type: "Type", Value: "users"},
708 References: []Reference{
709 {ForeignKey: "Type", ForeignSchema: "Toy", PrimaryValue: "users"},
710 },
711 },
712 },
713 },
714 })
715 })
716
717 t.Run("has many", func(t *testing.T) {
718 type Toy struct {
719 ID int
720 Name string
721 OwnerID int
722 OwnerType string
723 }
724
725 type Cat struct {
726 ID int
727 Name string
728 Toys []Toy `gorm:"polymorphic:Owner;"`
729 }
730
731 s, err := schema.Parse(&Cat{}, &sync.Map{}, schema.NamingStrategy{})
732 if err != nil {
733 t.Fatalf("Failed to parse schema, got error %v", err)
734 }
735
736 checkEmbeddedRelations(t, s.Relationships.EmbeddedRelations, map[string]EmbeddedRelations{
737 "Cat": {
738 Relations: map[string]Relation{
739 "Toys": {
740 Name: "Toys",
741 Type: schema.HasMany,
742 Schema: "User",
743 FieldSchema: "Toy",
744 Polymorphic: Polymorphic{ID: "OwnerID", Type: "OwnerType", Value: "users"},
745 References: []Reference{
746 {ForeignKey: "OwnerType", ForeignSchema: "Toy", PrimaryValue: "users"},
747 },
748 },
749 },
750 },
751 })
752 })
753
754 t.Run("has many with custom polymorphic type and id", func(t *testing.T) {
755 type Toy struct {
756 ID int
757 Name string
758 RefId int
759 Type string
760 }
761
762 type Cat struct {
763 ID int
764 Name string
765 Toys []Toy `gorm:"polymorphicType:Type;polymorphicId:RefId"`
766 }
767
768 s, err := schema.Parse(&Cat{}, &sync.Map{}, schema.NamingStrategy{})
769 if err != nil {
770 t.Fatalf("Failed to parse schema, got error %v", err)
771 }
772
773 checkEmbeddedRelations(t, s.Relationships.EmbeddedRelations, map[string]EmbeddedRelations{
774 "Cat": {
775 Relations: map[string]Relation{
776 "Toys": {
777 Name: "Toys",
778 Type: schema.HasMany,
779 Schema: "User",
780 FieldSchema: "Toy",
781 Polymorphic: Polymorphic{ID: "ref_id", Type: "Type", Value: "users"},
782 References: []Reference{
783 {ForeignKey: "Type", ForeignSchema: "Toy", PrimaryValue: "users"},
784 },
785 },
786 },
787 },
788 })
789 })
790 }
791
792 func TestEmbeddedBelongsTo(t *testing.T) {
793 type Country struct {
794 ID int `gorm:"primaryKey"`
795 Name string
796 }
797 type Address struct {
798 CountryID int
799 Country Country
800 }
801 type NestedAddress struct {
802 Address
803 }
804 type CountryMixin struct {
805 CountryID int
806 Country Country
807 }
808 type Org struct {
809 ID int
810 PostalAddress Address `gorm:"embedded;embeddedPrefix:postal_address_"`
811 VisitingAddress Address `gorm:"embedded;embeddedPrefix:visiting_address_"`
812 AddressID int
813 Address struct {
814 ID int
815 Address
816 }
817 NestedAddress *NestedAddress `gorm:"embedded;embeddedPrefix:nested_address_"`
818 CountryMixin
819 }
820
821 s, err := schema.Parse(&Org{}, &sync.Map{}, schema.NamingStrategy{})
822 if err != nil {
823 t.Errorf("Failed to parse schema, got error %v", err)
824 }
825
826 checkEmbeddedRelations(t, s.Relationships.EmbeddedRelations, map[string]EmbeddedRelations{
827 "PostalAddress": {
828 Relations: map[string]Relation{
829 "Country": {
830 Name: "Country", Type: schema.BelongsTo, Schema: "Org", FieldSchema: "Country",
831 References: []Reference{
832 {PrimaryKey: "ID", PrimarySchema: "Country", ForeignKey: "CountryID", ForeignSchema: "Org"},
833 },
834 },
835 },
836 },
837 "VisitingAddress": {
838 Relations: map[string]Relation{
839 "Country": {
840 Name: "Country", Type: schema.BelongsTo, Schema: "Org", FieldSchema: "Country",
841 References: []Reference{
842 {PrimaryKey: "ID", PrimarySchema: "Country", ForeignKey: "CountryID", ForeignSchema: "Org"},
843 },
844 },
845 },
846 },
847 "NestedAddress": {
848 Relations: map[string]Relation{
849 "Country": {
850 Name: "Country", Type: schema.BelongsTo, Schema: "Org", FieldSchema: "Country",
851 References: []Reference{
852 {PrimaryKey: "ID", PrimarySchema: "Country", ForeignKey: "CountryID", ForeignSchema: "Org"},
853 },
854 },
855 },
856 },
857 })
858 }
859
860 func TestVariableRelation(t *testing.T) {
861 var result struct {
862 User
863 }
864
865 checkStructRelation(t, &result, Relation{
866 Name: "Account", Type: schema.HasOne, Schema: "", FieldSchema: "Account",
867 References: []Reference{
868 {"ID", "", "UserID", "Account", "", true},
869 },
870 })
871
872 checkStructRelation(t, &result, Relation{
873 Name: "Company", Type: schema.BelongsTo, Schema: "", FieldSchema: "Company",
874 References: []Reference{
875 {"ID", "Company", "CompanyID", "", "", false},
876 },
877 })
878 }
879
880 func TestSameForeignKey(t *testing.T) {
881 type UserAux struct {
882 gorm.Model
883 Aux string
884 UUID string
885 }
886
887 type User struct {
888 gorm.Model
889 Name string
890 UUID string
891 Aux *UserAux `gorm:"foreignkey:UUID;references:UUID"`
892 }
893
894 checkStructRelation(t, &User{},
895 Relation{
896 Name: "Aux", Type: schema.HasOne, Schema: "User", FieldSchema: "UserAux",
897 References: []Reference{
898 {"UUID", "User", "UUID", "UserAux", "", true},
899 },
900 },
901 )
902 }
903
904 func TestBelongsToSameForeignKey(t *testing.T) {
905 type User struct {
906 gorm.Model
907 Name string
908 UUID string
909 }
910
911 type UserAux struct {
912 gorm.Model
913 Aux string
914 UUID string
915 User User `gorm:"ForeignKey:UUID;references:UUID;belongsTo"`
916 }
917
918 checkStructRelation(t, &UserAux{},
919 Relation{
920 Name: "User", Type: schema.BelongsTo, Schema: "UserAux", FieldSchema: "User",
921 References: []Reference{
922 {"UUID", "User", "UUID", "UserAux", "", false},
923 },
924 },
925 )
926 }
927
928 func TestHasOneWithSameForeignKey(t *testing.T) {
929 type Profile struct {
930 gorm.Model
931 Name string
932 ProfileRefer int // not used in relationship
933 }
934
935 type User struct {
936 gorm.Model
937 Profile Profile `gorm:"ForeignKey:ID;references:ProfileRefer"`
938 ProfileRefer int
939 }
940
941 checkStructRelation(t, &User{}, Relation{
942 Name: "Profile", Type: schema.HasOne, Schema: "User", FieldSchema: "Profile",
943 References: []Reference{{"ProfileRefer", "User", "ID", "Profile", "", true}},
944 })
945 }
946
947 func TestHasManySameForeignKey(t *testing.T) {
948 type Profile struct {
949 gorm.Model
950 Name string
951 UserRefer uint
952 }
953
954 type User struct {
955 gorm.Model
956 UserRefer uint
957 Profile []Profile `gorm:"ForeignKey:UserRefer"`
958 }
959
960 checkStructRelation(t, &User{}, Relation{
961 Name: "Profile", Type: schema.HasMany, Schema: "User", FieldSchema: "Profile",
962 References: []Reference{{"ID", "User", "UserRefer", "Profile", "", true}},
963 })
964 }
965
966 type Author struct {
967 gorm.Model
968 }
969
970 type Book struct {
971 gorm.Model
972 Author Author
973 AuthorID uint
974 }
975
976 func (Book) TableName() string {
977 return "my_schema.a_very_very_very_very_very_very_very_very_long_table_name"
978 }
979
980 func TestParseConstraintNameWithSchemaQualifiedLongTableName(t *testing.T) {
981 s, err := schema.Parse(
982 &Book{},
983 &sync.Map{},
984 schema.NamingStrategy{IdentifierMaxLength: 64},
985 )
986 if err != nil {
987 t.Fatalf("Failed to parse schema")
988 }
989
990 expectedConstraintName := "fk_my_schema_a_very_very_very_very_very_very_very_very_l4db13eec"
991 constraint := s.Relationships.Relations["Author"].ParseConstraint()
992
993 if constraint.Name != expectedConstraintName {
994 t.Fatalf(
995 "expected constraint name %s, got %s",
996 expectedConstraintName,
997 constraint.Name,
998 )
999 }
1000 }
1001
1002 type InfoRelation struct {
1003 ID int
1004 Code string
1005 Info1 []*Info1 `gorm:"foreignkey:Code;references:Code"`
1006 Info2 []*Info2 `gorm:"foreignkey:Code;references:Code"`
1007 }
1008
1009 type Info1 struct {
1010 CreatedAt time.Time
1011 UpdatedAt time.Time
1012 Code string
1013 Relation []*InfoRelation `gorm:"foreignkey:Code;references:Code"`
1014 }
1015
1016 type Info2 struct {
1017 CreatedAt time.Time
1018 UpdatedAt time.Time
1019 Code string
1020 Relation []*InfoRelation `gorm:"foreignkey:Code;references:Code"`
1021 }
1022
1023 func TestDataRace(t *testing.T) {
1024 syncMap := &sync.Map{}
1025 for i := 0; i < 10; i++ {
1026 go func() {
1027 schema.Parse(&Info1{}, syncMap, schema.NamingStrategy{IdentifierMaxLength: 64})
1028 }()
1029
1030 go func() {
1031 schema.Parse(&Info2{}, syncMap, schema.NamingStrategy{IdentifierMaxLength: 64})
1032 }()
1033
1034 go func() {
1035 var result User
1036 schema.Parse(&result, syncMap, schema.NamingStrategy{IdentifierMaxLength: 64})
1037 }()
1038 go func() {
1039 var result tests.Account
1040 schema.Parse(&result, syncMap, schema.NamingStrategy{IdentifierMaxLength: 64})
1041 }()
1042 }
1043 }