From 423d9496c15ece5ce69e5d5d594429dfc31da8e0 Mon Sep 17 00:00:00 2001 From: Jinzhu Date: Thu, 28 Aug 2014 15:33:43 +0800 Subject: [PATCH] update tests --- anonymous_struct_test.go | 28 ++++++ association_test.go | 100 ++++++++++----------- callbacks_test.go | 52 +++++------ create_test.go | 24 ++--- delete_test.go | 36 ++++---- main_test.go | 176 ++++++++++++++++++------------------- migration_test.go | 52 +++++------ query_test.go | 184 +++++++++++++++++++-------------------- scope.go | 11 ++- scope_test.go | 8 +- update_test.go | 70 +++++++-------- 11 files changed, 389 insertions(+), 352 deletions(-) create mode 100644 anonymous_struct_test.go diff --git a/anonymous_struct_test.go b/anonymous_struct_test.go new file mode 100644 index 00000000..20ed7864 --- /dev/null +++ b/anonymous_struct_test.go @@ -0,0 +1,28 @@ +package gorm_test + +import "testing" + +type BasePost struct { + Id int64 + Title string + Url string +} + +type HNPost struct { + BasePost + Upvotes int32 +} + +type EngadgetPost struct { + BasePost + ImageUrl string +} + +func TestAnonymousStruct(t *testing.T) { + hn := HNPost{} + hn.Title = "hn_news" + DB.Debug().Save(hn) + + var news HNPost + DB.Debug().First(&news) +} diff --git a/association_test.go b/association_test.go index 457b2183..37a904bb 100644 --- a/association_test.go +++ b/association_test.go @@ -3,13 +3,13 @@ package gorm_test import "testing" func TestHasOneAndHasManyAssociation(t *testing.T) { - db.DropTable(Category{}) - db.DropTable(Post{}) - db.DropTable(Comment{}) + DB.DropTable(Category{}) + DB.DropTable(Post{}) + DB.DropTable(Comment{}) - db.CreateTable(Category{}) - db.CreateTable(Post{}) - db.CreateTable(Comment{}) + DB.CreateTable(Category{}) + DB.CreateTable(Post{}) + DB.CreateTable(Comment{}) post := Post{ Title: "post 1", @@ -19,22 +19,22 @@ func TestHasOneAndHasManyAssociation(t *testing.T) { MainCategory: Category{Name: "Main Category 1"}, } - if err := db.Save(&post).Error; err != nil { + if err := DB.Save(&post).Error; err != nil { t.Errorf("Got errors when save post") } - if db.First(&Category{}, "name = ?", "Category 1").Error != nil { + if DB.First(&Category{}, "name = ?", "Category 1").Error != nil { t.Errorf("Category should be saved") } var p Post - db.First(&p, post.Id) + DB.First(&p, post.Id) if post.CategoryId.Int64 == 0 || p.CategoryId.Int64 == 0 || post.MainCategoryId == 0 || p.MainCategoryId == 0 { t.Errorf("Category Id should exist") } - if db.First(&Comment{}, "content = ?", "Comment 1").Error != nil { + if DB.First(&Comment{}, "content = ?", "Comment 1").Error != nil { t.Errorf("Comment 1 should be saved") } if post.Comments[0].PostId == 0 { @@ -42,7 +42,7 @@ func TestHasOneAndHasManyAssociation(t *testing.T) { } var comment Comment - if db.First(&comment, "content = ?", "Comment 2").Error != nil { + if DB.First(&comment, "content = ?", "Comment 2").Error != nil { t.Errorf("Comment 2 should be saved") } @@ -51,7 +51,7 @@ func TestHasOneAndHasManyAssociation(t *testing.T) { } comment3 := Comment{Content: "Comment 3", Post: Post{Title: "Title 3", Body: "Body 3"}} - db.Save(&comment3) + DB.Save(&comment3) } func TestRelated(t *testing.T) { @@ -63,7 +63,7 @@ func TestRelated(t *testing.T) { CreditCard: CreditCard{Number: "1234567890"}, } - db.Save(&user) + DB.Save(&user) if user.CreditCard.Id == 0 { t.Errorf("After user save, credit card should have id") @@ -78,131 +78,131 @@ func TestRelated(t *testing.T) { } var emails []Email - db.Model(&user).Related(&emails) + DB.Model(&user).Related(&emails) if len(emails) != 2 { t.Errorf("Should have two emails") } var emails2 []Email - db.Model(&user).Where("email = ?", "jinzhu@example.com").Related(&emails2) + DB.Model(&user).Where("email = ?", "jinzhu@example.com").Related(&emails2) if len(emails2) != 1 { t.Errorf("Should have two emails") } var user1 User - db.Model(&user).Related(&user1.Emails) + DB.Model(&user).Related(&user1.Emails) if len(user1.Emails) != 2 { t.Errorf("Should have only one email match related condition") } var address1 Address - db.Model(&user).Related(&address1, "BillingAddressId") + DB.Model(&user).Related(&address1, "BillingAddressId") if address1.Address1 != "Billing Address - Address 1" { t.Errorf("Should get billing address from user correctly") } user1 = User{} - db.Model(&address1).Related(&user1, "BillingAddressId") - if db.NewRecord(user1) { + DB.Model(&address1).Related(&user1, "BillingAddressId") + if DB.NewRecord(user1) { t.Errorf("Should get user from address correctly") } var user2 User - db.Model(&emails[0]).Related(&user2) + DB.Model(&emails[0]).Related(&user2) if user2.Id != user.Id || user2.Name != user.Name { t.Errorf("Should get user from email correctly") } var creditcard CreditCard var user3 User - db.First(&creditcard, "number = ?", "1234567890") - db.Model(&creditcard).Related(&user3) + DB.First(&creditcard, "number = ?", "1234567890") + DB.Model(&creditcard).Related(&user3) if user3.Id != user.Id || user3.Name != user.Name { t.Errorf("Should get user from credit card correctly") } - if !db.Model(&CreditCard{}).Related(&User{}).RecordNotFound() { + if !DB.Model(&CreditCard{}).Related(&User{}).RecordNotFound() { t.Errorf("RecordNotFound for Related") } } func TestManyToMany(t *testing.T) { - db.Raw("delete from languages") + DB.Raw("delete from languages") var languages = []Language{{Name: "ZH"}, {Name: "EN"}} user := User{Name: "Many2Many", Languages: languages} - db.Save(&user) + DB.Save(&user) // Query var newLanguages []Language - db.Model(&user).Related(&newLanguages, "Languages") + DB.Model(&user).Related(&newLanguages, "Languages") if len(newLanguages) != len([]string{"ZH", "EN"}) { t.Errorf("Query many to many relations") } newLanguages = []Language{} - db.Model(&user).Association("Languages").Find(&newLanguages) + DB.Model(&user).Association("Languages").Find(&newLanguages) if len(newLanguages) != len([]string{"ZH", "EN"}) { t.Errorf("Should be able to find many to many relations") } - if db.Model(&user).Association("Languages").Count() != len([]string{"ZH", "EN"}) { + if DB.Model(&user).Association("Languages").Count() != len([]string{"ZH", "EN"}) { t.Errorf("Count should return correct result") } // Append - db.Model(&user).Association("Languages").Append(&Language{Name: "DE"}) - if db.Where("name = ?", "DE").First(&Language{}).RecordNotFound() { + DB.Model(&user).Association("Languages").Append(&Language{Name: "DE"}) + if DB.Where("name = ?", "DE").First(&Language{}).RecordNotFound() { t.Errorf("New record should be saved when append") } languageA := Language{Name: "AA"} - db.Save(&languageA) - db.Model(&User{Id: user.Id}).Association("Languages").Append(languageA) + DB.Save(&languageA) + DB.Model(&User{Id: user.Id}).Association("Languages").Append(languageA) languageC := Language{Name: "CC"} - db.Save(&languageC) - db.Model(&user).Association("Languages").Append(&[]Language{{Name: "BB"}, languageC}) - db.Model(&User{Id: user.Id}).Association("Languages").Append([]Language{{Name: "DD"}, {Name: "EE"}}) + DB.Save(&languageC) + DB.Model(&user).Association("Languages").Append(&[]Language{{Name: "BB"}, languageC}) + DB.Model(&User{Id: user.Id}).Association("Languages").Append([]Language{{Name: "DD"}, {Name: "EE"}}) totalLanguages := []string{"ZH", "EN", "DE", "AA", "BB", "CC", "DD", "EE"} - if db.Model(&user).Association("Languages").Count() != len(totalLanguages) { + if DB.Model(&user).Association("Languages").Count() != len(totalLanguages) { t.Errorf("All appended languages should be saved") } // Delete var language Language - db.Where("name = ?", "EE").First(&language) - db.Model(&user).Association("Languages").Delete(language, &language) - if db.Model(&user).Association("Languages").Count() != len(totalLanguages)-1 { + DB.Where("name = ?", "EE").First(&language) + DB.Model(&user).Association("Languages").Delete(language, &language) + if DB.Model(&user).Association("Languages").Count() != len(totalLanguages)-1 { t.Errorf("Relations should be deleted with Delete") } - if db.Where("name = ?", "EE").First(&Language{}).RecordNotFound() { + if DB.Where("name = ?", "EE").First(&Language{}).RecordNotFound() { t.Errorf("Language EE should not be deleted") } languages = []Language{} - db.Where("name IN (?)", []string{"CC", "DD"}).Find(&languages) - db.Model(&user).Association("Languages").Delete(languages, &languages) - if db.Model(&user).Association("Languages").Count() != len(totalLanguages)-3 { + DB.Where("name IN (?)", []string{"CC", "DD"}).Find(&languages) + DB.Model(&user).Association("Languages").Delete(languages, &languages) + if DB.Model(&user).Association("Languages").Count() != len(totalLanguages)-3 { t.Errorf("Relations should be deleted with Delete") } // Replace var languageB Language - db.Where("name = ?", "BB").First(&languageB) - db.Model(&user).Association("Languages").Replace(languageB) - if db.Model(&user).Association("Languages").Count() != 1 { + DB.Where("name = ?", "BB").First(&languageB) + DB.Model(&user).Association("Languages").Replace(languageB) + if DB.Model(&user).Association("Languages").Count() != 1 { t.Errorf("Relations should be replaced") } - db.Model(&user).Association("Languages").Replace(&[]Language{{Name: "FF"}, {Name: "JJ"}}) - if db.Model(&user).Association("Languages").Count() != len([]string{"FF", "JJ"}) { + DB.Model(&user).Association("Languages").Replace(&[]Language{{Name: "FF"}, {Name: "JJ"}}) + if DB.Model(&user).Association("Languages").Count() != len([]string{"FF", "JJ"}) { t.Errorf("Relations should be replaced") } // Clear - db.Model(&user).Association("Languages").Clear() - if db.Model(&user).Association("Languages").Count() != 0 { + DB.Model(&user).Association("Languages").Clear() + if DB.Model(&user).Association("Languages").Count() != 0 { t.Errorf("Relations should be cleared") } } diff --git a/callbacks_test.go b/callbacks_test.go index 0f41a410..a58913d7 100644 --- a/callbacks_test.go +++ b/callbacks_test.go @@ -37,8 +37,8 @@ func (s *Product) AfterFind() { s.AfterFindCallTimes = s.AfterFindCallTimes + 1 } -func (s *Product) AfterCreate(db *gorm.DB) { - db.Model(s).UpdateColumn(Product{AfterCreateCallTimes: s.AfterCreateCallTimes + 1}) +func (s *Product) AfterCreate(tx *gorm.DB) { + tx.Model(s).UpdateColumn(Product{AfterCreateCallTimes: s.AfterCreateCallTimes + 1}) } func (s *Product) AfterUpdate() { @@ -75,103 +75,103 @@ func (s *Product) GetCallTimes() []int64 { func TestRunCallbacks(t *testing.T) { p := Product{Code: "unique_code", Price: 100} - db.Save(&p) + DB.Save(&p) if !reflect.DeepEqual(p.GetCallTimes(), []int64{1, 1, 0, 1, 1, 0, 0, 0, 0}) { t.Errorf("Callbacks should be invoked successfully, %v", p.GetCallTimes()) } - db.Where("Code = ?", "unique_code").First(&p) + DB.Where("Code = ?", "unique_code").First(&p) if !reflect.DeepEqual(p.GetCallTimes(), []int64{1, 1, 0, 1, 0, 0, 0, 0, 1}) { t.Errorf("After callbacks values are not saved, %v", p.GetCallTimes()) } p.Price = 200 - db.Save(&p) + DB.Save(&p) if !reflect.DeepEqual(p.GetCallTimes(), []int64{1, 2, 1, 1, 1, 1, 0, 0, 1}) { t.Errorf("After update callbacks should be invoked successfully, %v", p.GetCallTimes()) } var products []Product - db.Find(&products, "code = ?", "unique_code") + DB.Find(&products, "code = ?", "unique_code") if products[0].AfterFindCallTimes != 2 { t.Errorf("AfterFind callbacks should work with slice") } - db.Where("Code = ?", "unique_code").First(&p) + DB.Where("Code = ?", "unique_code").First(&p) if !reflect.DeepEqual(p.GetCallTimes(), []int64{1, 2, 1, 1, 0, 0, 0, 0, 2}) { t.Errorf("After update callbacks values are not saved, %v", p.GetCallTimes()) } - db.Delete(&p) + DB.Delete(&p) if !reflect.DeepEqual(p.GetCallTimes(), []int64{1, 2, 1, 1, 0, 0, 1, 1, 2}) { t.Errorf("After delete callbacks should be invoked successfully, %v", p.GetCallTimes()) } - if db.Where("Code = ?", "unique_code").First(&p).Error == nil { + if DB.Where("Code = ?", "unique_code").First(&p).Error == nil { t.Errorf("Can't find a deleted record") } } func TestCallbacksWithErrors(t *testing.T) { p := Product{Code: "Invalid", Price: 100} - if db.Save(&p).Error == nil { + if DB.Save(&p).Error == nil { t.Errorf("An error from before create callbacks happened when create with invalid value") } - if db.Where("code = ?", "Invalid").First(&Product{}).Error == nil { + if DB.Where("code = ?", "Invalid").First(&Product{}).Error == nil { t.Errorf("Should not save record that have errors") } - if db.Save(&Product{Code: "dont_save", Price: 100}).Error == nil { + if DB.Save(&Product{Code: "dont_save", Price: 100}).Error == nil { t.Errorf("An error from after create callbacks happened when create with invalid value") } p2 := Product{Code: "update_callback", Price: 100} - db.Save(&p2) + DB.Save(&p2) p2.Code = "dont_update" - if db.Save(&p2).Error == nil { + if DB.Save(&p2).Error == nil { t.Errorf("An error from before update callbacks happened when update with invalid value") } - if db.Where("code = ?", "update_callback").First(&Product{}).Error != nil { + if DB.Where("code = ?", "update_callback").First(&Product{}).Error != nil { t.Errorf("Record Should not be updated due to errors happened in before update callback") } - if db.Where("code = ?", "dont_update").First(&Product{}).Error == nil { + if DB.Where("code = ?", "dont_update").First(&Product{}).Error == nil { t.Errorf("Record Should not be updated due to errors happened in before update callback") } p2.Code = "dont_save" - if db.Save(&p2).Error == nil { + if DB.Save(&p2).Error == nil { t.Errorf("An error from before save callbacks happened when update with invalid value") } p3 := Product{Code: "dont_delete", Price: 100} - db.Save(&p3) - if db.Delete(&p3).Error == nil { + DB.Save(&p3) + if DB.Delete(&p3).Error == nil { t.Errorf("An error from before delete callbacks happened when delete") } - if db.Where("Code = ?", "dont_delete").First(&p3).Error != nil { + if DB.Where("Code = ?", "dont_delete").First(&p3).Error != nil { t.Errorf("An error from before delete callbacks happened") } p4 := Product{Code: "after_save_error", Price: 100} - db.Save(&p4) - if err := db.First(&Product{}, "code = ?", "after_save_error").Error; err == nil { + DB.Save(&p4) + if err := DB.First(&Product{}, "code = ?", "after_save_error").Error; err == nil { t.Errorf("Record should be reverted if get an error in after save callback") } p5 := Product{Code: "after_delete_error", Price: 100} - db.Save(&p5) - if err := db.First(&Product{}, "code = ?", "after_delete_error").Error; err != nil { + DB.Save(&p5) + if err := DB.First(&Product{}, "code = ?", "after_delete_error").Error; err != nil { t.Errorf("Record should be found") } - db.Delete(&p5) - if err := db.First(&Product{}, "code = ?", "after_delete_error").Error; err != nil { + DB.Delete(&p5) + if err := DB.First(&Product{}, "code = ?", "after_delete_error").Error; err != nil { t.Errorf("Record shouldn't be deleted because of an error happened in after delete callback") } } diff --git a/create_test.go b/create_test.go index 6f89455f..936b0001 100644 --- a/create_test.go +++ b/create_test.go @@ -10,20 +10,20 @@ func TestCreate(t *testing.T) { float := 35.03554004971999 user := User{Name: "CreateUser", Age: 18, Birthday: time.Now(), UserNum: Num(111), PasswordHash: []byte{'f', 'a', 'k', '4'}, Latitude: float} - if !db.NewRecord(user) || !db.NewRecord(&user) { + if !DB.NewRecord(user) || !DB.NewRecord(&user) { t.Error("User should be new record before create") } - if count := db.Save(&user).RowsAffected; count != 1 { + if count := DB.Save(&user).RowsAffected; count != 1 { t.Error("There should be one record be affected when create record") } - if db.NewRecord(user) || db.NewRecord(&user) { + if DB.NewRecord(user) || DB.NewRecord(&user) { t.Error("User should not new record after save") } var newUser User - db.First(&newUser, user.Id) + DB.First(&newUser, user.Id) if !reflect.DeepEqual(newUser.PasswordHash, []byte{'f', 'a', 'k', '4'}) { t.Errorf("User's PasswordHash should be saved ([]byte)") @@ -49,8 +49,8 @@ func TestCreate(t *testing.T) { t.Errorf("Should have created_at after create") } - db.Model(user).Update("name", "create_user_new_name") - db.First(&user, user.Id) + DB.Model(user).Update("name", "create_user_new_name") + DB.First(&user, user.Id) if user.CreatedAt != newUser.CreatedAt { t.Errorf("CreatedAt should not be changed after update") } @@ -58,7 +58,7 @@ func TestCreate(t *testing.T) { func TestCreateWithNoStdPrimaryKey(t *testing.T) { animal := Animal{Name: "Ferdinand"} - if db.Save(&animal).Error != nil { + if DB.Save(&animal).Error != nil { t.Errorf("No error should happen when create an record without std primary key") } @@ -69,10 +69,10 @@ func TestCreateWithNoStdPrimaryKey(t *testing.T) { func TestAnonymousScanner(t *testing.T) { user := User{Name: "anonymous_scanner", Role: Role{Name: "admin"}} - db.Save(&user) + DB.Save(&user) var user2 User - db.First(&user2, "name = ?", "anonymous_scanner") + DB.First(&user2, "name = ?", "anonymous_scanner") if user2.Role.Name != "admin" { t.Errorf("Should be able to get anonymous scanner") } @@ -84,11 +84,11 @@ func TestAnonymousScanner(t *testing.T) { func TestAnonymousField(t *testing.T) { user := User{Name: "anonymous_field", Company: Company{Name: "company"}} - db.Save(&user) + DB.Save(&user) var user2 User - db.First(&user2, "name = ?", "anonymous_field") - db.Model(&user2).Related(&user2.Company) + DB.First(&user2, "name = ?", "anonymous_field") + DB.Model(&user2).Related(&user2.Company) if user2.Company.Name != "company" { t.Errorf("Should be able to get anonymous field") } diff --git a/delete_test.go b/delete_test.go index 98f41b03..74224a75 100644 --- a/delete_test.go +++ b/delete_test.go @@ -7,36 +7,36 @@ import ( func TestDelete(t *testing.T) { user1, user2 := User{Name: "delete1"}, User{Name: "delete2"} - db.Save(&user1) - db.Save(&user2) + DB.Save(&user1) + DB.Save(&user2) - if db.Delete(&user1).Error != nil { + if DB.Delete(&user1).Error != nil { t.Errorf("No error should happen when delete a record") } - if !db.Where("name = ?", user1.Name).First(&User{}).RecordNotFound() { + if !DB.Where("name = ?", user1.Name).First(&User{}).RecordNotFound() { t.Errorf("User can't be found after delete") } - if db.Where("name = ?", user2.Name).First(&User{}).RecordNotFound() { + if DB.Where("name = ?", user2.Name).First(&User{}).RecordNotFound() { t.Errorf("Other users that not deleted should be found-able") } } func TestInlineDelete(t *testing.T) { user1, user2 := User{Name: "inline_delete1"}, User{Name: "inline_delete2"} - db.Save(&user1) - db.Save(&user2) + DB.Save(&user1) + DB.Save(&user2) - if db.Delete(&User{}, user1.Id).Error != nil { + if DB.Delete(&User{}, user1.Id).Error != nil { t.Errorf("No error should happen when delete a record") - } else if !db.Where("name = ?", user1.Name).First(&User{}).RecordNotFound() { + } else if !DB.Where("name = ?", user1.Name).First(&User{}).RecordNotFound() { t.Errorf("User can't be found after delete") } - if db.Delete(&User{}, "name = ?", user2.Name).Error != nil { + if DB.Delete(&User{}, "name = ?", user2.Name).Error != nil { t.Errorf("No error should happen when delete a record") - } else if !db.Where("name = ?", user2.Name).First(&User{}).RecordNotFound() { + } else if !DB.Where("name = ?", user2.Name).First(&User{}).RecordNotFound() { t.Errorf("User can't be found after delete") } } @@ -47,22 +47,22 @@ func TestSoftDelete(t *testing.T) { Name string DeletedAt time.Time } - db.AutoMigrate(&User{}) + DB.AutoMigrate(&User{}) user := User{Name: "soft_delete"} - db.Save(&user) - db.Delete(&user) + DB.Save(&user) + DB.Delete(&user) - if db.First(&User{}, "name = ?", user.Name).Error == nil { + if DB.First(&User{}, "name = ?", user.Name).Error == nil { t.Errorf("Can't find a soft deleted record") } - if db.Unscoped().First(&User{}, "name = ?", user.Name).Error != nil { + if DB.Unscoped().First(&User{}, "name = ?", user.Name).Error != nil { t.Errorf("Should be able to find soft deleted record with Unscoped") } - db.Unscoped().Delete(&user) - if !db.Unscoped().First(&User{}, "name = ?", user.Name).RecordNotFound() { + DB.Unscoped().Delete(&user) + if !DB.Unscoped().First(&User{}, "name = ?", user.Name).RecordNotFound() { t.Errorf("Can't find permanently deleted record") } } diff --git a/main_test.go b/main_test.go index e0b39e9f..ae2e489e 100644 --- a/main_test.go +++ b/main_test.go @@ -18,7 +18,7 @@ import ( ) var ( - db gorm.DB + DB gorm.DB t1, t2, t3, t4, t5 time.Time ) @@ -30,88 +30,88 @@ func init() { // CREATE DATABASE gorm; // GRANT ALL ON gorm.* TO 'gorm'@'localhost'; fmt.Println("testing mysql...") - db, err = gorm.Open("mysql", "gorm:gorm@/gorm?charset=utf8&parseTime=True") + DB, err = gorm.Open("mysql", "gorm:gorm@/gorm?charset=utf8&parseTime=True") case "postgres": fmt.Println("testing postgres...") - db, err = gorm.Open("postgres", "user=gorm dbname=gorm sslmode=disable") + DB, err = gorm.Open("postgres", "user=gorm DB.ame=gorm sslmode=disable") default: fmt.Println("testing sqlite3...") - db, err = gorm.Open("sqlite3", "/tmp/gorm.db") + DB, err = gorm.Open("sqlite3", "/tmp/gorm.db") } - // db.SetLogger(Logger{log.New(os.Stdout, "\r\n", 0)}) - // db.SetLogger(log.New(os.Stdout, "\r\n", 0)) - db.LogMode(true) - db.LogMode(false) + // DB.SetLogger(Logger{log.New(os.Stdout, "\r\n", 0)}) + // DB.SetLogger(log.New(os.Stdout, "\r\n", 0)) + DB.LogMode(true) + DB.LogMode(false) if err != nil { panic(fmt.Sprintf("No error should happen when connect database, but got %+v", err)) } - db.DB().SetMaxIdleConns(10) + DB.DB().SetMaxIdleConns(10) runMigration() } func TestExceptionsWithInvalidSql(t *testing.T) { var columns []string - if db.Where("sdsd.zaaa = ?", "sd;;;aa").Pluck("aaa", &columns).Error == nil { + if DB.Where("sdsd.zaaa = ?", "sd;;;aa").Pluck("aaa", &columns).Error == nil { t.Errorf("Should got error with invalid SQL") } - if db.Model(&User{}).Where("sdsd.zaaa = ?", "sd;;;aa").Pluck("aaa", &columns).Error == nil { + if DB.Model(&User{}).Where("sdsd.zaaa = ?", "sd;;;aa").Pluck("aaa", &columns).Error == nil { t.Errorf("Should got error with invalid SQL") } - if db.Where("sdsd.zaaa = ?", "sd;;;aa").Find(&User{}).Error == nil { + if DB.Where("sdsd.zaaa = ?", "sd;;;aa").Find(&User{}).Error == nil { t.Errorf("Should got error with invalid SQL") } var count1, count2 int64 - db.Model(&User{}).Count(&count1) + DB.Model(&User{}).Count(&count1) if count1 <= 0 { t.Errorf("Should find some users") } - if db.Where("name = ?", "jinzhu; delete * from users").First(&User{}).Error == nil { + if DB.Where("name = ?", "jinzhu; delete * from users").First(&User{}).Error == nil { t.Errorf("Should got error with invalid SQL") } - db.Model(&User{}).Count(&count2) + DB.Model(&User{}).Count(&count2) if count1 != count2 { t.Errorf("No user should not be deleted by invalid SQL") } } func TestSetTable(t *testing.T) { - if db.Table("users").Pluck("age", &[]int{}).Error != nil { + if DB.Table("users").Pluck("age", &[]int{}).Error != nil { t.Errorf("No errors should happen if set table for pluck") } var users []User - if db.Table("users").Find(&[]User{}).Error != nil { + if DB.Table("users").Find(&[]User{}).Error != nil { t.Errorf("No errors should happen if set table for find") } - if db.Table("invalid_table").Find(&users).Error == nil { + if DB.Table("invalid_table").Find(&users).Error == nil { t.Errorf("Should got error when table is set to an invalid table") } - db.Exec("drop table deleted_users;") - if db.Table("deleted_users").CreateTable(&User{}).Error != nil { + DB.Exec("drop table deleted_users;") + if DB.Table("deleted_users").CreateTable(&User{}).Error != nil { t.Errorf("Create table with specified table") } - db.Table("deleted_users").Save(&User{Name: "DeletedUser"}) + DB.Table("deleted_users").Save(&User{Name: "DeletedUser"}) var deletedUsers []User - db.Table("deleted_users").Find(&deletedUsers) + DB.Table("deleted_users").Find(&deletedUsers) if len(deletedUsers) != 1 { t.Errorf("Query from specified table") } var user1, user2, user3 User - db.First(&user1).Table("deleted_users").First(&user2).Table("").First(&user3) + DB.First(&user1).Table("deleted_users").First(&user2).Table("").First(&user3) if (user1.Name == user2.Name) || (user1.Name != user3.Name) { t.Errorf("unset specified table with blank string") } @@ -128,63 +128,63 @@ func (c Cart) TableName() string { } func TestTableName(t *testing.T) { - db := db.Model("") - if db.NewScope(Order{}).TableName() != "orders" { + DB := DB.Model("") + if DB.NewScope(Order{}).TableName() != "orders" { t.Errorf("Order's table name should be orders") } - if db.NewScope(&Order{}).TableName() != "orders" { + if DB.NewScope(&Order{}).TableName() != "orders" { t.Errorf("&Order's table name should be orders") } - if db.NewScope([]Order{}).TableName() != "orders" { + if DB.NewScope([]Order{}).TableName() != "orders" { t.Errorf("[]Order's table name should be orders") } - if db.NewScope(&[]Order{}).TableName() != "orders" { + if DB.NewScope(&[]Order{}).TableName() != "orders" { t.Errorf("&[]Order's table name should be orders") } - db.SingularTable(true) - if db.NewScope(Order{}).TableName() != "order" { + DB.SingularTable(true) + if DB.NewScope(Order{}).TableName() != "order" { t.Errorf("Order's singular table name should be order") } - if db.NewScope(&Order{}).TableName() != "order" { + if DB.NewScope(&Order{}).TableName() != "order" { t.Errorf("&Order's singular table name should be order") } - if db.NewScope([]Order{}).TableName() != "order" { + if DB.NewScope([]Order{}).TableName() != "order" { t.Errorf("[]Order's singular table name should be order") } - if db.NewScope(&[]Order{}).TableName() != "order" { + if DB.NewScope(&[]Order{}).TableName() != "order" { t.Errorf("&[]Order's singular table name should be order") } - if db.NewScope(&Cart{}).TableName() != "shopping_cart" { + if DB.NewScope(&Cart{}).TableName() != "shopping_cart" { t.Errorf("&Cart's singular table name should be shopping_cart") } - if db.NewScope(Cart{}).TableName() != "shopping_cart" { + if DB.NewScope(Cart{}).TableName() != "shopping_cart" { t.Errorf("Cart's singular table name should be shopping_cart") } - if db.NewScope(&[]Cart{}).TableName() != "shopping_cart" { + if DB.NewScope(&[]Cart{}).TableName() != "shopping_cart" { t.Errorf("&[]Cart's singular table name should be shopping_cart") } - if db.NewScope([]Cart{}).TableName() != "shopping_cart" { + if DB.NewScope([]Cart{}).TableName() != "shopping_cart" { t.Errorf("[]Cart's singular table name should be shopping_cart") } - db.SingularTable(false) + DB.SingularTable(false) } func TestSqlNullValue(t *testing.T) { - db.DropTable(&NullValue{}) - db.AutoMigrate(&NullValue{}) + DB.DropTable(&NullValue{}) + DB.AutoMigrate(&NullValue{}) - if err := db.Save(&NullValue{Name: sql.NullString{String: "hello", Valid: true}, + if err := DB.Save(&NullValue{Name: sql.NullString{String: "hello", Valid: true}, Age: sql.NullInt64{Int64: 18, Valid: true}, Male: sql.NullBool{Bool: true, Valid: true}, Height: sql.NullFloat64{Float64: 100.11, Valid: true}, @@ -194,13 +194,13 @@ func TestSqlNullValue(t *testing.T) { } var nv NullValue - db.First(&nv, "name = ?", "hello") + DB.First(&nv, "name = ?", "hello") if nv.Name.String != "hello" || nv.Age.Int64 != 18 || nv.Male.Bool != true || nv.Height.Float64 != 100.11 || nv.AddedAt.Valid != true { t.Errorf("Should be able to fetch null value") } - if err := db.Save(&NullValue{Name: sql.NullString{String: "hello-2", Valid: true}, + if err := DB.Save(&NullValue{Name: sql.NullString{String: "hello-2", Valid: true}, Age: sql.NullInt64{Int64: 18, Valid: false}, Male: sql.NullBool{Bool: true, Valid: true}, Height: sql.NullFloat64{Float64: 100.11, Valid: true}, @@ -210,12 +210,12 @@ func TestSqlNullValue(t *testing.T) { } var nv2 NullValue - db.First(&nv2, "name = ?", "hello-2") + DB.First(&nv2, "name = ?", "hello-2") if nv2.Name.String != "hello-2" || nv2.Age.Int64 != 0 || nv2.Male.Bool != true || nv2.Height.Float64 != 100.11 || nv2.AddedAt.Valid != false { t.Errorf("Should be able to fetch null value") } - if err := db.Save(&NullValue{Name: sql.NullString{String: "hello-3", Valid: false}, + if err := DB.Save(&NullValue{Name: sql.NullString{String: "hello-3", Valid: false}, Age: sql.NullInt64{Int64: 18, Valid: false}, Male: sql.NullBool{Bool: true, Valid: true}, Height: sql.NullFloat64{Float64: 100.11, Valid: true}, @@ -226,7 +226,7 @@ func TestSqlNullValue(t *testing.T) { } func TestTransaction(t *testing.T) { - tx := db.Begin() + tx := DB.Begin() u := User{Name: "transcation"} if err := tx.Save(&u).Error; err != nil { t.Errorf("No error should raise") @@ -246,7 +246,7 @@ func TestTransaction(t *testing.T) { t.Errorf("Should not find record after rollback") } - tx2 := db.Begin() + tx2 := DB.Begin() u2 := User{Name: "transcation-2"} if err := tx2.Save(&u2).Error; err != nil { t.Errorf("No error should raise") @@ -258,7 +258,7 @@ func TestTransaction(t *testing.T) { tx2.Commit() - if err := db.First(&User{}, "name = ?", "transcation-2").Error; err != nil { + if err := DB.First(&User{}, "name = ?", "transcation-2").Error; err != nil { t.Errorf("Should be able to find committed record") } } @@ -267,9 +267,9 @@ func TestRow(t *testing.T) { user1 := User{Name: "RowUser1", Age: 1, Birthday: now.MustParse("2000-1-1")} user2 := User{Name: "RowUser2", Age: 10, Birthday: now.MustParse("2010-1-1")} user3 := User{Name: "RowUser3", Age: 20, Birthday: now.MustParse("2020-1-1")} - db.Save(&user1).Save(&user2).Save(&user3) + DB.Save(&user1).Save(&user2).Save(&user3) - row := db.Table("users").Where("name = ?", user2.Name).Select("age").Row() + row := DB.Table("users").Where("name = ?", user2.Name).Select("age").Row() var age int64 row.Scan(&age) if age != 10 { @@ -281,9 +281,9 @@ func TestRows(t *testing.T) { user1 := User{Name: "RowsUser1", Age: 1, Birthday: now.MustParse("2000-1-1")} user2 := User{Name: "RowsUser2", Age: 10, Birthday: now.MustParse("2010-1-1")} user3 := User{Name: "RowsUser3", Age: 20, Birthday: now.MustParse("2020-1-1")} - db.Save(&user1).Save(&user2).Save(&user3) + DB.Save(&user1).Save(&user2).Save(&user3) - rows, err := db.Table("users").Where("name = ? or name = ?", user2.Name, user3.Name).Select("name, age").Rows() + rows, err := DB.Table("users").Where("name = ? or name = ?", user2.Name, user3.Name).Select("name, age").Rows() if err != nil { t.Errorf("Not error should happen, but got") } @@ -304,7 +304,7 @@ func TestScan(t *testing.T) { user1 := User{Name: "ScanUser1", Age: 1, Birthday: now.MustParse("2000-1-1")} user2 := User{Name: "ScanUser2", Age: 10, Birthday: now.MustParse("2010-1-1")} user3 := User{Name: "ScanUser3", Age: 20, Birthday: now.MustParse("2020-1-1")} - db.Save(&user1).Save(&user2).Save(&user3) + DB.Save(&user1).Save(&user2).Save(&user3) type result struct { Name string @@ -312,19 +312,19 @@ func TestScan(t *testing.T) { } var res result - db.Table("users").Select("name, age").Where("name = ?", user3.Name).Scan(&res) + DB.Table("users").Select("name, age").Where("name = ?", user3.Name).Scan(&res) if res.Name != user3.Name { t.Errorf("Scan into struct should work") } var doubleAgeRes result - db.Table("users").Select("age + age as age").Where("name = ?", user3.Name).Scan(&doubleAgeRes) + DB.Table("users").Select("age + age as age").Where("name = ?", user3.Name).Scan(&doubleAgeRes) if doubleAgeRes.Age != res.Age*2 { t.Errorf("Scan double age as age") } var ress []result - db.Table("users").Select("name, age").Where("name in (?)", []string{user2.Name, user3.Name}).Scan(&ress) + DB.Table("users").Select("name, age").Where("name in (?)", []string{user2.Name, user3.Name}).Scan(&ress) if len(ress) != 2 || ress[0].Name != user2.Name || ress[1].Name != user3.Name { t.Errorf("Scan into struct map") } @@ -334,7 +334,7 @@ func TestRaw(t *testing.T) { user1 := User{Name: "ExecRawSqlUser1", Age: 1, Birthday: now.MustParse("2000-1-1")} user2 := User{Name: "ExecRawSqlUser2", Age: 10, Birthday: now.MustParse("2010-1-1")} user3 := User{Name: "ExecRawSqlUser3", Age: 20, Birthday: now.MustParse("2020-1-1")} - db.Save(&user1).Save(&user2).Save(&user3) + DB.Save(&user1).Save(&user2).Save(&user3) type result struct { Name string @@ -342,12 +342,12 @@ func TestRaw(t *testing.T) { } var ress []result - db.Raw("SELECT name, age FROM users WHERE name = ? or name = ?", user2.Name, user3.Name).Scan(&ress) + DB.Raw("SELECT name, age FROM users WHERE name = ? or name = ?", user2.Name, user3.Name).Scan(&ress) if len(ress) != 2 || ress[0].Name != user2.Name || ress[1].Name != user3.Name { t.Errorf("Raw with scan") } - rows, _ := db.Raw("select name, age from users where name = ?", user3.Name).Rows() + rows, _ := DB.Raw("select name, age from users where name = ?", user3.Name).Rows() count := 0 for rows.Next() { count++ @@ -356,14 +356,14 @@ func TestRaw(t *testing.T) { t.Errorf("Raw with Rows should find one record with name 3") } - db.Exec("update users set name=? where name in (?)", "jinzhu", []string{user1.Name, user2.Name, user3.Name}) - if db.Where("name in (?)", []string{user1.Name, user2.Name, user3.Name}).First(&User{}).Error != gorm.RecordNotFound { + DB.Exec("update users set name=? where name in (?)", "jinzhu", []string{user1.Name, user2.Name, user3.Name}) + if DB.Where("name in (?)", []string{user1.Name, user2.Name, user3.Name}).First(&User{}).Error != gorm.RecordNotFound { t.Error("Raw sql to update records") } } func TestGroup(t *testing.T) { - rows, err := db.Select("name").Table("users").Group("name").Rows() + rows, err := DB.Select("name").Table("users").Group("name").Rows() if err == nil { defer rows.Close() @@ -386,17 +386,17 @@ func TestJoins(t *testing.T) { Name: "joins", Emails: []Email{{Email: "join1@example.com"}, {Email: "join2@example.com"}}, } - db.Save(&user) + DB.Save(&user) var results []result - db.Table("users").Select("name, email").Joins("left join emails on emails.user_id = users.id").Where("name = ?", "joins").Scan(&results) + DB.Table("users").Select("name, email").Joins("left join emails on emails.user_id = users.id").Where("name = ?", "joins").Scan(&results) if len(results) != 2 || results[0].Email != "join1@example.com" || results[1].Email != "join2@example.com" { t.Errorf("Should find all two emails with Join") } } func TestHaving(t *testing.T) { - rows, err := db.Select("name, count(*) as total").Table("users").Group("name").Having("name IN (?)", []string{"2", "3"}).Rows() + rows, err := DB.Select("name, count(*) as total").Table("users").Group("name").Having("name IN (?)", []string{"2", "3"}).Rows() if err == nil { defer rows.Close() @@ -427,22 +427,22 @@ func TestTimeWithZone(t *testing.T) { for index, vtime := range times { name := "time_with_zone_" + strconv.Itoa(index) user := User{Name: name, Birthday: vtime} - db.Save(&user) + DB.Save(&user) if user.Birthday.UTC().Format(format) != "2013-02-18 17:51:49 +0000" { t.Errorf("User's birthday should not be changed after save") } var findUser, findUser2, findUser3 User - db.First(&findUser, "name = ?", name) + DB.First(&findUser, "name = ?", name) if findUser.Birthday.UTC().Format(format) != "2013-02-18 17:51:49 +0000" { t.Errorf("User's birthday should not be changed after find") } - if db.Where("id = ? AND birthday >= ?", findUser.Id, vtime.Add(-time.Minute)).First(&findUser2).RecordNotFound() { + if DB.Where("id = ? AND birthday >= ?", findUser.Id, vtime.Add(-time.Minute)).First(&findUser2).RecordNotFound() { t.Errorf("User should be found") } - if !db.Where("id = ? AND birthday >= ?", findUser.Id, vtime.Add(time.Minute)).First(&findUser3).RecordNotFound() { + if !DB.Where("id = ? AND birthday >= ?", findUser.Id, vtime.Add(time.Minute)).First(&findUser3).RecordNotFound() { t.Errorf("User should not be found") } } @@ -458,14 +458,14 @@ func TestHstore(t *testing.T) { t.Skip() } - if err := db.Exec("CREATE EXTENSION IF NOT EXISTS hstore").Error; err != nil { + if err := DB.Exec("CREATE EXTENSION IF NOT EXISTS hstore").Error; err != nil { fmt.Println("\033[31mHINT: Must be superuser to create hstore extension (ALTER USER gorm WITH SUPERUSER;)\033[0m") panic(fmt.Sprintf("No error should happen when create hstore extension, but got %+v", err)) } - db.Exec("drop table details") + DB.Exec("drop table details") - if err := db.CreateTable(&Details{}).Error; err != nil { + if err := DB.CreateTable(&Details{}).Error; err != nil { panic(fmt.Sprintf("No error should happen when create table, but got %+v", err)) } @@ -476,10 +476,10 @@ func TestHstore(t *testing.T) { "opinion": &opinion, } d := Details{Bulk: bulk} - db.Save(&d) + DB.Save(&d) var d2 Details - if err := db.First(&d2).Error; err != nil { + if err := DB.First(&d2).Error; err != nil { t.Errorf("Got error when tried to fetch details: %+v", err) } @@ -495,7 +495,7 @@ func TestHstore(t *testing.T) { } func TestSetAndGet(t *testing.T) { - if value, ok := db.Set("hello", "world").Get("hello"); !ok { + if value, ok := DB.Set("hello", "world").Get("hello"); !ok { t.Errorf("Should be able to get setting after set") } else { if value.(string) != "world" { @@ -503,13 +503,13 @@ func TestSetAndGet(t *testing.T) { } } - if _, ok := db.Get("non_existing"); ok { + if _, ok := DB.Get("non_existing"); ok { t.Errorf("Get non existing key should return error") } } func TestCompatibilityMode(t *testing.T) { - db, _ := gorm.Open("testdb", "") + DB, _ := gorm.Open("testdb", "") testdb.SetQueryFunc(func(query string) (driver.Rows, error) { columns := []string{"id", "name", "age"} result := ` @@ -521,7 +521,7 @@ func TestCompatibilityMode(t *testing.T) { }) var users []User - db.Find(&users) + DB.Find(&users) if (users[0].Name != "Tim") || len(users) != 3 { t.Errorf("Unexcepted result returned") } @@ -533,19 +533,19 @@ func BenchmarkGorm(b *testing.B) { e := strconv.Itoa(x) + "benchmark@example.org" email := BigEmail{Email: e, UserAgent: "pc", RegisteredAt: time.Now()} // Insert - db.Save(&email) + DB.Save(&email) // Query - db.First(&BigEmail{}, "email = ?", e) + DB.First(&BigEmail{}, "email = ?", e) // Update - db.Model(&email).UpdateColumn("email", "new-"+e) + DB.Model(&email).UpdateColumn("email", "new-"+e) // Delete - db.Delete(&email) + DB.Delete(&email) } } func BenchmarkRawSql(b *testing.B) { - db, _ := sql.Open("postgres", "user=gorm dbname=gorm sslmode=disable") - db.SetMaxIdleConns(10) + DB, _ := sql.Open("postgres", "user=gorm DB.ame=gorm sslmode=disable") + DB.SetMaxIdleConns(10) insert_sql := "INSERT INTO emails (user_id,email,user_agent,registered_at,created_at,updated_at) VALUES ($1,$2,$3,$4,$5,$6) RETURNING id" query_sql := "SELECT * FROM emails WHERE email = $1 ORDER BY id LIMIT 1" update_sql := "UPDATE emails SET email = $1, updated_at = $2 WHERE id = $3" @@ -557,13 +557,13 @@ func BenchmarkRawSql(b *testing.B) { e := strconv.Itoa(x) + "benchmark@example.org" email := BigEmail{Email: e, UserAgent: "pc", RegisteredAt: time.Now()} // Insert - db.QueryRow(insert_sql, email.UserId, email.Email, email.UserAgent, email.RegisteredAt, time.Now(), time.Now()).Scan(&id) + DB.QueryRow(insert_sql, email.UserId, email.Email, email.UserAgent, email.RegisteredAt, time.Now(), time.Now()).Scan(&id) // Query - rows, _ := db.Query(query_sql, email.Email) + rows, _ := DB.Query(query_sql, email.Email) rows.Close() // Update - db.Exec(update_sql, "new-"+e, time.Now(), id) + DB.Exec(update_sql, "new-"+e, time.Now(), id) // Delete - db.Exec(delete_sql, id) + DB.Exec(delete_sql, id) } } diff --git a/migration_test.go b/migration_test.go index 1dfb4d10..211abd6d 100644 --- a/migration_test.go +++ b/migration_test.go @@ -7,63 +7,65 @@ import ( ) func runMigration() { - if err := db.DropTable(&User{}).Error; err != nil { + if err := DB.DropTable(&User{}).Error; err != nil { fmt.Printf("Got error when try to delete table users, %+v\n", err) } - db.Exec("drop table products;") - db.Exec("drop table emails;") - db.Exec("drop table addresses") - db.Exec("drop table credit_cards") - db.Exec("drop table roles") - db.Exec("drop table companies") - db.Exec("drop table animals") - db.Exec("drop table user_languages") - db.Exec("drop table languages") + DB.Exec("drop table products;") + DB.Exec("drop table emails;") + DB.Exec("drop table addresses") + DB.Exec("drop table credit_cards") + DB.Exec("drop table roles") + DB.Exec("drop table companies") + DB.Exec("drop table animals") + DB.Exec("drop table user_languages") + DB.Exec("drop table languages") - if err := db.CreateTable(&Animal{}).Error; err != nil { + if err := DB.CreateTable(&Animal{}).Error; err != nil { panic(fmt.Sprintf("No error should happen when create table, but got %+v", err)) } - if err := db.CreateTable(User{}).Error; err != nil { + if err := DB.CreateTable(User{}).Error; err != nil { panic(fmt.Sprintf("No error should happen when create table, but got %+v", err)) } - if err := db.AutoMigrate(&Product{}, Email{}, Address{}, CreditCard{}, Company{}, Role{}, Language{}).Error; err != nil { + if err := DB.AutoMigrate(&Product{}, Email{}, Address{}, CreditCard{}, Company{}, Role{}, Language{}).Error; err != nil { panic(fmt.Sprintf("No error should happen when create table, but got %+v", err)) } + + DB.AutoMigrate(HNPost{}, EngadgetPost{}) } func TestIndexes(t *testing.T) { - if err := db.Model(&Email{}).AddIndex("idx_email_email", "email").Error; err != nil { + if err := DB.Model(&Email{}).AddIndex("idx_email_email", "email").Error; err != nil { t.Errorf("Got error when tried to create index: %+v", err) } - if err := db.Model(&Email{}).RemoveIndex("idx_email_email").Error; err != nil { + if err := DB.Model(&Email{}).RemoveIndex("idx_email_email").Error; err != nil { t.Errorf("Got error when tried to remove index: %+v", err) } - if err := db.Model(&Email{}).AddIndex("idx_email_email_and_user_id", "user_id", "email").Error; err != nil { + if err := DB.Model(&Email{}).AddIndex("idx_email_email_and_user_id", "user_id", "email").Error; err != nil { t.Errorf("Got error when tried to create index: %+v", err) } - if err := db.Model(&Email{}).RemoveIndex("idx_email_email_and_user_id").Error; err != nil { + if err := DB.Model(&Email{}).RemoveIndex("idx_email_email_and_user_id").Error; err != nil { t.Errorf("Got error when tried to remove index: %+v", err) } - if err := db.Model(&Email{}).AddUniqueIndex("idx_email_email_and_user_id", "user_id", "email").Error; err != nil { + if err := DB.Model(&Email{}).AddUniqueIndex("idx_email_email_and_user_id", "user_id", "email").Error; err != nil { t.Errorf("Got error when tried to create index: %+v", err) } - if db.Save(&User{Name: "unique_indexes", Emails: []Email{{Email: "user1@example.comiii"}, {Email: "user1@example.com"}, {Email: "user1@example.com"}}}).Error == nil { + if DB.Save(&User{Name: "unique_indexes", Emails: []Email{{Email: "user1@example.comiii"}, {Email: "user1@example.com"}, {Email: "user1@example.com"}}}).Error == nil { t.Errorf("Should get to create duplicate record when having unique index") } - if err := db.Model(&Email{}).RemoveIndex("idx_email_email_and_user_id").Error; err != nil { + if err := DB.Model(&Email{}).RemoveIndex("idx_email_email_and_user_id").Error; err != nil { t.Errorf("Got error when tried to remove index: %+v", err) } - if db.Save(&User{Name: "unique_indexes", Emails: []Email{{Email: "user1@example.com"}, {Email: "user1@example.com"}}}).Error != nil { + if DB.Save(&User{Name: "unique_indexes", Emails: []Email{{Email: "user1@example.com"}, {Email: "user1@example.com"}}}).Error != nil { t.Errorf("Should be able to create duplicated emails after remove unique index") } } @@ -83,15 +85,15 @@ func (b BigEmail) TableName() string { } func TestAutoMigration(t *testing.T) { - db.AutoMigrate(Address{}) - if err := db.Table("emails").AutoMigrate(BigEmail{}).Error; err != nil { + DB.AutoMigrate(Address{}) + if err := DB.Table("emails").AutoMigrate(BigEmail{}).Error; err != nil { t.Errorf("Auto Migrate should not raise any error") } - db.Save(&BigEmail{Email: "jinzhu@example.org", UserAgent: "pc", RegisteredAt: time.Now()}) + DB.Save(&BigEmail{Email: "jinzhu@example.org", UserAgent: "pc", RegisteredAt: time.Now()}) var bigemail BigEmail - db.First(&bigemail, "user_agent = ?", "pc") + DB.First(&bigemail, "user_agent = ?", "pc") if bigemail.Email != "jinzhu@example.org" || bigemail.UserAgent != "pc" || bigemail.RegisteredAt.IsZero() { t.Error("Big Emails should be saved and fetched correctly") } diff --git a/query_test.go b/query_test.go index ce42ae5b..b8a304e7 100644 --- a/query_test.go +++ b/query_test.go @@ -10,53 +10,53 @@ import ( ) func TestFirstAndLast(t *testing.T) { - db.Save(&User{Name: "user1", Emails: []Email{{Email: "user1@example.com"}}}) - db.Save(&User{Name: "user2", Emails: []Email{{Email: "user2@example.com"}}}) + DB.Save(&User{Name: "user1", Emails: []Email{{Email: "user1@example.com"}}}) + DB.Save(&User{Name: "user2", Emails: []Email{{Email: "user2@example.com"}}}) var user1, user2, user3, user4 User - db.First(&user1) - db.Order("id").Find(&user2) + DB.First(&user1) + DB.Order("id").Find(&user2) - db.Last(&user3) - db.Order("id desc").Find(&user4) + DB.Last(&user3) + DB.Order("id desc").Find(&user4) if user1.Id != user2.Id || user3.Id != user4.Id { t.Errorf("First and Last should by order by primary key") } var users []User - db.First(&users) + DB.First(&users) if len(users) != 1 { t.Errorf("Find first record as slice") } - if db.Joins("left join emails on emails.user_id = users.id").First(&User{}).Error != nil { + if DB.Joins("left join emails on emails.user_id = users.id").First(&User{}).Error != nil { t.Errorf("Should not raise any error when order with Join table") } } func TestFirstAndLastWithNoStdPrimaryKey(t *testing.T) { - db.Save(&Animal{Name: "animal1"}) - db.Save(&Animal{Name: "animal2"}) + DB.Save(&Animal{Name: "animal1"}) + DB.Save(&Animal{Name: "animal2"}) var animal1, animal2, animal3, animal4 Animal - db.First(&animal1) - db.Order("counter").Find(&animal2) + DB.First(&animal1) + DB.Order("counter").Find(&animal2) - db.Last(&animal3) - db.Order("counter desc").Find(&animal4) + DB.Last(&animal3) + DB.Order("counter desc").Find(&animal4) if animal1.Counter != animal2.Counter || animal3.Counter != animal4.Counter { t.Errorf("First and Last should work correctly") } } func TestFindAsSliceOfPointers(t *testing.T) { - db.Save(&User{Name: "user"}) + DB.Save(&User{Name: "user"}) var users []User - db.Find(&users) + DB.Find(&users) var userPointers []*User - db.Find(&userPointers) + DB.Find(&userPointers) if len(users) == 0 || len(users) != len(userPointers) { t.Errorf("Find slice of pointers") @@ -67,25 +67,25 @@ func TestSearchWithPlainSQL(t *testing.T) { user1 := User{Name: "PlainSqlUser1", Age: 1, Birthday: now.MustParse("2000-1-1")} user2 := User{Name: "PlainSqlUser2", Age: 10, Birthday: now.MustParse("2010-1-1")} user3 := User{Name: "PlainSqlUser3", Age: 20, Birthday: now.MustParse("2020-1-1")} - db.Save(&user1).Save(&user2).Save(&user3) - scopedb := db.Where("name LIKE ?", "%PlainSqlUser%") + DB.Save(&user1).Save(&user2).Save(&user3) + scopedb := DB.Where("name LIKE ?", "%PlainSqlUser%") - if db.Where("name = ?", user1.Name).First(&User{}).RecordNotFound() { + if DB.Where("name = ?", user1.Name).First(&User{}).RecordNotFound() { t.Errorf("Search with plain SQL") } - if db.Where("name LIKE ?", "%"+user1.Name+"%").First(&User{}).RecordNotFound() { + if DB.Where("name LIKE ?", "%"+user1.Name+"%").First(&User{}).RecordNotFound() { t.Errorf("Search with plan SQL (regexp)") } var users []User - db.Find(&users, "name LIKE ? and age > ?", "%PlainSqlUser%", 1) + DB.Find(&users, "name LIKE ? and age > ?", "%PlainSqlUser%", 1) if len(users) != 2 { t.Errorf("Should found 2 users that age > 1, but got %v", len(users)) } users = []User{} - db.Where("name LIKE ?", "%PlainSqlUser%").Where("age >= ?", 1).Find(&users) + DB.Where("name LIKE ?", "%PlainSqlUser%").Where("age >= ?", 1).Find(&users) if len(users) != 3 { t.Errorf("Should found 3 users that age >= 1, but got %v", len(users)) } @@ -115,24 +115,24 @@ func TestSearchWithPlainSQL(t *testing.T) { } users = []User{} - db.Where("name in (?)", []string{user1.Name, user2.Name}).Find(&users) + DB.Where("name in (?)", []string{user1.Name, user2.Name}).Find(&users) if len(users) != 2 { t.Errorf("Should found 2 users, but got %v", len(users)) } users = []User{} - db.Where("id in (?)", []int64{user1.Id, user2.Id, user3.Id}).Find(&users) + DB.Where("id in (?)", []int64{user1.Id, user2.Id, user3.Id}).Find(&users) if len(users) != 3 { t.Errorf("Should found 3 users, but got %v", len(users)) } users = []User{} - db.Where("id in (?)", user1.Id).Find(&users) + DB.Where("id in (?)", user1.Id).Find(&users) if len(users) != 1 { t.Errorf("Should found 1 users, but got %v", len(users)) } - if !db.Where("name = ?", "none existing").Find(&[]User{}).RecordNotFound() { + if !DB.Where("name = ?", "none existing").Find(&[]User{}).RecordNotFound() { t.Errorf("Should get RecordNotFound error when looking for none existing records") } } @@ -141,44 +141,44 @@ func TestSearchWithStruct(t *testing.T) { user1 := User{Name: "StructSearchUser1", Age: 1, Birthday: now.MustParse("2000-1-1")} user2 := User{Name: "StructSearchUser2", Age: 10, Birthday: now.MustParse("2010-1-1")} user3 := User{Name: "StructSearchUser3", Age: 20, Birthday: now.MustParse("2020-1-1")} - db.Save(&user1).Save(&user2).Save(&user3) + DB.Save(&user1).Save(&user2).Save(&user3) - if db.Where(user1.Id).First(&User{}).RecordNotFound() { + if DB.Where(user1.Id).First(&User{}).RecordNotFound() { t.Errorf("Search with primary key") } - if db.First(&User{}, user1.Id).RecordNotFound() { + if DB.First(&User{}, user1.Id).RecordNotFound() { t.Errorf("Search with primary key as inline condition") } - if db.First(&User{}, fmt.Sprintf("%v", user1.Id)).RecordNotFound() { + if DB.First(&User{}, fmt.Sprintf("%v", user1.Id)).RecordNotFound() { t.Errorf("Search with primary key as inline condition") } var users []User - db.Where([]int64{user1.Id, user2.Id, user3.Id}).Find(&users) + DB.Where([]int64{user1.Id, user2.Id, user3.Id}).Find(&users) if len(users) != 3 { t.Errorf("Should found 3 users when search with primary keys, but got %v", len(users)) } var user User - db.First(&user, &User{Name: user1.Name}) + DB.First(&user, &User{Name: user1.Name}) if user.Id == 0 || user.Name != user1.Name { t.Errorf("Search first record with inline pointer of struct") } - db.First(&user, User{Name: user1.Name}) + DB.First(&user, User{Name: user1.Name}) if user.Id == 0 || user.Name != user.Name { t.Errorf("Search first record with inline struct") } - db.Where(&User{Name: user1.Name}).First(&user) + DB.Where(&User{Name: user1.Name}).First(&user) if user.Id == 0 || user.Name != user1.Name { t.Errorf("Search first record with where struct") } users = []User{} - db.Find(&users, &User{Name: user2.Name}) + DB.Find(&users, &User{Name: user2.Name}) if len(users) != 1 { t.Errorf("Search all records with inline struct") } @@ -188,28 +188,28 @@ func TestSearchWithMap(t *testing.T) { user1 := User{Name: "MapSearchUser1", Age: 1, Birthday: now.MustParse("2000-1-1")} user2 := User{Name: "MapSearchUser2", Age: 10, Birthday: now.MustParse("2010-1-1")} user3 := User{Name: "MapSearchUser3", Age: 20, Birthday: now.MustParse("2020-1-1")} - db.Save(&user1).Save(&user2).Save(&user3) + DB.Save(&user1).Save(&user2).Save(&user3) var user User - db.First(&user, map[string]interface{}{"name": user1.Name}) + DB.First(&user, map[string]interface{}{"name": user1.Name}) if user.Id == 0 || user.Name != user1.Name { t.Errorf("Search first record with inline map") } user = User{} - db.Where(map[string]interface{}{"name": user2.Name}).First(&user) + DB.Where(map[string]interface{}{"name": user2.Name}).First(&user) if user.Id == 0 || user.Name != user2.Name { t.Errorf("Search first record with where map") } var users []User - db.Where(map[string]interface{}{"name": user3.Name}).Find(&users) + DB.Where(map[string]interface{}{"name": user3.Name}).Find(&users) if len(users) != 1 { t.Errorf("Search all records with inline map") } users = []User{} - db.Find(&users, map[string]interface{}{"name": user3.Name}) + DB.Find(&users, map[string]interface{}{"name": user3.Name}) if len(users) != 1 { t.Errorf("Search all records with inline map") } @@ -217,10 +217,10 @@ func TestSearchWithMap(t *testing.T) { func TestSelect(t *testing.T) { user1 := User{Name: "SelectUser1"} - db.Save(&user1) + DB.Save(&user1) var user User - db.Where("name = ?", user1.Name).Select("name").Find(&user) + DB.Where("name = ?", user1.Name).Select("name").Find(&user) if user.Id != 0 { t.Errorf("Should not have ID because only selected name, %+v", user.Id) } @@ -234,8 +234,8 @@ func TestOrderAndPluck(t *testing.T) { user1 := User{Name: "OrderPluckUser1", Age: 1} user2 := User{Name: "OrderPluckUser2", Age: 10} user3 := User{Name: "OrderPluckUser3", Age: 20} - db.Save(&user1).Save(&user2).Save(&user3) - scopedb := db.Model(&User{}).Where("name like ?", "%OrderPluckUser%") + DB.Save(&user1).Save(&user2).Save(&user3) + scopedb := DB.Model(&User{}).Where("name like ?", "%OrderPluckUser%") var ages []int64 scopedb.Order("age desc").Pluck("age", &ages) @@ -262,7 +262,7 @@ func TestOrderAndPluck(t *testing.T) { t.Errorf("Order with multiple orders") } - db.Model(User{}).Select("name, age").Find(&[]User{}) + DB.Model(User{}).Select("name, age").Find(&[]User{}) } func TestLimit(t *testing.T) { @@ -271,10 +271,10 @@ func TestLimit(t *testing.T) { user3 := User{Name: "LimitUser3", Age: 20} user4 := User{Name: "LimitUser4", Age: 10} user5 := User{Name: "LimitUser5", Age: 20} - db.Save(&user1).Save(&user2).Save(&user3).Save(&user4).Save(&user5) + DB.Save(&user1).Save(&user2).Save(&user3).Save(&user4).Save(&user5) var users1, users2, users3 []User - db.Order("age desc").Limit(3).Find(&users1).Limit(5).Find(&users2).Limit(-1).Find(&users3) + DB.Order("age desc").Limit(3).Find(&users1).Limit(5).Find(&users2).Limit(-1).Find(&users3) if len(users1) != 3 || len(users2) != 5 || len(users3) <= 5 { t.Errorf("Limit should works") @@ -283,10 +283,10 @@ func TestLimit(t *testing.T) { func TestOffset(t *testing.T) { for i := 0; i < 20; i++ { - db.Save(&User{Name: fmt.Sprintf("OffsetUser%v", i)}) + DB.Save(&User{Name: fmt.Sprintf("OffsetUser%v", i)}) } var users1, users2, users3, users4 []User - db.Limit(100).Order("age desc").Find(&users1).Offset(3).Find(&users2).Offset(5).Find(&users3).Offset(-1).Find(&users4) + DB.Limit(100).Order("age desc").Find(&users1).Offset(3).Find(&users2).Offset(5).Find(&users3).Offset(-1).Find(&users4) if (len(users1) != len(users4)) || (len(users1)-len(users2) != 3) || (len(users1)-len(users3) != 5) { t.Errorf("Offset should work") @@ -297,10 +297,10 @@ func TestOr(t *testing.T) { user1 := User{Name: "OrUser1", Age: 1} user2 := User{Name: "OrUser2", Age: 10} user3 := User{Name: "OrUser3", Age: 20} - db.Save(&user1).Save(&user2).Save(&user3) + DB.Save(&user1).Save(&user2).Save(&user3) var users []User - db.Where("name = ?", user1.Name).Or("name = ?", user2.Name).Find(&users) + DB.Where("name = ?", user1.Name).Or("name = ?", user2.Name).Find(&users) if len(users) != 2 { t.Errorf("Find users with or") } @@ -311,11 +311,11 @@ func TestCount(t *testing.T) { user2 := User{Name: "CountUser2", Age: 10} user3 := User{Name: "CountUser3", Age: 20} - db.Save(&user1).Save(&user2).Save(&user3) + DB.Save(&user1).Save(&user2).Save(&user3) var count, count1, count2 int64 var users []User - if err := db.Where("name = ?", user1.Name).Or("name = ?", user3.Name).Find(&users).Count(&count).Error; err != nil { + if err := DB.Where("name = ?", user1.Name).Or("name = ?", user3.Name).Find(&users).Count(&count).Error; err != nil { t.Errorf(fmt.Sprintf("Count should work, but got err %v", err)) } @@ -323,7 +323,7 @@ func TestCount(t *testing.T) { t.Errorf("Count() method should get correct value") } - db.Model(&User{}).Where("name = ?", user1.Name).Count(&count1).Or("name in (?)", []string{user2.Name, user3.Name}).Count(&count2) + DB.Model(&User{}).Where("name = ?", user1.Name).Count(&count1).Or("name in (?)", []string{user2.Name, user3.Name}).Count(&count2) if count1 != 1 || count2 != 3 { t.Errorf("Multiple count in chain") } @@ -331,56 +331,56 @@ func TestCount(t *testing.T) { func TestNot(t *testing.T) { var users1, users2, users3, users4, users5, users6, users7, users8 []User - db.Find(&users1) - db.Not(users1[0].Id).Find(&users2) + DB.Find(&users1) + DB.Not(users1[0].Id).Find(&users2) if len(users1)-len(users2) != 1 { t.Errorf("Should ignore the first users with Not") } - db.Not([]int{}).Find(&users3) + DB.Not([]int{}).Find(&users3) if len(users1)-len(users3) != 0 { t.Errorf("Should find all users with a blank condition") } var name3Count int64 - db.Table("users").Where("name = ?", "3").Count(&name3Count) - db.Not("name", "3").Find(&users4) + DB.Table("users").Where("name = ?", "3").Count(&name3Count) + DB.Not("name", "3").Find(&users4) if len(users1)-len(users4) != int(name3Count) { t.Errorf("Should find all users's name not equal 3") } users4 = []User{} - db.Not("name = ?", "3").Find(&users4) + DB.Not("name = ?", "3").Find(&users4) if len(users1)-len(users4) != int(name3Count) { t.Errorf("Should find all users's name not equal 3") } users4 = []User{} - db.Not("name <> ?", "3").Find(&users4) + DB.Not("name <> ?", "3").Find(&users4) if len(users4) != int(name3Count) { t.Errorf("Should find all users's name not equal 3") } - db.Not(User{Name: "3"}).Find(&users5) + DB.Not(User{Name: "3"}).Find(&users5) if len(users1)-len(users5) != int(name3Count) { t.Errorf("Should find all users's name not equal 3") } - db.Not(map[string]interface{}{"name": "3"}).Find(&users6) + DB.Not(map[string]interface{}{"name": "3"}).Find(&users6) if len(users1)-len(users6) != int(name3Count) { t.Errorf("Should find all users's name not equal 3") } - db.Not("name", []string{"3"}).Find(&users7) + DB.Not("name", []string{"3"}).Find(&users7) if len(users1)-len(users7) != int(name3Count) { t.Errorf("Should find all users's name not equal 3") } var name2Count int64 - db.Table("users").Where("name = ?", "2").Count(&name2Count) - db.Not("name", []string{"3", "2"}).Find(&users8) + DB.Table("users").Where("name = ?", "2").Count(&name2Count) + DB.Not("name", []string{"3", "2"}).Find(&users8) if len(users1)-len(users8) != (int(name3Count) + int(name2Count)) { t.Errorf("Should find all users's name not equal 3") } @@ -388,7 +388,7 @@ func TestNot(t *testing.T) { func TestFillSmallerStruct(t *testing.T) { user1 := User{Name: "SmallerUser", Age: 100} - db.Save(&user1) + DB.Save(&user1) type SimpleUser struct { Name string Id int64 @@ -397,7 +397,7 @@ func TestFillSmallerStruct(t *testing.T) { } var simpleUser SimpleUser - db.Table("users").Where("name = ?", user1.Name).First(&simpleUser) + DB.Table("users").Where("name = ?", user1.Name).First(&simpleUser) if simpleUser.Id == 0 || simpleUser.Name == "" { t.Errorf("Should fill data correctly into smaller struct") @@ -406,43 +406,43 @@ func TestFillSmallerStruct(t *testing.T) { func TestFindOrInitialize(t *testing.T) { var user1, user2, user3, user4, user5, user6 User - db.Where(&User{Name: "find or init", Age: 33}).FirstOrInit(&user1) + DB.Where(&User{Name: "find or init", Age: 33}).FirstOrInit(&user1) if user1.Name != "find or init" || user1.Id != 0 || user1.Age != 33 { t.Errorf("user should be initialized with search value") } - db.Where(User{Name: "find or init", Age: 33}).FirstOrInit(&user2) + DB.Where(User{Name: "find or init", Age: 33}).FirstOrInit(&user2) if user2.Name != "find or init" || user2.Id != 0 || user2.Age != 33 { t.Errorf("user should be initialized with search value") } - db.FirstOrInit(&user3, map[string]interface{}{"name": "find or init 2"}) + DB.FirstOrInit(&user3, map[string]interface{}{"name": "find or init 2"}) if user3.Name != "find or init 2" || user3.Id != 0 { t.Errorf("user should be initialized with inline search value") } - db.Where(&User{Name: "find or init"}).Attrs(User{Age: 44}).FirstOrInit(&user4) + DB.Where(&User{Name: "find or init"}).Attrs(User{Age: 44}).FirstOrInit(&user4) if user4.Name != "find or init" || user4.Id != 0 || user4.Age != 44 { t.Errorf("user should be initialized with search value and attrs") } - db.Where(&User{Name: "find or init"}).Assign("age", 44).FirstOrInit(&user4) + DB.Where(&User{Name: "find or init"}).Assign("age", 44).FirstOrInit(&user4) if user4.Name != "find or init" || user4.Id != 0 || user4.Age != 44 { t.Errorf("user should be initialized with search value and assign attrs") } - db.Save(&User{Name: "find or init", Age: 33}) - db.Where(&User{Name: "find or init"}).Attrs("age", 44).FirstOrInit(&user5) + DB.Save(&User{Name: "find or init", Age: 33}) + DB.Where(&User{Name: "find or init"}).Attrs("age", 44).FirstOrInit(&user5) if user5.Name != "find or init" || user5.Id == 0 || user5.Age != 33 { t.Errorf("user should be found and not initialized by Attrs") } - db.Where(&User{Name: "find or init", Age: 33}).FirstOrInit(&user6) + DB.Where(&User{Name: "find or init", Age: 33}).FirstOrInit(&user6) if user6.Name != "find or init" || user6.Id == 0 || user6.Age != 33 { t.Errorf("user should be found with FirstOrInit") } - db.Where(&User{Name: "find or init"}).Assign(User{Age: 44}).FirstOrInit(&user6) + DB.Where(&User{Name: "find or init"}).Assign(User{Age: 44}).FirstOrInit(&user6) if user6.Name != "find or init" || user6.Id == 0 || user6.Age != 44 { t.Errorf("user should be found and updated with assigned attrs") } @@ -450,58 +450,58 @@ func TestFindOrInitialize(t *testing.T) { func TestFindOrCreate(t *testing.T) { var user1, user2, user3, user4, user5, user6, user7, user8 User - db.Where(&User{Name: "find or create", Age: 33}).FirstOrCreate(&user1) + DB.Where(&User{Name: "find or create", Age: 33}).FirstOrCreate(&user1) if user1.Name != "find or create" || user1.Id == 0 || user1.Age != 33 { t.Errorf("user should be created with search value") } - db.Where(&User{Name: "find or create", Age: 33}).FirstOrCreate(&user2) + DB.Where(&User{Name: "find or create", Age: 33}).FirstOrCreate(&user2) if user1.Id != user2.Id || user2.Name != "find or create" || user2.Id == 0 || user2.Age != 33 { t.Errorf("user should be created with search value") } - db.FirstOrCreate(&user3, map[string]interface{}{"name": "find or create 2"}) + DB.FirstOrCreate(&user3, map[string]interface{}{"name": "find or create 2"}) if user3.Name != "find or create 2" || user3.Id == 0 { t.Errorf("user should be created with inline search value") } - db.Where(&User{Name: "find or create 3"}).Attrs("age", 44).FirstOrCreate(&user4) + DB.Where(&User{Name: "find or create 3"}).Attrs("age", 44).FirstOrCreate(&user4) if user4.Name != "find or create 3" || user4.Id == 0 || user4.Age != 44 { t.Errorf("user should be created with search value and attrs") } updatedAt1 := user4.UpdatedAt - db.Where(&User{Name: "find or create 3"}).Assign("age", 55).FirstOrCreate(&user4) + DB.Where(&User{Name: "find or create 3"}).Assign("age", 55).FirstOrCreate(&user4) if updatedAt1.Format(time.RFC3339Nano) == user4.UpdatedAt.Format(time.RFC3339Nano) { t.Errorf("UpdateAt should be changed when update values with assign") } - db.Where(&User{Name: "find or create 4"}).Assign(User{Age: 44}).FirstOrCreate(&user4) + DB.Where(&User{Name: "find or create 4"}).Assign(User{Age: 44}).FirstOrCreate(&user4) if user4.Name != "find or create 4" || user4.Id == 0 || user4.Age != 44 { t.Errorf("user should be created with search value and assigned attrs") } - db.Where(&User{Name: "find or create"}).Attrs("age", 44).FirstOrInit(&user5) + DB.Where(&User{Name: "find or create"}).Attrs("age", 44).FirstOrInit(&user5) if user5.Name != "find or create" || user5.Id == 0 || user5.Age != 33 { t.Errorf("user should be found and not initialized by Attrs") } - db.Where(&User{Name: "find or create"}).Assign(User{Age: 44}).FirstOrCreate(&user6) + DB.Where(&User{Name: "find or create"}).Assign(User{Age: 44}).FirstOrCreate(&user6) if user6.Name != "find or create" || user6.Id == 0 || user6.Age != 44 { t.Errorf("user should be found and updated with assigned attrs") } - db.Where(&User{Name: "find or create"}).Find(&user7) + DB.Where(&User{Name: "find or create"}).Find(&user7) if user7.Name != "find or create" || user7.Id == 0 || user7.Age != 44 { t.Errorf("user should be found and updated with assigned attrs") } - db.Where(&User{Name: "find or create embedded struct"}).Assign(User{Age: 44, CreditCard: CreditCard{Number: "1231231231"}, Emails: []Email{{Email: "jinzhu@assign_embedded_struct.com"}, {Email: "jinzhu-2@assign_embedded_struct.com"}}}).FirstOrCreate(&user8) - if db.Where("email = ?", "jinzhu-2@assign_embedded_struct.com").First(&Email{}).RecordNotFound() { + DB.Where(&User{Name: "find or create embedded struct"}).Assign(User{Age: 44, CreditCard: CreditCard{Number: "1231231231"}, Emails: []Email{{Email: "jinzhu@assign_embedded_struct.com"}, {Email: "jinzhu-2@assign_embedded_struct.com"}}}).FirstOrCreate(&user8) + if DB.Where("email = ?", "jinzhu-2@assign_embedded_struct.com").First(&Email{}).RecordNotFound() { t.Errorf("embedded struct email should be saved") } - if db.Where("email = ?", "1231231231").First(&CreditCard{}).RecordNotFound() { + if DB.Where("email = ?", "1231231231").First(&CreditCard{}).RecordNotFound() { t.Errorf("embedded struct credit card should be saved") } } @@ -510,10 +510,10 @@ func TestSelectWithEscapedFieldName(t *testing.T) { user1 := User{Name: "EscapedFieldNameUser", Age: 1} user2 := User{Name: "EscapedFieldNameUser", Age: 10} user3 := User{Name: "EscapedFieldNameUser", Age: 20} - db.Save(&user1).Save(&user2).Save(&user3) + DB.Save(&user1).Save(&user2).Save(&user3) var names []string - db.Model(User{}).Where(&User{Name: "EscapedFieldNameUser"}).Pluck("\"name\"", &names) + DB.Model(User{}).Where(&User{Name: "EscapedFieldNameUser"}).Pluck("\"name\"", &names) if len(names) != 3 { t.Errorf("Expected 3 name, but got: %d", len(names)) diff --git a/scope.go b/scope.go index 6ce87cea..b2973dd6 100644 --- a/scope.go +++ b/scope.go @@ -249,7 +249,6 @@ func (scope *Scope) FieldByName(name string) (field *Field, ok bool) { func (scope *Scope) fieldFromStruct(fieldStruct reflect.StructField) *Field { var field Field field.Name = fieldStruct.Name - field.DBName = ToSnake(fieldStruct.Name) value := scope.IndirectValue().FieldByName(fieldStruct.Name) indirectValue := reflect.Indirect(value) @@ -258,6 +257,13 @@ func (scope *Scope) fieldFromStruct(fieldStruct reflect.StructField) *Field { // Search for primary key tag identifier settings := parseTagSetting(fieldStruct.Tag.Get("gorm")) + + prefix := settings["PREFIX"] + if prefix == "-" { + prefix = "" + } + field.DBName = prefix + ToSnake(fieldStruct.Name) + if scope.PrimaryKey() == field.DBName { field.IsPrimaryKey = true } @@ -271,10 +277,11 @@ func (scope *Scope) fieldFromStruct(fieldStruct reflect.StructField) *Field { indirectValue = reflect.New(value.Type()) } typ := indirectValue.Type() + scopeTyp := scope.IndirectValue().Type() + foreignKey := SnakeToUpperCamel(settings["FOREIGNKEY"]) associationForeignKey := SnakeToUpperCamel(settings["ASSOCIATIONFOREIGNKEY"]) many2many := settings["MANY2MANY"] - scopeTyp := scope.IndirectValue().Type() switch indirectValue.Kind() { case reflect.Slice: diff --git a/scope_test.go b/scope_test.go index 7499b1f0..cf2f626c 100644 --- a/scope_test.go +++ b/scope_test.go @@ -24,20 +24,20 @@ func TestScopes(t *testing.T) { user1 := User{Name: "ScopeUser1", Age: 1} user2 := User{Name: "ScopeUser2", Age: 1} user3 := User{Name: "ScopeUser3", Age: 2} - db.Save(&user1).Save(&user2).Save(&user3) + DB.Save(&user1).Save(&user2).Save(&user3) var users1, users2, users3 []User - db.Scopes(NameIn1And2).Find(&users1) + DB.Scopes(NameIn1And2).Find(&users1) if len(users1) != 2 { t.Errorf("Should found two users's name in 1, 2") } - db.Scopes(NameIn1And2, NameIn2And3).Find(&users2) + DB.Scopes(NameIn1And2, NameIn2And3).Find(&users2) if len(users2) != 1 { t.Errorf("Should found one user's name is 2") } - db.Scopes(NameIn([]string{user1.Name, user3.Name})).Find(&users3) + DB.Scopes(NameIn([]string{user1.Name, user3.Name})).Find(&users3) if len(users3) != 2 { t.Errorf("Should found two users's name in 1, 3") } diff --git a/update_test.go b/update_test.go index ade1507c..7302bb8a 100644 --- a/update_test.go +++ b/update_test.go @@ -9,80 +9,80 @@ func TestUpdate(t *testing.T) { product1 := Product{Code: "product1code"} product2 := Product{Code: "product2code"} - db.Save(&product1).Save(&product2).Update("code", "product2newcode") + DB.Save(&product1).Save(&product2).Update("code", "product2newcode") if product2.Code != "product2newcode" { t.Errorf("Record should be updated") } - db.First(&product1, product1.Id) - db.First(&product2, product2.Id) + DB.First(&product1, product1.Id) + DB.First(&product2, product2.Id) updatedAt1 := product1.UpdatedAt updatedAt2 := product2.UpdatedAt var product3 Product - db.First(&product3, product2.Id).Update("code", "product2newcode") + DB.First(&product3, product2.Id).Update("code", "product2newcode") if updatedAt2.Format(time.RFC3339Nano) != product3.UpdatedAt.Format(time.RFC3339Nano) { t.Errorf("updatedAt should not be updated if nothing changed") } - if db.First(&Product{}, "code = ?", product1.Code).RecordNotFound() { + if DB.First(&Product{}, "code = ?", product1.Code).RecordNotFound() { t.Errorf("Product1 should not be updated") } - if !db.First(&Product{}, "code = ?", "product2code").RecordNotFound() { + if !DB.First(&Product{}, "code = ?", "product2code").RecordNotFound() { t.Errorf("Product2's code should be updated") } - if db.First(&Product{}, "code = ?", "product2newcode").RecordNotFound() { + if DB.First(&Product{}, "code = ?", "product2newcode").RecordNotFound() { t.Errorf("Product2's code should be updated") } - db.Table("products").Where("code in (?)", []string{"product1code"}).Update("code", "product1newcode") + DB.Table("products").Where("code in (?)", []string{"product1code"}).Update("code", "product1newcode") var product4 Product - db.First(&product4, product1.Id) + DB.First(&product4, product1.Id) if updatedAt1.Format(time.RFC3339Nano) != product4.UpdatedAt.Format(time.RFC3339Nano) { t.Errorf("updatedAt should be updated if something changed") } - if !db.First(&Product{}, "code = 'product1code'").RecordNotFound() { + if !DB.First(&Product{}, "code = 'product1code'").RecordNotFound() { t.Errorf("Product1's code should be updated") } - if db.First(&Product{}, "code = 'product1newcode'").RecordNotFound() { + if DB.First(&Product{}, "code = 'product1newcode'").RecordNotFound() { t.Errorf("Product should not be changed to 789") } - if db.Model(product2).Update("CreatedAt", time.Now().Add(time.Hour)).Error != nil { + if DB.Model(product2).Update("CreatedAt", time.Now().Add(time.Hour)).Error != nil { t.Error("No error should raise when update with CamelCase") } - if db.Model(&product2).UpdateColumn("CreatedAt", time.Now().Add(time.Hour)).Error != nil { + if DB.Model(&product2).UpdateColumn("CreatedAt", time.Now().Add(time.Hour)).Error != nil { t.Error("No error should raise when update_column with CamelCase") } var products []Product - db.Find(&products) - if count := db.Model(Product{}).Update("CreatedAt", time.Now().Add(2*time.Hour)).RowsAffected; count != int64(len(products)) { + DB.Find(&products) + if count := DB.Model(Product{}).Update("CreatedAt", time.Now().Add(2*time.Hour)).RowsAffected; count != int64(len(products)) { t.Error("RowsAffected should be correct when do batch update") } } func TestUpdateWithNoStdPrimaryKey(t *testing.T) { animal := Animal{Name: "Ferdinand"} - db.Save(&animal) + DB.Save(&animal) updatedAt1 := animal.UpdatedAt - db.Save(&animal).Update("name", "Francis") + DB.Save(&animal).Update("name", "Francis") if updatedAt1.Format(time.RFC3339Nano) == animal.UpdatedAt.Format(time.RFC3339Nano) { t.Errorf("updatedAt should not be updated if nothing changed") } var animals []Animal - db.Find(&animals) - if count := db.Model(Animal{}).Update("CreatedAt", time.Now().Add(2*time.Hour)).RowsAffected; count != int64(len(animals)) { + DB.Find(&animals) + if count := DB.Model(Animal{}).Update("CreatedAt", time.Now().Add(2*time.Hour)).RowsAffected; count != int64(len(animals)) { t.Error("RowsAffected should be correct when do batch update") } } @@ -90,19 +90,19 @@ func TestUpdateWithNoStdPrimaryKey(t *testing.T) { func TestUpdates(t *testing.T) { product1 := Product{Code: "product1code", Price: 10} product2 := Product{Code: "product2code", Price: 10} - db.Save(&product1).Save(&product2) - db.Model(&product1).Updates(map[string]interface{}{"code": "product1newcode", "price": 100}) + DB.Save(&product1).Save(&product2) + DB.Model(&product1).Updates(map[string]interface{}{"code": "product1newcode", "price": 100}) if product1.Code != "product1newcode" || product1.Price != 100 { t.Errorf("Record should be updated also with map") } - db.First(&product1, product1.Id) - db.First(&product2, product2.Id) + DB.First(&product1, product1.Id) + DB.First(&product2, product2.Id) updatedAt1 := product1.UpdatedAt updatedAt2 := product2.UpdatedAt var product3 Product - db.First(&product3, product1.Id).Updates(Product{Code: "product1newcode", Price: 100}) + DB.First(&product3, product1.Id).Updates(Product{Code: "product1newcode", Price: 100}) if product3.Code != "product1newcode" || product3.Price != 100 { t.Errorf("Record should be updated with struct") } @@ -111,26 +111,26 @@ func TestUpdates(t *testing.T) { t.Errorf("updatedAt should not be updated if nothing changed") } - if db.First(&Product{}, "code = ? and price = ?", product2.Code, product2.Price).RecordNotFound() { + if DB.First(&Product{}, "code = ? and price = ?", product2.Code, product2.Price).RecordNotFound() { t.Errorf("Product2 should not be updated") } - if db.First(&Product{}, "code = ?", "product1newcode").RecordNotFound() { + if DB.First(&Product{}, "code = ?", "product1newcode").RecordNotFound() { t.Errorf("Product1 should be updated") } - db.Table("products").Where("code in (?)", []string{"product2code"}).Updates(Product{Code: "product2newcode"}) - if !db.First(&Product{}, "code = 'product2code'").RecordNotFound() { + DB.Table("products").Where("code in (?)", []string{"product2code"}).Updates(Product{Code: "product2newcode"}) + if !DB.First(&Product{}, "code = 'product2code'").RecordNotFound() { t.Errorf("Product2's code should be updated") } var product4 Product - db.First(&product4, product2.Id) + DB.First(&product4, product2.Id) if updatedAt2.Format(time.RFC3339Nano) != product4.UpdatedAt.Format(time.RFC3339Nano) { t.Errorf("updatedAt should be updated if something changed") } - if db.First(&Product{}, "code = ?", "product2newcode").RecordNotFound() { + if DB.First(&Product{}, "code = ?", "product2newcode").RecordNotFound() { t.Errorf("product2's code should be updated") } } @@ -138,22 +138,22 @@ func TestUpdates(t *testing.T) { func TestUpdateColumn(t *testing.T) { product1 := Product{Code: "product1code", Price: 10} product2 := Product{Code: "product2code", Price: 20} - db.Save(&product1).Save(&product2).UpdateColumn(map[string]interface{}{"code": "product2newcode", "price": 100}) + DB.Save(&product1).Save(&product2).UpdateColumn(map[string]interface{}{"code": "product2newcode", "price": 100}) if product2.Code != "product2newcode" || product2.Price != 100 { t.Errorf("product 2 should be updated with update column") } var product3 Product - db.First(&product3, product1.Id) + DB.First(&product3, product1.Id) if product3.Code != "product1code" || product3.Price != 10 { t.Errorf("product 1 should not be updated") } - db.First(&product2, product2.Id) + DB.First(&product2, product2.Id) updatedAt2 := product2.UpdatedAt - db.Model(product2).UpdateColumn("code", "update_column_new") + DB.Model(product2).UpdateColumn("code", "update_column_new") var product4 Product - db.First(&product4, product2.Id) + DB.First(&product4, product2.Id) if updatedAt2.Format(time.RFC3339Nano) != product4.UpdatedAt.Format(time.RFC3339Nano) { t.Errorf("updatedAt should not be updated with update column") }