initial commit

This commit is contained in:
Andriy Cherniy 2024-12-27 11:22:56 +02:00
commit 3115c6b782
2 changed files with 75 additions and 0 deletions

72
db/struct_reflect.go Normal file
View file

@ -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
}

3
go.mod Normal file
View file

@ -0,0 +1,3 @@
module git.m0e.space/qugalet/qutils
go 1.23.4