Skip to content

Commit

Permalink
Memoise NewTable
Browse files Browse the repository at this point in the history
a

e
  • Loading branch information
sentriz committed Aug 27, 2024
1 parent d57b5c9 commit d776afb
Showing 1 changed file with 25 additions and 2 deletions.
27 changes: 25 additions & 2 deletions table.go
Original file line number Diff line number Diff line change
@@ -1,13 +1,30 @@
package crud

import (
"reflect"
"sync"

"github.com/azer/crud/v2/meta"
"github.com/azer/crud/v2/sql"
)

var (
tableCache = map[reflect.Type]*Table{}
tableCacheMu sync.RWMutex
)

// Create an internal representation of a database table, including its fields from given
// struct record
func NewTable(any interface{}) (*Table, error) {
anyT := reflect.TypeOf(any)

tableCacheMu.RLock()
if t, ok := tableCache[anyT]; ok {
tableCacheMu.RUnlock()
return t, nil
}
tableCacheMu.RUnlock()

if meta.IsSlice(any) {
any = meta.CreateElement(any).Interface()
}
Expand All @@ -21,11 +38,17 @@ func NewTable(any interface{}) (*Table, error) {

name, sqlName := ReadTableName(any)

return &Table{
t := &Table{
Name: name,
SQLName: sqlName,
Fields: fields,
}, nil
}

tableCacheMu.Lock()
tableCache[anyT] = t
tableCacheMu.Unlock()

return t, nil
}

type Table struct {
Expand Down

0 comments on commit d776afb

Please sign in to comment.