forked from mirror/gorm
add mysql insert modifiers (#2269)
This commit is contained in:
parent
d239c4cab8
commit
8b07437717
|
@ -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, ","),
|
||||
|
|
|
@ -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 ")
|
||||
}
|
||||
}
|
||||
|
|
Loading…
Reference in New Issue