Upsert selected columns

This commit is contained in:
Jinzhu 2020-06-10 10:48:48 +08:00
parent f3424c6864
commit 0d58d5a3a7
2 changed files with 49 additions and 4 deletions

View File

@ -278,11 +278,11 @@ func ConvertToCreateValues(stmt *gorm.Statement) (values clause.Values) {
if stmt.UpdatingColumn {
if stmt.Schema != nil {
columns := make([]string, 0, len(stmt.Schema.DBNames)-1)
for _, name := range stmt.Schema.DBNames {
if field := stmt.Schema.LookUpField(name); field != nil {
columns := make([]string, 0, len(values.Columns)-1)
for _, column := range values.Columns {
if field := stmt.Schema.LookUpField(column.Name); field != nil {
if !field.PrimaryKey && !field.HasDefaultValue && field.AutoCreateTime == 0 {
columns = append(columns, name)
columns = append(columns, column.Name)
}
}
}

View File

@ -95,6 +95,7 @@ func TestUpsertWithSave(t *testing.T) {
{Code: "upsert-save-1", Name: "Upsert-save-1"},
{Code: "upsert-save-2", Name: "Upsert-save-2"},
}
if err := DB.Save(&langs).Error; err != nil {
t.Errorf("Failed to create, got error %v", err)
}
@ -103,8 +104,52 @@ func TestUpsertWithSave(t *testing.T) {
var result Language
if err := DB.First(&result, "code = ?", lang.Code).Error; err != nil {
t.Errorf("Failed to query lang, got error %v", err)
} else {
AssertEqual(t, result, lang)
}
}
for idx, lang := range langs {
lang.Name += "_new"
langs[idx] = lang
}
if err := DB.Save(&langs).Error; err != nil {
t.Errorf("Failed to upsert, got error %v", err)
}
for _, lang := range langs {
var result Language
if err := DB.First(&result, "code = ?", lang.Code).Error; err != nil {
t.Errorf("Failed to query lang, got error %v", err)
} else {
AssertEqual(t, result, lang)
}
}
// lang := Language{Code: "upsert-save-3", Name: "Upsert-save-3"}
// if err := DB.Save(&lang).Error; err != nil {
// t.Errorf("Failed to create, got error %v", err)
// }
// var result Language
// if err := DB.First(&result, "code = ?", lang.Code).Error; err != nil {
// t.Errorf("Failed to query lang, got error %v", err)
// } else {
// AssertEqual(t, result, lang)
// }
// lang.Name += "_new"
// if err := DB.Save(&lang).Error; err != nil {
// t.Errorf("Failed to create, got error %v", err)
// }
// var result2 Language
// if err := DB.First(&result2, "code = ?", lang.Code).Error; err != nil {
// t.Errorf("Failed to query lang, got error %v", err)
// } else {
// AssertEqual(t, result2, lang)
// }
}
func TestFindOrInitialize(t *testing.T) {