add get alias func

This commit is contained in:
zhangyongding
2023-07-28 15:06:54 +08:00
parent 096b0896e9
commit 73b1f4d410
2 changed files with 22 additions and 9 deletions
+16
View File
@@ -1,6 +1,8 @@
package sqlbuilder
import (
"reflect"
"github.com/huandu/xstrings"
)
@@ -13,8 +15,19 @@ var (
//
// Field mapper is called only once on a Struct when the Struct is used to create builder for the first time.
DefaultFieldMapper FieldMapperFunc
// DefaultGetAlias is the default alias and dbtag get func
DefaultGetAlias GetAliasFunc
)
func init() {
DefaultGetAlias = func(field *reflect.StructField) (alias string, dbtag string) {
dbtag = field.Tag.Get(DBTag)
alias = dbtag
return
}
}
// FieldMapperFunc is a func to map struct field names to column names,
// which will be used in query as columns.
type FieldMapperFunc func(name string) string
@@ -28,3 +41,6 @@ type FieldMapperFunc func(name string) string
func SnakeCaseMapper(field string) string {
return xstrings.ToSnakeCase(field)
}
// GetAliasFunc is a func to get alias and dbtag
type GetAliasFunc func(field *reflect.StructField) (alias string, dbtag string)
+6 -9
View File
@@ -86,20 +86,17 @@ func (sfs *structFields) parse(t reflect.Type, mapper FieldMapperFunc, prefix st
}
// Parse DBTag.
dbtag := field.Tag.Get(DBTag)
alias, dbtag := DefaultGetAlias(&field)
if dbtag == "-" {
if alias == "-" {
continue
}
alias := dbtag
if dbtag == "" {
if alias == "" {
alias = field.Name
}
if mapper != nil {
alias = mapper(alias)
if mapper != nil {
alias = mapper(alias)
}
}
// Parse FieldOpt.