From 0b9218f1e5330cdd6217af459edaca845793288b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Vytautas=20=C5=A0altenis?= Date: Sat, 30 Aug 2014 20:41:20 +0300 Subject: [PATCH] Improve column->field map construction Extract column map construction to a separate func and make it recursively collect fields from embedded structs. --- callback_query.go | 37 +++++++++++++++++++++++++------------ 1 file changed, 25 insertions(+), 12 deletions(-) diff --git a/callback_query.go b/callback_query.go index 87a7f07c..c2a53433 100644 --- a/callback_query.go +++ b/callback_query.go @@ -6,6 +6,30 @@ import ( "time" ) +func getColumnMap(destType reflect.Type) map[string]string { + colToFieldMap := make(map[string]string) + if destType != nil && destType.Kind() == reflect.Struct { + for i := 0; i < destType.NumField(); i++ { + field := destType.Field(i) + if field.Anonymous { + embeddedStructFields := getColumnMap(field.Type) + for k, v := range embeddedStructFields { + colToFieldMap[k] = v + } + continue + } + fieldName := field.Name + dbColumnName := ToSnake(fieldName) + settings := parseTagSetting(destType.Field(i).Tag.Get("gorm")) + if colName, ok := settings["COLUMN"]; ok && colName != "" { + dbColumnName = colName + } + colToFieldMap[dbColumnName] = fieldName + } + } + return colToFieldMap +} + func Query(scope *Scope) { defer scope.Trace(time.Now()) @@ -41,18 +65,7 @@ func Query(scope *Scope) { return } - colToFieldMap := make(map[string]string) - if destType != nil && destType.Kind() == reflect.Struct { - for i := 0; i < destType.NumField(); i++ { - fieldName := destType.Field(i).Name - dbColumnName := ToSnake(fieldName) - settings := parseTagSetting(destType.Field(i).Tag.Get("gorm")) - if colName, ok := settings["COLUMN"]; ok && colName != "" { - dbColumnName = colName - } - colToFieldMap[dbColumnName] = fieldName - } - } + colToFieldMap := getColumnMap(destType) defer rows.Close() for rows.Next() {