summaryrefslogtreecommitdiff
path: root/internal/mapr/parserfieldplan.go
blob: fd831a5e1e7de2b6bf9421cbafb0180eea40d18f (plain)
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
package mapr

// ParserFieldPlan describes which raw fields a parser needs to materialize.
type ParserFieldPlan struct {
	AllFields bool
	Fields    map[string]struct{}
}

// Needs reports whether the parser plan requires a field.
func (p ParserFieldPlan) Needs(field string) bool {
	if p.AllFields {
		return true
	}
	_, ok := p.Fields[field]
	return ok
}

// Capacity returns a reasonable initial capacity for a parsed field map.
func (p ParserFieldPlan) Capacity() int {
	if p.AllFields {
		return 20
	}
	if len(p.Fields) == 0 {
		return 4
	}
	return len(p.Fields) + 2
}

// ParserFieldPlan returns the raw fields required to evaluate the query.
func (q *Query) ParserFieldPlan() ParserFieldPlan {
	if q == nil {
		return ParserFieldPlan{AllFields: true}
	}

	fields := make(map[string]struct{}, len(q.Select)+len(q.GroupBy)+len(q.Where)*2+len(q.Set))
	producedBySet := make(map[string]struct{}, len(q.Set))

	add := func(field string) {
		if field == "" {
			return
		}
		fields[field] = struct{}{}
	}
	isProduced := func(field string) bool {
		_, ok := producedBySet[field]
		return ok
	}

	for _, wc := range q.Where {
		if wc.lType == Field {
			add(wc.lString)
		}
		if wc.rType == Field {
			add(wc.rString)
		}
	}

	for _, sc := range q.Set {
		switch sc.rType {
		case Field, FunctionStack:
			if !isProduced(sc.rString) {
				add(sc.rString)
			}
		}
		producedBySet[sc.lString] = struct{}{}
	}

	for _, groupBy := range q.GroupBy {
		if !isProduced(groupBy) {
			add(groupBy)
		}
	}

	for _, sc := range q.Select {
		if !isProduced(sc.Field) {
			add(sc.Field)
		}
	}

	return ParserFieldPlan{Fields: fields}
}