瀏覽代碼

fix pk can't set value when pk is point value or rename

xormplus 8 年之前
父節點
當前提交
46f99cdce2
共有 2 個文件被更改,包括 64 次插入10 次删除
  1. 32 10
      helpers.go
  2. 32 0
      session_insert_test.go

+ 32 - 10
helpers.go

@@ -196,25 +196,43 @@ func isArrayValueZero(v reflect.Value) bool {
 
 func int64ToIntValue(id int64, tp reflect.Type) reflect.Value {
 	var v interface{}
-	switch tp.Kind() {
+	kind := tp.Kind()
+
+	if kind == reflect.Ptr {
+		kind = tp.Elem().Kind()
+	}
+
+	switch kind {
 	case reflect.Int16:
-		v = int16(id)
+		temp := int16(id)
+		v = &temp
 	case reflect.Int32:
-		v = int32(id)
+		temp := int32(id)
+		v = &temp
 	case reflect.Int:
-		v = int(id)
+		temp := int(id)
+		v = &temp
 	case reflect.Int64:
-		v = id
+		temp := id
+		v = &temp
 	case reflect.Uint16:
-		v = uint16(id)
+		temp := uint16(id)
+		v = &temp
 	case reflect.Uint32:
-		v = uint32(id)
+		temp := uint32(id)
+		v = &temp
 	case reflect.Uint64:
-		v = uint64(id)
+		temp := uint64(id)
+		v = &temp
 	case reflect.Uint:
-		v = uint(id)
+		temp := uint(id)
+		v = &temp
 	}
-	return reflect.ValueOf(v).Convert(tp)
+
+	if tp.Kind() == reflect.Ptr {
+		return reflect.ValueOf(v).Convert(tp)
+	}
+	return reflect.ValueOf(v).Elem().Convert(tp)
 }
 
 func int64ToInt(id int64, tp reflect.Type) interface{} {
@@ -537,6 +555,10 @@ func genCols(table *core.Table, session *Session, bean interface{}, useCol bool,
 				if len(fieldValue.String()) == 0 {
 					continue
 				}
+			case reflect.Ptr:
+				if fieldValue.Pointer() == 0 {
+					continue
+				}
 			}
 		}
 

+ 32 - 0
session_insert_test.go

@@ -42,3 +42,35 @@ func TestInsertOne2(t *testing.T) {
 	_, err := testEngine.InsertOne(data)
 	assert.NoError(t, err)
 }
+
+func TestInsertOneIfPkIsPoint(t *testing.T) {
+	assert.NoError(t, prepareEngine())
+
+	type TestPoint struct {
+		Id      *int64     `xorm:"autoincr pk notnull 'id'"`
+		Msg     *string    `xorm:"varchar(255)"`
+		Created *time.Time `xorm:"created"`
+	}
+
+	assert.NoError(t, testEngine.Sync2(new(TestPoint)))
+	msg := "hi"
+	data := TestPoint{Msg: &msg}
+	_, err := testEngine.InsertOne(&data)
+	assert.NoError(t, err)
+}
+
+func TestInsertOneIfPkIsPointRename(t *testing.T) {
+	assert.NoError(t, prepareEngine())
+	type ID *int64
+	type TestPoint struct {
+		Id      ID         `xorm:"autoincr pk notnull 'id'"`
+		Msg     *string    `xorm:"varchar(255)"`
+		Created *time.Time `xorm:"created"`
+	}
+
+	assert.NoError(t, testEngine.Sync2(new(TestPoint)))
+	msg := "hi"
+	data := TestPoint{Msg: &msg}
+	_, err := testEngine.InsertOne(&data)
+	assert.NoError(t, err)
+}