From 3115c6b782a8d410023a4427e3b5f5dcdfb14d6b Mon Sep 17 00:00:00 2001 From: Andriy Cherniy Date: Fri, 27 Dec 2024 11:22:56 +0200 Subject: [PATCH] initial commit --- db/struct_reflect.go | 72 ++++++++++++++++++++++++++++++++++++++++++++ go.mod | 3 ++ 2 files changed, 75 insertions(+) create mode 100644 db/struct_reflect.go create mode 100644 go.mod diff --git a/db/struct_reflect.go b/db/struct_reflect.go new file mode 100644 index 0000000..2e521da --- /dev/null +++ b/db/struct_reflect.go @@ -0,0 +1,72 @@ +package db + +import ( + "fmt" + "reflect" +) + +func StructToDBColumns(s any) ([]string, error) { + typ := reflect.TypeOf(s) + if typ.Kind() != reflect.Struct { + return nil, fmt.Errorf("%s is not a struct", typ) + } + + var res []string + + for i := 0; i < typ.NumField(); i++ { + fld := typ.Field(i) + + if column := fld.Tag.Get("params"); column == "nocreate" { + continue + } + if column := fld.Tag.Get("db"); column != "" { + res = append(res, column) + } + } + return res, nil +} + +func StructToDBValues(s any) ([]any, error) { + val := reflect.ValueOf(s) + typ := reflect.TypeOf(s) + if val.Kind() != reflect.Struct { + return nil, fmt.Errorf("%s is not a struct", val) + } + + var res []any + + for i := 0; i < val.NumField(); i++ { + if column := typ.Field(i).Tag.Get("params"); column == "nocreate" { + continue + } + // switch val.Field(i).Kind() { + // case reflect.Struct: + // structVal, err := StructToDBValues(val.Field(i).Interface()) + // if err != nil { + // return res, err + // } + // res = append(res, structVal...) + // default: + res = append(res, val.Field(i).Interface()) + // } + } + return res, nil +} + +func StructToUpdateMap(s any) (map[string]interface{}, error) { + val := reflect.ValueOf(s) + typ := reflect.TypeOf(s) + if val.Kind() != reflect.Struct { + return nil, fmt.Errorf("%s is not a struct", val) + } + + res := make(map[string]interface{}) + + for i := 0; i < val.NumField(); i++ { + if column := typ.Field(i).Tag.Get("params"); column == "noupdate" { + continue + } + res[typ.Field(i).Tag.Get("db")] = val.Field(i).Interface() + } + return res, nil +} diff --git a/go.mod b/go.mod new file mode 100644 index 0000000..7d1c070 --- /dev/null +++ b/go.mod @@ -0,0 +1,3 @@ +module git.m0e.space/qugalet/qutils + +go 1.23.4