From e16601cdc08b2a24af2ca48e6ccc84cf006d3c2f Mon Sep 17 00:00:00 2001 From: Paolo Galeone Date: Wed, 2 Apr 2014 11:00:07 +0200 Subject: [PATCH] Add getPrimaryKey: analize the tag string in the struct fields and find the one marked as primaryKey --- scope_private.go | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) diff --git a/scope_private.go b/scope_private.go index 72f631cc..71f50408 100644 --- a/scope_private.go +++ b/scope_private.go @@ -10,6 +10,7 @@ import ( "strconv" "strings" "time" + "go/ast" ) func (scope *Scope) primaryCondiation(value interface{}) string { @@ -472,3 +473,27 @@ func (scope *Scope) autoMigrate() *Scope { } return scope } + +func (scope *Scope) getPrimaryKey() string { + indirectValue := reflect.Indirect(reflect.ValueOf(scope.Value)) + + if !indirectValue.IsValid() { + return "id" + } + + scopeTyp := indirectValue.Type() + for i := 0; i < scopeTyp.NumField(); i++ { + fieldStruct := scopeTyp.Field(i) + if !ast.IsExported(fieldStruct.Name) { + continue + } + + // if primaryKey tag found, return column name + if fieldStruct.Tag.Get("primaryKey") != "" { + return toSnake(fieldStruct.Name) + } + } + + //If primaryKey tag not found, fallback to id + return "id" +}