From 251e372f72d43521da21f6a06055962de207c291 Mon Sep 17 00:00:00 2001 From: PhatPhuckDave Date: Sun, 27 Oct 2024 17:57:01 +0100 Subject: [PATCH] Implement query parser --- types.go | 8 ++++---- utils.go | 37 +++++++++++++++++++++++++++++++++++++ 2 files changed, 41 insertions(+), 4 deletions(-) create mode 100644 utils.go diff --git a/types.go b/types.go index 0fa21c6..0150b31 100644 --- a/types.go +++ b/types.go @@ -4,22 +4,22 @@ import "time" type ( Guild struct { - ID int + ID int64 Name string `json:"name"` } Player struct { - ID int + ID int64 Name string `json:"name"` Guild Guild `json:"guild"` } Association struct { - ID int + ID int64 LHS Player RHS Player Note string } Note struct { - ID int + ID int64 Content string Timestamp time.Time Player Player diff --git a/utils.go b/utils.go new file mode 100644 index 0000000..39c3b85 --- /dev/null +++ b/utils.go @@ -0,0 +1,37 @@ +package main + +import ( + "fmt" + "reflect" + "strings" +) + +func BuildWhereQuery(params interface{}) string { + conditions := []string{} + v := reflect.ValueOf(params) + t := v.Type() + + for i := 0; i < v.NumField(); i++ { + field := v.Field(i) + if field.Kind() == reflect.Ptr && !field.IsNil() { + dbTag := t.Field(i).Tag.Get("db") + if dbTag != "" { + switch field.Elem().Kind() { + case reflect.String: + conditions = append(conditions, fmt.Sprintf("%s = '%s'", dbTag, field.Elem().String())) + case reflect.Bool: + conditions = append(conditions, fmt.Sprintf("%s = %t", dbTag, field.Elem().Bool())) + case reflect.Int: + conditions = append(conditions, fmt.Sprintf("%s = %d", dbTag, field.Elem().Int())) + case reflect.Int64: + conditions = append(conditions, fmt.Sprintf("%s = %d", dbTag, field.Elem().Int())) + } + } + } + } + + if len(conditions) > 0 { + return "WHERE " + strings.Join(conditions, " AND ") + } + return "" +}