From e3550c79694979587628fe0e3f4439a6af6bdf6c Mon Sep 17 00:00:00 2001 From: Lunny Xiao Date: Sun, 29 Apr 2018 19:58:25 +0800 Subject: [PATCH] fix some bug on extends find (#916) --- engine.go | 20 +++++++++++- session_find_test.go | 72 ++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 91 insertions(+), 1 deletion(-) diff --git a/engine.go b/engine.go index 4984d3746..f5af6d9d4 100644 --- a/engine.go +++ b/engine.go @@ -1091,7 +1091,25 @@ func (engine *Engine) idOfV(rv reflect.Value) (core.PK, error) { pk := make([]interface{}, len(table.PrimaryKeys)) for i, col := range table.PKColumns() { var err error - pkField := v.FieldByName(col.FieldName) + + fieldName := col.FieldName + for { + parts := strings.SplitN(fieldName, ".", 2) + if len(parts) == 1 { + break + } + + v = v.FieldByName(parts[0]) + if v.Kind() == reflect.Ptr { + v = v.Elem() + } + if v.Kind() != reflect.Struct { + return nil, ErrUnSupportedType + } + fieldName = parts[1] + } + fmt.Println(table.Name, fieldName, v) + pkField := v.FieldByName(fieldName) switch pkField.Kind() { case reflect.String: pk[i], err = engine.idTypeAssertion(col, pkField.String()) diff --git a/session_find_test.go b/session_find_test.go index 6a04dc57a..c215fd573 100644 --- a/session_find_test.go +++ b/session_find_test.go @@ -655,5 +655,77 @@ func TestFindMapStringId(t *testing.T) { cnt, err = testEngine.ID("1").Delete(new(FindMapDevice)) assert.NoError(t, err) assert.EqualValues(t, 1, cnt) +} + +func TestFindExtends(t *testing.T) { + type FindExtendsB struct { + ID int64 + } + + type FindExtendsA struct { + FindExtendsB `xorm:"extends"` + } + + assert.NoError(t, prepareEngine()) + assertSync(t, new(FindExtendsA)) + + cnt, err := testEngine.Insert(&FindExtendsA{ + FindExtendsB: FindExtendsB{}, + }) + assert.NoError(t, err) + assert.EqualValues(t, 1, cnt) + + cnt, err = testEngine.Insert(&FindExtendsA{ + FindExtendsB: FindExtendsB{}, + }) + assert.NoError(t, err) + assert.EqualValues(t, 1, cnt) + + var results []FindExtendsA + err = testEngine.Find(&results) + assert.NoError(t, err) + assert.EqualValues(t, 2, len(results)) +} + +func TestFindExtends3(t *testing.T) { + type FindExtendsCC struct { + ID int64 + Name string + } + + type FindExtendsBB struct { + FindExtendsCC `xorm:"extends"` + } + + type FindExtendsAA struct { + FindExtendsBB `xorm:"extends"` + } + assert.NoError(t, prepareEngine()) + assertSync(t, new(FindExtendsAA)) + + cnt, err := testEngine.Insert(&FindExtendsAA{ + FindExtendsBB: FindExtendsBB{ + FindExtendsCC: FindExtendsCC{ + Name: "cc1", + }, + }, + }) + assert.NoError(t, err) + assert.EqualValues(t, 1, cnt) + + cnt, err = testEngine.Insert(&FindExtendsAA{ + FindExtendsBB: FindExtendsBB{ + FindExtendsCC: FindExtendsCC{ + Name: "cc2", + }, + }, + }) + assert.NoError(t, err) + assert.EqualValues(t, 1, cnt) + + var results []FindExtendsAA + err = testEngine.Find(&results) + assert.NoError(t, err) + assert.EqualValues(t, 2, len(results)) }