github.com/safing/portbase@v0.19.5/database/query/condition-float.go (about) 1 package query 2 3 import ( 4 "errors" 5 "fmt" 6 "strconv" 7 8 "github.com/safing/portbase/database/accessor" 9 ) 10 11 type floatCondition struct { 12 key string 13 operator uint8 14 value float64 15 } 16 17 func newFloatCondition(key string, operator uint8, value interface{}) *floatCondition { 18 var parsedValue float64 19 20 switch v := value.(type) { 21 case int: 22 parsedValue = float64(v) 23 case int8: 24 parsedValue = float64(v) 25 case int16: 26 parsedValue = float64(v) 27 case int32: 28 parsedValue = float64(v) 29 case int64: 30 parsedValue = float64(v) 31 case uint: 32 parsedValue = float64(v) 33 case uint8: 34 parsedValue = float64(v) 35 case uint16: 36 parsedValue = float64(v) 37 case uint32: 38 parsedValue = float64(v) 39 case float32: 40 parsedValue = float64(v) 41 case float64: 42 parsedValue = v 43 case string: 44 var err error 45 parsedValue, err = strconv.ParseFloat(v, 64) 46 if err != nil { 47 return &floatCondition{ 48 key: fmt.Sprintf("could not parse %s to float64: %s", v, err), 49 operator: errorPresent, 50 } 51 } 52 default: 53 return &floatCondition{ 54 key: fmt.Sprintf("incompatible value %v for float64", value), 55 operator: errorPresent, 56 } 57 } 58 59 return &floatCondition{ 60 key: key, 61 operator: operator, 62 value: parsedValue, 63 } 64 } 65 66 func (c *floatCondition) complies(acc accessor.Accessor) bool { 67 comp, ok := acc.GetFloat(c.key) 68 if !ok { 69 return false 70 } 71 72 switch c.operator { 73 case FloatEquals: 74 return comp == c.value 75 case FloatGreaterThan: 76 return comp > c.value 77 case FloatGreaterThanOrEqual: 78 return comp >= c.value 79 case FloatLessThan: 80 return comp < c.value 81 case FloatLessThanOrEqual: 82 return comp <= c.value 83 default: 84 return false 85 } 86 } 87 88 func (c *floatCondition) check() error { 89 if c.operator == errorPresent { 90 return errors.New(c.key) 91 } 92 return nil 93 } 94 95 func (c *floatCondition) string() string { 96 return fmt.Sprintf("%s %s %g", escapeString(c.key), getOpName(c.operator), c.value) 97 }