Merge branch 'gogf:master' into zhiwei

This commit is contained in:
564104865
2021-11-05 09:38:41 +08:00
committed by GitHub
6 changed files with 1842 additions and 100 deletions

View File

@ -7,24 +7,400 @@
package gset_test
import (
"encoding/json"
"fmt"
"github.com/gogf/gf/v2/container/gset"
"github.com/gogf/gf/v2/frame/g"
)
// NewStrSet create and returns a new set, which contains un-repeated items.
// The parameter `safe` is used to specify whether using set in concurrent-safety,
// which is false in default.
func ExampleNewStrSet() {
strSet := gset.NewStrSet(true)
strSet.Add([]string{"str1", "str2", "str3"}...)
fmt.Println(strSet.Slice())
// May Output:
// [str3 str1 str2]
}
// NewStrSetFrom returns a new set from `items`.
func ExampleNewStrSetFrom() {
strSet := gset.NewStrSetFrom([]string{"str1", "str2", "str3"}, true)
fmt.Println(strSet.Slice())
// May Output:
// [str1 str2 str3]
}
// Add adds one or multiple items to the set.
func ExampleStrSet_Add() {
strSet := gset.NewStrSetFrom([]string{"str1", "str2", "str3"}, true)
strSet.Add("str")
fmt.Println(strSet.Slice())
fmt.Println(strSet.AddIfNotExist("str"))
// Mya Output:
// [str str1 str2 str3]
// false
}
// AddIfNotExist checks whether item exists in the set,
// it adds the item to set and returns true if it does not exists in the set,
// or else it does nothing and returns false.
func ExampleStrSet_AddIfNotExist() {
strSet := gset.NewStrSetFrom([]string{"str1", "str2", "str3"}, true)
strSet.Add("str")
fmt.Println(strSet.Slice())
fmt.Println(strSet.AddIfNotExist("str"))
// Mya Output:
// [str str1 str2 str3]
// false
}
// AddIfNotExistFunc checks whether item exists in the set,
// it adds the item to set and returns true if it does not exists in the set and function `f` returns true,
// or else it does nothing and returns false.
// Note that, the function `f` is executed without writing lock.
func ExampleStrSet_AddIfNotExistFunc() {
strSet := gset.NewStrSetFrom([]string{"str1", "str2", "str3"}, true)
strSet.Add("str")
fmt.Println(strSet.Slice())
fmt.Println(strSet.AddIfNotExistFunc("str5", func() bool {
return true
}))
// May Output:
// [str1 str2 str3 str]
// true
}
// AddIfNotExistFunc checks whether item exists in the set,
// it adds the item to set and returns true if it does not exists in the set and function `f` returns true,
// or else it does nothing and returns false.
// Note that, the function `f` is executed without writing lock.
func ExampleStrSet_AddIfNotExistFuncLock() {
strSet := gset.NewStrSetFrom([]string{"str1", "str2", "str3"}, true)
strSet.Add("str")
fmt.Println(strSet.Slice())
fmt.Println(strSet.AddIfNotExistFuncLock("str4", func() bool {
return true
}))
// May Output:
// [str1 str2 str3 str]
// true
}
// Clear deletes all items of the set.
func ExampleStrSet_Clear() {
strSet := gset.NewStrSetFrom([]string{"str1", "str2", "str3"}, true)
fmt.Println(strSet.Size())
strSet.Clear()
fmt.Println(strSet.Size())
// Output:
// 3
// 0
}
// Complement returns a new set which is the complement from `set` to `full`.
// Which means, all the items in `newSet` are in `full` and not in `set`.
// It returns the difference between `full` and `set` if the given set `full` is not the full set of `set`.
func ExampleStrSet_Complement() {
strSet := gset.NewStrSetFrom([]string{"str1", "str2", "str3", "str4", "str5"}, true)
s := gset.NewStrSetFrom([]string{"str1", "str2", "str3"}, true)
fmt.Println(s.Complement(strSet).Slice())
// May Output:
// [str4 str5]
}
// Contains checks whether the set contains `item`.
func ExampleStrSet_Contains() {
var set gset.StrSet
set.Add("a")
fmt.Println(set.Contains("a"))
fmt.Println(set.Contains("A"))
fmt.Println(set.ContainsI("A"))
// Output:
// true
// false
}
// ContainsI checks whether a value exists in the set with case-insensitively.
// Note that it internally iterates the whole set to do the comparison with case-insensitively.
func ExampleStrSet_ContainsI() {
var set gset.StrSet
set.Add("a")
fmt.Println(set.ContainsI("a"))
fmt.Println(set.ContainsI("A"))
// Output:
// true
// true
}
// Diff returns a new set which is the difference set from `set` to `other`.
// Which means, all the items in `newSet` are in `set` but not in `other`.
func ExampleStrSet_Diff() {
s1 := gset.NewStrSetFrom([]string{"a", "b", "c"}, true)
s2 := gset.NewStrSetFrom([]string{"a", "b", "c", "d"}, true)
fmt.Println(s2.Diff(s1).Slice())
// Output:
// [d]
}
// Equal checks whether the two sets equal.
func ExampleStrSet_Equal() {
s1 := gset.NewStrSetFrom([]string{"a", "b", "c"}, true)
s2 := gset.NewStrSetFrom([]string{"a", "b", "c", "d"}, true)
fmt.Println(s2.Equal(s1))
s3 := gset.NewStrSetFrom([]string{"a", "b", "c"}, true)
s4 := gset.NewStrSetFrom([]string{"a", "b", "c"}, true)
fmt.Println(s3.Equal(s4))
// Output:
// false
// true
}
// Intersect returns a new set which is the intersection from `set` to `other`.
// Which means, all the items in `newSet` are in `set` and also in `other`.
func ExampleStrSet_Intersect() {
s1 := gset.NewStrSet(true)
s1.Add([]string{"a", "b", "c"}...)
var s2 gset.StrSet
s2.Add([]string{"a", "b", "c", "d"}...)
fmt.Println(s2.Intersect(s1).Slice())
// May Output:
// [c a b]
}
// IsSubsetOf checks whether the current set is a sub-set of `other`
func ExampleStrSet_IsSubsetOf() {
s1 := gset.NewStrSet(true)
s1.Add([]string{"a", "b", "c", "d"}...)
var s2 gset.StrSet
s2.Add([]string{"a", "b", "d"}...)
fmt.Println(s2.IsSubsetOf(s1))
// Output:
// true
}
// Iterator iterates the set readonly with given callback function `f`,
// if `f` returns true then continue iterating; or false to stop.
func ExampleStrSet_Iterator() {
s1 := gset.NewStrSet(true)
s1.Add([]string{"a", "b", "c", "d"}...)
s1.Iterator(func(v string) bool {
fmt.Println("Iterator", v)
return true
})
// May Output:
// Iterator a
// Iterator b
// Iterator c
// Iterator d
}
// Join joins items with a string `glue`.
func ExampleStrSet_Join() {
s1 := gset.NewStrSet(true)
s1.Add([]string{"a", "b", "c", "d"}...)
fmt.Println(s1.Join(","))
// May Output:
// b,c,d,a
}
// LockFunc locks writing with callback function `f`.
func ExampleStrSet_LockFunc() {
s1 := gset.NewStrSet(true)
s1.Add([]string{"1", "2"}...)
s1.LockFunc(func(m map[string]struct{}) {
m["3"] = struct{}{}
})
fmt.Println(s1.Slice())
// May Output
// [2 3 1]
}
// MarshalJSON implements the interface MarshalJSON for json.Marshal.
func ExampleStrSet_MarshalJSON() {
type Student struct {
Id int
Name string
Scores *gset.StrSet
}
s := Student{
Id: 1,
Name: "john",
Scores: gset.NewStrSetFrom([]string{"100", "99", "98"}, true),
}
b, _ := json.Marshal(s)
fmt.Println(string(b))
// May Output:
// {"Id":1,"Name":"john","Scores":["100","99","98"]}
}
// Merge adds items from `others` sets into `set`.
func ExampleStrSet_Merge() {
s1 := gset.NewStrSet(true)
s1.Add([]string{"a", "b", "c", "d"}...)
s2 := gset.NewStrSet(true)
fmt.Println(s1.Merge(s2).Slice())
// May Output:
// [d a b c]
}
// Pops randomly pops an item from set.
func ExampleStrSet_Pop() {
s1 := gset.NewStrSet(true)
s1.Add([]string{"a", "b", "c", "d"}...)
fmt.Println(s1.Pop())
// May Output:
// a
}
// Pops randomly pops `size` items from set.
// It returns all items if size == -1.
func ExampleStrSet_Pops() {
s1 := gset.NewStrSet(true)
s1.Add([]string{"a", "b", "c", "d"}...)
for _, v := range s1.Pops(2) {
fmt.Println(v)
}
// May Output:
// a
// b
}
// RLockFunc locks reading with callback function `f`.
func ExampleStrSet_RLockFunc() {
s1 := gset.NewStrSet(true)
s1.Add([]string{"a", "b", "c", "d"}...)
s1.RLockFunc(func(m map[string]struct{}) {
fmt.Println(m)
})
// Output:
// map[a:{} b:{} c:{} d:{}]
}
// Remove deletes `item` from set.
func ExampleStrSet_Remove() {
s1 := gset.NewStrSet(true)
s1.Add([]string{"a", "b", "c", "d"}...)
s1.Remove("a")
fmt.Println(s1.Slice())
// May Output:
// [b c d]
}
// Size returns the size of the set.
func ExampleStrSet_Size() {
s1 := gset.NewStrSet(true)
s1.Add([]string{"a", "b", "c", "d"}...)
fmt.Println(s1.Size())
// Output:
// 4
}
// Slice returns the a of items of the set as slice.
func ExampleStrSet_Slice() {
s1 := gset.NewStrSet(true)
s1.Add([]string{"a", "b", "c", "d"}...)
fmt.Println(s1.Slice())
// May Output:
// [a,b,c,d]
}
// String returns items as a string, which implements like json.Marshal does.
func ExampleStrSet_String() {
s1 := gset.NewStrSet(true)
s1.Add([]string{"a", "b", "c", "d"}...)
fmt.Println(s1.String())
// May Output:
// "a","b","c","d"
}
// Sum sums items. Note: The items should be converted to int type,
// or you'd get a result that you unexpected.
func ExampleStrSet_Sum() {
s1 := gset.NewStrSet(true)
s1.Add([]string{"1", "2", "3", "4"}...)
fmt.Println(s1.Sum())
// Output:
// 10
}
// Union returns a new set which is the union of `set` and `other`.
// Which means, all the items in `newSet` are in `set` or in `other`.
func ExampleStrSet_Union() {
s1 := gset.NewStrSet(true)
s1.Add([]string{"a", "b", "c", "d"}...)
s2 := gset.NewStrSet(true)
s2.Add([]string{"a", "b", "d"}...)
fmt.Println(s1.Union(s2).Slice())
// May Output:
// [a b c d]
}
// UnmarshalJSON implements the interface UnmarshalJSON for json.Unmarshal.
func ExampleStrSet_UnmarshalJSON() {
b := []byte(`{"Id":1,"Name":"john","Scores":["100","99","98"]}`)
type Student struct {
Id int
Name string
Scores *gset.StrSet
}
s := Student{}
json.Unmarshal(b, &s)
fmt.Println(s)
// May Output:
// {1 john "99","98","100"}
}
// UnmarshalValue is an interface implement which sets any type of value for set.
func ExampleStrSet_UnmarshalValue() {
b := []byte(`{"Id":1,"Name":"john","Scores":["100","99","98"]}`)
type Student struct {
Id int
Name string
Scores *gset.StrSet
}
s := Student{}
json.Unmarshal(b, &s)
fmt.Println(s)
// May Output:
// {1 john "99","98","100"}
}
// Walk applies a user supplied function `f` to every item of set.
func ExampleStrSet_Walk() {
var (
set gset.StrSet

View File

@ -319,32 +319,25 @@ func (m *Model) Scan(pointer interface{}, where ...interface{}) error {
// ScanList converts `r` to struct slice which contains other complex struct attributes.
// Note that the parameter `listPointer` should be type of *[]struct/*[]*struct.
// Usage example:
//
// type Entity struct {
// User *EntityUser
// UserDetail *EntityUserDetail
// UserScores []*EntityUserScores
// }
// var users []*Entity
// or
// var users []Entity
//
// ScanList(&users, "User")
// ScanList(&users, "UserDetail", "User", "uid:Uid")
// ScanList(&users, "UserScores", "User", "uid:Uid")
// The parameters "User"/"UserDetail"/"UserScores" in the example codes specify the target attribute struct
// that current result will be bound to.
// The "uid" in the example codes is the table field name of the result, and the "Uid" is the relational
// struct attribute name. It automatically calculates the HasOne/HasMany relationship with given `relation`
// parameter.
// See the example or unit testing cases for clear understanding for this function.
func (m *Model) ScanList(listPointer interface{}, attributeName string, relation ...string) (err error) {
// See Result.ScanList.
func (m *Model) ScanList(structSlicePointer interface{}, bindToAttrName string, relationAttrNameAndFields ...string) (err error) {
result, err := m.All()
if err != nil {
return err
}
return doScanList(m, result, listPointer, attributeName, relation...)
var (
relationAttrName string
relationFields string
)
switch len(relationAttrNameAndFields) {
case 2:
relationAttrName = relationAttrNameAndFields[0]
relationFields = relationAttrNameAndFields[1]
case 1:
relationFields = relationAttrNameAndFields[0]
}
return doScanList(m, result, structSlicePointer, bindToAttrName, relationAttrName, relationFields)
}
// Count does "SELECT COUNT(x) FROM ..." statement for the model.

View File

@ -10,6 +10,7 @@ import (
"database/sql"
"github.com/gogf/gf/v2/errors/gcode"
"github.com/gogf/gf/v2/errors/gerror"
"github.com/gogf/gf/v2/internal/structs"
"github.com/gogf/gf/v2/text/gstr"
"github.com/gogf/gf/v2/util/gconv"
"github.com/gogf/gf/v2/util/gutil"
@ -17,21 +18,61 @@ import (
)
// ScanList converts `r` to struct slice which contains other complex struct attributes.
// Note that the parameter `listPointer` should be type of *[]struct/*[]*struct.
// Usage example:
// Note that the parameter `structSlicePointer` should be type of *[]struct/*[]*struct.
//
// Usage example 1: Normal attribute struct relation:
// type EntityUser struct {
// Uid int
// Name string
// }
// type EntityUserDetail struct {
// Uid int
// Address string
// }
// type EntityUserScores struct {
// Id int
// Uid int
// Score int
// Course string
// }
// type Entity struct {
// User *EntityUser
// User *EntityUser
// UserDetail *EntityUserDetail
// UserScores []*EntityUserScores
// UserScores []*EntityUserScores
// }
// var users []*Entity
// or
// var users []Entity
//
// ScanList(&users, "User")
// ScanList(&users, "User", "uid")
// ScanList(&users, "UserDetail", "User", "uid:Uid")
// ScanList(&users, "UserScores", "User", "uid:Uid")
// ScanList(&users, "UserScores", "User", "uid")
//
//
// Usage example 2: Embedded attribute struct relation:
// type EntityUser struct {
// Uid int
// Name string
// }
// type EntityUserDetail struct {
// Uid int
// Address string
// }
// type EntityUserScores struct {
// Id int
// Uid int
// Score int
// }
// type Entity struct {
// EntityUser
// UserDetail EntityUserDetail
// UserScores []EntityUserScores
// }
//
// var users []*Entity
// ScanList(&users)
// ScanList(&users, "UserDetail", "uid")
// ScanList(&users, "UserScores", "uid")
//
//
// The parameters "User/UserDetail/UserScores" in the example codes specify the target attribute struct
// that current result will be bound to.
@ -42,15 +83,26 @@ import (
// given `relation` parameter.
//
// See the example or unit testing cases for clear understanding for this function.
func (r Result) ScanList(listPointer interface{}, bindToAttrName string, relationKV ...string) (err error) {
return doScanList(nil, r, listPointer, bindToAttrName, relationKV...)
func (r Result) ScanList(structSlicePointer interface{}, bindToAttrName string, relationAttrNameAndFields ...string) (err error) {
var (
relationAttrName string
relationFields string
)
switch len(relationAttrNameAndFields) {
case 2:
relationAttrName = relationAttrNameAndFields[0]
relationFields = relationAttrNameAndFields[1]
case 1:
relationFields = relationAttrNameAndFields[0]
}
return doScanList(nil, r, structSlicePointer, bindToAttrName, relationAttrName, relationFields)
}
// doScanList converts `result` to struct slice which contains other complex struct attributes recursively.
// The parameter `model` is used for recursively scanning purpose, which means, it can scans the attribute struct/structs recursively but
// it needs the Model for database accessing.
// Note that the parameter `listPointer` should be type of *[]struct/*[]*struct.
func doScanList(model *Model, result Result, listPointer interface{}, bindToAttrName string, relationKV ...string) (err error) {
// The parameter `model` is used for recursively scanning purpose, which means, it can scan the attribute struct/structs recursively,
// but it needs the Model for database accessing.
// Note that the parameter `structSlicePointer` should be type of *[]struct/*[]*struct.
func doScanList(model *Model, result Result, structSlicePointer interface{}, bindToAttrName, relationAttrName, relationFields string) (err error) {
if result.IsEmpty() {
return nil
}
@ -59,8 +111,12 @@ func doScanList(model *Model, result Result, listPointer interface{}, bindToAttr
return gerror.NewCode(gcode.CodeInvalidParameter, `bindToAttrName should not be empty`)
}
if relationAttrName == "." {
relationAttrName = ""
}
var (
reflectValue = reflect.ValueOf(listPointer)
reflectValue = reflect.ValueOf(structSlicePointer)
reflectKind = reflectValue.Kind()
)
if reflectKind == reflect.Interface {
@ -70,7 +126,7 @@ func doScanList(model *Model, result Result, listPointer interface{}, bindToAttr
if reflectKind != reflect.Ptr {
return gerror.NewCodef(
gcode.CodeInvalidParameter,
"listPointer should be type of *[]struct/*[]*struct, but got: %v",
"structSlicePointer should be type of *[]struct/*[]*struct, but got: %v",
reflectKind,
)
}
@ -79,7 +135,7 @@ func doScanList(model *Model, result Result, listPointer interface{}, bindToAttr
if reflectKind != reflect.Slice && reflectKind != reflect.Array {
return gerror.NewCodef(
gcode.CodeInvalidParameter,
"listPointer should be type of *[]struct/*[]*struct, but got: %v",
"structSlicePointer should be type of *[]struct/*[]*struct, but got: %v",
reflectKind,
)
}
@ -99,7 +155,7 @@ func doScanList(model *Model, result Result, listPointer interface{}, bindToAttr
var (
arrayValue reflect.Value // Like: []*Entity
arrayItemType reflect.Type // Like: *Entity
reflectType = reflect.TypeOf(listPointer)
reflectType = reflect.TypeOf(structSlicePointer)
)
if reflectValue.Len() > 0 {
arrayValue = reflectValue
@ -112,46 +168,38 @@ func doScanList(model *Model, result Result, listPointer interface{}, bindToAttr
// Relation variables.
var (
relationKVStr string
relationDataMap map[string]Value
relationFromAttrName string // Eg: relationKV: User, uid:Uid -> User
relationResultFieldName string // Eg: relationKV: uid:Uid -> uid
relationBindToSubAttrName string // Eg: relationKV: uid:Uid -> Uid
relationDataMap map[string]Value
relationFromFieldName string // Eg: relationKV: id:uid -> id
relationBindToFieldName string // Eg: relationKV: id:uid -> uid
)
if len(relationKV) > 0 {
if len(relationKV) == 1 {
relationKVStr = relationKV[0]
} else {
relationFromAttrName = relationKV[0]
relationKVStr = relationKV[1]
}
if len(relationFields) > 0 {
// The relation key string of table filed name and attribute name
// can be joined with char '=' or ':'.
array := gstr.SplitAndTrim(relationKVStr, "=")
array := gstr.SplitAndTrim(relationFields, "=")
if len(array) == 1 {
// Compatible with old splitting char ':'.
array = gstr.SplitAndTrim(relationKVStr, ":")
array = gstr.SplitAndTrim(relationFields, ":")
}
if len(array) == 1 {
// The relation names are the same.
array = []string{relationKVStr, relationKVStr}
array = []string{relationFields, relationFields}
}
if len(array) == 2 {
// Defined table field to relation attribute name.
// Like:
// uid:Uid
// uid:UserId
relationResultFieldName = array[0]
relationBindToSubAttrName = array[1]
if key, _ := gutil.MapPossibleItemByKey(result[0].Map(), relationResultFieldName); key == "" {
relationFromFieldName = array[0]
relationBindToFieldName = array[1]
if key, _ := gutil.MapPossibleItemByKey(result[0].Map(), relationFromFieldName); key == "" {
return gerror.NewCodef(
gcode.CodeInvalidParameter,
`cannot find possible related table field name "%s" from given relation key "%s"`,
relationResultFieldName,
relationKVStr,
`cannot find possible related table field name "%s" from given relation fields "%s"`,
relationFromFieldName,
relationFields,
)
} else {
relationResultFieldName = key
relationFromFieldName = key
}
} else {
return gerror.NewCode(
@ -159,15 +207,15 @@ func doScanList(model *Model, result Result, listPointer interface{}, bindToAttr
`parameter relationKV should be format of "ResultFieldName:BindToAttrName"`,
)
}
if relationResultFieldName != "" {
if relationFromFieldName != "" {
// Note that the value might be type of slice.
relationDataMap = result.MapKeyValue(relationResultFieldName)
relationDataMap = result.MapKeyValue(relationFromFieldName)
}
if len(relationDataMap) == 0 {
return gerror.NewCodef(
gcode.CodeInvalidParameter,
`cannot find the relation data map, maybe invalid relation given "%v"`,
relationKV,
`cannot find the relation data map, maybe invalid relation fields given "%v"`,
relationFields,
)
}
}
@ -201,9 +249,9 @@ func doScanList(model *Model, result Result, listPointer interface{}, bindToAttr
// Bind to relation conditions.
var (
relationFromAttrValue reflect.Value
relationFromAttrField reflect.Value
relationBindToSubAttrNameChecked bool
relationFromAttrValue reflect.Value
relationFromAttrField reflect.Value
relationBindToFieldNameChecked bool
)
for i := 0; i < arrayValue.Len(); i++ {
arrayElemValue := arrayValue.Index(i)
@ -224,9 +272,9 @@ func doScanList(model *Model, result Result, listPointer interface{}, bindToAttr
// Like: []Entity
}
bindToAttrValue = arrayElemValue.FieldByName(bindToAttrName)
if relationFromAttrName != "" {
if relationAttrName != "" {
// Attribute value of current slice element.
relationFromAttrValue = arrayElemValue.FieldByName(relationFromAttrName)
relationFromAttrValue = arrayElemValue.FieldByName(relationAttrName)
if relationFromAttrValue.Kind() == reflect.Ptr {
relationFromAttrValue = relationFromAttrValue.Elem()
}
@ -235,36 +283,35 @@ func doScanList(model *Model, result Result, listPointer interface{}, bindToAttr
relationFromAttrValue = arrayElemValue
}
if len(relationDataMap) > 0 && !relationFromAttrValue.IsValid() {
return gerror.NewCodef(gcode.CodeInvalidParameter, `invalid relation specified: "%v"`, relationKV)
return gerror.NewCodef(gcode.CodeInvalidParameter, `invalid relation fields specified: "%v"`, relationFields)
}
// Check and find possible bind to attribute name.
if relationKVStr != "" && !relationBindToSubAttrNameChecked {
relationFromAttrField = relationFromAttrValue.FieldByName(relationBindToSubAttrName)
if relationFields != "" && !relationBindToFieldNameChecked {
relationFromAttrField = relationFromAttrValue.FieldByName(relationBindToFieldName)
if !relationFromAttrField.IsValid() {
var (
relationFromAttrType = relationFromAttrValue.Type()
filedMap = make(map[string]interface{})
filedMap, _ = structs.FieldMap(structs.FieldMapInput{
Pointer: relationFromAttrValue,
RecursiveOption: structs.RecursiveOptionEmbeddedNoTag,
})
)
for i := 0; i < relationFromAttrType.NumField(); i++ {
filedMap[relationFromAttrType.Field(i).Name] = struct{}{}
}
if key, _ := gutil.MapPossibleItemByKey(filedMap, relationBindToSubAttrName); key == "" {
if key, _ := gutil.MapPossibleItemByKey(gconv.Map(filedMap), relationBindToFieldName); key == "" {
return gerror.NewCodef(
gcode.CodeInvalidParameter,
`cannot find possible related attribute name "%s" from given relation key "%s"`,
relationBindToSubAttrName,
relationKVStr,
`cannot find possible related attribute name "%s" from given relation fields "%s"`,
relationBindToFieldName,
relationFields,
)
} else {
relationBindToSubAttrName = key
relationBindToFieldName = key
}
}
relationBindToSubAttrNameChecked = true
relationBindToFieldNameChecked = true
}
switch bindToAttrKind {
case reflect.Array, reflect.Slice:
if len(relationDataMap) > 0 {
relationFromAttrField = relationFromAttrValue.FieldByName(relationBindToSubAttrName)
relationFromAttrField = relationFromAttrValue.FieldByName(relationBindToFieldName)
if relationFromAttrField.IsValid() {
results := make(Result, 0)
for _, v := range relationDataMap[gconv.String(relationFromAttrField.Interface())].Slice() {
@ -280,8 +327,8 @@ func doScanList(model *Model, result Result, listPointer interface{}, bindToAttr
}
}
} else {
// May be the attribute does not exist yet.
return gerror.NewCodef(gcode.CodeInvalidParameter, `invalid relation specified: "%v"`, relationKV)
// Maybe the attribute does not exist yet.
return gerror.NewCodef(gcode.CodeInvalidParameter, `invalid relation fields specified: "%v"`, relationFields)
}
} else {
return gerror.NewCodef(
@ -299,7 +346,7 @@ func doScanList(model *Model, result Result, listPointer interface{}, bindToAttr
element = bindToAttrValue.Elem()
}
if len(relationDataMap) > 0 {
relationFromAttrField = relationFromAttrValue.FieldByName(relationBindToSubAttrName)
relationFromAttrField = relationFromAttrValue.FieldByName(relationBindToFieldName)
if relationFromAttrField.IsValid() {
v := relationDataMap[gconv.String(relationFromAttrField.Interface())]
if v == nil {
@ -316,8 +363,8 @@ func doScanList(model *Model, result Result, listPointer interface{}, bindToAttr
}
}
} else {
// May be the attribute does not exist yet.
return gerror.NewCodef(gcode.CodeInvalidParameter, `invalid relation specified: "%v"`, relationKV)
// Maybe the attribute does not exist yet.
return gerror.NewCodef(gcode.CodeInvalidParameter, `invalid relation fields specified: "%v"`, relationFields)
}
} else {
if i >= len(result) {
@ -343,7 +390,7 @@ func doScanList(model *Model, result Result, listPointer interface{}, bindToAttr
case reflect.Struct:
if len(relationDataMap) > 0 {
relationFromAttrField = relationFromAttrValue.FieldByName(relationBindToSubAttrName)
relationFromAttrField = relationFromAttrValue.FieldByName(relationBindToFieldName)
if relationFromAttrField.IsValid() {
relationDataItem := relationDataMap[gconv.String(relationFromAttrField.Interface())]
if relationDataItem == nil {
@ -360,8 +407,8 @@ func doScanList(model *Model, result Result, listPointer interface{}, bindToAttr
}
}
} else {
// May be the attribute does not exist yet.
return gerror.NewCodef(gcode.CodeInvalidParameter, `invalid relation specified: "%v"`, relationKV)
// Maybe the attribute does not exist yet.
return gerror.NewCodef(gcode.CodeInvalidParameter, `invalid relation fields specified: "%v"`, relationFields)
}
} else {
if i >= len(result) {
@ -388,6 +435,6 @@ func doScanList(model *Model, result Result, listPointer interface{}, bindToAttr
return gerror.NewCodef(gcode.CodeInvalidParameter, `unsupported attribute type: %s`, bindToAttrKind.String())
}
}
reflect.ValueOf(listPointer).Elem().Set(arrayValue)
reflect.ValueOf(structSlicePointer).Elem().Set(arrayValue)
return nil
}

View File

@ -1553,7 +1553,7 @@ CREATE TABLE %s (
})
}
func Test_Table_Relation_EmbeddedStruct(t *testing.T) {
func Test_Table_Relation_EmbeddedStruct1(t *testing.T) {
var (
tableUser = "user_" + gtime.TimestampMicroStr()
tableUserDetail = "user_detail_" + gtime.TimestampMicroStr()
@ -1670,3 +1670,310 @@ CREATE TABLE %s (
t.Assert(scores[24].Address, "address_5")
})
}
func Test_Table_Relation_EmbeddedStruct2(t *testing.T) {
var (
tableUser = "user_" + gtime.TimestampMicroStr()
tableUserDetail = "user_detail_" + gtime.TimestampMicroStr()
tableUserScores = "user_scores_" + gtime.TimestampMicroStr()
)
if _, err := db.Exec(ctx, fmt.Sprintf(`
CREATE TABLE %s (
uid int(10) unsigned NOT NULL AUTO_INCREMENT,
name varchar(45) NOT NULL,
PRIMARY KEY (uid)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
`, tableUser)); err != nil {
gtest.Error(err)
}
defer dropTable(tableUser)
if _, err := db.Exec(ctx, fmt.Sprintf(`
CREATE TABLE %s (
uid int(10) unsigned NOT NULL AUTO_INCREMENT,
address varchar(45) NOT NULL,
PRIMARY KEY (uid)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
`, tableUserDetail)); err != nil {
gtest.Error(err)
}
defer dropTable(tableUserDetail)
if _, err := db.Exec(ctx, fmt.Sprintf(`
CREATE TABLE %s (
id int(10) unsigned NOT NULL AUTO_INCREMENT,
uid int(10) unsigned NOT NULL,
score int(10) unsigned NOT NULL,
PRIMARY KEY (id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
`, tableUserScores)); err != nil {
gtest.Error(err)
}
defer dropTable(tableUserScores)
type EntityUser struct {
Uid int `json:"uid"`
Name string `json:"name"`
}
type EntityUserDetail struct {
Uid int `json:"uid"`
Address string `json:"address"`
}
type EntityUserScores struct {
Id int `json:"id"`
Uid int `json:"uid"`
Score int `json:"score"`
}
type Entity struct {
*EntityUser
UserDetail *EntityUserDetail
UserScores []*EntityUserScores
}
// Initialize the data.
gtest.C(t, func(t *gtest.T) {
var err error
for i := 1; i <= 5; i++ {
// User.
_, err = db.Insert(ctx, tableUser, g.Map{
"uid": i,
"name": fmt.Sprintf(`name_%d`, i),
})
t.AssertNil(err)
// Detail.
_, err = db.Insert(ctx, tableUserDetail, g.Map{
"uid": i,
"address": fmt.Sprintf(`address_%d`, i),
})
t.AssertNil(err)
// Scores.
for j := 1; j <= 5; j++ {
_, err = db.Insert(ctx, tableUserScores, g.Map{
"uid": i,
"score": j,
})
t.AssertNil(err)
}
}
})
// MapKeyValue.
gtest.C(t, func(t *gtest.T) {
all, err := db.Model(tableUser).Where("uid", g.Slice{3, 4}).Order("uid asc").All()
t.AssertNil(err)
t.Assert(all.Len(), 2)
t.Assert(len(all.MapKeyValue("uid")), 2)
t.Assert(all.MapKeyValue("uid")["3"].Map()["uid"], 3)
t.Assert(all.MapKeyValue("uid")["4"].Map()["uid"], 4)
all, err = db.Model(tableUserScores).Where("uid", g.Slice{3, 4}).Order("id asc").All()
t.AssertNil(err)
t.Assert(all.Len(), 10)
t.Assert(len(all.MapKeyValue("uid")), 2)
t.Assert(len(all.MapKeyValue("uid")["3"].Slice()), 5)
t.Assert(len(all.MapKeyValue("uid")["4"].Slice()), 5)
t.Assert(gconv.Map(all.MapKeyValue("uid")["3"].Slice()[0])["uid"], 3)
t.Assert(gconv.Map(all.MapKeyValue("uid")["3"].Slice()[0])["score"], 1)
t.Assert(gconv.Map(all.MapKeyValue("uid")["3"].Slice()[4])["uid"], 3)
t.Assert(gconv.Map(all.MapKeyValue("uid")["3"].Slice()[4])["score"], 5)
})
db.SetDebug(true)
// Result ScanList with struct elements and pointer attributes.
gtest.C(t, func(t *gtest.T) {
var users []Entity
// User
err := db.Model(tableUser).Where("uid", g.Slice{3, 4}).Order("uid asc").Scan(&users)
t.AssertNil(err)
t.Assert(len(users), 2)
t.Assert(users[0].EntityUser, &EntityUser{3, "name_3"})
t.Assert(users[1].EntityUser, &EntityUser{4, "name_4"})
// Detail
all, err := db.Model(tableUserDetail).Where("uid", gdb.ListItemValues(users, "Uid")).Order("uid asc").All()
t.AssertNil(err)
err = all.ScanList(&users, "UserDetail", "uid")
t.AssertNil(err)
t.Assert(users[0].UserDetail, &EntityUserDetail{3, "address_3"})
t.Assert(users[1].UserDetail, &EntityUserDetail{4, "address_4"})
// Scores
all, err = db.Model(tableUserScores).Where("uid", gdb.ListItemValues(users, "Uid")).Order("id asc").All()
t.AssertNil(err)
err = all.ScanList(&users, "UserScores", "uid")
t.AssertNil(err)
t.Assert(len(users[0].UserScores), 5)
t.Assert(len(users[1].UserScores), 5)
t.Assert(users[0].UserScores[0].Uid, 3)
t.Assert(users[0].UserScores[0].Score, 1)
t.Assert(users[0].UserScores[4].Score, 5)
t.Assert(users[1].UserScores[0].Uid, 4)
t.Assert(users[1].UserScores[0].Score, 1)
t.Assert(users[1].UserScores[4].Score, 5)
})
// Result ScanList with pointer elements and pointer attributes.
gtest.C(t, func(t *gtest.T) {
var users []*Entity
// User
err := db.Model(tableUser).Where("uid", g.Slice{3, 4}).Order("uid asc").Scan(&users)
t.AssertNil(err)
t.Assert(len(users), 2)
t.Assert(users[0].EntityUser, &EntityUser{3, "name_3"})
t.Assert(users[1].EntityUser, &EntityUser{4, "name_4"})
// Detail
all, err := db.Model(tableUserDetail).Where("uid", gdb.ListItemValues(users, "Uid")).Order("uid asc").All()
t.AssertNil(err)
err = all.ScanList(&users, "UserDetail", "uid")
t.AssertNil(err)
t.Assert(users[0].UserDetail, &EntityUserDetail{3, "address_3"})
t.Assert(users[1].UserDetail, &EntityUserDetail{4, "address_4"})
// Scores
all, err = db.Model(tableUserScores).Where("uid", gdb.ListItemValues(users, "Uid")).Order("id asc").All()
t.AssertNil(err)
err = all.ScanList(&users, "UserScores", "uid")
t.AssertNil(err)
t.Assert(len(users[0].UserScores), 5)
t.Assert(len(users[1].UserScores), 5)
t.Assert(users[0].UserScores[0].Uid, 3)
t.Assert(users[0].UserScores[0].Score, 1)
t.Assert(users[0].UserScores[4].Score, 5)
t.Assert(users[1].UserScores[0].Uid, 4)
t.Assert(users[1].UserScores[0].Score, 1)
t.Assert(users[1].UserScores[4].Score, 5)
})
// Result ScanList with struct elements and struct attributes.
gtest.C(t, func(t *gtest.T) {
type EntityUser struct {
Uid int `json:"uid"`
Name string `json:"name"`
}
type EntityUserDetail struct {
Uid int `json:"uid"`
Address string `json:"address"`
}
type EntityUserScores struct {
Id int `json:"id"`
Uid int `json:"uid"`
Score int `json:"score"`
}
type Entity struct {
EntityUser
UserDetail EntityUserDetail
UserScores []EntityUserScores
}
var users []Entity
// User
err := db.Model(tableUser).Where("uid", g.Slice{3, 4}).Order("uid asc").Scan(&users)
t.AssertNil(err)
t.Assert(len(users), 2)
t.Assert(users[0].EntityUser, &EntityUser{3, "name_3"})
t.Assert(users[1].EntityUser, &EntityUser{4, "name_4"})
// Detail
all, err := db.Model(tableUserDetail).Where("uid", gdb.ListItemValues(users, "Uid")).Order("uid asc").All()
t.AssertNil(err)
err = all.ScanList(&users, "UserDetail", "uid")
t.AssertNil(err)
t.Assert(users[0].UserDetail, &EntityUserDetail{3, "address_3"})
t.Assert(users[1].UserDetail, &EntityUserDetail{4, "address_4"})
// Scores
all, err = db.Model(tableUserScores).Where("uid", gdb.ListItemValues(users, "Uid")).Order("id asc").All()
t.AssertNil(err)
err = all.ScanList(&users, "UserScores", "uid")
t.AssertNil(err)
t.Assert(len(users[0].UserScores), 5)
t.Assert(len(users[1].UserScores), 5)
t.Assert(users[0].UserScores[0].Uid, 3)
t.Assert(users[0].UserScores[0].Score, 1)
t.Assert(users[0].UserScores[4].Score, 5)
t.Assert(users[1].UserScores[0].Uid, 4)
t.Assert(users[1].UserScores[0].Score, 1)
t.Assert(users[1].UserScores[4].Score, 5)
})
// Result ScanList with pointer elements and struct attributes.
gtest.C(t, func(t *gtest.T) {
type EntityUser struct {
Uid int `json:"uid"`
Name string `json:"name"`
}
type EntityUserDetail struct {
Uid int `json:"uid"`
Address string `json:"address"`
}
type EntityUserScores struct {
Id int `json:"id"`
Uid int `json:"uid"`
Score int `json:"score"`
}
type Entity struct {
EntityUser
UserDetail EntityUserDetail
UserScores []EntityUserScores
}
var users []*Entity
// User
err := db.Model(tableUser).Where("uid", g.Slice{3, 4}).Order("uid asc").Scan(&users)
t.AssertNil(err)
t.Assert(len(users), 2)
t.Assert(users[0].EntityUser, &EntityUser{3, "name_3"})
t.Assert(users[1].EntityUser, &EntityUser{4, "name_4"})
// Detail
all, err := db.Model(tableUserDetail).Where("uid", gdb.ListItemValues(users, "Uid")).Order("uid asc").All()
t.AssertNil(err)
err = all.ScanList(&users, "UserDetail", "uid")
t.AssertNil(err)
t.Assert(users[0].UserDetail, &EntityUserDetail{3, "address_3"})
t.Assert(users[1].UserDetail, &EntityUserDetail{4, "address_4"})
// Scores
all, err = db.Model(tableUserScores).Where("uid", gdb.ListItemValues(users, "Uid")).Order("id asc").All()
t.AssertNil(err)
err = all.ScanList(&users, "UserScores", "uid")
t.AssertNil(err)
t.Assert(len(users[0].UserScores), 5)
t.Assert(len(users[1].UserScores), 5)
t.Assert(users[0].UserScores[0].Uid, 3)
t.Assert(users[0].UserScores[0].Score, 1)
t.Assert(users[0].UserScores[4].Score, 5)
t.Assert(users[1].UserScores[0].Uid, 4)
t.Assert(users[1].UserScores[0].Score, 1)
t.Assert(users[1].UserScores[4].Score, 5)
})
// Model ScanList with pointer elements and pointer attributes.
gtest.C(t, func(t *gtest.T) {
var users []*Entity
// User
err := db.Model(tableUser).
Where("uid", g.Slice{3, 4}).
Order("uid asc").
Scan(&users)
t.AssertNil(err)
// Detail
err = db.Model(tableUserDetail).
Where("uid", gdb.ListItemValues(users, "Uid")).
Order("uid asc").
ScanList(&users, "UserDetail", "uid:Uid")
t.AssertNil(err)
// Scores
err = db.Model(tableUserScores).
Where("uid", gdb.ListItemValues(users, "Uid")).
Order("id asc").
ScanList(&users, "UserScores", "uid:Uid")
t.AssertNil(err)
t.Assert(len(users), 2)
t.Assert(users[0].EntityUser, &EntityUser{3, "name_3"})
t.Assert(users[1].EntityUser, &EntityUser{4, "name_4"})
t.Assert(users[0].UserDetail, &EntityUserDetail{3, "address_3"})
t.Assert(users[1].UserDetail, &EntityUserDetail{4, "address_4"})
t.Assert(len(users[0].UserScores), 5)
t.Assert(len(users[1].UserScores), 5)
t.Assert(users[0].UserScores[0].Uid, 3)
t.Assert(users[0].UserScores[0].Score, 1)
t.Assert(users[0].UserScores[4].Score, 5)
t.Assert(users[1].UserScores[0].Uid, 4)
t.Assert(users[1].UserScores[0].Score, 1)
t.Assert(users[1].UserScores[4].Score, 5)
})
}

View File

@ -20,7 +20,7 @@ import (
// Struct maps the params key-value pairs to the corresponding struct object's attributes.
// The third parameter `mapping` is unnecessary, indicating the mapping rules between the
// custom key name and the attribute name(case sensitive).
// custom key name and the attribute name(case-sensitive).
//
// Note:
// 1. The `params` can be any type of map/struct, usually a map.

File diff suppressed because it is too large Load Diff