Skip to content

Commit

Permalink
supports custom DBTag content
Browse files Browse the repository at this point in the history
  • Loading branch information
zhangyongding committed Jul 25, 2023
1 parent 18c5787 commit c733b2e
Show file tree
Hide file tree
Showing 3 changed files with 36 additions and 3 deletions.
24 changes: 24 additions & 0 deletions struct.go
Original file line number Diff line number Diff line change
Expand Up @@ -704,6 +704,30 @@ func (s *Struct) valuesWithTags(with, without []string, value interface{}) (valu
return
}

// DBTags returns db tags of s for all exported struct fields.
func (s *Struct) DBTags() (dbTags []string) {
return s.dbTagsWithTags(s.withTags, s.withoutTags)
}

// DBTagsForTag returns db tags of the s tagged with tag.
func (s *Struct) DBTagsForTag(tag string) (dbTags []string) {
return s.dbTagsWithTags([]string{tag}, nil)
}

func (s *Struct) dbTagsWithTags(with, without []string) (dbTags []string) {
sfs := s.structFieldsParser()
tagged := sfs.FilterTags(with, without)
if tagged == nil {
return
}

dbTags = make([]string, 0, len(tagged.ForRead))
for _, sf := range tagged.ForRead {
dbTags = append(dbTags, sf.DBTag)
}
return
}

func dereferencedType(t reflect.Type) reflect.Type {
for k := t.Kind(); k == reflect.Ptr || k == reflect.Interface; k = t.Kind() {
t = t.Elem()
Expand Down
7 changes: 7 additions & 0 deletions struct_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -302,6 +302,13 @@ func TestWithAndWithoutTags(t *testing.T) {
a.Equal(structTags.WithoutTag("tag3").WithTag("tag1").WithTag("tag3", "tag2").WithoutTag("tag1", "", "tag3").Columns(), []string{"b"})
}

func TestStructDBTags(t *testing.T) {
a := assert.New(t)
a.Equal(userForTest.DBTags(), []string{"id", "", "status", "created_at"})
a.Equal(userForTest.DBTagsForTag("important"), []string{"id", "", "status"})
a.Equal(userForTest.DBTagsForTag("invalid"), nil)
}

type State int
type testDB int
type testRows int
Expand Down
8 changes: 5 additions & 3 deletions structfields.go
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ type structField struct {
As string
Tags []string
IsQuoted bool
DBTag string

omitEmptyTags omitEmptyTagMap
}
Expand Down Expand Up @@ -95,10 +96,10 @@ func (sfs *structFields) parse(t reflect.Type, mapper FieldMapperFunc, prefix st

if dbtag == "" {
alias = field.Name
}

if mapper != nil {
alias = mapper(alias)
}
if mapper != nil {
alias = mapper(alias)
}

// Parse FieldOpt.
Expand Down Expand Up @@ -137,6 +138,7 @@ func (sfs *structFields) parse(t reflect.Type, mapper FieldMapperFunc, prefix st
As: fieldas,
Tags: tags,
IsQuoted: isQuoted,
DBTag: dbtag,
omitEmptyTags: omitEmptyTags,
}

Expand Down

0 comments on commit c733b2e

Please sign in to comment.