advsql/old/object_structure.go

35 lines
882 B
Go
Raw Permalink Normal View History

2022-07-05 12:44:25 +02:00
package advsql
import (
"reflect"
"errors"
)
var ErrNoStructure = errors.New("value is not of type structure")
// analyze returns the structure of value
func objectStructure(value interface{}) (*structure, error) {
t := reflect.TypeOf(value)
k := t.Kind()
// only structs are allowed to be stored in DB
// if pointer: dereference and check again via recursion
if k == reflect.Ptr {
v := reflect.ValueOf(value)
return objectStructure(reflect.Indirect(v).Interface())
} else if k != reflect.Struct {
return nil, ErrNoStructure
}
fieldAmount := t.NumField()
structure := new(structure)
structure.TypeName = t.Name()
structure.Fields = make([]field, fieldAmount)
for fieldIndex := 0; fieldIndex < fieldAmount; fieldIndex++ {
reflectField := t.Field(fieldIndex)
structure.Fields[fieldIndex] = makeFieldUsingReflect(reflectField)
}
return structure, nil
}