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 }