From a480bd85450d444d2526a309f2ecae07cac814c0 Mon Sep 17 00:00:00 2001 From: Chen Quan Date: Mon, 10 May 2021 09:51:50 +0800 Subject: [PATCH] Update Optimize schema (#4364) --- schema/schema.go | 19 +++++++++++-------- 1 file changed, 11 insertions(+), 8 deletions(-) diff --git a/schema/schema.go b/schema/schema.go index d08842e6..1ce88fa5 100644 --- a/schema/schema.go +++ b/schema/schema.go @@ -71,7 +71,7 @@ type Tabler interface { TableName() string } -// get data type from dialector +// Parse get data type from dialector func Parse(dest interface{}, cacheStore *sync.Map, namer Namer) (*Schema, error) { if dest == nil { return nil, fmt.Errorf("%w: %+v", ErrUnsupportedDataType, dest) @@ -91,6 +91,7 @@ func Parse(dest interface{}, cacheStore *sync.Map, namer Namer) (*Schema, error) if v, ok := cacheStore.Load(modelType); ok { s := v.(*Schema) + // Wait for the initialization of other goroutines to complete <-s.initialized return s, s.err } @@ -115,6 +116,15 @@ func Parse(dest interface{}, cacheStore *sync.Map, namer Namer) (*Schema, error) namer: namer, initialized: make(chan struct{}), } + // When the schema initialization is completed, the channel will be closed + defer close(schema.initialized) + + if v, loaded := cacheStore.LoadOrStore(modelType, schema); loaded { + s := v.(*Schema) + // Wait for the initialization of other goroutines to complete + <-s.initialized + return s, s.err + } defer func() { if schema.err != nil { @@ -223,13 +233,6 @@ func Parse(dest interface{}, cacheStore *sync.Map, namer Namer) (*Schema, error) } } - if v, loaded := cacheStore.LoadOrStore(modelType, schema); loaded { - s := v.(*Schema) - <-s.initialized - return s, s.err - } - - defer close(schema.initialized) if _, embedded := schema.cacheStore.Load(embeddedCacheKey); !embedded { for _, field := range schema.Fields { if field.DataType == "" && (field.Creatable || field.Updatable || field.Readable) {