| 1 |
package tests_test |
| 2 |
|
| 3 |
import ( |
| 4 |
"testing" |
| 5 |
|
| 6 |
"gorm.io/gorm" |
| 7 |
"gorm.io/gorm/clause" |
| 8 |
"gorm.io/gorm/schema" |
| 9 |
. "gorm.io/gorm/utils/tests" |
| 10 |
) |
| 11 |
|
| 12 |
func AssertAssociationCount(t *testing.T, data interface{}, name string, result int64, reason string) { |
| 13 |
if count := DB.Model(data).Association(name).Count(); count != result { |
| 14 |
t.Fatalf("invalid %v count %v, expects: %v got %v", name, reason, result, count) |
| 15 |
} |
| 16 |
|
| 17 |
var newUser User |
| 18 |
if user, ok := data.(User); ok { |
| 19 |
DB.Find(&newUser, "id = ?", user.ID) |
| 20 |
} else if user, ok := data.(*User); ok { |
| 21 |
DB.Find(&newUser, "id = ?", user.ID) |
| 22 |
} |
| 23 |
|
| 24 |
if newUser.ID != 0 { |
| 25 |
if count := DB.Model(&newUser).Association(name).Count(); count != result { |
| 26 |
t.Fatalf("invalid %v count %v, expects: %v got %v", name, reason, result, count) |
| 27 |
} |
| 28 |
} |
| 29 |
} |
| 30 |
|
| 31 |
func TestInvalidAssociation(t *testing.T) { |
| 32 |
user := *GetUser("invalid", Config{Company: true, Manager: true}) |
| 33 |
if err := DB.Model(&user).Association("Invalid").Find(&user.Company).Error; err == nil { |
| 34 |
t.Fatalf("should return errors for invalid association, but got nil") |
| 35 |
} |
| 36 |
} |
| 37 |
|
| 38 |
func TestAssociationNotNullClear(t *testing.T) { |
| 39 |
type Profile struct { |
| 40 |
gorm.Model |
| 41 |
Number string |
| 42 |
MemberID uint `gorm:"not null"` |
| 43 |
} |
| 44 |
|
| 45 |
type Member struct { |
| 46 |
gorm.Model |
| 47 |
Profiles []Profile |
| 48 |
} |
| 49 |
|
| 50 |
DB.Migrator().DropTable(&Member{}, &Profile{}) |
| 51 |
|
| 52 |
if err := DB.AutoMigrate(&Member{}, &Profile{}); err != nil { |
| 53 |
t.Fatalf("Failed to migrate, got error: %v", err) |
| 54 |
} |
| 55 |
|
| 56 |
member := &Member{ |
| 57 |
Profiles: []Profile{{ |
| 58 |
Number: "1", |
| 59 |
}, { |
| 60 |
Number: "2", |
| 61 |
}}, |
| 62 |
} |
| 63 |
|
| 64 |
if err := DB.Create(&member).Error; err != nil { |
| 65 |
t.Fatalf("Failed to create test data, got error: %v", err) |
| 66 |
} |
| 67 |
|
| 68 |
if err := DB.Model(member).Association("Profiles").Clear(); err == nil { |
| 69 |
t.Fatalf("No error occurred during clearind not null association") |
| 70 |
} |
| 71 |
} |
| 72 |
|
| 73 |
func TestForeignKeyConstraints(t *testing.T) { |
| 74 |
tidbSkip(t, "not support the foreign key feature") |
| 75 |
|
| 76 |
type Profile struct { |
| 77 |
ID uint |
| 78 |
Name string |
| 79 |
MemberID uint |
| 80 |
} |
| 81 |
|
| 82 |
type Member struct { |
| 83 |
ID uint |
| 84 |
Refer uint `gorm:"uniqueIndex"` |
| 85 |
Name string |
| 86 |
Profile Profile `gorm:"Constraint:OnUpdate:CASCADE,OnDelete:CASCADE;FOREIGNKEY:MemberID;References:Refer"` |
| 87 |
} |
| 88 |
|
| 89 |
DB.Migrator().DropTable(&Profile{}, &Member{}) |
| 90 |
|
| 91 |
if err := DB.AutoMigrate(&Profile{}, &Member{}); err != nil { |
| 92 |
t.Fatalf("Failed to migrate, got error: %v", err) |
| 93 |
} |
| 94 |
|
| 95 |
member := Member{Refer: 1, Name: "foreign_key_constraints", Profile: Profile{Name: "my_profile"}} |
| 96 |
|
| 97 |
DB.Create(&member) |
| 98 |
|
| 99 |
var profile Profile |
| 100 |
if err := DB.First(&profile, "id = ?", member.Profile.ID).Error; err != nil { |
| 101 |
t.Fatalf("failed to find profile, got error: %v", err) |
| 102 |
} else if profile.MemberID != member.ID { |
| 103 |
t.Fatalf("member id is not equal: expects: %v, got: %v", member.ID, profile.MemberID) |
| 104 |
} |
| 105 |
|
| 106 |
member.Profile = Profile{} |
| 107 |
DB.Model(&member).Update("Refer", 100) |
| 108 |
|
| 109 |
var profile2 Profile |
| 110 |
if err := DB.First(&profile2, "id = ?", profile.ID).Error; err != nil { |
| 111 |
t.Fatalf("failed to find profile, got error: %v", err) |
| 112 |
} else if profile2.MemberID != 100 { |
| 113 |
t.Fatalf("member id is not equal: expects: %v, got: %v", 100, profile2.MemberID) |
| 114 |
} |
| 115 |
|
| 116 |
if r := DB.Delete(&member); r.Error != nil || r.RowsAffected != 1 { |
| 117 |
t.Fatalf("Should delete member, got error: %v, affected: %v", r.Error, r.RowsAffected) |
| 118 |
} |
| 119 |
|
| 120 |
var result Member |
| 121 |
if err := DB.First(&result, member.ID).Error; err == nil { |
| 122 |
t.Fatalf("Should not find deleted member") |
| 123 |
} |
| 124 |
|
| 125 |
if err := DB.First(&profile2, profile.ID).Error; err == nil { |
| 126 |
t.Fatalf("Should not find deleted profile") |
| 127 |
} |
| 128 |
} |
| 129 |
|
| 130 |
func TestForeignKeyConstraintsBelongsTo(t *testing.T) { |
| 131 |
tidbSkip(t, "not support the foreign key feature") |
| 132 |
|
| 133 |
type Profile struct { |
| 134 |
ID uint |
| 135 |
Name string |
| 136 |
Refer uint `gorm:"uniqueIndex"` |
| 137 |
} |
| 138 |
|
| 139 |
type Member struct { |
| 140 |
ID uint |
| 141 |
Name string |
| 142 |
ProfileID uint |
| 143 |
Profile Profile `gorm:"Constraint:OnUpdate:CASCADE,OnDelete:CASCADE;FOREIGNKEY:ProfileID;References:Refer"` |
| 144 |
} |
| 145 |
|
| 146 |
DB.Migrator().DropTable(&Profile{}, &Member{}) |
| 147 |
|
| 148 |
if err := DB.AutoMigrate(&Profile{}, &Member{}); err != nil { |
| 149 |
t.Fatalf("Failed to migrate, got error: %v", err) |
| 150 |
} |
| 151 |
|
| 152 |
member := Member{Name: "foreign_key_constraints_belongs_to", Profile: Profile{Name: "my_profile_belongs_to", Refer: 1}} |
| 153 |
|
| 154 |
DB.Create(&member) |
| 155 |
|
| 156 |
var profile Profile |
| 157 |
if err := DB.First(&profile, "id = ?", member.Profile.ID).Error; err != nil { |
| 158 |
t.Fatalf("failed to find profile, got error: %v", err) |
| 159 |
} else if profile.Refer != member.ProfileID { |
| 160 |
t.Fatalf("member id is not equal: expects: %v, got: %v", profile.Refer, member.ProfileID) |
| 161 |
} |
| 162 |
|
| 163 |
DB.Model(&profile).Update("Refer", 100) |
| 164 |
|
| 165 |
var member2 Member |
| 166 |
if err := DB.First(&member2, "id = ?", member.ID).Error; err != nil { |
| 167 |
t.Fatalf("failed to find member, got error: %v", err) |
| 168 |
} else if member2.ProfileID != 100 { |
| 169 |
t.Fatalf("member id is not equal: expects: %v, got: %v", 100, member2.ProfileID) |
| 170 |
} |
| 171 |
|
| 172 |
if r := DB.Delete(&profile); r.Error != nil || r.RowsAffected != 1 { |
| 173 |
t.Fatalf("Should delete member, got error: %v, affected: %v", r.Error, r.RowsAffected) |
| 174 |
} |
| 175 |
|
| 176 |
var result Member |
| 177 |
if err := DB.First(&result, member.ID).Error; err == nil { |
| 178 |
t.Fatalf("Should not find deleted member") |
| 179 |
} |
| 180 |
|
| 181 |
if err := DB.First(&profile, profile.ID).Error; err == nil { |
| 182 |
t.Fatalf("Should not find deleted profile") |
| 183 |
} |
| 184 |
} |
| 185 |
|
| 186 |
func TestFullSaveAssociations(t *testing.T) { |
| 187 |
coupon := &Coupon{ |
| 188 |
AppliesToProduct: []*CouponProduct{ |
| 189 |
{ProductId: "full-save-association-product1"}, |
| 190 |
}, |
| 191 |
AmountOff: 10, |
| 192 |
PercentOff: 0.0, |
| 193 |
} |
| 194 |
|
| 195 |
err := DB. |
| 196 |
Session(&gorm.Session{FullSaveAssociations: true}). |
| 197 |
Create(coupon).Error |
| 198 |
if err != nil { |
| 199 |
t.Errorf("Failed, got error: %v", err) |
| 200 |
} |
| 201 |
|
| 202 |
if DB.First(&Coupon{}, "id = ?", coupon.ID).Error != nil { |
| 203 |
t.Errorf("Failed to query saved coupon") |
| 204 |
} |
| 205 |
|
| 206 |
if DB.First(&CouponProduct{}, "coupon_id = ? AND product_id = ?", coupon.ID, "full-save-association-product1").Error != nil { |
| 207 |
t.Errorf("Failed to query saved association") |
| 208 |
} |
| 209 |
|
| 210 |
orders := []Order{{Num: "order1", Coupon: coupon}, {Num: "order2", Coupon: coupon}} |
| 211 |
if err := DB.Create(&orders).Error; err != nil { |
| 212 |
t.Errorf("failed to create orders, got %v", err) |
| 213 |
} |
| 214 |
|
| 215 |
coupon2 := Coupon{ |
| 216 |
AppliesToProduct: []*CouponProduct{{Desc: "coupon-description"}}, |
| 217 |
} |
| 218 |
|
| 219 |
DB.Session(&gorm.Session{FullSaveAssociations: true}).Create(&coupon2) |
| 220 |
var result Coupon |
| 221 |
if err := DB.Preload("AppliesToProduct").First(&result, "id = ?", coupon2.ID).Error; err != nil { |
| 222 |
t.Errorf("Failed to create coupon w/o name, got error: %v", err) |
| 223 |
} |
| 224 |
|
| 225 |
if len(result.AppliesToProduct) != 1 { |
| 226 |
t.Errorf("Failed to preload AppliesToProduct") |
| 227 |
} |
| 228 |
} |
| 229 |
|
| 230 |
func TestSaveBelongsCircularReference(t *testing.T) { |
| 231 |
parent := Parent{} |
| 232 |
DB.Create(&parent) |
| 233 |
|
| 234 |
child := Child{ParentID: &parent.ID, Parent: &parent} |
| 235 |
DB.Create(&child) |
| 236 |
|
| 237 |
parent.FavChildID = child.ID |
| 238 |
parent.FavChild = &child |
| 239 |
DB.Save(&parent) |
| 240 |
|
| 241 |
var parent1 Parent |
| 242 |
DB.First(&parent1, parent.ID) |
| 243 |
AssertObjEqual(t, parent, parent1, "ID", "FavChildID") |
| 244 |
|
| 245 |
// Save and Updates is the same |
| 246 |
DB.Updates(&parent) |
| 247 |
DB.First(&parent1, parent.ID) |
| 248 |
AssertObjEqual(t, parent, parent1, "ID", "FavChildID") |
| 249 |
} |
| 250 |
|
| 251 |
func TestSaveHasManyCircularReference(t *testing.T) { |
| 252 |
parent := Parent{} |
| 253 |
DB.Create(&parent) |
| 254 |
|
| 255 |
child := Child{ParentID: &parent.ID, Parent: &parent, Name: "HasManyCircularReference"} |
| 256 |
child1 := Child{ParentID: &parent.ID, Parent: &parent, Name: "HasManyCircularReference1"} |
| 257 |
|
| 258 |
parent.Children = []*Child{&child, &child1} |
| 259 |
DB.Save(&parent) |
| 260 |
|
| 261 |
var children []*Child |
| 262 |
DB.Where("parent_id = ?", parent.ID).Find(&children) |
| 263 |
if len(children) != len(parent.Children) || |
| 264 |
children[0].ID != parent.Children[0].ID || |
| 265 |
children[1].ID != parent.Children[1].ID { |
| 266 |
t.Errorf("circular reference children save not equal children:%v parent.Children:%v", |
| 267 |
children, parent.Children) |
| 268 |
} |
| 269 |
} |
| 270 |
|
| 271 |
func TestAssociationError(t *testing.T) { |
| 272 |
user := *GetUser("TestAssociationError", Config{Pets: 2, Company: true, Account: true, Languages: 2}) |
| 273 |
DB.Create(&user) |
| 274 |
|
| 275 |
var user1 User |
| 276 |
DB.Preload("Company").Preload("Pets").Preload("Account").Preload("Languages").First(&user1) |
| 277 |
|
| 278 |
var emptyUser User |
| 279 |
var err error |
| 280 |
// belongs to |
| 281 |
err = DB.Model(&emptyUser).Association("Company").Delete(&user1.Company) |
| 282 |
AssertEqual(t, err, gorm.ErrPrimaryKeyRequired) |
| 283 |
// has many |
| 284 |
err = DB.Model(&emptyUser).Association("Pets").Delete(&user1.Pets) |
| 285 |
AssertEqual(t, err, gorm.ErrPrimaryKeyRequired) |
| 286 |
// has one |
| 287 |
err = DB.Model(&emptyUser).Association("Account").Delete(&user1.Account) |
| 288 |
AssertEqual(t, err, gorm.ErrPrimaryKeyRequired) |
| 289 |
// many to many |
| 290 |
err = DB.Model(&emptyUser).Association("Languages").Delete(&user1.Languages) |
| 291 |
AssertEqual(t, err, gorm.ErrPrimaryKeyRequired) |
| 292 |
} |
| 293 |
|
| 294 |
type ( |
| 295 |
myType string |
| 296 |
emptyQueryClause struct { |
| 297 |
Field *schema.Field |
| 298 |
} |
| 299 |
) |
| 300 |
|
| 301 |
func (myType) QueryClauses(f *schema.Field) []clause.Interface { |
| 302 |
return []clause.Interface{emptyQueryClause{Field: f}} |
| 303 |
} |
| 304 |
|
| 305 |
func (sd emptyQueryClause) Name() string { |
| 306 |
return "empty" |
| 307 |
} |
| 308 |
|
| 309 |
func (sd emptyQueryClause) Build(clause.Builder) { |
| 310 |
} |
| 311 |
|
| 312 |
func (sd emptyQueryClause) MergeClause(*clause.Clause) { |
| 313 |
} |
| 314 |
|
| 315 |
func (sd emptyQueryClause) ModifyStatement(stmt *gorm.Statement) { |
| 316 |
// do nothing |
| 317 |
} |
| 318 |
|
| 319 |
func TestAssociationEmptyQueryClause(t *testing.T) { |
| 320 |
type Organization struct { |
| 321 |
gorm.Model |
| 322 |
Name string |
| 323 |
} |
| 324 |
type Region struct { |
| 325 |
gorm.Model |
| 326 |
Name string |
| 327 |
Organizations []Organization `gorm:"many2many:region_orgs;"` |
| 328 |
} |
| 329 |
type RegionOrg struct { |
| 330 |
RegionId uint |
| 331 |
OrganizationId uint |
| 332 |
Empty myType |
| 333 |
} |
| 334 |
if err := DB.SetupJoinTable(&Region{}, "Organizations", &RegionOrg{}); err != nil { |
| 335 |
t.Fatalf("Failed to set up join table, got error: %s", err) |
| 336 |
} |
| 337 |
if err := DB.Migrator().DropTable(&Organization{}, &Region{}); err != nil { |
| 338 |
t.Fatalf("Failed to migrate, got error: %s", err) |
| 339 |
} |
| 340 |
if err := DB.AutoMigrate(&Organization{}, &Region{}); err != nil { |
| 341 |
t.Fatalf("Failed to migrate, got error: %v", err) |
| 342 |
} |
| 343 |
region := &Region{Name: "Region1"} |
| 344 |
if err := DB.Create(region).Error; err != nil { |
| 345 |
t.Fatalf("fail to create region %v", err) |
| 346 |
} |
| 347 |
var orgs []Organization |
| 348 |
|
| 349 |
if err := DB.Model(&Region{}).Association("Organizations").Find(&orgs); err != nil { |
| 350 |
t.Fatalf("fail to find region organizations %v", err) |
| 351 |
} else { |
| 352 |
AssertEqual(t, len(orgs), 0) |
| 353 |
} |
| 354 |
} |
| 355 |
|
| 356 |
type AssociationEmptyUser struct { |
| 357 |
ID uint |
| 358 |
Name string |
| 359 |
Pets []AssociationEmptyPet |
| 360 |
} |
| 361 |
|
| 362 |
type AssociationEmptyPet struct { |
| 363 |
AssociationEmptyUserID *uint `gorm:"uniqueIndex:uniq_user_id_name"` |
| 364 |
Name string `gorm:"uniqueIndex:uniq_user_id_name;size:256"` |
| 365 |
} |
| 366 |
|
| 367 |
func TestAssociationEmptyPrimaryKey(t *testing.T) { |
| 368 |
if DB.Dialector.Name() != "mysql" { |
| 369 |
t.Skip() |
| 370 |
} |
| 371 |
DB.Migrator().DropTable(&AssociationEmptyUser{}, &AssociationEmptyPet{}) |
| 372 |
DB.AutoMigrate(&AssociationEmptyUser{}, &AssociationEmptyPet{}) |
| 373 |
|
| 374 |
id := uint(100) |
| 375 |
user := AssociationEmptyUser{ |
| 376 |
ID: id, |
| 377 |
Name: "jinzhu", |
| 378 |
Pets: []AssociationEmptyPet{ |
| 379 |
{AssociationEmptyUserID: &id, Name: "bar"}, |
| 380 |
{AssociationEmptyUserID: &id, Name: "foo"}, |
| 381 |
}, |
| 382 |
} |
| 383 |
|
| 384 |
err := DB.Session(&gorm.Session{FullSaveAssociations: true}).Create(&user).Error |
| 385 |
if err != nil { |
| 386 |
t.Fatalf("Failed to create, got error: %v", err) |
| 387 |
} |
| 388 |
|
| 389 |
var result AssociationEmptyUser |
| 390 |
err = DB.Preload("Pets").First(&result, &id).Error |
| 391 |
if err != nil { |
| 392 |
t.Fatalf("Failed to find, got error: %v", err) |
| 393 |
} |
| 394 |
|
| 395 |
AssertEqual(t, result, user) |
| 396 |
} |
| 397 |
|
| 398 |
// Ensure Association.Append/Replace supports map for many2many |
| 399 |
func TestAssociationMany2ManyAppendMap(t *testing.T) { |
| 400 |
user := *GetUser("assoc_m2m_append_map", Config{}) |
| 401 |
if err := DB.Create(&user).Error; err != nil { |
| 402 |
t.Fatalf("create user: %v", err) |
| 403 |
} |
| 404 |
|
| 405 |
// Append single map |
| 406 |
if err := DB.Model(&user).Association("Languages").Append(map[string]interface{}{ |
| 407 |
"code": "am2m_map_1", "name": "AppendMap1", |
| 408 |
}); err != nil { |
| 409 |
t.Fatalf("append map: %v", err) |
| 410 |
} |
| 411 |
AssertAssociationCount(t, user, "Languages", 1, "after append 1 map") |
| 412 |
|
| 413 |
// Append more maps individually |
| 414 |
if err := DB.Model(&user).Association("Languages").Append(map[string]interface{}{"code": "am2m_map_2", "name": "AppendMap2"}); err != nil { |
| 415 |
t.Fatalf("append map 2: %v", err) |
| 416 |
} |
| 417 |
if err := DB.Model(&user).Association("Languages").Append(map[string]interface{}{"code": "am2m_map_3", "name": "AppendMap3"}); err != nil { |
| 418 |
t.Fatalf("append map 3: %v", err) |
| 419 |
} |
| 420 |
AssertAssociationCount(t, user, "Languages", 3, "after append 3 maps total") |
| 421 |
|
| 422 |
// Verify codes exist |
| 423 |
var langs []Language |
| 424 |
if err := DB.Model(&user).Association("Languages").Find(&langs); err != nil { |
| 425 |
t.Fatalf("find languages: %v", err) |
| 426 |
} |
| 427 |
codeSet := map[string]bool{} |
| 428 |
for _, l := range langs { |
| 429 |
codeSet[l.Code] = true |
| 430 |
} |
| 431 |
for _, c := range []string{"am2m_map_1", "am2m_map_2", "am2m_map_3"} { |
| 432 |
if !codeSet[c] { |
| 433 |
t.Fatalf("expected language code %s present", c) |
| 434 |
} |
| 435 |
} |
| 436 |
} |
| 437 |
|
| 438 |
func TestAssociationMany2ManyReplaceMap(t *testing.T) { |
| 439 |
user := *GetUser("assoc_m2m_replace_map", Config{}) |
| 440 |
if err := DB.Create(&user).Error; err != nil { |
| 441 |
t.Fatalf("create user: %v", err) |
| 442 |
} |
| 443 |
|
| 444 |
// Prime with one language |
| 445 |
if err := DB.Model(&user).Association("Languages").Append(&Language{Code: "prime", Name: "Prime"}); err != nil { |
| 446 |
t.Fatalf("prime append: %v", err) |
| 447 |
} |
| 448 |
AssertAssociationCount(t, user, "Languages", 1, "before replace") |
| 449 |
|
| 450 |
// Replace with a new map value |
| 451 |
if err := DB.Model(&user).Association("Languages").Replace(map[string]interface{}{ |
| 452 |
"code": "rm2m_map_1", "name": "ReplaceMap1", |
| 453 |
}); err != nil { |
| 454 |
t.Fatalf("replace map: %v", err) |
| 455 |
} |
| 456 |
AssertAssociationCount(t, user, "Languages", 1, "after replace with 1 map") |
| 457 |
|
| 458 |
var langs []Language |
| 459 |
if err := DB.Model(&user).Association("Languages").Find(&langs); err != nil { |
| 460 |
t.Fatalf("find languages after replace: %v", err) |
| 461 |
} |
| 462 |
if len(langs) != 1 || langs[0].Code != "rm2m_map_1" { |
| 463 |
t.Fatalf("expected only rm2m_map_1 after replace, got %+v", langs) |
| 464 |
} |
| 465 |
} |