mirror of https://github.com/go-gorm/gorm.git
update tests
This commit is contained in:
parent
e6715ce175
commit
423d9496c1
|
@ -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)
|
||||||
|
}
|
|
@ -3,13 +3,13 @@ package gorm_test
|
||||||
import "testing"
|
import "testing"
|
||||||
|
|
||||||
func TestHasOneAndHasManyAssociation(t *testing.T) {
|
func TestHasOneAndHasManyAssociation(t *testing.T) {
|
||||||
db.DropTable(Category{})
|
DB.DropTable(Category{})
|
||||||
db.DropTable(Post{})
|
DB.DropTable(Post{})
|
||||||
db.DropTable(Comment{})
|
DB.DropTable(Comment{})
|
||||||
|
|
||||||
db.CreateTable(Category{})
|
DB.CreateTable(Category{})
|
||||||
db.CreateTable(Post{})
|
DB.CreateTable(Post{})
|
||||||
db.CreateTable(Comment{})
|
DB.CreateTable(Comment{})
|
||||||
|
|
||||||
post := Post{
|
post := Post{
|
||||||
Title: "post 1",
|
Title: "post 1",
|
||||||
|
@ -19,22 +19,22 @@ func TestHasOneAndHasManyAssociation(t *testing.T) {
|
||||||
MainCategory: Category{Name: "Main Category 1"},
|
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")
|
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")
|
t.Errorf("Category should be saved")
|
||||||
}
|
}
|
||||||
|
|
||||||
var p Post
|
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 {
|
if post.CategoryId.Int64 == 0 || p.CategoryId.Int64 == 0 || post.MainCategoryId == 0 || p.MainCategoryId == 0 {
|
||||||
t.Errorf("Category Id should exist")
|
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")
|
t.Errorf("Comment 1 should be saved")
|
||||||
}
|
}
|
||||||
if post.Comments[0].PostId == 0 {
|
if post.Comments[0].PostId == 0 {
|
||||||
|
@ -42,7 +42,7 @@ func TestHasOneAndHasManyAssociation(t *testing.T) {
|
||||||
}
|
}
|
||||||
|
|
||||||
var comment Comment
|
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")
|
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"}}
|
comment3 := Comment{Content: "Comment 3", Post: Post{Title: "Title 3", Body: "Body 3"}}
|
||||||
db.Save(&comment3)
|
DB.Save(&comment3)
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestRelated(t *testing.T) {
|
func TestRelated(t *testing.T) {
|
||||||
|
@ -63,7 +63,7 @@ func TestRelated(t *testing.T) {
|
||||||
CreditCard: CreditCard{Number: "1234567890"},
|
CreditCard: CreditCard{Number: "1234567890"},
|
||||||
}
|
}
|
||||||
|
|
||||||
db.Save(&user)
|
DB.Save(&user)
|
||||||
|
|
||||||
if user.CreditCard.Id == 0 {
|
if user.CreditCard.Id == 0 {
|
||||||
t.Errorf("After user save, credit card should have id")
|
t.Errorf("After user save, credit card should have id")
|
||||||
|
@ -78,131 +78,131 @@ func TestRelated(t *testing.T) {
|
||||||
}
|
}
|
||||||
|
|
||||||
var emails []Email
|
var emails []Email
|
||||||
db.Model(&user).Related(&emails)
|
DB.Model(&user).Related(&emails)
|
||||||
if len(emails) != 2 {
|
if len(emails) != 2 {
|
||||||
t.Errorf("Should have two emails")
|
t.Errorf("Should have two emails")
|
||||||
}
|
}
|
||||||
|
|
||||||
var emails2 []Email
|
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 {
|
if len(emails2) != 1 {
|
||||||
t.Errorf("Should have two emails")
|
t.Errorf("Should have two emails")
|
||||||
}
|
}
|
||||||
|
|
||||||
var user1 User
|
var user1 User
|
||||||
db.Model(&user).Related(&user1.Emails)
|
DB.Model(&user).Related(&user1.Emails)
|
||||||
if len(user1.Emails) != 2 {
|
if len(user1.Emails) != 2 {
|
||||||
t.Errorf("Should have only one email match related condition")
|
t.Errorf("Should have only one email match related condition")
|
||||||
}
|
}
|
||||||
|
|
||||||
var address1 Address
|
var address1 Address
|
||||||
db.Model(&user).Related(&address1, "BillingAddressId")
|
DB.Model(&user).Related(&address1, "BillingAddressId")
|
||||||
if address1.Address1 != "Billing Address - Address 1" {
|
if address1.Address1 != "Billing Address - Address 1" {
|
||||||
t.Errorf("Should get billing address from user correctly")
|
t.Errorf("Should get billing address from user correctly")
|
||||||
}
|
}
|
||||||
|
|
||||||
user1 = User{}
|
user1 = User{}
|
||||||
db.Model(&address1).Related(&user1, "BillingAddressId")
|
DB.Model(&address1).Related(&user1, "BillingAddressId")
|
||||||
if db.NewRecord(user1) {
|
if DB.NewRecord(user1) {
|
||||||
t.Errorf("Should get user from address correctly")
|
t.Errorf("Should get user from address correctly")
|
||||||
}
|
}
|
||||||
|
|
||||||
var user2 User
|
var user2 User
|
||||||
db.Model(&emails[0]).Related(&user2)
|
DB.Model(&emails[0]).Related(&user2)
|
||||||
if user2.Id != user.Id || user2.Name != user.Name {
|
if user2.Id != user.Id || user2.Name != user.Name {
|
||||||
t.Errorf("Should get user from email correctly")
|
t.Errorf("Should get user from email correctly")
|
||||||
}
|
}
|
||||||
|
|
||||||
var creditcard CreditCard
|
var creditcard CreditCard
|
||||||
var user3 User
|
var user3 User
|
||||||
db.First(&creditcard, "number = ?", "1234567890")
|
DB.First(&creditcard, "number = ?", "1234567890")
|
||||||
db.Model(&creditcard).Related(&user3)
|
DB.Model(&creditcard).Related(&user3)
|
||||||
if user3.Id != user.Id || user3.Name != user.Name {
|
if user3.Id != user.Id || user3.Name != user.Name {
|
||||||
t.Errorf("Should get user from credit card correctly")
|
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")
|
t.Errorf("RecordNotFound for Related")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestManyToMany(t *testing.T) {
|
func TestManyToMany(t *testing.T) {
|
||||||
db.Raw("delete from languages")
|
DB.Raw("delete from languages")
|
||||||
var languages = []Language{{Name: "ZH"}, {Name: "EN"}}
|
var languages = []Language{{Name: "ZH"}, {Name: "EN"}}
|
||||||
user := User{Name: "Many2Many", Languages: languages}
|
user := User{Name: "Many2Many", Languages: languages}
|
||||||
db.Save(&user)
|
DB.Save(&user)
|
||||||
|
|
||||||
// Query
|
// Query
|
||||||
var newLanguages []Language
|
var newLanguages []Language
|
||||||
db.Model(&user).Related(&newLanguages, "Languages")
|
DB.Model(&user).Related(&newLanguages, "Languages")
|
||||||
if len(newLanguages) != len([]string{"ZH", "EN"}) {
|
if len(newLanguages) != len([]string{"ZH", "EN"}) {
|
||||||
t.Errorf("Query many to many relations")
|
t.Errorf("Query many to many relations")
|
||||||
}
|
}
|
||||||
|
|
||||||
newLanguages = []Language{}
|
newLanguages = []Language{}
|
||||||
db.Model(&user).Association("Languages").Find(&newLanguages)
|
DB.Model(&user).Association("Languages").Find(&newLanguages)
|
||||||
if len(newLanguages) != len([]string{"ZH", "EN"}) {
|
if len(newLanguages) != len([]string{"ZH", "EN"}) {
|
||||||
t.Errorf("Should be able to find many to many relations")
|
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")
|
t.Errorf("Count should return correct result")
|
||||||
}
|
}
|
||||||
|
|
||||||
// Append
|
// Append
|
||||||
db.Model(&user).Association("Languages").Append(&Language{Name: "DE"})
|
DB.Model(&user).Association("Languages").Append(&Language{Name: "DE"})
|
||||||
if db.Where("name = ?", "DE").First(&Language{}).RecordNotFound() {
|
if DB.Where("name = ?", "DE").First(&Language{}).RecordNotFound() {
|
||||||
t.Errorf("New record should be saved when append")
|
t.Errorf("New record should be saved when append")
|
||||||
}
|
}
|
||||||
|
|
||||||
languageA := Language{Name: "AA"}
|
languageA := Language{Name: "AA"}
|
||||||
db.Save(&languageA)
|
DB.Save(&languageA)
|
||||||
db.Model(&User{Id: user.Id}).Association("Languages").Append(languageA)
|
DB.Model(&User{Id: user.Id}).Association("Languages").Append(languageA)
|
||||||
languageC := Language{Name: "CC"}
|
languageC := Language{Name: "CC"}
|
||||||
db.Save(&languageC)
|
DB.Save(&languageC)
|
||||||
db.Model(&user).Association("Languages").Append(&[]Language{{Name: "BB"}, 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.Model(&User{Id: user.Id}).Association("Languages").Append([]Language{{Name: "DD"}, {Name: "EE"}})
|
||||||
|
|
||||||
totalLanguages := []string{"ZH", "EN", "DE", "AA", "BB", "CC", "DD", "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")
|
t.Errorf("All appended languages should be saved")
|
||||||
}
|
}
|
||||||
|
|
||||||
// Delete
|
// Delete
|
||||||
var language Language
|
var language Language
|
||||||
db.Where("name = ?", "EE").First(&language)
|
DB.Where("name = ?", "EE").First(&language)
|
||||||
db.Model(&user).Association("Languages").Delete(language, &language)
|
DB.Model(&user).Association("Languages").Delete(language, &language)
|
||||||
if db.Model(&user).Association("Languages").Count() != len(totalLanguages)-1 {
|
if DB.Model(&user).Association("Languages").Count() != len(totalLanguages)-1 {
|
||||||
t.Errorf("Relations should be deleted with Delete")
|
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")
|
t.Errorf("Language EE should not be deleted")
|
||||||
}
|
}
|
||||||
|
|
||||||
languages = []Language{}
|
languages = []Language{}
|
||||||
db.Where("name IN (?)", []string{"CC", "DD"}).Find(&languages)
|
DB.Where("name IN (?)", []string{"CC", "DD"}).Find(&languages)
|
||||||
db.Model(&user).Association("Languages").Delete(languages, &languages)
|
DB.Model(&user).Association("Languages").Delete(languages, &languages)
|
||||||
if db.Model(&user).Association("Languages").Count() != len(totalLanguages)-3 {
|
if DB.Model(&user).Association("Languages").Count() != len(totalLanguages)-3 {
|
||||||
t.Errorf("Relations should be deleted with Delete")
|
t.Errorf("Relations should be deleted with Delete")
|
||||||
}
|
}
|
||||||
|
|
||||||
// Replace
|
// Replace
|
||||||
var languageB Language
|
var languageB Language
|
||||||
db.Where("name = ?", "BB").First(&languageB)
|
DB.Where("name = ?", "BB").First(&languageB)
|
||||||
db.Model(&user).Association("Languages").Replace(languageB)
|
DB.Model(&user).Association("Languages").Replace(languageB)
|
||||||
if db.Model(&user).Association("Languages").Count() != 1 {
|
if DB.Model(&user).Association("Languages").Count() != 1 {
|
||||||
t.Errorf("Relations should be replaced")
|
t.Errorf("Relations should be replaced")
|
||||||
}
|
}
|
||||||
|
|
||||||
db.Model(&user).Association("Languages").Replace(&[]Language{{Name: "FF"}, {Name: "JJ"}})
|
DB.Model(&user).Association("Languages").Replace(&[]Language{{Name: "FF"}, {Name: "JJ"}})
|
||||||
if db.Model(&user).Association("Languages").Count() != len([]string{"FF", "JJ"}) {
|
if DB.Model(&user).Association("Languages").Count() != len([]string{"FF", "JJ"}) {
|
||||||
t.Errorf("Relations should be replaced")
|
t.Errorf("Relations should be replaced")
|
||||||
}
|
}
|
||||||
|
|
||||||
// Clear
|
// Clear
|
||||||
db.Model(&user).Association("Languages").Clear()
|
DB.Model(&user).Association("Languages").Clear()
|
||||||
if db.Model(&user).Association("Languages").Count() != 0 {
|
if DB.Model(&user).Association("Languages").Count() != 0 {
|
||||||
t.Errorf("Relations should be cleared")
|
t.Errorf("Relations should be cleared")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -37,8 +37,8 @@ func (s *Product) AfterFind() {
|
||||||
s.AfterFindCallTimes = s.AfterFindCallTimes + 1
|
s.AfterFindCallTimes = s.AfterFindCallTimes + 1
|
||||||
}
|
}
|
||||||
|
|
||||||
func (s *Product) AfterCreate(db *gorm.DB) {
|
func (s *Product) AfterCreate(tx *gorm.DB) {
|
||||||
db.Model(s).UpdateColumn(Product{AfterCreateCallTimes: s.AfterCreateCallTimes + 1})
|
tx.Model(s).UpdateColumn(Product{AfterCreateCallTimes: s.AfterCreateCallTimes + 1})
|
||||||
}
|
}
|
||||||
|
|
||||||
func (s *Product) AfterUpdate() {
|
func (s *Product) AfterUpdate() {
|
||||||
|
@ -75,103 +75,103 @@ func (s *Product) GetCallTimes() []int64 {
|
||||||
|
|
||||||
func TestRunCallbacks(t *testing.T) {
|
func TestRunCallbacks(t *testing.T) {
|
||||||
p := Product{Code: "unique_code", Price: 100}
|
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}) {
|
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())
|
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}) {
|
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())
|
t.Errorf("After callbacks values are not saved, %v", p.GetCallTimes())
|
||||||
}
|
}
|
||||||
|
|
||||||
p.Price = 200
|
p.Price = 200
|
||||||
db.Save(&p)
|
DB.Save(&p)
|
||||||
if !reflect.DeepEqual(p.GetCallTimes(), []int64{1, 2, 1, 1, 1, 1, 0, 0, 1}) {
|
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())
|
t.Errorf("After update callbacks should be invoked successfully, %v", p.GetCallTimes())
|
||||||
}
|
}
|
||||||
|
|
||||||
var products []Product
|
var products []Product
|
||||||
db.Find(&products, "code = ?", "unique_code")
|
DB.Find(&products, "code = ?", "unique_code")
|
||||||
if products[0].AfterFindCallTimes != 2 {
|
if products[0].AfterFindCallTimes != 2 {
|
||||||
t.Errorf("AfterFind callbacks should work with slice")
|
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}) {
|
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())
|
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}) {
|
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())
|
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")
|
t.Errorf("Can't find a deleted record")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestCallbacksWithErrors(t *testing.T) {
|
func TestCallbacksWithErrors(t *testing.T) {
|
||||||
p := Product{Code: "Invalid", Price: 100}
|
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")
|
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")
|
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")
|
t.Errorf("An error from after create callbacks happened when create with invalid value")
|
||||||
}
|
}
|
||||||
|
|
||||||
p2 := Product{Code: "update_callback", Price: 100}
|
p2 := Product{Code: "update_callback", Price: 100}
|
||||||
db.Save(&p2)
|
DB.Save(&p2)
|
||||||
|
|
||||||
p2.Code = "dont_update"
|
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")
|
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")
|
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")
|
t.Errorf("Record Should not be updated due to errors happened in before update callback")
|
||||||
}
|
}
|
||||||
|
|
||||||
p2.Code = "dont_save"
|
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")
|
t.Errorf("An error from before save callbacks happened when update with invalid value")
|
||||||
}
|
}
|
||||||
|
|
||||||
p3 := Product{Code: "dont_delete", Price: 100}
|
p3 := Product{Code: "dont_delete", Price: 100}
|
||||||
db.Save(&p3)
|
DB.Save(&p3)
|
||||||
if db.Delete(&p3).Error == nil {
|
if DB.Delete(&p3).Error == nil {
|
||||||
t.Errorf("An error from before delete callbacks happened when delete")
|
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")
|
t.Errorf("An error from before delete callbacks happened")
|
||||||
}
|
}
|
||||||
|
|
||||||
p4 := Product{Code: "after_save_error", Price: 100}
|
p4 := Product{Code: "after_save_error", Price: 100}
|
||||||
db.Save(&p4)
|
DB.Save(&p4)
|
||||||
if err := db.First(&Product{}, "code = ?", "after_save_error").Error; err == nil {
|
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")
|
t.Errorf("Record should be reverted if get an error in after save callback")
|
||||||
}
|
}
|
||||||
|
|
||||||
p5 := Product{Code: "after_delete_error", Price: 100}
|
p5 := Product{Code: "after_delete_error", Price: 100}
|
||||||
db.Save(&p5)
|
DB.Save(&p5)
|
||||||
if err := db.First(&Product{}, "code = ?", "after_delete_error").Error; err != nil {
|
if err := DB.First(&Product{}, "code = ?", "after_delete_error").Error; err != nil {
|
||||||
t.Errorf("Record should be found")
|
t.Errorf("Record should be found")
|
||||||
}
|
}
|
||||||
|
|
||||||
db.Delete(&p5)
|
DB.Delete(&p5)
|
||||||
if err := db.First(&Product{}, "code = ?", "after_delete_error").Error; err != nil {
|
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")
|
t.Errorf("Record shouldn't be deleted because of an error happened in after delete callback")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -10,20 +10,20 @@ func TestCreate(t *testing.T) {
|
||||||
float := 35.03554004971999
|
float := 35.03554004971999
|
||||||
user := User{Name: "CreateUser", Age: 18, Birthday: time.Now(), UserNum: Num(111), PasswordHash: []byte{'f', 'a', 'k', '4'}, Latitude: float}
|
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")
|
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")
|
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")
|
t.Error("User should not new record after save")
|
||||||
}
|
}
|
||||||
|
|
||||||
var newUser User
|
var newUser User
|
||||||
db.First(&newUser, user.Id)
|
DB.First(&newUser, user.Id)
|
||||||
|
|
||||||
if !reflect.DeepEqual(newUser.PasswordHash, []byte{'f', 'a', 'k', '4'}) {
|
if !reflect.DeepEqual(newUser.PasswordHash, []byte{'f', 'a', 'k', '4'}) {
|
||||||
t.Errorf("User's PasswordHash should be saved ([]byte)")
|
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")
|
t.Errorf("Should have created_at after create")
|
||||||
}
|
}
|
||||||
|
|
||||||
db.Model(user).Update("name", "create_user_new_name")
|
DB.Model(user).Update("name", "create_user_new_name")
|
||||||
db.First(&user, user.Id)
|
DB.First(&user, user.Id)
|
||||||
if user.CreatedAt != newUser.CreatedAt {
|
if user.CreatedAt != newUser.CreatedAt {
|
||||||
t.Errorf("CreatedAt should not be changed after update")
|
t.Errorf("CreatedAt should not be changed after update")
|
||||||
}
|
}
|
||||||
|
@ -58,7 +58,7 @@ func TestCreate(t *testing.T) {
|
||||||
|
|
||||||
func TestCreateWithNoStdPrimaryKey(t *testing.T) {
|
func TestCreateWithNoStdPrimaryKey(t *testing.T) {
|
||||||
animal := Animal{Name: "Ferdinand"}
|
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")
|
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) {
|
func TestAnonymousScanner(t *testing.T) {
|
||||||
user := User{Name: "anonymous_scanner", Role: Role{Name: "admin"}}
|
user := User{Name: "anonymous_scanner", Role: Role{Name: "admin"}}
|
||||||
db.Save(&user)
|
DB.Save(&user)
|
||||||
|
|
||||||
var user2 User
|
var user2 User
|
||||||
db.First(&user2, "name = ?", "anonymous_scanner")
|
DB.First(&user2, "name = ?", "anonymous_scanner")
|
||||||
if user2.Role.Name != "admin" {
|
if user2.Role.Name != "admin" {
|
||||||
t.Errorf("Should be able to get anonymous scanner")
|
t.Errorf("Should be able to get anonymous scanner")
|
||||||
}
|
}
|
||||||
|
@ -84,11 +84,11 @@ func TestAnonymousScanner(t *testing.T) {
|
||||||
|
|
||||||
func TestAnonymousField(t *testing.T) {
|
func TestAnonymousField(t *testing.T) {
|
||||||
user := User{Name: "anonymous_field", Company: Company{Name: "company"}}
|
user := User{Name: "anonymous_field", Company: Company{Name: "company"}}
|
||||||
db.Save(&user)
|
DB.Save(&user)
|
||||||
|
|
||||||
var user2 User
|
var user2 User
|
||||||
db.First(&user2, "name = ?", "anonymous_field")
|
DB.First(&user2, "name = ?", "anonymous_field")
|
||||||
db.Model(&user2).Related(&user2.Company)
|
DB.Model(&user2).Related(&user2.Company)
|
||||||
if user2.Company.Name != "company" {
|
if user2.Company.Name != "company" {
|
||||||
t.Errorf("Should be able to get anonymous field")
|
t.Errorf("Should be able to get anonymous field")
|
||||||
}
|
}
|
||||||
|
|
|
@ -7,36 +7,36 @@ import (
|
||||||
|
|
||||||
func TestDelete(t *testing.T) {
|
func TestDelete(t *testing.T) {
|
||||||
user1, user2 := User{Name: "delete1"}, User{Name: "delete2"}
|
user1, user2 := User{Name: "delete1"}, User{Name: "delete2"}
|
||||||
db.Save(&user1)
|
DB.Save(&user1)
|
||||||
db.Save(&user2)
|
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")
|
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")
|
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")
|
t.Errorf("Other users that not deleted should be found-able")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestInlineDelete(t *testing.T) {
|
func TestInlineDelete(t *testing.T) {
|
||||||
user1, user2 := User{Name: "inline_delete1"}, User{Name: "inline_delete2"}
|
user1, user2 := User{Name: "inline_delete1"}, User{Name: "inline_delete2"}
|
||||||
db.Save(&user1)
|
DB.Save(&user1)
|
||||||
db.Save(&user2)
|
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")
|
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")
|
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")
|
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")
|
t.Errorf("User can't be found after delete")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -47,22 +47,22 @@ func TestSoftDelete(t *testing.T) {
|
||||||
Name string
|
Name string
|
||||||
DeletedAt time.Time
|
DeletedAt time.Time
|
||||||
}
|
}
|
||||||
db.AutoMigrate(&User{})
|
DB.AutoMigrate(&User{})
|
||||||
|
|
||||||
user := User{Name: "soft_delete"}
|
user := User{Name: "soft_delete"}
|
||||||
db.Save(&user)
|
DB.Save(&user)
|
||||||
db.Delete(&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")
|
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")
|
t.Errorf("Should be able to find soft deleted record with Unscoped")
|
||||||
}
|
}
|
||||||
|
|
||||||
db.Unscoped().Delete(&user)
|
DB.Unscoped().Delete(&user)
|
||||||
if !db.Unscoped().First(&User{}, "name = ?", user.Name).RecordNotFound() {
|
if !DB.Unscoped().First(&User{}, "name = ?", user.Name).RecordNotFound() {
|
||||||
t.Errorf("Can't find permanently deleted record")
|
t.Errorf("Can't find permanently deleted record")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
176
main_test.go
176
main_test.go
|
@ -18,7 +18,7 @@ import (
|
||||||
)
|
)
|
||||||
|
|
||||||
var (
|
var (
|
||||||
db gorm.DB
|
DB gorm.DB
|
||||||
t1, t2, t3, t4, t5 time.Time
|
t1, t2, t3, t4, t5 time.Time
|
||||||
)
|
)
|
||||||
|
|
||||||
|
@ -30,88 +30,88 @@ func init() {
|
||||||
// CREATE DATABASE gorm;
|
// CREATE DATABASE gorm;
|
||||||
// GRANT ALL ON gorm.* TO 'gorm'@'localhost';
|
// GRANT ALL ON gorm.* TO 'gorm'@'localhost';
|
||||||
fmt.Println("testing mysql...")
|
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":
|
case "postgres":
|
||||||
fmt.Println("testing 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:
|
default:
|
||||||
fmt.Println("testing sqlite3...")
|
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(Logger{log.New(os.Stdout, "\r\n", 0)})
|
||||||
// db.SetLogger(log.New(os.Stdout, "\r\n", 0))
|
// DB.SetLogger(log.New(os.Stdout, "\r\n", 0))
|
||||||
db.LogMode(true)
|
DB.LogMode(true)
|
||||||
db.LogMode(false)
|
DB.LogMode(false)
|
||||||
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
panic(fmt.Sprintf("No error should happen when connect database, but got %+v", err))
|
panic(fmt.Sprintf("No error should happen when connect database, but got %+v", err))
|
||||||
}
|
}
|
||||||
|
|
||||||
db.DB().SetMaxIdleConns(10)
|
DB.DB().SetMaxIdleConns(10)
|
||||||
|
|
||||||
runMigration()
|
runMigration()
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestExceptionsWithInvalidSql(t *testing.T) {
|
func TestExceptionsWithInvalidSql(t *testing.T) {
|
||||||
var columns []string
|
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")
|
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")
|
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")
|
t.Errorf("Should got error with invalid SQL")
|
||||||
}
|
}
|
||||||
|
|
||||||
var count1, count2 int64
|
var count1, count2 int64
|
||||||
db.Model(&User{}).Count(&count1)
|
DB.Model(&User{}).Count(&count1)
|
||||||
if count1 <= 0 {
|
if count1 <= 0 {
|
||||||
t.Errorf("Should find some users")
|
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")
|
t.Errorf("Should got error with invalid SQL")
|
||||||
}
|
}
|
||||||
|
|
||||||
db.Model(&User{}).Count(&count2)
|
DB.Model(&User{}).Count(&count2)
|
||||||
if count1 != count2 {
|
if count1 != count2 {
|
||||||
t.Errorf("No user should not be deleted by invalid SQL")
|
t.Errorf("No user should not be deleted by invalid SQL")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestSetTable(t *testing.T) {
|
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")
|
t.Errorf("No errors should happen if set table for pluck")
|
||||||
}
|
}
|
||||||
|
|
||||||
var users []User
|
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")
|
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")
|
t.Errorf("Should got error when table is set to an invalid table")
|
||||||
}
|
}
|
||||||
|
|
||||||
db.Exec("drop table deleted_users;")
|
DB.Exec("drop table deleted_users;")
|
||||||
if db.Table("deleted_users").CreateTable(&User{}).Error != nil {
|
if DB.Table("deleted_users").CreateTable(&User{}).Error != nil {
|
||||||
t.Errorf("Create table with specified table")
|
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
|
var deletedUsers []User
|
||||||
db.Table("deleted_users").Find(&deletedUsers)
|
DB.Table("deleted_users").Find(&deletedUsers)
|
||||||
if len(deletedUsers) != 1 {
|
if len(deletedUsers) != 1 {
|
||||||
t.Errorf("Query from specified table")
|
t.Errorf("Query from specified table")
|
||||||
}
|
}
|
||||||
|
|
||||||
var user1, user2, user3 User
|
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) {
|
if (user1.Name == user2.Name) || (user1.Name != user3.Name) {
|
||||||
t.Errorf("unset specified table with blank string")
|
t.Errorf("unset specified table with blank string")
|
||||||
}
|
}
|
||||||
|
@ -128,63 +128,63 @@ func (c Cart) TableName() string {
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestTableName(t *testing.T) {
|
func TestTableName(t *testing.T) {
|
||||||
db := db.Model("")
|
DB := DB.Model("")
|
||||||
if db.NewScope(Order{}).TableName() != "orders" {
|
if DB.NewScope(Order{}).TableName() != "orders" {
|
||||||
t.Errorf("Order's table name should be 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")
|
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")
|
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")
|
t.Errorf("&[]Order's table name should be orders")
|
||||||
}
|
}
|
||||||
|
|
||||||
db.SingularTable(true)
|
DB.SingularTable(true)
|
||||||
if db.NewScope(Order{}).TableName() != "order" {
|
if DB.NewScope(Order{}).TableName() != "order" {
|
||||||
t.Errorf("Order's singular table name should be 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")
|
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")
|
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")
|
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")
|
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")
|
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")
|
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")
|
t.Errorf("[]Cart's singular table name should be shopping_cart")
|
||||||
}
|
}
|
||||||
db.SingularTable(false)
|
DB.SingularTable(false)
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestSqlNullValue(t *testing.T) {
|
func TestSqlNullValue(t *testing.T) {
|
||||||
db.DropTable(&NullValue{})
|
DB.DropTable(&NullValue{})
|
||||||
db.AutoMigrate(&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},
|
Age: sql.NullInt64{Int64: 18, Valid: true},
|
||||||
Male: sql.NullBool{Bool: true, Valid: true},
|
Male: sql.NullBool{Bool: true, Valid: true},
|
||||||
Height: sql.NullFloat64{Float64: 100.11, Valid: true},
|
Height: sql.NullFloat64{Float64: 100.11, Valid: true},
|
||||||
|
@ -194,13 +194,13 @@ func TestSqlNullValue(t *testing.T) {
|
||||||
}
|
}
|
||||||
|
|
||||||
var nv NullValue
|
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 {
|
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")
|
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},
|
Age: sql.NullInt64{Int64: 18, Valid: false},
|
||||||
Male: sql.NullBool{Bool: true, Valid: true},
|
Male: sql.NullBool{Bool: true, Valid: true},
|
||||||
Height: sql.NullFloat64{Float64: 100.11, Valid: true},
|
Height: sql.NullFloat64{Float64: 100.11, Valid: true},
|
||||||
|
@ -210,12 +210,12 @@ func TestSqlNullValue(t *testing.T) {
|
||||||
}
|
}
|
||||||
|
|
||||||
var nv2 NullValue
|
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 {
|
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")
|
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},
|
Age: sql.NullInt64{Int64: 18, Valid: false},
|
||||||
Male: sql.NullBool{Bool: true, Valid: true},
|
Male: sql.NullBool{Bool: true, Valid: true},
|
||||||
Height: sql.NullFloat64{Float64: 100.11, Valid: true},
|
Height: sql.NullFloat64{Float64: 100.11, Valid: true},
|
||||||
|
@ -226,7 +226,7 @@ func TestSqlNullValue(t *testing.T) {
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestTransaction(t *testing.T) {
|
func TestTransaction(t *testing.T) {
|
||||||
tx := db.Begin()
|
tx := DB.Begin()
|
||||||
u := User{Name: "transcation"}
|
u := User{Name: "transcation"}
|
||||||
if err := tx.Save(&u).Error; err != nil {
|
if err := tx.Save(&u).Error; err != nil {
|
||||||
t.Errorf("No error should raise")
|
t.Errorf("No error should raise")
|
||||||
|
@ -246,7 +246,7 @@ func TestTransaction(t *testing.T) {
|
||||||
t.Errorf("Should not find record after rollback")
|
t.Errorf("Should not find record after rollback")
|
||||||
}
|
}
|
||||||
|
|
||||||
tx2 := db.Begin()
|
tx2 := DB.Begin()
|
||||||
u2 := User{Name: "transcation-2"}
|
u2 := User{Name: "transcation-2"}
|
||||||
if err := tx2.Save(&u2).Error; err != nil {
|
if err := tx2.Save(&u2).Error; err != nil {
|
||||||
t.Errorf("No error should raise")
|
t.Errorf("No error should raise")
|
||||||
|
@ -258,7 +258,7 @@ func TestTransaction(t *testing.T) {
|
||||||
|
|
||||||
tx2.Commit()
|
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")
|
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")}
|
user1 := User{Name: "RowUser1", Age: 1, Birthday: now.MustParse("2000-1-1")}
|
||||||
user2 := User{Name: "RowUser2", Age: 10, Birthday: now.MustParse("2010-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")}
|
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
|
var age int64
|
||||||
row.Scan(&age)
|
row.Scan(&age)
|
||||||
if age != 10 {
|
if age != 10 {
|
||||||
|
@ -281,9 +281,9 @@ func TestRows(t *testing.T) {
|
||||||
user1 := User{Name: "RowsUser1", Age: 1, Birthday: now.MustParse("2000-1-1")}
|
user1 := User{Name: "RowsUser1", Age: 1, Birthday: now.MustParse("2000-1-1")}
|
||||||
user2 := User{Name: "RowsUser2", Age: 10, Birthday: now.MustParse("2010-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")}
|
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 {
|
if err != nil {
|
||||||
t.Errorf("Not error should happen, but got")
|
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")}
|
user1 := User{Name: "ScanUser1", Age: 1, Birthday: now.MustParse("2000-1-1")}
|
||||||
user2 := User{Name: "ScanUser2", Age: 10, Birthday: now.MustParse("2010-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")}
|
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 {
|
type result struct {
|
||||||
Name string
|
Name string
|
||||||
|
@ -312,19 +312,19 @@ func TestScan(t *testing.T) {
|
||||||
}
|
}
|
||||||
|
|
||||||
var res result
|
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 {
|
if res.Name != user3.Name {
|
||||||
t.Errorf("Scan into struct should work")
|
t.Errorf("Scan into struct should work")
|
||||||
}
|
}
|
||||||
|
|
||||||
var doubleAgeRes result
|
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 {
|
if doubleAgeRes.Age != res.Age*2 {
|
||||||
t.Errorf("Scan double age as age")
|
t.Errorf("Scan double age as age")
|
||||||
}
|
}
|
||||||
|
|
||||||
var ress []result
|
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 {
|
if len(ress) != 2 || ress[0].Name != user2.Name || ress[1].Name != user3.Name {
|
||||||
t.Errorf("Scan into struct map")
|
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")}
|
user1 := User{Name: "ExecRawSqlUser1", Age: 1, Birthday: now.MustParse("2000-1-1")}
|
||||||
user2 := User{Name: "ExecRawSqlUser2", Age: 10, Birthday: now.MustParse("2010-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")}
|
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 {
|
type result struct {
|
||||||
Name string
|
Name string
|
||||||
|
@ -342,12 +342,12 @@ func TestRaw(t *testing.T) {
|
||||||
}
|
}
|
||||||
|
|
||||||
var ress []result
|
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 {
|
if len(ress) != 2 || ress[0].Name != user2.Name || ress[1].Name != user3.Name {
|
||||||
t.Errorf("Raw with scan")
|
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
|
count := 0
|
||||||
for rows.Next() {
|
for rows.Next() {
|
||||||
count++
|
count++
|
||||||
|
@ -356,14 +356,14 @@ func TestRaw(t *testing.T) {
|
||||||
t.Errorf("Raw with Rows should find one record with name 3")
|
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})
|
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 {
|
if DB.Where("name in (?)", []string{user1.Name, user2.Name, user3.Name}).First(&User{}).Error != gorm.RecordNotFound {
|
||||||
t.Error("Raw sql to update records")
|
t.Error("Raw sql to update records")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestGroup(t *testing.T) {
|
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 {
|
if err == nil {
|
||||||
defer rows.Close()
|
defer rows.Close()
|
||||||
|
@ -386,17 +386,17 @@ func TestJoins(t *testing.T) {
|
||||||
Name: "joins",
|
Name: "joins",
|
||||||
Emails: []Email{{Email: "join1@example.com"}, {Email: "join2@example.com"}},
|
Emails: []Email{{Email: "join1@example.com"}, {Email: "join2@example.com"}},
|
||||||
}
|
}
|
||||||
db.Save(&user)
|
DB.Save(&user)
|
||||||
|
|
||||||
var results []result
|
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" {
|
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")
|
t.Errorf("Should find all two emails with Join")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestHaving(t *testing.T) {
|
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 {
|
if err == nil {
|
||||||
defer rows.Close()
|
defer rows.Close()
|
||||||
|
@ -427,22 +427,22 @@ func TestTimeWithZone(t *testing.T) {
|
||||||
for index, vtime := range times {
|
for index, vtime := range times {
|
||||||
name := "time_with_zone_" + strconv.Itoa(index)
|
name := "time_with_zone_" + strconv.Itoa(index)
|
||||||
user := User{Name: name, Birthday: vtime}
|
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" {
|
if user.Birthday.UTC().Format(format) != "2013-02-18 17:51:49 +0000" {
|
||||||
t.Errorf("User's birthday should not be changed after save")
|
t.Errorf("User's birthday should not be changed after save")
|
||||||
}
|
}
|
||||||
|
|
||||||
var findUser, findUser2, findUser3 User
|
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" {
|
if findUser.Birthday.UTC().Format(format) != "2013-02-18 17:51:49 +0000" {
|
||||||
t.Errorf("User's birthday should not be changed after find")
|
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")
|
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")
|
t.Errorf("User should not be found")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -458,14 +458,14 @@ func TestHstore(t *testing.T) {
|
||||||
t.Skip()
|
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")
|
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))
|
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))
|
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,
|
"opinion": &opinion,
|
||||||
}
|
}
|
||||||
d := Details{Bulk: bulk}
|
d := Details{Bulk: bulk}
|
||||||
db.Save(&d)
|
DB.Save(&d)
|
||||||
|
|
||||||
var d2 Details
|
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)
|
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) {
|
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")
|
t.Errorf("Should be able to get setting after set")
|
||||||
} else {
|
} else {
|
||||||
if value.(string) != "world" {
|
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")
|
t.Errorf("Get non existing key should return error")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestCompatibilityMode(t *testing.T) {
|
func TestCompatibilityMode(t *testing.T) {
|
||||||
db, _ := gorm.Open("testdb", "")
|
DB, _ := gorm.Open("testdb", "")
|
||||||
testdb.SetQueryFunc(func(query string) (driver.Rows, error) {
|
testdb.SetQueryFunc(func(query string) (driver.Rows, error) {
|
||||||
columns := []string{"id", "name", "age"}
|
columns := []string{"id", "name", "age"}
|
||||||
result := `
|
result := `
|
||||||
|
@ -521,7 +521,7 @@ func TestCompatibilityMode(t *testing.T) {
|
||||||
})
|
})
|
||||||
|
|
||||||
var users []User
|
var users []User
|
||||||
db.Find(&users)
|
DB.Find(&users)
|
||||||
if (users[0].Name != "Tim") || len(users) != 3 {
|
if (users[0].Name != "Tim") || len(users) != 3 {
|
||||||
t.Errorf("Unexcepted result returned")
|
t.Errorf("Unexcepted result returned")
|
||||||
}
|
}
|
||||||
|
@ -533,19 +533,19 @@ func BenchmarkGorm(b *testing.B) {
|
||||||
e := strconv.Itoa(x) + "benchmark@example.org"
|
e := strconv.Itoa(x) + "benchmark@example.org"
|
||||||
email := BigEmail{Email: e, UserAgent: "pc", RegisteredAt: time.Now()}
|
email := BigEmail{Email: e, UserAgent: "pc", RegisteredAt: time.Now()}
|
||||||
// Insert
|
// Insert
|
||||||
db.Save(&email)
|
DB.Save(&email)
|
||||||
// Query
|
// Query
|
||||||
db.First(&BigEmail{}, "email = ?", e)
|
DB.First(&BigEmail{}, "email = ?", e)
|
||||||
// Update
|
// Update
|
||||||
db.Model(&email).UpdateColumn("email", "new-"+e)
|
DB.Model(&email).UpdateColumn("email", "new-"+e)
|
||||||
// Delete
|
// Delete
|
||||||
db.Delete(&email)
|
DB.Delete(&email)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func BenchmarkRawSql(b *testing.B) {
|
func BenchmarkRawSql(b *testing.B) {
|
||||||
db, _ := sql.Open("postgres", "user=gorm dbname=gorm sslmode=disable")
|
DB, _ := sql.Open("postgres", "user=gorm DB.ame=gorm sslmode=disable")
|
||||||
db.SetMaxIdleConns(10)
|
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"
|
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"
|
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"
|
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"
|
e := strconv.Itoa(x) + "benchmark@example.org"
|
||||||
email := BigEmail{Email: e, UserAgent: "pc", RegisteredAt: time.Now()}
|
email := BigEmail{Email: e, UserAgent: "pc", RegisteredAt: time.Now()}
|
||||||
// Insert
|
// 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
|
// Query
|
||||||
rows, _ := db.Query(query_sql, email.Email)
|
rows, _ := DB.Query(query_sql, email.Email)
|
||||||
rows.Close()
|
rows.Close()
|
||||||
// Update
|
// Update
|
||||||
db.Exec(update_sql, "new-"+e, time.Now(), id)
|
DB.Exec(update_sql, "new-"+e, time.Now(), id)
|
||||||
// Delete
|
// Delete
|
||||||
db.Exec(delete_sql, id)
|
DB.Exec(delete_sql, id)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -7,63 +7,65 @@ import (
|
||||||
)
|
)
|
||||||
|
|
||||||
func runMigration() {
|
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)
|
fmt.Printf("Got error when try to delete table users, %+v\n", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
db.Exec("drop table products;")
|
DB.Exec("drop table products;")
|
||||||
db.Exec("drop table emails;")
|
DB.Exec("drop table emails;")
|
||||||
db.Exec("drop table addresses")
|
DB.Exec("drop table addresses")
|
||||||
db.Exec("drop table credit_cards")
|
DB.Exec("drop table credit_cards")
|
||||||
db.Exec("drop table roles")
|
DB.Exec("drop table roles")
|
||||||
db.Exec("drop table companies")
|
DB.Exec("drop table companies")
|
||||||
db.Exec("drop table animals")
|
DB.Exec("drop table animals")
|
||||||
db.Exec("drop table user_languages")
|
DB.Exec("drop table user_languages")
|
||||||
db.Exec("drop table 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))
|
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))
|
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))
|
panic(fmt.Sprintf("No error should happen when create table, but got %+v", err))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
DB.AutoMigrate(HNPost{}, EngadgetPost{})
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestIndexes(t *testing.T) {
|
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)
|
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)
|
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)
|
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)
|
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)
|
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")
|
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)
|
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")
|
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) {
|
func TestAutoMigration(t *testing.T) {
|
||||||
db.AutoMigrate(Address{})
|
DB.AutoMigrate(Address{})
|
||||||
if err := db.Table("emails").AutoMigrate(BigEmail{}).Error; err != nil {
|
if err := DB.Table("emails").AutoMigrate(BigEmail{}).Error; err != nil {
|
||||||
t.Errorf("Auto Migrate should not raise any error")
|
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
|
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() {
|
if bigemail.Email != "jinzhu@example.org" || bigemail.UserAgent != "pc" || bigemail.RegisteredAt.IsZero() {
|
||||||
t.Error("Big Emails should be saved and fetched correctly")
|
t.Error("Big Emails should be saved and fetched correctly")
|
||||||
}
|
}
|
||||||
|
|
184
query_test.go
184
query_test.go
|
@ -10,53 +10,53 @@ import (
|
||||||
)
|
)
|
||||||
|
|
||||||
func TestFirstAndLast(t *testing.T) {
|
func TestFirstAndLast(t *testing.T) {
|
||||||
db.Save(&User{Name: "user1", Emails: []Email{{Email: "user1@example.com"}}})
|
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: "user2", Emails: []Email{{Email: "user2@example.com"}}})
|
||||||
|
|
||||||
var user1, user2, user3, user4 User
|
var user1, user2, user3, user4 User
|
||||||
db.First(&user1)
|
DB.First(&user1)
|
||||||
db.Order("id").Find(&user2)
|
DB.Order("id").Find(&user2)
|
||||||
|
|
||||||
db.Last(&user3)
|
DB.Last(&user3)
|
||||||
db.Order("id desc").Find(&user4)
|
DB.Order("id desc").Find(&user4)
|
||||||
if user1.Id != user2.Id || user3.Id != user4.Id {
|
if user1.Id != user2.Id || user3.Id != user4.Id {
|
||||||
t.Errorf("First and Last should by order by primary key")
|
t.Errorf("First and Last should by order by primary key")
|
||||||
}
|
}
|
||||||
|
|
||||||
var users []User
|
var users []User
|
||||||
db.First(&users)
|
DB.First(&users)
|
||||||
if len(users) != 1 {
|
if len(users) != 1 {
|
||||||
t.Errorf("Find first record as slice")
|
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")
|
t.Errorf("Should not raise any error when order with Join table")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestFirstAndLastWithNoStdPrimaryKey(t *testing.T) {
|
func TestFirstAndLastWithNoStdPrimaryKey(t *testing.T) {
|
||||||
db.Save(&Animal{Name: "animal1"})
|
DB.Save(&Animal{Name: "animal1"})
|
||||||
db.Save(&Animal{Name: "animal2"})
|
DB.Save(&Animal{Name: "animal2"})
|
||||||
|
|
||||||
var animal1, animal2, animal3, animal4 Animal
|
var animal1, animal2, animal3, animal4 Animal
|
||||||
db.First(&animal1)
|
DB.First(&animal1)
|
||||||
db.Order("counter").Find(&animal2)
|
DB.Order("counter").Find(&animal2)
|
||||||
|
|
||||||
db.Last(&animal3)
|
DB.Last(&animal3)
|
||||||
db.Order("counter desc").Find(&animal4)
|
DB.Order("counter desc").Find(&animal4)
|
||||||
if animal1.Counter != animal2.Counter || animal3.Counter != animal4.Counter {
|
if animal1.Counter != animal2.Counter || animal3.Counter != animal4.Counter {
|
||||||
t.Errorf("First and Last should work correctly")
|
t.Errorf("First and Last should work correctly")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestFindAsSliceOfPointers(t *testing.T) {
|
func TestFindAsSliceOfPointers(t *testing.T) {
|
||||||
db.Save(&User{Name: "user"})
|
DB.Save(&User{Name: "user"})
|
||||||
|
|
||||||
var users []User
|
var users []User
|
||||||
db.Find(&users)
|
DB.Find(&users)
|
||||||
|
|
||||||
var userPointers []*User
|
var userPointers []*User
|
||||||
db.Find(&userPointers)
|
DB.Find(&userPointers)
|
||||||
|
|
||||||
if len(users) == 0 || len(users) != len(userPointers) {
|
if len(users) == 0 || len(users) != len(userPointers) {
|
||||||
t.Errorf("Find slice of pointers")
|
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")}
|
user1 := User{Name: "PlainSqlUser1", Age: 1, Birthday: now.MustParse("2000-1-1")}
|
||||||
user2 := User{Name: "PlainSqlUser2", Age: 10, Birthday: now.MustParse("2010-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")}
|
user3 := User{Name: "PlainSqlUser3", Age: 20, Birthday: now.MustParse("2020-1-1")}
|
||||||
db.Save(&user1).Save(&user2).Save(&user3)
|
DB.Save(&user1).Save(&user2).Save(&user3)
|
||||||
scopedb := db.Where("name LIKE ?", "%PlainSqlUser%")
|
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")
|
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)")
|
t.Errorf("Search with plan SQL (regexp)")
|
||||||
}
|
}
|
||||||
|
|
||||||
var users []User
|
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 {
|
if len(users) != 2 {
|
||||||
t.Errorf("Should found 2 users that age > 1, but got %v", len(users))
|
t.Errorf("Should found 2 users that age > 1, but got %v", len(users))
|
||||||
}
|
}
|
||||||
|
|
||||||
users = []User{}
|
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 {
|
if len(users) != 3 {
|
||||||
t.Errorf("Should found 3 users that age >= 1, but got %v", len(users))
|
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{}
|
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 {
|
if len(users) != 2 {
|
||||||
t.Errorf("Should found 2 users, but got %v", len(users))
|
t.Errorf("Should found 2 users, but got %v", len(users))
|
||||||
}
|
}
|
||||||
|
|
||||||
users = []User{}
|
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 {
|
if len(users) != 3 {
|
||||||
t.Errorf("Should found 3 users, but got %v", len(users))
|
t.Errorf("Should found 3 users, but got %v", len(users))
|
||||||
}
|
}
|
||||||
|
|
||||||
users = []User{}
|
users = []User{}
|
||||||
db.Where("id in (?)", user1.Id).Find(&users)
|
DB.Where("id in (?)", user1.Id).Find(&users)
|
||||||
if len(users) != 1 {
|
if len(users) != 1 {
|
||||||
t.Errorf("Should found 1 users, but got %v", len(users))
|
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")
|
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")}
|
user1 := User{Name: "StructSearchUser1", Age: 1, Birthday: now.MustParse("2000-1-1")}
|
||||||
user2 := User{Name: "StructSearchUser2", Age: 10, Birthday: now.MustParse("2010-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")}
|
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")
|
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")
|
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")
|
t.Errorf("Search with primary key as inline condition")
|
||||||
}
|
}
|
||||||
|
|
||||||
var users []User
|
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 {
|
if len(users) != 3 {
|
||||||
t.Errorf("Should found 3 users when search with primary keys, but got %v", len(users))
|
t.Errorf("Should found 3 users when search with primary keys, but got %v", len(users))
|
||||||
}
|
}
|
||||||
|
|
||||||
var user User
|
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 {
|
if user.Id == 0 || user.Name != user1.Name {
|
||||||
t.Errorf("Search first record with inline pointer of struct")
|
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 {
|
if user.Id == 0 || user.Name != user.Name {
|
||||||
t.Errorf("Search first record with inline struct")
|
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 {
|
if user.Id == 0 || user.Name != user1.Name {
|
||||||
t.Errorf("Search first record with where struct")
|
t.Errorf("Search first record with where struct")
|
||||||
}
|
}
|
||||||
|
|
||||||
users = []User{}
|
users = []User{}
|
||||||
db.Find(&users, &User{Name: user2.Name})
|
DB.Find(&users, &User{Name: user2.Name})
|
||||||
if len(users) != 1 {
|
if len(users) != 1 {
|
||||||
t.Errorf("Search all records with inline struct")
|
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")}
|
user1 := User{Name: "MapSearchUser1", Age: 1, Birthday: now.MustParse("2000-1-1")}
|
||||||
user2 := User{Name: "MapSearchUser2", Age: 10, Birthday: now.MustParse("2010-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")}
|
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
|
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 {
|
if user.Id == 0 || user.Name != user1.Name {
|
||||||
t.Errorf("Search first record with inline map")
|
t.Errorf("Search first record with inline map")
|
||||||
}
|
}
|
||||||
|
|
||||||
user = User{}
|
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 {
|
if user.Id == 0 || user.Name != user2.Name {
|
||||||
t.Errorf("Search first record with where map")
|
t.Errorf("Search first record with where map")
|
||||||
}
|
}
|
||||||
|
|
||||||
var users []User
|
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 {
|
if len(users) != 1 {
|
||||||
t.Errorf("Search all records with inline map")
|
t.Errorf("Search all records with inline map")
|
||||||
}
|
}
|
||||||
|
|
||||||
users = []User{}
|
users = []User{}
|
||||||
db.Find(&users, map[string]interface{}{"name": user3.Name})
|
DB.Find(&users, map[string]interface{}{"name": user3.Name})
|
||||||
if len(users) != 1 {
|
if len(users) != 1 {
|
||||||
t.Errorf("Search all records with inline map")
|
t.Errorf("Search all records with inline map")
|
||||||
}
|
}
|
||||||
|
@ -217,10 +217,10 @@ func TestSearchWithMap(t *testing.T) {
|
||||||
|
|
||||||
func TestSelect(t *testing.T) {
|
func TestSelect(t *testing.T) {
|
||||||
user1 := User{Name: "SelectUser1"}
|
user1 := User{Name: "SelectUser1"}
|
||||||
db.Save(&user1)
|
DB.Save(&user1)
|
||||||
|
|
||||||
var user User
|
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 {
|
if user.Id != 0 {
|
||||||
t.Errorf("Should not have ID because only selected name, %+v", user.Id)
|
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}
|
user1 := User{Name: "OrderPluckUser1", Age: 1}
|
||||||
user2 := User{Name: "OrderPluckUser2", Age: 10}
|
user2 := User{Name: "OrderPluckUser2", Age: 10}
|
||||||
user3 := User{Name: "OrderPluckUser3", Age: 20}
|
user3 := User{Name: "OrderPluckUser3", Age: 20}
|
||||||
db.Save(&user1).Save(&user2).Save(&user3)
|
DB.Save(&user1).Save(&user2).Save(&user3)
|
||||||
scopedb := db.Model(&User{}).Where("name like ?", "%OrderPluckUser%")
|
scopedb := DB.Model(&User{}).Where("name like ?", "%OrderPluckUser%")
|
||||||
|
|
||||||
var ages []int64
|
var ages []int64
|
||||||
scopedb.Order("age desc").Pluck("age", &ages)
|
scopedb.Order("age desc").Pluck("age", &ages)
|
||||||
|
@ -262,7 +262,7 @@ func TestOrderAndPluck(t *testing.T) {
|
||||||
t.Errorf("Order with multiple orders")
|
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) {
|
func TestLimit(t *testing.T) {
|
||||||
|
@ -271,10 +271,10 @@ func TestLimit(t *testing.T) {
|
||||||
user3 := User{Name: "LimitUser3", Age: 20}
|
user3 := User{Name: "LimitUser3", Age: 20}
|
||||||
user4 := User{Name: "LimitUser4", Age: 10}
|
user4 := User{Name: "LimitUser4", Age: 10}
|
||||||
user5 := User{Name: "LimitUser5", Age: 20}
|
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
|
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 {
|
if len(users1) != 3 || len(users2) != 5 || len(users3) <= 5 {
|
||||||
t.Errorf("Limit should works")
|
t.Errorf("Limit should works")
|
||||||
|
@ -283,10 +283,10 @@ func TestLimit(t *testing.T) {
|
||||||
|
|
||||||
func TestOffset(t *testing.T) {
|
func TestOffset(t *testing.T) {
|
||||||
for i := 0; i < 20; i++ {
|
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
|
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) {
|
if (len(users1) != len(users4)) || (len(users1)-len(users2) != 3) || (len(users1)-len(users3) != 5) {
|
||||||
t.Errorf("Offset should work")
|
t.Errorf("Offset should work")
|
||||||
|
@ -297,10 +297,10 @@ func TestOr(t *testing.T) {
|
||||||
user1 := User{Name: "OrUser1", Age: 1}
|
user1 := User{Name: "OrUser1", Age: 1}
|
||||||
user2 := User{Name: "OrUser2", Age: 10}
|
user2 := User{Name: "OrUser2", Age: 10}
|
||||||
user3 := User{Name: "OrUser3", Age: 20}
|
user3 := User{Name: "OrUser3", Age: 20}
|
||||||
db.Save(&user1).Save(&user2).Save(&user3)
|
DB.Save(&user1).Save(&user2).Save(&user3)
|
||||||
|
|
||||||
var users []User
|
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 {
|
if len(users) != 2 {
|
||||||
t.Errorf("Find users with or")
|
t.Errorf("Find users with or")
|
||||||
}
|
}
|
||||||
|
@ -311,11 +311,11 @@ func TestCount(t *testing.T) {
|
||||||
user2 := User{Name: "CountUser2", Age: 10}
|
user2 := User{Name: "CountUser2", Age: 10}
|
||||||
user3 := User{Name: "CountUser3", Age: 20}
|
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 count, count1, count2 int64
|
||||||
var users []User
|
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))
|
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")
|
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 {
|
if count1 != 1 || count2 != 3 {
|
||||||
t.Errorf("Multiple count in chain")
|
t.Errorf("Multiple count in chain")
|
||||||
}
|
}
|
||||||
|
@ -331,56 +331,56 @@ func TestCount(t *testing.T) {
|
||||||
|
|
||||||
func TestNot(t *testing.T) {
|
func TestNot(t *testing.T) {
|
||||||
var users1, users2, users3, users4, users5, users6, users7, users8 []User
|
var users1, users2, users3, users4, users5, users6, users7, users8 []User
|
||||||
db.Find(&users1)
|
DB.Find(&users1)
|
||||||
db.Not(users1[0].Id).Find(&users2)
|
DB.Not(users1[0].Id).Find(&users2)
|
||||||
|
|
||||||
if len(users1)-len(users2) != 1 {
|
if len(users1)-len(users2) != 1 {
|
||||||
t.Errorf("Should ignore the first users with Not")
|
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 {
|
if len(users1)-len(users3) != 0 {
|
||||||
t.Errorf("Should find all users with a blank condition")
|
t.Errorf("Should find all users with a blank condition")
|
||||||
}
|
}
|
||||||
|
|
||||||
var name3Count int64
|
var name3Count int64
|
||||||
db.Table("users").Where("name = ?", "3").Count(&name3Count)
|
DB.Table("users").Where("name = ?", "3").Count(&name3Count)
|
||||||
db.Not("name", "3").Find(&users4)
|
DB.Not("name", "3").Find(&users4)
|
||||||
if len(users1)-len(users4) != int(name3Count) {
|
if len(users1)-len(users4) != int(name3Count) {
|
||||||
t.Errorf("Should find all users's name not equal 3")
|
t.Errorf("Should find all users's name not equal 3")
|
||||||
}
|
}
|
||||||
|
|
||||||
users4 = []User{}
|
users4 = []User{}
|
||||||
db.Not("name = ?", "3").Find(&users4)
|
DB.Not("name = ?", "3").Find(&users4)
|
||||||
if len(users1)-len(users4) != int(name3Count) {
|
if len(users1)-len(users4) != int(name3Count) {
|
||||||
t.Errorf("Should find all users's name not equal 3")
|
t.Errorf("Should find all users's name not equal 3")
|
||||||
}
|
}
|
||||||
|
|
||||||
users4 = []User{}
|
users4 = []User{}
|
||||||
db.Not("name <> ?", "3").Find(&users4)
|
DB.Not("name <> ?", "3").Find(&users4)
|
||||||
if len(users4) != int(name3Count) {
|
if len(users4) != int(name3Count) {
|
||||||
t.Errorf("Should find all users's name not equal 3")
|
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) {
|
if len(users1)-len(users5) != int(name3Count) {
|
||||||
t.Errorf("Should find all users's name not equal 3")
|
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) {
|
if len(users1)-len(users6) != int(name3Count) {
|
||||||
t.Errorf("Should find all users's name not equal 3")
|
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) {
|
if len(users1)-len(users7) != int(name3Count) {
|
||||||
t.Errorf("Should find all users's name not equal 3")
|
t.Errorf("Should find all users's name not equal 3")
|
||||||
}
|
}
|
||||||
|
|
||||||
var name2Count int64
|
var name2Count int64
|
||||||
db.Table("users").Where("name = ?", "2").Count(&name2Count)
|
DB.Table("users").Where("name = ?", "2").Count(&name2Count)
|
||||||
db.Not("name", []string{"3", "2"}).Find(&users8)
|
DB.Not("name", []string{"3", "2"}).Find(&users8)
|
||||||
if len(users1)-len(users8) != (int(name3Count) + int(name2Count)) {
|
if len(users1)-len(users8) != (int(name3Count) + int(name2Count)) {
|
||||||
t.Errorf("Should find all users's name not equal 3")
|
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) {
|
func TestFillSmallerStruct(t *testing.T) {
|
||||||
user1 := User{Name: "SmallerUser", Age: 100}
|
user1 := User{Name: "SmallerUser", Age: 100}
|
||||||
db.Save(&user1)
|
DB.Save(&user1)
|
||||||
type SimpleUser struct {
|
type SimpleUser struct {
|
||||||
Name string
|
Name string
|
||||||
Id int64
|
Id int64
|
||||||
|
@ -397,7 +397,7 @@ func TestFillSmallerStruct(t *testing.T) {
|
||||||
}
|
}
|
||||||
|
|
||||||
var simpleUser SimpleUser
|
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 == "" {
|
if simpleUser.Id == 0 || simpleUser.Name == "" {
|
||||||
t.Errorf("Should fill data correctly into smaller struct")
|
t.Errorf("Should fill data correctly into smaller struct")
|
||||||
|
@ -406,43 +406,43 @@ func TestFillSmallerStruct(t *testing.T) {
|
||||||
|
|
||||||
func TestFindOrInitialize(t *testing.T) {
|
func TestFindOrInitialize(t *testing.T) {
|
||||||
var user1, user2, user3, user4, user5, user6 User
|
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 {
|
if user1.Name != "find or init" || user1.Id != 0 || user1.Age != 33 {
|
||||||
t.Errorf("user should be initialized with search value")
|
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 {
|
if user2.Name != "find or init" || user2.Id != 0 || user2.Age != 33 {
|
||||||
t.Errorf("user should be initialized with search value")
|
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 {
|
if user3.Name != "find or init 2" || user3.Id != 0 {
|
||||||
t.Errorf("user should be initialized with inline search value")
|
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 {
|
if user4.Name != "find or init" || user4.Id != 0 || user4.Age != 44 {
|
||||||
t.Errorf("user should be initialized with search value and attrs")
|
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 {
|
if user4.Name != "find or init" || user4.Id != 0 || user4.Age != 44 {
|
||||||
t.Errorf("user should be initialized with search value and assign attrs")
|
t.Errorf("user should be initialized with search value and assign attrs")
|
||||||
}
|
}
|
||||||
|
|
||||||
db.Save(&User{Name: "find or init", Age: 33})
|
DB.Save(&User{Name: "find or init", Age: 33})
|
||||||
db.Where(&User{Name: "find or init"}).Attrs("age", 44).FirstOrInit(&user5)
|
DB.Where(&User{Name: "find or init"}).Attrs("age", 44).FirstOrInit(&user5)
|
||||||
if user5.Name != "find or init" || user5.Id == 0 || user5.Age != 33 {
|
if user5.Name != "find or init" || user5.Id == 0 || user5.Age != 33 {
|
||||||
t.Errorf("user should be found and not initialized by Attrs")
|
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 {
|
if user6.Name != "find or init" || user6.Id == 0 || user6.Age != 33 {
|
||||||
t.Errorf("user should be found with FirstOrInit")
|
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 {
|
if user6.Name != "find or init" || user6.Id == 0 || user6.Age != 44 {
|
||||||
t.Errorf("user should be found and updated with assigned attrs")
|
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) {
|
func TestFindOrCreate(t *testing.T) {
|
||||||
var user1, user2, user3, user4, user5, user6, user7, user8 User
|
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 {
|
if user1.Name != "find or create" || user1.Id == 0 || user1.Age != 33 {
|
||||||
t.Errorf("user should be created with search value")
|
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 {
|
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")
|
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 {
|
if user3.Name != "find or create 2" || user3.Id == 0 {
|
||||||
t.Errorf("user should be created with inline search value")
|
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 {
|
if user4.Name != "find or create 3" || user4.Id == 0 || user4.Age != 44 {
|
||||||
t.Errorf("user should be created with search value and attrs")
|
t.Errorf("user should be created with search value and attrs")
|
||||||
}
|
}
|
||||||
|
|
||||||
updatedAt1 := user4.UpdatedAt
|
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) {
|
if updatedAt1.Format(time.RFC3339Nano) == user4.UpdatedAt.Format(time.RFC3339Nano) {
|
||||||
t.Errorf("UpdateAt should be changed when update values with assign")
|
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 {
|
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")
|
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 {
|
if user5.Name != "find or create" || user5.Id == 0 || user5.Age != 33 {
|
||||||
t.Errorf("user should be found and not initialized by Attrs")
|
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 {
|
if user6.Name != "find or create" || user6.Id == 0 || user6.Age != 44 {
|
||||||
t.Errorf("user should be found and updated with assigned attrs")
|
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 {
|
if user7.Name != "find or create" || user7.Id == 0 || user7.Age != 44 {
|
||||||
t.Errorf("user should be found and updated with assigned attrs")
|
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)
|
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() {
|
if DB.Where("email = ?", "jinzhu-2@assign_embedded_struct.com").First(&Email{}).RecordNotFound() {
|
||||||
t.Errorf("embedded struct email should be saved")
|
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")
|
t.Errorf("embedded struct credit card should be saved")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -510,10 +510,10 @@ func TestSelectWithEscapedFieldName(t *testing.T) {
|
||||||
user1 := User{Name: "EscapedFieldNameUser", Age: 1}
|
user1 := User{Name: "EscapedFieldNameUser", Age: 1}
|
||||||
user2 := User{Name: "EscapedFieldNameUser", Age: 10}
|
user2 := User{Name: "EscapedFieldNameUser", Age: 10}
|
||||||
user3 := User{Name: "EscapedFieldNameUser", Age: 20}
|
user3 := User{Name: "EscapedFieldNameUser", Age: 20}
|
||||||
db.Save(&user1).Save(&user2).Save(&user3)
|
DB.Save(&user1).Save(&user2).Save(&user3)
|
||||||
|
|
||||||
var names []string
|
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 {
|
if len(names) != 3 {
|
||||||
t.Errorf("Expected 3 name, but got: %d", len(names))
|
t.Errorf("Expected 3 name, but got: %d", len(names))
|
||||||
|
|
11
scope.go
11
scope.go
|
@ -249,7 +249,6 @@ func (scope *Scope) FieldByName(name string) (field *Field, ok bool) {
|
||||||
func (scope *Scope) fieldFromStruct(fieldStruct reflect.StructField) *Field {
|
func (scope *Scope) fieldFromStruct(fieldStruct reflect.StructField) *Field {
|
||||||
var field Field
|
var field Field
|
||||||
field.Name = fieldStruct.Name
|
field.Name = fieldStruct.Name
|
||||||
field.DBName = ToSnake(fieldStruct.Name)
|
|
||||||
|
|
||||||
value := scope.IndirectValue().FieldByName(fieldStruct.Name)
|
value := scope.IndirectValue().FieldByName(fieldStruct.Name)
|
||||||
indirectValue := reflect.Indirect(value)
|
indirectValue := reflect.Indirect(value)
|
||||||
|
@ -258,6 +257,13 @@ func (scope *Scope) fieldFromStruct(fieldStruct reflect.StructField) *Field {
|
||||||
|
|
||||||
// Search for primary key tag identifier
|
// Search for primary key tag identifier
|
||||||
settings := parseTagSetting(fieldStruct.Tag.Get("gorm"))
|
settings := parseTagSetting(fieldStruct.Tag.Get("gorm"))
|
||||||
|
|
||||||
|
prefix := settings["PREFIX"]
|
||||||
|
if prefix == "-" {
|
||||||
|
prefix = ""
|
||||||
|
}
|
||||||
|
field.DBName = prefix + ToSnake(fieldStruct.Name)
|
||||||
|
|
||||||
if scope.PrimaryKey() == field.DBName {
|
if scope.PrimaryKey() == field.DBName {
|
||||||
field.IsPrimaryKey = true
|
field.IsPrimaryKey = true
|
||||||
}
|
}
|
||||||
|
@ -271,10 +277,11 @@ func (scope *Scope) fieldFromStruct(fieldStruct reflect.StructField) *Field {
|
||||||
indirectValue = reflect.New(value.Type())
|
indirectValue = reflect.New(value.Type())
|
||||||
}
|
}
|
||||||
typ := indirectValue.Type()
|
typ := indirectValue.Type()
|
||||||
|
scopeTyp := scope.IndirectValue().Type()
|
||||||
|
|
||||||
foreignKey := SnakeToUpperCamel(settings["FOREIGNKEY"])
|
foreignKey := SnakeToUpperCamel(settings["FOREIGNKEY"])
|
||||||
associationForeignKey := SnakeToUpperCamel(settings["ASSOCIATIONFOREIGNKEY"])
|
associationForeignKey := SnakeToUpperCamel(settings["ASSOCIATIONFOREIGNKEY"])
|
||||||
many2many := settings["MANY2MANY"]
|
many2many := settings["MANY2MANY"]
|
||||||
scopeTyp := scope.IndirectValue().Type()
|
|
||||||
|
|
||||||
switch indirectValue.Kind() {
|
switch indirectValue.Kind() {
|
||||||
case reflect.Slice:
|
case reflect.Slice:
|
||||||
|
|
|
@ -24,20 +24,20 @@ func TestScopes(t *testing.T) {
|
||||||
user1 := User{Name: "ScopeUser1", Age: 1}
|
user1 := User{Name: "ScopeUser1", Age: 1}
|
||||||
user2 := User{Name: "ScopeUser2", Age: 1}
|
user2 := User{Name: "ScopeUser2", Age: 1}
|
||||||
user3 := User{Name: "ScopeUser3", Age: 2}
|
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
|
var users1, users2, users3 []User
|
||||||
db.Scopes(NameIn1And2).Find(&users1)
|
DB.Scopes(NameIn1And2).Find(&users1)
|
||||||
if len(users1) != 2 {
|
if len(users1) != 2 {
|
||||||
t.Errorf("Should found two users's name in 1, 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 {
|
if len(users2) != 1 {
|
||||||
t.Errorf("Should found one user's name is 2")
|
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 {
|
if len(users3) != 2 {
|
||||||
t.Errorf("Should found two users's name in 1, 3")
|
t.Errorf("Should found two users's name in 1, 3")
|
||||||
}
|
}
|
||||||
|
|
|
@ -9,80 +9,80 @@ func TestUpdate(t *testing.T) {
|
||||||
product1 := Product{Code: "product1code"}
|
product1 := Product{Code: "product1code"}
|
||||||
product2 := Product{Code: "product2code"}
|
product2 := Product{Code: "product2code"}
|
||||||
|
|
||||||
db.Save(&product1).Save(&product2).Update("code", "product2newcode")
|
DB.Save(&product1).Save(&product2).Update("code", "product2newcode")
|
||||||
|
|
||||||
if product2.Code != "product2newcode" {
|
if product2.Code != "product2newcode" {
|
||||||
t.Errorf("Record should be updated")
|
t.Errorf("Record should be updated")
|
||||||
}
|
}
|
||||||
|
|
||||||
db.First(&product1, product1.Id)
|
DB.First(&product1, product1.Id)
|
||||||
db.First(&product2, product2.Id)
|
DB.First(&product2, product2.Id)
|
||||||
updatedAt1 := product1.UpdatedAt
|
updatedAt1 := product1.UpdatedAt
|
||||||
updatedAt2 := product2.UpdatedAt
|
updatedAt2 := product2.UpdatedAt
|
||||||
|
|
||||||
var product3 Product
|
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) {
|
if updatedAt2.Format(time.RFC3339Nano) != product3.UpdatedAt.Format(time.RFC3339Nano) {
|
||||||
t.Errorf("updatedAt should not be updated if nothing changed")
|
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")
|
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")
|
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")
|
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
|
var product4 Product
|
||||||
db.First(&product4, product1.Id)
|
DB.First(&product4, product1.Id)
|
||||||
if updatedAt1.Format(time.RFC3339Nano) != product4.UpdatedAt.Format(time.RFC3339Nano) {
|
if updatedAt1.Format(time.RFC3339Nano) != product4.UpdatedAt.Format(time.RFC3339Nano) {
|
||||||
t.Errorf("updatedAt should be updated if something changed")
|
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")
|
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")
|
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")
|
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")
|
t.Error("No error should raise when update_column with CamelCase")
|
||||||
}
|
}
|
||||||
|
|
||||||
var products []Product
|
var products []Product
|
||||||
db.Find(&products)
|
DB.Find(&products)
|
||||||
if count := db.Model(Product{}).Update("CreatedAt", time.Now().Add(2*time.Hour)).RowsAffected; count != int64(len(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")
|
t.Error("RowsAffected should be correct when do batch update")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestUpdateWithNoStdPrimaryKey(t *testing.T) {
|
func TestUpdateWithNoStdPrimaryKey(t *testing.T) {
|
||||||
animal := Animal{Name: "Ferdinand"}
|
animal := Animal{Name: "Ferdinand"}
|
||||||
db.Save(&animal)
|
DB.Save(&animal)
|
||||||
updatedAt1 := animal.UpdatedAt
|
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) {
|
if updatedAt1.Format(time.RFC3339Nano) == animal.UpdatedAt.Format(time.RFC3339Nano) {
|
||||||
t.Errorf("updatedAt should not be updated if nothing changed")
|
t.Errorf("updatedAt should not be updated if nothing changed")
|
||||||
}
|
}
|
||||||
|
|
||||||
var animals []Animal
|
var animals []Animal
|
||||||
db.Find(&animals)
|
DB.Find(&animals)
|
||||||
if count := db.Model(Animal{}).Update("CreatedAt", time.Now().Add(2*time.Hour)).RowsAffected; count != int64(len(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")
|
t.Error("RowsAffected should be correct when do batch update")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -90,19 +90,19 @@ func TestUpdateWithNoStdPrimaryKey(t *testing.T) {
|
||||||
func TestUpdates(t *testing.T) {
|
func TestUpdates(t *testing.T) {
|
||||||
product1 := Product{Code: "product1code", Price: 10}
|
product1 := Product{Code: "product1code", Price: 10}
|
||||||
product2 := Product{Code: "product2code", Price: 10}
|
product2 := Product{Code: "product2code", Price: 10}
|
||||||
db.Save(&product1).Save(&product2)
|
DB.Save(&product1).Save(&product2)
|
||||||
db.Model(&product1).Updates(map[string]interface{}{"code": "product1newcode", "price": 100})
|
DB.Model(&product1).Updates(map[string]interface{}{"code": "product1newcode", "price": 100})
|
||||||
if product1.Code != "product1newcode" || product1.Price != 100 {
|
if product1.Code != "product1newcode" || product1.Price != 100 {
|
||||||
t.Errorf("Record should be updated also with map")
|
t.Errorf("Record should be updated also with map")
|
||||||
}
|
}
|
||||||
|
|
||||||
db.First(&product1, product1.Id)
|
DB.First(&product1, product1.Id)
|
||||||
db.First(&product2, product2.Id)
|
DB.First(&product2, product2.Id)
|
||||||
updatedAt1 := product1.UpdatedAt
|
updatedAt1 := product1.UpdatedAt
|
||||||
updatedAt2 := product2.UpdatedAt
|
updatedAt2 := product2.UpdatedAt
|
||||||
|
|
||||||
var product3 Product
|
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 {
|
if product3.Code != "product1newcode" || product3.Price != 100 {
|
||||||
t.Errorf("Record should be updated with struct")
|
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")
|
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")
|
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")
|
t.Errorf("Product1 should be updated")
|
||||||
}
|
}
|
||||||
|
|
||||||
db.Table("products").Where("code in (?)", []string{"product2code"}).Updates(Product{Code: "product2newcode"})
|
DB.Table("products").Where("code in (?)", []string{"product2code"}).Updates(Product{Code: "product2newcode"})
|
||||||
if !db.First(&Product{}, "code = 'product2code'").RecordNotFound() {
|
if !DB.First(&Product{}, "code = 'product2code'").RecordNotFound() {
|
||||||
t.Errorf("Product2's code should be updated")
|
t.Errorf("Product2's code should be updated")
|
||||||
}
|
}
|
||||||
|
|
||||||
var product4 Product
|
var product4 Product
|
||||||
db.First(&product4, product2.Id)
|
DB.First(&product4, product2.Id)
|
||||||
if updatedAt2.Format(time.RFC3339Nano) != product4.UpdatedAt.Format(time.RFC3339Nano) {
|
if updatedAt2.Format(time.RFC3339Nano) != product4.UpdatedAt.Format(time.RFC3339Nano) {
|
||||||
t.Errorf("updatedAt should be updated if something changed")
|
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")
|
t.Errorf("product2's code should be updated")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -138,22 +138,22 @@ func TestUpdates(t *testing.T) {
|
||||||
func TestUpdateColumn(t *testing.T) {
|
func TestUpdateColumn(t *testing.T) {
|
||||||
product1 := Product{Code: "product1code", Price: 10}
|
product1 := Product{Code: "product1code", Price: 10}
|
||||||
product2 := Product{Code: "product2code", Price: 20}
|
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 {
|
if product2.Code != "product2newcode" || product2.Price != 100 {
|
||||||
t.Errorf("product 2 should be updated with update column")
|
t.Errorf("product 2 should be updated with update column")
|
||||||
}
|
}
|
||||||
|
|
||||||
var product3 Product
|
var product3 Product
|
||||||
db.First(&product3, product1.Id)
|
DB.First(&product3, product1.Id)
|
||||||
if product3.Code != "product1code" || product3.Price != 10 {
|
if product3.Code != "product1code" || product3.Price != 10 {
|
||||||
t.Errorf("product 1 should not be updated")
|
t.Errorf("product 1 should not be updated")
|
||||||
}
|
}
|
||||||
|
|
||||||
db.First(&product2, product2.Id)
|
DB.First(&product2, product2.Id)
|
||||||
updatedAt2 := product2.UpdatedAt
|
updatedAt2 := product2.UpdatedAt
|
||||||
db.Model(product2).UpdateColumn("code", "update_column_new")
|
DB.Model(product2).UpdateColumn("code", "update_column_new")
|
||||||
var product4 Product
|
var product4 Product
|
||||||
db.First(&product4, product2.Id)
|
DB.First(&product4, product2.Id)
|
||||||
if updatedAt2.Format(time.RFC3339Nano) != product4.UpdatedAt.Format(time.RFC3339Nano) {
|
if updatedAt2.Format(time.RFC3339Nano) != product4.UpdatedAt.Format(time.RFC3339Nano) {
|
||||||
t.Errorf("updatedAt should not be updated with update column")
|
t.Errorf("updatedAt should not be updated with update column")
|
||||||
}
|
}
|
||||||
|
|
Loading…
Reference in New Issue