From d2e526bc2d4576c20ba60b98d09251be5b469d8c Mon Sep 17 00:00:00 2001 From: Vladimir Garvardt Date: Thu, 12 Jun 2014 00:51:27 +0400 Subject: [PATCH] db.Create() for force insert with predefined primary key --- README.md | 6 ++++++ callback_create.go | 11 +++++++++-- main.go | 5 +++++ main_test.go | 14 ++++++++++++++ 4 files changed, 34 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index ee80c444..d29a5edc 100644 --- a/README.md +++ b/README.md @@ -237,6 +237,12 @@ db.Save(&user) //// COMMIT; ``` +### Create With Predefined Primary key + +```go +db.Create(&User{Id: 999, Name: "user 999"}) +``` + ## Query ```go diff --git a/callback_create.go b/callback_create.go index 8276f0d2..1cf4fcb4 100644 --- a/callback_create.go +++ b/callback_create.go @@ -26,8 +26,15 @@ func Create(scope *Scope) { // set create sql var sqls, columns []string + primaryKeyPredefined := false for _, field := range scope.Fields() { - if field.DBName != scope.PrimaryKey() && len(field.SqlTag) > 0 && !field.IsIgnored { + if field.DBName == scope.PrimaryKey() { + primaryKeyValue := fmt.Sprintf("%v", field.Value) + if primaryKeyValue != "" && primaryKeyValue != "0" { + primaryKeyPredefined = true + } + } + if len(field.SqlTag) > 0 && !field.IsIgnored && (field.DBName != scope.PrimaryKey() || primaryKeyPredefined) { columns = append(columns, scope.Quote(field.DBName)) sqls = append(sqls, scope.AddToVars(field.Value)) } @@ -65,7 +72,7 @@ func Create(scope *Scope) { } } - if !scope.HasError() { + if !scope.HasError() && !primaryKeyPredefined { scope.SetColumn(scope.PrimaryKey(), id) } } diff --git a/main.go b/main.go index e3fd9fe2..17e3246c 100644 --- a/main.go +++ b/main.go @@ -214,6 +214,11 @@ func (s *DB) Save(value interface{}) *DB { } } +func (s *DB) Create(value interface{}) *DB { + scope := s.clone().NewScope(value) + return scope.callCallbacks(s.parent.callback.creates).db +} + func (s *DB) Delete(value interface{}) *DB { return s.clone().NewScope(value).callCallbacks(s.parent.callback.deletes).db } diff --git a/main_test.go b/main_test.go index 6d0d17e1..46d6e6e4 100644 --- a/main_test.go +++ b/main_test.go @@ -2083,3 +2083,17 @@ func TestHstore(t *testing.T) { } } + +func TestCreate(t *testing.T) { + if err := db.Create(&UserCompany{Id: 10, UserId: 1, CompanyId: 1}).Error; err != nil { + t.Error("Should be able to create record with predefined Id") + } + + if db.First(&UserCompany{}, 10).RecordNotFound() { + t.Error("Record created with predefined primary key not found") + } + + if err := db.Create(&UserCompany{Id: 10, UserId: 10, CompanyId: 10}).Error; err == nil { + t.Error("Should not be able to create record with predefined duplicate Id") + } +}