Working on Structure Reflection

This commit is contained in:
Brian Buller 2023-05-25 11:11:41 -05:00
parent 4131d1be15
commit 0ac08f775e
3 changed files with 121 additions and 0 deletions

83
bolteasable.go Normal file
View File

@ -0,0 +1,83 @@
package boltease
import (
"reflect"
)
func (b *DB) LoadStruct(path []string, dest interface{}) error {
return nil
}
func (b *DB) SaveStruct(path []string, src interface{}) error {
t := reflect.TypeOf(src)
fields := reflect.VisibleFields(t)
// Build the PropertyList
var props PropertyList
for _, fld := range fields {
if FieldIgnored(fld) {
continue
}
p := Property{
Path: path,
Name: FieldName(fld),
Value: reflect.ValueOf(fld),
}
props = append(props, p)
}
return b.SavePropertyList(path, &props)
}
type Property struct {
Path []string
Name string
Value reflect.Value
}
func PropertyValueToInterface(val reflect.Value) interface{} {
if val.CanInterface() {
return val.Interface()
}
switch val.Kind() {
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
return val.Int()
case reflect.Bool:
return val.Bool()
case reflect.String:
return val.String()
default:
return val.Bytes()
}
}
func FieldName(fld reflect.StructField) string {
nm := fld.Name
tag := fld.Tag.Get("boltease")
if tag != "" {
nm = tag
}
return nm
}
func FieldIgnored(fld reflect.StructField) bool {
return fld.Tag.Get("boltease") == "-"
}
type PropertyList []Property
func (b *DB) LoadPropertyList(path []string) (*PropertyList, error) {
return nil, nil
}
func (b *DB) SavePropertyList(path []string, l *PropertyList) error {
// Make sure the path exists
err := b.MkBucketPath(path)
if err != nil {
return err
}
for _, prop := range *l {
propPath := append(path, prop.Path...)
err = b.MkBucketPath(propPath)
if err != nil {
return err
}
b.Set(propPath, prop.Name, prop.Value)
}
return nil
}

View File

@ -5,6 +5,7 @@ import (
"errors"
"fmt"
"os"
"reflect"
"strconv"
"strings"
"time"
@ -103,6 +104,8 @@ func (b *DB) MkBucketPath(path []string) error {
func (b *DB) Set(path []string, key string, val interface{}) error {
switch v := val.(type) {
case reflect.Value:
return b.Set(path, key, PropertyValueToInterface(v))
case string:
return b.SetString(path, key, v)
case int:

35
example/main.go Normal file
View File

@ -0,0 +1,35 @@
package main
import (
"fmt"
"os"
"git.bullercodeworks.com/brian/boltease"
)
type ExampleType struct {
Name string `boltease:"name"`
Age int `boltease:"age"`
}
type ExampleSubType struct {
SubName string `boltease:"subname"`
}
func main() {
db, err := boltease.Create("example.db", 0600, nil)
if err != nil {
fmt.Printf("Error Opening File: %s\n", err.Error())
os.Exit(1)
}
err = db.SaveStruct(
[]string{"examples", "example1"},
ExampleType{
Name: "Example 1",
Age: 5,
})
if err != nil {
fmt.Printf("Error saving struct: %s\n", err.Error())
os.Exit(1)
}
}