github.com/kunlun-qilian/sqlx/v3@v3.0.0/builder/utils_field_test.go (about) 1 package builder 2 3 import ( 4 "context" 5 "reflect" 6 "testing" 7 8 "github.com/go-courier/x/ptr" 9 typex "github.com/go-courier/x/types" 10 g "github.com/onsi/gomega" 11 ) 12 13 type SubSubSub struct { 14 X string `db:"f_x"` 15 } 16 17 type SubSub struct { 18 SubSubSub 19 } 20 21 type Sub struct { 22 SubSub 23 A string `db:"f_a"` 24 } 25 26 type PtrSub struct { 27 B []string `db:"f_b"` 28 Map map[string]string `db:"f_b_map"` 29 } 30 31 type P struct { 32 Sub 33 *PtrSub 34 C *string `db:"f_c"` 35 } 36 37 var p *P 38 39 func init() { 40 p = &P{} 41 p.X = "x" 42 p.A = "a" 43 p.PtrSub = &PtrSub{ 44 Map: map[string]string{ 45 "1": "!", 46 }, 47 B: []string{"b"}, 48 } 49 p.C = ptr.String("c") 50 } 51 52 func TestTableFieldsFor(t *testing.T) { 53 fields := StructFieldsFor(context.Background(), typex.FromRType(reflect.TypeOf(p))) 54 55 rv := reflect.ValueOf(p) 56 57 g.NewWithT(t).Expect(fields).To(g.HaveLen(5)) 58 59 g.NewWithT(t).Expect(fields[0].Name).To(g.Equal("f_x")) 60 g.NewWithT(t).Expect(fields[0].FieldValue(rv).Interface()).To(g.Equal(p.X)) 61 62 g.NewWithT(t).Expect(fields[1].Name).To(g.Equal("f_a")) 63 g.NewWithT(t).Expect(fields[1].FieldValue(rv).Interface()).To(g.Equal(p.A)) 64 65 g.NewWithT(t).Expect(fields[2].Name).To(g.Equal("f_b")) 66 g.NewWithT(t).Expect(fields[2].FieldValue(rv).Interface()).To(g.Equal(p.B)) 67 68 g.NewWithT(t).Expect(fields[3].Name).To(g.Equal("f_b_map")) 69 g.NewWithT(t).Expect(fields[3].FieldValue(rv).Interface()).To(g.Equal(p.Map)) 70 71 g.NewWithT(t).Expect(fields[4].Name).To(g.Equal("f_c")) 72 g.NewWithT(t).Expect(fields[4].FieldValue(rv).Interface()).To(g.Equal(p.C)) 73 } 74 75 func BenchmarkTableFieldsFor(b *testing.B) { 76 typeP := reflect.TypeOf(p) 77 78 _ = StructFieldsFor(context.Background(), typex.FromRType(typeP)) 79 80 //b.Log(typex.FromRType(reflect.TypeOf(p)).Unwrap() == typex.FromRType(reflect.TypeOf(p)).Unwrap()) 81 82 b.Run("StructFieldsFor", func(b *testing.B) { 83 typP := typex.FromRType(typeP) 84 85 for i := 0; i < b.N; i++ { 86 _ = StructFieldsFor(context.Background(), typP) 87 } 88 }) 89 }