github.com/safing/portbase@v0.19.5/database/query/condition-int.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 intCondition struct {
    12  	key      string
    13  	operator uint8
    14  	value    int64
    15  }
    16  
    17  func newIntCondition(key string, operator uint8, value interface{}) *intCondition {
    18  	var parsedValue int64
    19  
    20  	switch v := value.(type) {
    21  	case int:
    22  		parsedValue = int64(v)
    23  	case int8:
    24  		parsedValue = int64(v)
    25  	case int16:
    26  		parsedValue = int64(v)
    27  	case int32:
    28  		parsedValue = int64(v)
    29  	case int64:
    30  		parsedValue = v
    31  	case uint:
    32  		parsedValue = int64(v)
    33  	case uint8:
    34  		parsedValue = int64(v)
    35  	case uint16:
    36  		parsedValue = int64(v)
    37  	case uint32:
    38  		parsedValue = int64(v)
    39  	case string:
    40  		var err error
    41  		parsedValue, err = strconv.ParseInt(v, 10, 64)
    42  		if err != nil {
    43  			return &intCondition{
    44  				key:      fmt.Sprintf("could not parse %s to int64: %s (hint: use \"sameas\" to compare strings)", v, err),
    45  				operator: errorPresent,
    46  			}
    47  		}
    48  	default:
    49  		return &intCondition{
    50  			key:      fmt.Sprintf("incompatible value %v for int64", value),
    51  			operator: errorPresent,
    52  		}
    53  	}
    54  
    55  	return &intCondition{
    56  		key:      key,
    57  		operator: operator,
    58  		value:    parsedValue,
    59  	}
    60  }
    61  
    62  func (c *intCondition) complies(acc accessor.Accessor) bool {
    63  	comp, ok := acc.GetInt(c.key)
    64  	if !ok {
    65  		return false
    66  	}
    67  
    68  	switch c.operator {
    69  	case Equals:
    70  		return comp == c.value
    71  	case GreaterThan:
    72  		return comp > c.value
    73  	case GreaterThanOrEqual:
    74  		return comp >= c.value
    75  	case LessThan:
    76  		return comp < c.value
    77  	case LessThanOrEqual:
    78  		return comp <= c.value
    79  	default:
    80  		return false
    81  	}
    82  }
    83  
    84  func (c *intCondition) check() error {
    85  	if c.operator == errorPresent {
    86  		return errors.New(c.key)
    87  	}
    88  	return nil
    89  }
    90  
    91  func (c *intCondition) string() string {
    92  	return fmt.Sprintf("%s %s %d", escapeString(c.key), getOpName(c.operator), c.value)
    93  }