浏览代码

bug fixed for empty struct when update

xormplus 9 年之前
父节点
当前提交
1601c637cd
共有 3 个文件被更改,包括 35 次插入10 次删除
  1. 20 0
      helpers.go
  2. 14 9
      statement.go
  3. 1 1
      xorm.go

+ 20 - 0
helpers.go

@@ -147,6 +147,26 @@ func isZero(k interface{}) bool {
 	return false
 }
 
+func isStructZero(v reflect.Value) bool {
+	for i := 0; i < v.NumField(); i++ {
+		field := v.Field(i)
+		switch field.Kind() {
+		case reflect.Ptr:
+			field = field.Elem()
+			fallthrough
+		case reflect.Struct:
+			if !isStructZero(field) {
+				return false
+			}
+		default:
+			if !isZero(field.Interface()) {
+				return false
+			}
+		}
+	}
+	return true
+}
+
 func int64ToIntValue(id int64, tp reflect.Type) reflect.Value {
 	var v interface{}
 	switch tp.Kind() {

+ 14 - 9
statement.go

@@ -352,7 +352,7 @@ func buildUpdates(engine *Engine, table *core.Table, bean interface{},
 						if len(table.PrimaryKeys) == 1 {
 							pkField := reflect.Indirect(fieldValue).FieldByName(table.PKColumns()[0].FieldName)
 							// fix non-int pk issues
-							if pkField.IsValid() && !isZero(pkField.Interface()) {
+							if pkField.IsValid() && (!requiredField && !isZero(pkField.Interface())) {
 								val = pkField.Interface()
 							} else {
 								continue
@@ -365,14 +365,19 @@ func buildUpdates(engine *Engine, table *core.Table, bean interface{},
 						val = fieldValue.Interface()
 					}
 				} else {
-					bytes, err := json.Marshal(fieldValue.Interface())
-					if err != nil {
-						panic(fmt.Sprintf("mashal %v failed", fieldValue.Interface()))
-					}
-					if col.SQLType.IsText() {
-						val = string(bytes)
-					} else if col.SQLType.IsBlob() {
-						val = bytes
+					// Blank struct could not be as update data
+					if requiredField || !isStructZero(fieldValue) {
+						bytes, err := json.Marshal(fieldValue.Interface())
+						if err != nil {
+							panic(fmt.Sprintf("mashal %v failed", fieldValue.Interface()))
+						}
+						if col.SQLType.IsText() {
+							val = string(bytes)
+						} else if col.SQLType.IsBlob() {
+							val = bytes
+						}
+					} else {
+						continue
 					}
 				}
 			}

+ 1 - 1
xorm.go

@@ -16,7 +16,7 @@ import (
 )
 
 const (
-	Version string = "0.5.4.0422"
+	Version string = "0.5.4.0427"
 )
 
 func regDrvsNDialects() bool {