forked from openflagr/flagr
/
constraint.go
95 lines (84 loc) · 2.54 KB
/
constraint.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
package entity
import (
"fmt"
"strings"
"github.com/paubox/paubox-flagr/swagger_gen/models"
"github.com/zhouzhuojie/conditions"
"gorm.io/gorm"
)
// Constraint is the unit of constraints
type Constraint struct {
gorm.Model
SegmentID uint `gorm:"index:idx_constraint_segmentid"`
Property string
Operator string
Value string `gorm:"type:text"`
}
// ConstraintArray is an array of Constraint
type ConstraintArray []Constraint
// OperatorToExprMap maps from the swagger model operator to condition operator
var OperatorToExprMap = map[string]string{
models.ConstraintOperatorEQ: "==",
models.ConstraintOperatorNEQ: "!=",
models.ConstraintOperatorLT: "<",
models.ConstraintOperatorLTE: "<=",
models.ConstraintOperatorGT: ">",
models.ConstraintOperatorGTE: ">=",
models.ConstraintOperatorEREG: "=~",
models.ConstraintOperatorNEREG: "!~",
models.ConstraintOperatorIN: "IN",
models.ConstraintOperatorNOTIN: "NOT IN",
models.ConstraintOperatorCONTAINS: "CONTAINS",
models.ConstraintOperatorNOTCONTAINS: "NOT CONTAINS",
}
// ToExpr transfer the constraint to conditions.Expr for evaluation
func (c *Constraint) ToExpr() (conditions.Expr, error) {
s, err := c.toExprStr()
if err != nil {
return nil, err
}
p := conditions.NewParser(strings.NewReader(s))
expr, err := p.Parse()
if err != nil {
return nil, fmt.Errorf("%s. Note: if it's string or array of string, warp it with quotes \"...\"", err)
}
return expr, nil
}
func (c *Constraint) toExprStr() (string, error) {
if c.Property == "" || c.Operator == "" || c.Value == "" {
return "", fmt.Errorf(
"empty Property/Operator/Value: %s/%s/%s",
c.Property,
c.Operator,
c.Value,
)
}
o, ok := OperatorToExprMap[c.Operator]
if !ok {
return "", fmt.Errorf("not supported operator: %s", c.Operator)
}
return fmt.Sprintf("({%s} %s %s)", c.Property, o, c.Value), nil
}
// Validate validates Constraint
func (c *Constraint) Validate() error {
_, err := c.ToExpr()
return err
}
// ToExpr maps ConstraintArray to expr by joining 'AND'
func (cs ConstraintArray) ToExpr() (conditions.Expr, error) {
strs := make([]string, 0, len(cs))
for _, c := range cs {
s, err := c.toExprStr()
if err != nil {
return nil, err
}
strs = append(strs, s)
}
exprStr := strings.Join(strs, " AND ")
p := conditions.NewParser(strings.NewReader(exprStr))
expr, err := p.Parse()
if err != nil {
return nil, fmt.Errorf("%s. Note: if it's string or array of string, wrap it with quotes \"...\"", err)
}
return expr, nil
}