Skip to content

Commit

Permalink
add mysql insert modifiers (go-gorm#2269)
Browse files Browse the repository at this point in the history
  • Loading branch information
kync authored and jinzhu committed Mar 10, 2019
1 parent d239c4c commit 8b07437
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 2 deletions.
13 changes: 11 additions & 2 deletions callback_create.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand All @@ -97,15 +104,17 @@ 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),
addExtraSpaceIfExist(lastInsertIDReturningSuffix),
))
} 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, ","),
Expand Down
17 changes: 17 additions & 0 deletions create_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 ")
}
}

0 comments on commit 8b07437

Please sign in to comment.