mirror of https://github.com/go-gorm/gorm.git
fix: on confilct with default null (#6129)
* fix: on confilct with default null * Update create.go --------- Co-authored-by: Jinzhu <wosmvp@gmail.com>
This commit is contained in:
parent
85eaf9eeda
commit
e9f25c73ee
|
@ -3,6 +3,7 @@ package callbacks
|
|||
import (
|
||||
"fmt"
|
||||
"reflect"
|
||||
"strings"
|
||||
|
||||
"gorm.io/gorm"
|
||||
"gorm.io/gorm/clause"
|
||||
|
@ -302,7 +303,8 @@ func ConvertToCreateValues(stmt *gorm.Statement) (values clause.Values) {
|
|||
for _, column := range values.Columns {
|
||||
if field := stmt.Schema.LookUpField(column.Name); field != nil {
|
||||
if v, ok := selectColumns[field.DBName]; (ok && v) || (!ok && !restricted) {
|
||||
if !field.PrimaryKey && (!field.HasDefaultValue || field.DefaultValueInterface != nil) && field.AutoCreateTime == 0 {
|
||||
if !field.PrimaryKey && (!field.HasDefaultValue || field.DefaultValueInterface != nil ||
|
||||
strings.EqualFold(field.DefaultValue, "NULL")) && field.AutoCreateTime == 0 {
|
||||
if field.AutoUpdateTime > 0 {
|
||||
assignment := clause.Assignment{Column: clause.Column{Name: field.DBName}, Value: curTime}
|
||||
switch field.AutoUpdateTime {
|
||||
|
|
|
@ -547,3 +547,39 @@ func TestFirstOrCreateRowsAffected(t *testing.T) {
|
|||
t.Fatalf("first or create rows affect err:%v rows:%d", res.Error, res.RowsAffected)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCreateOnConfilctWithDefalutNull(t *testing.T) {
|
||||
type OnConfilctUser struct {
|
||||
ID string
|
||||
Name string `gorm:"default:null"`
|
||||
Email string
|
||||
Mobile string `gorm:"default:'133xxxx'"`
|
||||
}
|
||||
|
||||
err := DB.Migrator().DropTable(&OnConfilctUser{})
|
||||
AssertEqual(t, err, nil)
|
||||
err = DB.AutoMigrate(&OnConfilctUser{})
|
||||
AssertEqual(t, err, nil)
|
||||
|
||||
u := OnConfilctUser{
|
||||
ID: "on-confilct-user-id",
|
||||
Name: "on-confilct-user-name",
|
||||
Email: "on-confilct-user-email",
|
||||
Mobile: "on-confilct-user-mobile",
|
||||
}
|
||||
err = DB.Create(&u).Error
|
||||
AssertEqual(t, err, nil)
|
||||
|
||||
u.Name = "on-confilct-user-name-2"
|
||||
u.Email = "on-confilct-user-email-2"
|
||||
u.Mobile = ""
|
||||
err = DB.Clauses(clause.OnConflict{UpdateAll: true}).Create(&u).Error
|
||||
AssertEqual(t, err, nil)
|
||||
|
||||
var u2 OnConfilctUser
|
||||
err = DB.Where("id = ?", u.ID).First(&u2).Error
|
||||
AssertEqual(t, err, nil)
|
||||
AssertEqual(t, u2.Name, "on-confilct-user-name-2")
|
||||
AssertEqual(t, u2.Email, "on-confilct-user-email-2")
|
||||
AssertEqual(t, u2.Mobile, "133xxxx")
|
||||
}
|
||||
|
|
Loading…
Reference in New Issue