From 8b07437717e71c2ff00602ae19f8353ba10aafbb Mon Sep 17 00:00:00 2001 From: Ali Koyuncu Date: Sun, 10 Mar 2019 14:17:21 +0200 Subject: [PATCH] add mysql insert modifiers (#2269) --- callback_create.go | 13 +++++++++++-- create_test.go | 17 +++++++++++++++++ 2 files changed, 28 insertions(+), 2 deletions(-) diff --git a/callback_create.go b/callback_create.go index 2ab05d3b0..763a2dfde 100644 --- a/callback_create.go +++ b/callback_create.go @@ -83,11 +83,18 @@ func createCallback(scope *Scope) { quotedTableName = scope.QuotedTableName() primaryField = scope.PrimaryField() extraOption string + insertModifier string ) if str, ok := scope.Get("gorm:insert_option"); ok { extraOption = fmt.Sprint(str) } + if str, ok := scope.Get("gorm:insert_modifier"); ok { + insertModifier = strings.ToUpper(fmt.Sprint(str)) + if insertModifier == "INTO" { + insertModifier = "" + } + } if primaryField != nil { returningColumn = scope.Quote(primaryField.DBName) @@ -97,7 +104,8 @@ func createCallback(scope *Scope) { if len(columns) == 0 { scope.Raw(fmt.Sprintf( - "INSERT INTO %v %v%v%v", + "INSERT %v INTO %v %v%v%v", + addExtraSpaceIfExist(insertModifier), quotedTableName, scope.Dialect().DefaultValueStr(), addExtraSpaceIfExist(extraOption), @@ -105,7 +113,8 @@ func createCallback(scope *Scope) { )) } else { scope.Raw(fmt.Sprintf( - "INSERT INTO %v (%v) VALUES (%v)%v%v", + "INSERT %v INTO %v (%v) VALUES (%v)%v%v", + addExtraSpaceIfExist(insertModifier), scope.QuotedTableName(), strings.Join(columns, ","), strings.Join(placeholders, ","), diff --git a/create_test.go b/create_test.go index 925606437..450dd8a44 100644 --- a/create_test.go +++ b/create_test.go @@ -229,3 +229,20 @@ func TestOmitWithCreate(t *testing.T) { t.Errorf("Should not create omitted relationships") } } + +func TestCreateIgnore(t *testing.T) { + float := 35.03554004971999 + now := time.Now() + user := User{Name: "CreateUser", Age: 18, Birthday: &now, UserNum: Num(111), PasswordHash: []byte{'f', 'a', 'k', '4'}, Latitude: float} + + if !DB.NewRecord(user) || !DB.NewRecord(&user) { + t.Error("User should be new record before create") + } + + if count := DB.Create(&user).RowsAffected; count != 1 { + t.Error("There should be one record be affected when create record") + } + if DB.Dialect().GetName() == "mysql" && DB.Set("gorm:insert_modifier", "IGNORE").Create(&user).Error != nil { + t.Error("Should ignore duplicate user insert by insert modifier:IGNORE ") + } +}