2014-08-28 11:33:43 +04:00
|
|
|
package gorm_test
|
|
|
|
|
|
|
|
import "testing"
|
|
|
|
|
|
|
|
type BasePost struct {
|
2014-08-28 14:53:27 +04:00
|
|
|
Id int64
|
2014-08-28 11:33:43 +04:00
|
|
|
Title string
|
2015-02-13 05:57:35 +03:00
|
|
|
URL string
|
2014-08-28 11:33:43 +04:00
|
|
|
}
|
|
|
|
|
|
|
|
type HNPost struct {
|
2014-08-30 19:08:58 +04:00
|
|
|
BasePost
|
|
|
|
Upvotes int32
|
2014-08-28 11:33:43 +04:00
|
|
|
}
|
|
|
|
|
|
|
|
type EngadgetPost struct {
|
2014-08-28 15:14:58 +04:00
|
|
|
BasePost BasePost `gorm:"embedded"`
|
2014-08-28 11:33:43 +04:00
|
|
|
ImageUrl string
|
|
|
|
}
|
|
|
|
|
2014-08-28 13:21:43 +04:00
|
|
|
func TestSaveAndQueryEmbeddedStruct(t *testing.T) {
|
2014-08-28 15:14:58 +04:00
|
|
|
DB.Save(&HNPost{BasePost: BasePost{Title: "news"}})
|
2014-08-28 14:25:05 +04:00
|
|
|
DB.Save(&HNPost{BasePost: BasePost{Title: "hn_news"}})
|
2014-08-28 11:33:43 +04:00
|
|
|
var news HNPost
|
2014-08-28 13:21:43 +04:00
|
|
|
if err := DB.First(&news, "title = ?", "hn_news").Error; err != nil {
|
|
|
|
t.Errorf("no error should happen when query with embedded struct, but got %v", err)
|
2015-02-13 05:57:35 +03:00
|
|
|
} else if news.Title != "hn_news" {
|
|
|
|
t.Errorf("embedded struct's value should be scanned correctly")
|
2014-08-28 13:21:43 +04:00
|
|
|
}
|
2014-08-28 15:14:58 +04:00
|
|
|
|
|
|
|
DB.Save(&EngadgetPost{BasePost: BasePost{Title: "engadget_news"}})
|
|
|
|
var egNews EngadgetPost
|
|
|
|
if err := DB.First(&egNews, "title = ?", "engadget_news").Error; err != nil {
|
|
|
|
t.Errorf("no error should happen when query with embedded struct, but got %v", err)
|
2015-02-13 05:57:35 +03:00
|
|
|
} else if egNews.BasePost.Title != "engadget_news" {
|
|
|
|
t.Errorf("embedded struct's value should be scanned correctly")
|
2014-08-28 15:14:58 +04:00
|
|
|
}
|
2015-02-25 05:56:05 +03:00
|
|
|
|
|
|
|
if DB.NewScope(&HNPost{}).PrimaryKeyField() == nil {
|
|
|
|
t.Errorf("primary key with embedded struct should works")
|
|
|
|
}
|
2015-02-25 06:17:33 +03:00
|
|
|
|
|
|
|
for _, field := range DB.NewScope(&HNPost{}).Fields() {
|
|
|
|
if field.Name == "BasePost" {
|
|
|
|
t.Errorf("scope Fields should not contain embedded struct")
|
|
|
|
}
|
|
|
|
}
|
2014-08-28 11:33:43 +04:00
|
|
|
}
|