Add more tests for Update

This commit is contained in:
Jinzhu 2020-03-08 13:24:08 +08:00
parent cbd55dbcd5
commit 2da0ad5bed
6 changed files with 169 additions and 38 deletions

View File

@ -13,6 +13,13 @@ func SelectAndOmitColumns(stmt *gorm.Statement) (map[string]bool, bool) {
// select columns
for _, column := range stmt.Selects {
if column == "*" {
for _, dbName := range stmt.Schema.DBNames {
results[dbName] = true
}
return results, true
}
if field := stmt.Schema.LookUpField(column); field != nil {
results[field.DBName] = true
} else {

View File

@ -3,6 +3,7 @@ package callbacks
import (
"reflect"
"sort"
"time"
"github.com/jinzhu/gorm"
"github.com/jinzhu/gorm/clause"
@ -89,13 +90,13 @@ func AfterUpdate(db *gorm.DB) {
}
// ConvertToAssignments convert to update assignments
func ConvertToAssignments(stmt *gorm.Statement) clause.Set {
func ConvertToAssignments(stmt *gorm.Statement) (set clause.Set) {
selectColumns, restricted := SelectAndOmitColumns(stmt)
reflectModelValue := reflect.ValueOf(stmt.Model)
switch value := stmt.Dest.(type) {
case map[string]interface{}:
var set clause.Set = make([]clause.Assignment, 0, len(value))
set = make([]clause.Assignment, 0, len(value))
var keys []string
for k, _ := range value {
@ -106,6 +107,9 @@ func ConvertToAssignments(stmt *gorm.Statement) clause.Set {
for _, k := range keys {
if field := stmt.Schema.LookUpField(k); field != nil {
if v, ok := selectColumns[field.DBName]; (ok && v) || (!ok && !restricted) {
if field.AutoUpdateTime > 0 {
value[k] = time.Now()
}
set = append(set, clause.Assignment{Column: clause.Column{Name: field.DBName}, Value: value[k]})
field.Set(reflectModelValue, value[k])
}
@ -114,21 +118,47 @@ func ConvertToAssignments(stmt *gorm.Statement) clause.Set {
}
}
return set
for _, field := range stmt.Schema.FieldsByDBName {
if field.AutoUpdateTime > 0 && value[field.Name] == nil && value[field.DBName] == nil {
now := time.Now()
set = append(set, clause.Assignment{Column: clause.Column{Name: field.DBName}, Value: now})
field.Set(reflectModelValue, now)
}
}
default:
switch stmt.ReflectValue.Kind() {
case reflect.Struct:
var set clause.Set = make([]clause.Assignment, 0, len(stmt.Schema.FieldsByDBName))
set = make([]clause.Assignment, 0, len(stmt.Schema.FieldsByDBName))
for _, field := range stmt.Schema.FieldsByDBName {
if v, ok := selectColumns[field.DBName]; (ok && v) || (!ok && !restricted) {
value, _ := field.ValueOf(stmt.ReflectValue)
set = append(set, clause.Assignment{Column: clause.Column{Name: field.DBName}, Value: value})
field.Set(reflectModelValue, value)
if !field.PrimaryKey || stmt.Dest != stmt.Model {
if v, ok := selectColumns[field.DBName]; (ok && v) || (!ok && !restricted) {
value, isZero := field.ValueOf(stmt.ReflectValue)
if field.AutoUpdateTime > 0 {
value = time.Now()
isZero = false
}
if ok || !isZero {
set = append(set, clause.Assignment{Column: clause.Column{Name: field.DBName}, Value: value})
field.Set(reflectModelValue, value)
}
}
} else {
if value, isZero := field.ValueOf(stmt.ReflectValue); !isZero {
stmt.AddClause(clause.Where{Exprs: []clause.Expression{clause.Eq{Column: field.DBName, Value: value}}})
}
}
}
return set
}
}
return clause.Set{}
if stmt.Dest != stmt.Model {
reflectValue := reflect.ValueOf(stmt.Model)
for _, field := range stmt.Schema.PrimaryFields {
if value, isZero := field.ValueOf(reflectValue); !isZero {
stmt.AddClause(clause.Where{Exprs: []clause.Expression{clause.Eq{Column: field.DBName, Value: value}}})
}
}
}
return
}

View File

@ -2,6 +2,7 @@ package gorm
import (
"database/sql"
"reflect"
"strings"
"github.com/jinzhu/gorm/clause"
@ -18,6 +19,26 @@ func (db *DB) Create(value interface{}) (tx *DB) {
// Save update value in database, if the value doesn't have primary key, will insert it
func (db *DB) Save(value interface{}) (tx *DB) {
tx = db.getInstance()
tx.Statement.Dest = value
if err := tx.Statement.Parse(value); err != nil && tx.Statement.Schema != nil {
where := clause.Where{Exprs: make([]clause.Expression, len(tx.Statement.Schema.PrimaryFields))}
reflectValue := reflect.ValueOf(value)
for idx, pf := range tx.Statement.Schema.PrimaryFields {
if pv, isZero := pf.ValueOf(reflectValue); isZero {
tx.callbacks.Create().Execute(tx)
where.Exprs[idx] = clause.Eq{Column: pf.DBName, Value: pv}
return
}
}
tx.Statement.AddClause(where)
}
if len(tx.Statement.Selects) == 0 {
tx.Statement.Selects = []string{"*"}
}
tx.callbacks.Update().Execute(tx)
return
}

View File

@ -164,22 +164,6 @@ func (schema *Schema) ParseField(fieldStruct reflect.StructField) *Field {
field.DBDataType = val
}
if v, ok := field.TagSettings["AUTOCREATETIME"]; ok || (field.Name == "CreatedAt" && (field.DataType == Time || field.DataType == Int)) {
if strings.ToUpper(v) == "NANO" {
field.AutoCreateTime = UnixNanosecond
} else {
field.AutoCreateTime = UnixSecond
}
}
if v, ok := field.TagSettings["AUTOUPDATETIME"]; ok || (field.Name == "UpdatedAt" && (field.DataType == Time || field.DataType == Int)) {
if strings.ToUpper(v) == "NANO" {
field.AutoUpdateTime = UnixNanosecond
} else {
field.AutoUpdateTime = UnixSecond
}
}
switch fieldValue.Elem().Kind() {
case reflect.Bool:
field.DataType = Bool
@ -218,6 +202,22 @@ func (schema *Schema) ParseField(fieldStruct reflect.StructField) *Field {
}
}
if v, ok := field.TagSettings["AUTOCREATETIME"]; ok || (field.Name == "CreatedAt" && (field.DataType == Time || field.DataType == Int)) {
if strings.ToUpper(v) == "NANO" {
field.AutoCreateTime = UnixNanosecond
} else {
field.AutoCreateTime = UnixSecond
}
}
if v, ok := field.TagSettings["AUTOUPDATETIME"]; ok || (field.Name == "UpdatedAt" && (field.DataType == Time || field.DataType == Int)) {
if strings.ToUpper(v) == "NANO" {
field.AutoUpdateTime = UnixNanosecond
} else {
field.AutoUpdateTime = UnixSecond
}
}
if field.Size == 0 {
switch fieldValue.Kind() {
case reflect.Int, reflect.Int64, reflect.Uint, reflect.Uint64, reflect.Float64:

View File

@ -1,7 +1,6 @@
package tests
import (
"log"
"reflect"
"strconv"
"testing"
@ -22,6 +21,7 @@ func RunTestsSuit(t *testing.T, db *gorm.DB) {
}
func TestCreate(t *testing.T, db *gorm.DB) {
db.Migrator().DropTable(&User{})
db.AutoMigrate(&User{})
t.Run("Create", func(t *testing.T) {
@ -39,6 +39,14 @@ func TestCreate(t *testing.T, db *gorm.DB) {
t.Errorf("user's primary key should has value after create, got : %v", user.ID)
}
if user.CreatedAt.IsZero() {
t.Errorf("user's created at should be not zero")
}
if user.UpdatedAt.IsZero() {
t.Errorf("user's updated at should be not zero")
}
var newUser User
if err := db.Where("id = ?", user.ID).First(&newUser).Error; err != nil {
t.Errorf("errors happened when query: %v", err)
@ -119,7 +127,6 @@ func TestFind(t *testing.T, db *gorm.DB) {
if err := db.Model(&User{}).Where("name = ?", "find").Find(&allMap).Error; err != nil {
t.Errorf("errors happened when query first: %v", err)
} else {
log.Printf("all map %+v %+v", len(allMap), allMap)
for idx, user := range users {
t.Run("FindAllMap#"+strconv.Itoa(idx+1), func(t *testing.T) {
for _, name := range []string{"Name", "Age", "Birthday"} {
@ -140,21 +147,64 @@ func TestUpdate(t *testing.T, db *gorm.DB) {
db.AutoMigrate(&User{})
t.Run("Update", func(t *testing.T) {
var user = User{
Name: "create",
Age: 18,
Birthday: Now(),
var (
users = []*User{{
Name: "update-before",
Age: 1,
Birthday: Now(),
}, {
Name: "update",
Age: 18,
Birthday: Now(),
}, {
Name: "update-after",
Age: 1,
Birthday: Now(),
}}
user = users[1]
lastUpdatedAt time.Time
)
checkUpdatedTime := func(name string, n time.Time) {
if n.UnixNano() == lastUpdatedAt.UnixNano() {
t.Errorf("%v: user's updated at should be changed, but got %v, was %v", name, n, lastUpdatedAt)
}
lastUpdatedAt = n
}
if err := db.Create(&user).Error; err != nil {
checkOtherData := func(name string) {
var beforeUser, afterUser User
if err := db.Where("id = ?", users[0].ID).First(&beforeUser).Error; err != nil {
t.Errorf("errors happened when query before user: %v", err)
}
t.Run(name, func(t *testing.T) {
AssertObjEqual(t, beforeUser, users[0], "Name", "Age", "Birthday")
})
if err := db.Where("id = ?", users[2].ID).First(&afterUser).Error; err != nil {
t.Errorf("errors happened when query after user: %v", err)
}
t.Run(name, func(t *testing.T) {
AssertObjEqual(t, afterUser, users[2], "Name", "Age", "Birthday")
})
}
if err := db.Create(&users).Error; err != nil {
t.Errorf("errors happened when create: %v", err)
} else if user.ID == 0 {
t.Errorf("user's primary value should not zero, %v", user.ID)
} else if user.UpdatedAt.IsZero() {
t.Errorf("user's updated at should not zero, %v", user.UpdatedAt)
}
lastUpdatedAt = user.UpdatedAt
if err := db.Model(&user).Update("Age", 10).Error; err != nil {
if err := db.Model(user).Update("Age", 10).Error; err != nil {
t.Errorf("errors happened when update: %v", err)
} else if user.Age != 10 {
t.Errorf("Age should equals to 10, but got %v", user.Age)
}
checkUpdatedTime("Update", user.UpdatedAt)
checkOtherData("Update")
var result User
if err := db.Where("id = ?", user.ID).First(&result).Error; err != nil {
@ -164,13 +214,15 @@ func TestUpdate(t *testing.T, db *gorm.DB) {
}
values := map[string]interface{}{"Active": true, "age": 5}
if err := db.Model(&user).Updates(values).Error; err != nil {
if err := db.Model(user).Updates(values).Error; err != nil {
t.Errorf("errors happened when update: %v", err)
} else if user.Age != 5 {
t.Errorf("Age should equals to 5, but got %v", user.Age)
} else if user.Active != true {
t.Errorf("Active should be true, but got %v", user.Active)
}
checkUpdatedTime("Updates with map", user.UpdatedAt)
checkOtherData("Updates with map")
var result2 User
if err := db.Where("id = ?", user.ID).First(&result2).Error; err != nil {
@ -179,11 +231,13 @@ func TestUpdate(t *testing.T, db *gorm.DB) {
AssertObjEqual(t, result2, user, "Name", "Age", "Birthday")
}
if err := db.Model(&user).Updates(User{Age: 2}).Error; err != nil {
if err := db.Model(user).Updates(User{Age: 2}).Error; err != nil {
t.Errorf("errors happened when update: %v", err)
} else if user.Age != 2 {
t.Errorf("Age should equals to 2, but got %v", user.Age)
}
checkUpdatedTime("Updates with struct", user.UpdatedAt)
checkOtherData("Updates with struct")
var result3 User
if err := db.Where("id = ?", user.ID).First(&result3).Error; err != nil {
@ -191,5 +245,24 @@ func TestUpdate(t *testing.T, db *gorm.DB) {
} else {
AssertObjEqual(t, result3, user, "Name", "Age", "Birthday")
}
user.Active = false
user.Age = 1
if err := db.Save(user).Error; err != nil {
t.Errorf("errors happened when update: %v", err)
} else if user.Age != 1 {
t.Errorf("Age should equals to 1, but got %v", user.Age)
} else if user.Active != false {
t.Errorf("Active should equals to false, but got %v", user.Active)
}
checkUpdatedTime("Save", user.UpdatedAt)
checkOtherData("Save")
var result4 User
if err := db.Where("id = ?", user.ID).First(&result4).Error; err != nil {
t.Errorf("errors happened when query: %v", err)
} else {
AssertObjEqual(t, result4, user, "Name", "Age", "Birthday")
}
})
}

View File

@ -6,8 +6,8 @@ import (
"runtime"
)
var goSrcRegexp = regexp.MustCompile(`/gorm/.*\.go`)
var goTestRegexp = regexp.MustCompile(`/gorm/.*test\.go`)
var goSrcRegexp = regexp.MustCompile(`/gorm/.*.go`)
var goTestRegexp = regexp.MustCompile(`/gorm/.*test.*.go`)
func FileWithLineNum() string {
for i := 2; i < 15; i++ {