summaryrefslogtreecommitdiff
path: root/db/struct_reflect.go
diff options
context:
space:
mode:
authorAndriy Cherniy <qugalet@m0e.space>2024-12-27 11:22:56 +0200
committerAndriy Cherniy <qugalet@m0e.space>2024-12-27 11:22:56 +0200
commit3115c6b782a8d410023a4427e3b5f5dcdfb14d6b (patch)
tree4ef1493897233b88babf6e917845142f764b52dc /db/struct_reflect.go
downloadqutils-3115c6b782a8d410023a4427e3b5f5dcdfb14d6b.tar.gz
qutils-3115c6b782a8d410023a4427e3b5f5dcdfb14d6b.zip
initial commit
Diffstat (limited to 'db/struct_reflect.go')
-rw-r--r--db/struct_reflect.go72
1 files changed, 72 insertions, 0 deletions
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
+}