1
This commit is contained in:
parent
6c4d17e4fe
commit
2282591789
55
metatable.go
55
metatable.go
@ -2,6 +2,11 @@ package f5
|
||||
|
||||
import (
|
||||
"reflect"
|
||||
"q5"
|
||||
"os"
|
||||
"bufio"
|
||||
"fmt"
|
||||
"encoding/json"
|
||||
)
|
||||
|
||||
type MetaTable interface {
|
||||
@ -12,8 +17,8 @@ type MetaTable interface {
|
||||
PostInit1()
|
||||
}
|
||||
|
||||
type LoadFromJson interface {
|
||||
LoadFromJsonStr(string)
|
||||
type LoadFromKeyValue interface {
|
||||
LoadFromKv(map[string]interface{})
|
||||
}
|
||||
|
||||
type RawMetaTable[T any] struct {
|
||||
@ -86,10 +91,50 @@ func (this *IdMetaTable[T]) GetById(id int64) *T {
|
||||
}
|
||||
}
|
||||
|
||||
func (this *IdMetaTable[T]) Load() {
|
||||
func (this *RawMetaTable[T]) Load() {
|
||||
if this.NoLoad {
|
||||
return
|
||||
}
|
||||
if f, err := os.Open(this.FileName); err == nil {
|
||||
jsonStr, _ := bufio.NewReader(f).ReadString(0)
|
||||
switch q5.JsonStrType(jsonStr) {
|
||||
case q5.JSON_ARRAY:
|
||||
break
|
||||
case q5.JSON_OBJECT:
|
||||
jsonStr = "[" + jsonStr + "]"
|
||||
default:
|
||||
panic(fmt.Sprintf("error json format %s", this.FileName))
|
||||
}
|
||||
var rows []map[string]interface{}
|
||||
json.Unmarshal([]byte(jsonStr), &rows)
|
||||
for _, row := range rows {
|
||||
var obj = new(T)
|
||||
var x interface{} = obj
|
||||
if loader, ok := x.(LoadFromKeyValue); ok {
|
||||
loader.LoadFromKv(row)
|
||||
}
|
||||
this.rawList = append(this.rawList, obj)
|
||||
}
|
||||
} else {
|
||||
panic(fmt.Sprintf("load metafile error %s %s", this.FileName, err))
|
||||
}
|
||||
}
|
||||
|
||||
func (this *IdMetaTable[T]) Load() {
|
||||
this.RawMetaTable.Load()
|
||||
i := int64(0)
|
||||
getFuncName := "Get" + q5.ConvertUpperCamelCase(this.PrimKey)
|
||||
this.Traverse(func (obj *T) bool {
|
||||
if this.PrimKey == "" {
|
||||
this.idHash[i] = obj
|
||||
} else {
|
||||
ele := reflect.ValueOf(obj).Elem()
|
||||
in := []reflect.Value{}
|
||||
ele.FieldByName(getFuncName).Call(in)
|
||||
}
|
||||
i++
|
||||
return true
|
||||
})
|
||||
}
|
||||
|
||||
func (this *NameMetaTable[T]) GetByName(name string) *T {
|
||||
@ -101,9 +146,7 @@ func (this *NameMetaTable[T]) GetByName(name string) *T {
|
||||
}
|
||||
|
||||
func (this *NameMetaTable[T]) Load() {
|
||||
if this.NoLoad {
|
||||
return
|
||||
}
|
||||
this.RawMetaTable.Load()
|
||||
}
|
||||
|
||||
func LoadMetaTable(table interface{}) {
|
||||
|
Loading…
x
Reference in New Issue
Block a user