Added tag handlers for custom DB field names

This commit is contained in:
drgomesp 2017-01-16 18:07:38 +04:00
parent 1c01606add
commit 8d6b599b54
2 changed files with 18 additions and 9 deletions

View File

@ -33,7 +33,7 @@ func createBatchCallback(scope *Scope) {
// Filling up the columns
for _, field := range fields(scope) {
// We don't treat non-normal fields on batch operations (relationships, etc)
if !field.IsNormal {
if !field.IsNormal || field.IsIgnored {
continue
}
@ -51,7 +51,7 @@ func createBatchCallback(scope *Scope) {
for _, structField := range structFields {
// When inserting, the primary key is usually auto-increment
if !structField.IsPrimaryKey {
if !structField.IsPrimaryKey && !structField.IsIgnored {
fieldValue := reflect.Indirect(value.Index(elementIndex)).FieldByName(structField.Names[0]).Interface()
valuePlaceholders = append(valuePlaceholders, scope.AddToVars(fieldValue))
}

View File

@ -12,11 +12,19 @@ import (
"github.com/jinzhu/inflection"
)
type tagHandlerFunc func(*StructField)
// DefaultTableNameHandler default table name handler
var DefaultTableNameHandler = func(db *DB, defaultTableName string) string {
return defaultTableName
}
var tagHandlers = map[string]tagHandlerFunc{}
func AddTagHandler(tagName string, handler tagHandlerFunc) {
tagHandlers[tagName] = handler
}
type safeModelStructsMap struct {
m map[reflect.Type]*ModelStruct
l *sync.RWMutex
@ -205,19 +213,14 @@ func (scope *Scope) GetModelStruct() *ModelStruct {
field.IsNormal = true
} else if _, ok := field.TagSettings["EMBEDDED"]; ok || fieldStruct.Anonymous {
// is embedded struct
for _, subField := range scope.New(fieldValue).GetModelStruct().StructFields {
for _, subField := range scope.New(fieldValue).GetStructFields() {
subField = subField.clone()
subField.Names = append([]string{fieldStruct.Name}, subField.Names...)
if prefix, ok := field.TagSettings["EMBEDDED_PREFIX"]; ok {
subField.DBName = prefix + subField.DBName
}
if subField.IsPrimaryKey {
if _, ok := subField.TagSettings["PRIMARY_KEY"]; ok {
modelStruct.PrimaryFields = append(modelStruct.PrimaryFields, subField)
} else {
subField.IsPrimaryKey = false
}
modelStruct.PrimaryFields = append(modelStruct.PrimaryFields, subField)
}
modelStruct.StructFields = append(modelStruct.StructFields, subField)
}
@ -545,6 +548,12 @@ func (scope *Scope) GetModelStruct() *ModelStruct {
field.DBName = ToDBName(fieldStruct.Name)
}
for tagName := range field.TagSettings {
if handler, ok := tagHandlers[tagName]; ok {
handler(field)
}
}
modelStruct.StructFields = append(modelStruct.StructFields, field)
}
}