This repository has been archived by the owner on Feb 21, 2024. It is now read-only.
/
opgroupby.go
315 lines (275 loc) · 7.63 KB
/
opgroupby.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
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
// Copyright 2022 Molecula Corp. All rights reserved.
package planner
import (
"bytes"
"context"
"fmt"
"github.com/featurebasedb/featurebase/v3/sql3"
"github.com/featurebasedb/featurebase/v3/sql3/planner/types"
)
// PlanOpGroupBy handles the GROUP BY clause
// this is the default GROUP BY operator and may be replaced by the optimizer
// with one or more of the PQL related group by or aggregate operators
type PlanOpGroupBy struct {
ChildOp types.PlanOperator
Aggregates []types.PlanExpression
GroupByExprs []types.PlanExpression
warnings []string
}
func NewPlanOpGroupBy(aggregates []types.PlanExpression, groupByExprs []types.PlanExpression, child types.PlanOperator) *PlanOpGroupBy {
return &PlanOpGroupBy{
ChildOp: child,
Aggregates: aggregates,
GroupByExprs: groupByExprs,
warnings: make([]string, 0),
}
}
// Schema for GroupBy is the group by expressions followed by the aggregate expressions
func (p *PlanOpGroupBy) Schema() types.Schema {
result := make(types.Schema, len(p.GroupByExprs)+len(p.Aggregates))
for idx, expr := range p.GroupByExprs {
ref, ok := expr.(*qualifiedRefPlanExpression)
if !ok {
continue
}
s := &types.PlannerColumn{
ColumnName: ref.columnName,
RelationName: ref.tableName,
Type: expr.Type(),
}
result[idx] = s
}
offset := len(p.GroupByExprs)
for idx, agg := range p.Aggregates {
s := &types.PlannerColumn{
ColumnName: agg.String(),
RelationName: "",
Type: agg.Type(),
}
result[idx+offset] = s
}
return result
}
func (p *PlanOpGroupBy) Iterator(ctx context.Context, row types.Row) (types.RowIterator, error) {
i, err := p.ChildOp.Iterator(ctx, row)
if err != nil {
return nil, err
}
if len(p.GroupByExprs) == 0 {
return newGroupByIter(ctx, p.Aggregates, i), nil
} else {
return newGroupByGroupingIter(ctx, p.Aggregates, p.GroupByExprs, i), nil
}
}
func (p *PlanOpGroupBy) Children() []types.PlanOperator {
return []types.PlanOperator{
p.ChildOp,
}
}
func (p *PlanOpGroupBy) WithChildren(children ...types.PlanOperator) (types.PlanOperator, error) {
if len(children) != 1 {
return nil, sql3.NewErrInternalf("unexpected number of children '%d'", len(children))
}
return NewPlanOpGroupBy(p.Aggregates, p.GroupByExprs, children[0]), nil
}
func (p *PlanOpGroupBy) Expressions() []types.PlanExpression {
result := []types.PlanExpression{}
result = append(result, p.Aggregates...)
return result
}
func (p *PlanOpGroupBy) WithUpdatedExpressions(exprs ...types.PlanExpression) (types.PlanOperator, error) {
if len(exprs) != 1 {
return nil, sql3.NewErrInternalf("unexpected number of exprs '%d'", len(exprs))
}
return NewPlanOpGroupBy(exprs, p.GroupByExprs, p.ChildOp), nil
}
func (p *PlanOpGroupBy) Plan() map[string]interface{} {
result := make(map[string]interface{})
result["_op"] = fmt.Sprintf("%T", p)
result["_schema"] = p.Schema().Plan()
result["child"] = p.ChildOp.Plan()
ps := make([]interface{}, 0)
for _, e := range p.Aggregates {
ps = append(ps, e.Plan())
}
result["aggregates"] = ps
ps = make([]interface{}, 0)
for _, e := range p.GroupByExprs {
ps = append(ps, e.Plan())
}
result["groupByExprs"] = ps
return result
}
func (p *PlanOpGroupBy) String() string {
return ""
}
func (p *PlanOpGroupBy) AddWarning(warning string) {
p.warnings = append(p.warnings, warning)
}
func (p *PlanOpGroupBy) Warnings() []string {
var w []string
w = append(w, p.warnings...)
w = append(w, p.ChildOp.Warnings()...)
return w
}
type groupByIter struct {
aggregates []types.PlanExpression
child types.RowIterator
ctx context.Context
aggregationBuffers *keysAndAggregations
done bool
}
func newGroupByIter(ctx context.Context, aggregates []types.PlanExpression, child types.RowIterator) *groupByIter {
return &groupByIter{
aggregates: aggregates,
child: child,
ctx: ctx,
aggregationBuffers: &keysAndAggregations{
buffers: make([]types.AggregationBuffer, len(aggregates)),
},
}
}
func (i *groupByIter) Next(ctx context.Context) (types.Row, error) {
if i.done {
return nil, types.ErrNoMoreRows
}
i.done = true
var err error
for j, a := range i.aggregates {
i.aggregationBuffers.buffers[j], err = newAggregationBuffer(a)
if err != nil {
return nil, err
}
}
for {
row, err := i.child.Next(ctx)
if err != nil {
if err == types.ErrNoMoreRows {
break
}
return nil, err
}
if err := updateBuffers(ctx, i.aggregationBuffers, row); err != nil {
return nil, err
}
}
return evalBuffers(ctx, i.aggregationBuffers)
}
type keysAndAggregations struct {
groupByKeys []interface{}
buffers []types.AggregationBuffer
}
type groupByGroupingIter struct {
aggregates []types.PlanExpression
groupByExprs []types.PlanExpression
aggregations map[string]*keysAndAggregations
keys []string
child types.RowIterator
}
func newGroupByGroupingIter(ctx context.Context, aggregates, groupByExprs []types.PlanExpression, child types.RowIterator) *groupByGroupingIter {
return &groupByGroupingIter{
aggregates: aggregates,
groupByExprs: groupByExprs,
child: child,
}
}
func (i *groupByGroupingIter) Next(ctx context.Context) (types.Row, error) {
if i.aggregations == nil {
i.aggregations = make(map[string]*keysAndAggregations)
if err := i.compute(ctx); err != nil {
return nil, err
}
}
if len(i.keys) > 0 {
buffers, ok := i.aggregations[i.keys[0]]
if !ok {
return nil, sql3.NewErrInternalf("unexpected absence of key")
}
i.keys = i.keys[1:]
aggRow, err := evalBuffers(ctx, buffers)
if err != nil {
return nil, err
}
var row = make(types.Row, len(i.groupByExprs)+len(aggRow))
copy(row, buffers.groupByKeys)
copy(row[len(buffers.groupByKeys):], aggRow)
return row, nil
}
return nil, types.ErrNoMoreRows
}
func (i *groupByGroupingIter) compute(ctx context.Context) error {
for {
row, err := i.child.Next(ctx)
if err != nil {
if err == types.ErrNoMoreRows {
break
}
return err
}
key, keyValues, err := groupingKey(ctx, i.groupByExprs, row)
if err != nil {
return err
}
b, ok := i.aggregations[key]
if !ok {
b = &keysAndAggregations{}
b.buffers = make([]types.AggregationBuffer, len(i.aggregates))
for j, a := range i.aggregates {
b.buffers[j], err = newAggregationBuffer(a)
if err != nil {
return err
}
}
b.groupByKeys = keyValues
i.aggregations[key] = b
i.keys = append(i.keys, key)
} else if err != nil {
return err
}
err = updateBuffers(ctx, b, row)
if err != nil {
return err
}
}
return nil
}
func newAggregationBuffer(expr types.PlanExpression) (types.AggregationBuffer, error) {
switch n := expr.(type) {
case types.Aggregable:
return n.NewBuffer()
default:
return NewAggLastBuffer(expr), nil
}
}
func updateBuffers(ctx context.Context, buffers *keysAndAggregations, row types.Row) error {
for _, b := range buffers.buffers {
if err := b.Update(ctx, row); err != nil {
return err
}
}
return nil
}
func evalBuffers(ctx context.Context, aggregationBuffers *keysAndAggregations) (types.Row, error) {
var row = make(types.Row, len(aggregationBuffers.buffers))
var err error
for i, b := range aggregationBuffers.buffers {
row[i], err = b.Eval(ctx)
if err != nil {
return nil, err
}
}
return row, nil
}
func groupingKey(ctx context.Context, groupByExprs []types.PlanExpression, row types.Row) (string, types.Row, error) {
var buf bytes.Buffer
rowKeys := make([]interface{}, len(groupByExprs))
for i, expr := range groupByExprs {
v, err := expr.Evaluate(row)
if err != nil {
return "", nil, err
}
buf.WriteString(fmt.Sprintf("%#v", v))
rowKeys[i] = v
}
return buf.String(), rowKeys, nil
}