From 0c63e57f5cd7f509d4fe7df6d88ea9072a4a5d26 Mon Sep 17 00:00:00 2001 From: Jinzhu Date: Tue, 29 Jul 2014 18:21:36 +0800 Subject: [PATCH] Use tag to set primary key --- README.md | 2 +- create_test.go | 11 +++++++++++ main_private.go | 2 +- scope.go | 5 ++++- structs_test.go | 2 +- utils.go | 3 ++- 6 files changed, 20 insertions(+), 5 deletions(-) diff --git a/README.md b/README.md index 24779d1be..feec12902 100644 --- a/README.md +++ b/README.md @@ -891,7 +891,7 @@ If you have an existing database schema, and the primary key field is different ```go type Animal struct { - AnimalId int64 `primaryKey:"yes"` + AnimalId int64 `gorm:"primary_key:yes"` Birthday time.Time Age int64 } diff --git a/create_test.go b/create_test.go index 20a12ab53..6f89455f1 100644 --- a/create_test.go +++ b/create_test.go @@ -56,6 +56,17 @@ func TestCreate(t *testing.T) { } } +func TestCreateWithNoStdPrimaryKey(t *testing.T) { + animal := Animal{Name: "Ferdinand"} + if db.Save(&animal).Error != nil { + t.Errorf("No error should happen when create an record without std primary key") + } + + if animal.Counter == 0 { + t.Errorf("No std primary key should be filled value after create") + } +} + func TestAnonymousScanner(t *testing.T) { user := User{Name: "anonymous_scanner", Role: Role{Name: "admin"}} db.Save(&user) diff --git a/main_private.go b/main_private.go index fe198c1df..dbb59dd0b 100644 --- a/main_private.go +++ b/main_private.go @@ -45,7 +45,7 @@ func (s *DB) print(v ...interface{}) { } func (s *DB) log(v ...interface{}) { - if s.logMode == 2 { + if s != nil && s.logMode == 2 { s.print(append([]interface{}{"log", fileWithLineNum()}, v...)...) } } diff --git a/scope.go b/scope.go index a77baa147..181b0453c 100644 --- a/scope.go +++ b/scope.go @@ -253,7 +253,10 @@ func (scope *Scope) Fields() []*Field { field.IsBlank = isBlank(value) // Search for primary key tag identifier - field.isPrimaryKey = scope.PrimaryKey() == field.DBName || fieldStruct.Tag.Get("primaryKey") != "" + settings := parseTagSetting(fieldStruct.Tag.Get("gorm")) + if _, ok := settings["PRIMARY_KEY"]; scope.PrimaryKey() == field.DBName || ok { + field.isPrimaryKey = true + } if field.isPrimaryKey { scope.primaryKey = field.DBName diff --git a/structs_test.go b/structs_test.go index bd515a6be..e6aff4582 100644 --- a/structs_test.go +++ b/structs_test.go @@ -119,7 +119,7 @@ func (i *Num) Scan(src interface{}) error { } type Animal struct { - Counter int64 `primaryKey:"yes"` + Counter int64 `gorm:"primary_key:yes"` Name string From string //test reserved sql keyword as field name CreatedAt time.Time diff --git a/utils.go b/utils.go index 4fcce4c8d..04f02a310 100644 --- a/utils.go +++ b/utils.go @@ -106,7 +106,8 @@ func GetPrimaryKey(value interface{}) string { continue } - if fieldStruct.Tag.Get("primaryKey") != "" { + settings := parseTagSetting(fieldStruct.Tag.Get("gorm")) + if _, ok := settings["PRIMARY_KEY"]; ok { return fieldStruct.Name } }