From 60fac3033588eee23b68f8fe4ef2878697aa4038 Mon Sep 17 00:00:00 2001 From: sunyuanhua Date: Thu, 4 Feb 2021 17:04:34 +0800 Subject: [PATCH] replace parser cached interface with dest interface --- schema/schema.go | 3 ++- schema/schema_test.go | 25 +++++++++++++++++++++++++ 2 files changed, 27 insertions(+), 1 deletion(-) diff --git a/schema/schema.go b/schema/schema.go index e36ed7b6..9682ca15 100644 --- a/schema/schema.go +++ b/schema/schema.go @@ -97,7 +97,8 @@ func Parse(dest interface{}, cacheStore *sync.Map, namer Namer) (*Schema, error) modelValue := reflect.New(modelType) tableName := namer.TableName(modelType.Name()) - if tabler, ok := modelValue.Interface().(Tabler); ok { + //if tabler, ok := modelValue.Interface().(Tabler); ok { + if tabler, ok := dest.(Tabler); ok { tableName = tabler.TableName() } if en, ok := namer.(embeddedNamer); ok { diff --git a/schema/schema_test.go b/schema/schema_test.go index a426cd90..911be7c0 100644 --- a/schema/schema_test.go +++ b/schema/schema_test.go @@ -1,6 +1,7 @@ package schema_test import ( + "fmt" "strings" "sync" "testing" @@ -297,3 +298,27 @@ func TestEmbeddedStructForCustomizedNamingStrategy(t *testing.T) { }) } } + + +type DynamicTable struct { + ID int +} + +func (d *DynamicTable) TableName() string { + return fmt.Sprintf("dynamic_%d",d.ID) +} + +func TestDynamicTableName(t *testing.T) { + for i:=0;i<=10;i++ { + dt := &DynamicTable{ID:i} + dynamic, err := schema.Parse(dt, &sync.Map{}, schema.NamingStrategy{}) + if err != nil { + t.Fatalf("failed to parse pointer user, got error %v", err) + } + + if dynamic.Table != dt.TableName(){ + t.Errorf("Failed to customize table with TableName method") + } + } +} +