forked from ebhomengo/niki
fix(BuildFilterQuery): use regex to validate date and date time
Signed-off-by: Reza Mobaraki <rezam578@gmail.com>
This commit is contained in:
parent
e006ff5898
commit
cc53a7ddc8
|
|
@ -2,23 +2,20 @@ package mysqlquerybuilder
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"fmt"
|
"fmt"
|
||||||
"reflect"
|
"regexp"
|
||||||
"time"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
const DateFormat = "2006-01-02"
|
var datePattern = regexp.MustCompile(`^\d{4}-\d{2}-\d{2}(T\d{2}:\d{2}:\d{2}Z)?$`)
|
||||||
|
|
||||||
func isTimeType(value interface{}) bool {
|
func isValidDateOrDateTime(value string) bool {
|
||||||
return reflect.TypeOf(value) == reflect.TypeOf(time.Time{})
|
return datePattern.MatchString(value)
|
||||||
}
|
}
|
||||||
|
|
||||||
// BuildFilterQuery constructs the query and handles datetime fields
|
|
||||||
func BuildFilterQuery(filter map[string]interface{}) (filterQuery string, args []any) {
|
func BuildFilterQuery(filter map[string]interface{}) (filterQuery string, args []any) {
|
||||||
for key, value := range filter {
|
for key, value := range filter {
|
||||||
if isTimeType(value) {
|
if strVal, ok := value.(string); ok && isValidDateOrDateTime(strVal) {
|
||||||
filterQuery += fmt.Sprintf("AND DATE(%s) = ? ", key)
|
filterQuery += fmt.Sprintf("AND DATE(%s) = ? ", key)
|
||||||
dateValue := value.(time.Time).Format(DateFormat)
|
args = append(args, strVal)
|
||||||
args = append(args, dateValue)
|
|
||||||
} else {
|
} else {
|
||||||
filterQuery += fmt.Sprintf("AND %s = ? ", key)
|
filterQuery += fmt.Sprintf("AND %s = ? ", key)
|
||||||
args = append(args, value)
|
args = append(args, value)
|
||||||
|
|
|
||||||
Loading…
Reference in New Issue