Skip to content

Commit

Permalink
Cache columeToIndexFieldMap
Browse files Browse the repository at this point in the history
  • Loading branch information
zolstein committed Mar 25, 2024
1 parent 041a992 commit aaeacbd
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 0 deletions.
4 changes: 4 additions & 0 deletions dbscan/dbscan.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import (
"reflect"
"regexp"
"strings"
"sync"
)

// Rows is an abstract database rows that dbscan can iterate over and get the data from.
Expand Down Expand Up @@ -54,13 +55,16 @@ func SnakeCaseMapper(str string) string {

// API is the core type in dbscan. It implements all the logic and exposes functionality available in the package.
// With API type users can create a custom API instance and override default settings hence configure dbscan.
// API should not be copied after first use.
type API struct {
structTagKey string
columnSeparator string
fieldMapperFn NameMapperFunc
scannableTypesOption []interface{}
scannableTypesReflect []reflect.Type
allowUnknownColumns bool
// columnToIndexFieldMapCache stores a map of reflect.Type -> map[string][]int
columnToIndexFieldMapCache sync.Map
}

// APIOption is a function type that changes API configuration.
Expand Down
12 changes: 12 additions & 0 deletions dbscan/structref.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,18 @@ type toTraverse struct {
}

func (api *API) getColumnToFieldIndexMap(structType reflect.Type) map[string][]int {
resultIface, ok := api.columnToIndexFieldMapCache.Load(structType)
if ok {
return resultIface.(map[string][]int)
}

result := api.buildColumnToFieldIndexMap(structType)
resultIface, _ = api.columnToIndexFieldMapCache.LoadOrStore(structType, result)
result = resultIface.(map[string][]int)
return result
}

func (api *API) buildColumnToFieldIndexMap(structType reflect.Type) map[string][]int {
result := make(map[string][]int, structType.NumField())
var queue []*toTraverse
queue = append(queue, &toTraverse{Type: structType, IndexPrefix: nil, ColumnPrefix: ""})
Expand Down

0 comments on commit aaeacbd

Please sign in to comment.