-
Notifications
You must be signed in to change notification settings - Fork 2
/
visitor.go
102 lines (82 loc) · 1.88 KB
/
visitor.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
96
97
98
99
100
101
102
package mgs
import (
"fmt"
"strings"
"github.com/ajclopez/mgs/parser"
"github.com/antlr4-go/antlr/v4"
)
type Visitor struct {
*parser.BaseQueryVisitor
QueryHandler *QueryHandler
Caster *map[string]CastType
}
func NewGeneratorVisitor(qh *QueryHandler, caster *map[string]CastType) *Visitor {
return &Visitor{
QueryHandler: qh,
Caster: caster,
}
}
func (v *Visitor) Visit(tree antlr.ParseTree) interface{} {
return tree.Accept(v)
}
func (v *Visitor) VisitInput(ctx *parser.InputContext) interface{} {
if ctx == nil {
return ErrQueryVisitor
}
return v.Visit(ctx.Query())
}
func (v *Visitor) VisitPriorityQuery(ctx *parser.PriorityQueryContext) interface{} {
if ctx == nil {
return ErrQueryVisitor
}
return v.Visit(ctx.Query())
}
func (v *Visitor) VisitAtomQuery(ctx *parser.AtomQueryContext) interface{} {
if ctx == nil {
return ErrQueryVisitor
}
return v.Visit(ctx.Criteria())
}
func (v *Visitor) VisitOpQuery(ctx *parser.OpQueryContext) interface{} {
if ctx == nil {
return ErrQueryVisitor
}
left := v.Visit(ctx.GetLeft())
right := v.Visit(ctx.GetRight())
op := ctx.GetLogicalOp().GetText()
var operator string
switch op {
case "and", "AND":
operator = "$and"
case "or", "OR":
operator = "$or"
default:
operator = "$and"
}
return map[string][]interface{}{
operator: {
left,
right,
},
}
}
func (v *Visitor) VisitCriteria(ctx *parser.CriteriaContext) interface{} {
if ctx == nil {
return ErrQueryVisitor
}
key := ctx.Key()
if key == nil {
return ErrQueryVisitor
}
op := ctx.Op()
if op == nil {
return ErrQueryVisitor
}
value := ctx.Value()
if value == nil {
return ErrQueryVisitor
}
expression := fmt.Sprintf("%s%s%s", strings.TrimSpace(key.GetText()), strings.TrimSpace(op.GetText()), strings.TrimSpace(value.GetText()))
criteria := CriteriaParser(expression, v.Caster)
return Convert(criteria, v.QueryHandler)
}