github.com/octohelm/storage@v0.0.0-20240516030302-1ac2cc1ea347/pkg/sqlbuilder/utils_field_test.go (about)

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