forked from goccy/go-zetasqlite
-
Notifications
You must be signed in to change notification settings - Fork 1
/
function_window_option.go
633 lines (584 loc) · 16.3 KB
/
function_window_option.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
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
package internal
import (
"fmt"
"sort"
"strings"
"sync"
"github.com/goccy/go-json"
ast "github.com/goccy/go-zetasql/resolved_ast"
)
type WindowFuncOptionType string
const (
WindowFuncOptionUnknown WindowFuncOptionType = "window_unknown"
WindowFuncOptionFrameUnit WindowFuncOptionType = "window_frame_unit"
WindowFuncOptionStart WindowFuncOptionType = "window_boundary_start"
WindowFuncOptionEnd WindowFuncOptionType = "window_boundary_end"
WindowFuncOptionPartition WindowFuncOptionType = "window_partition"
WindowFuncOptionRowID WindowFuncOptionType = "window_rowid"
WindowFuncOptionOrderBy WindowFuncOptionType = "window_order_by"
)
type WindowFuncOption struct {
Type WindowFuncOptionType `json:"type"`
Value interface{} `json:"value"`
}
func (o *WindowFuncOption) UnmarshalJSON(b []byte) error {
type windowFuncOption WindowFuncOption
var v windowFuncOption
if err := json.Unmarshal(b, &v); err != nil {
return err
}
o.Type = v.Type
switch v.Type {
case WindowFuncOptionFrameUnit:
var value struct {
Value WindowFrameUnitType `json:"value"`
}
if err := json.Unmarshal(b, &value); err != nil {
return err
}
o.Value = value.Value
case WindowFuncOptionStart, WindowFuncOptionEnd:
var value struct {
Value *WindowBoundary `json:"value"`
}
if err := json.Unmarshal(b, &value); err != nil {
return err
}
o.Value = value.Value
case WindowFuncOptionRowID:
var value struct {
Value int64 `json:"value"`
}
if err := json.Unmarshal(b, &value); err != nil {
return err
}
o.Value = value.Value
case WindowFuncOptionPartition:
value, err := DecodeValue(v.Value)
if err != nil {
return fmt.Errorf("failed to convert %v to Value: %w", v.Value, err)
}
o.Value = value
case WindowFuncOptionOrderBy:
var value struct {
Value *WindowOrderBy `json:"value"`
}
if err := json.Unmarshal(b, &value); err != nil {
return err
}
o.Value = value.Value
}
return nil
}
type WindowFrameUnitType int
const (
WindowFrameUnitUnknown WindowFrameUnitType = 0
WindowFrameUnitRows WindowFrameUnitType = 1
WindowFrameUnitRange WindowFrameUnitType = 2
)
type WindowBoundaryType int
const (
WindowBoundaryTypeUnknown WindowBoundaryType = 0
WindowUnboundedPrecedingType WindowBoundaryType = 1
WindowOffsetPrecedingType WindowBoundaryType = 2
WindowCurrentRowType WindowBoundaryType = 3
WindowOffsetFollowingType WindowBoundaryType = 4
WindowUnboundedFollowingType WindowBoundaryType = 5
)
type WindowBoundary struct {
Type WindowBoundaryType `json:"type"`
Offset int64 `json:"offset"`
}
func getWindowFrameUnitOptionFuncSQL(frameUnit ast.FrameUnit) string {
var typ WindowFrameUnitType
switch frameUnit {
case ast.FrameUnitRows:
typ = WindowFrameUnitRows
case ast.FrameUnitRange:
typ = WindowFrameUnitRange
}
return fmt.Sprintf("zetasqlite_window_frame_unit(%d)", typ)
}
func toWindowBoundaryType(boundaryType ast.BoundaryType) WindowBoundaryType {
switch boundaryType {
case ast.UnboundedPrecedingType:
return WindowUnboundedPrecedingType
case ast.OffsetPrecedingType:
return WindowOffsetPrecedingType
case ast.CurrentRowType:
return WindowCurrentRowType
case ast.OffsetFollowingType:
return WindowOffsetFollowingType
case ast.UnboundedFollowingType:
return WindowUnboundedFollowingType
}
return WindowBoundaryTypeUnknown
}
func getWindowBoundaryStartOptionFuncSQL(boundaryType ast.BoundaryType, offset string) string {
typ := toWindowBoundaryType(boundaryType)
if offset == "" {
offset = "0"
}
return fmt.Sprintf("zetasqlite_window_boundary_start(%d, %s)", typ, offset)
}
func getWindowBoundaryEndOptionFuncSQL(boundaryType ast.BoundaryType, offset string) string {
typ := toWindowBoundaryType(boundaryType)
if offset == "" {
offset = "0"
}
return fmt.Sprintf("zetasqlite_window_boundary_end(%d, %s)", typ, offset)
}
func getWindowPartitionOptionFuncSQL(column string) string {
return fmt.Sprintf("zetasqlite_window_partition(%s)", column)
}
func getWindowRowIDOptionFuncSQL() string {
return "zetasqlite_window_rowid(`row_id`)"
}
func getWindowOrderByOptionFuncSQL(column string, isAsc bool) string {
return fmt.Sprintf("zetasqlite_window_order_by(%s, %t)", column, isAsc)
}
func WINDOW_FRAME_UNIT(frameUnit int64) (Value, error) {
b, err := json.Marshal(&WindowFuncOption{
Type: WindowFuncOptionFrameUnit,
Value: frameUnit,
})
if err != nil {
return nil, err
}
return StringValue(string(b)), nil
}
func WINDOW_BOUNDARY_START(boundaryType, offset int64) (Value, error) {
b, err := json.Marshal(&WindowFuncOption{
Type: WindowFuncOptionStart,
Value: &WindowBoundary{
Type: WindowBoundaryType(boundaryType),
Offset: offset,
},
})
if err != nil {
return nil, err
}
return StringValue(string(b)), nil
}
func WINDOW_BOUNDARY_END(boundaryType, offset int64) (Value, error) {
b, err := json.Marshal(&WindowFuncOption{
Type: WindowFuncOptionEnd,
Value: &WindowBoundary{
Type: WindowBoundaryType(boundaryType),
Offset: offset,
},
})
if err != nil {
return nil, err
}
return StringValue(string(b)), nil
}
func WINDOW_PARTITION(partition Value) (Value, error) {
v, err := EncodeValue(partition)
if err != nil {
return nil, err
}
b, err := json.Marshal(&WindowFuncOption{
Type: WindowFuncOptionPartition,
Value: v,
})
if err != nil {
return nil, err
}
return StringValue(string(b)), nil
}
func WINDOW_ROWID(id int64) (Value, error) {
b, err := json.Marshal(&WindowFuncOption{
Type: WindowFuncOptionRowID,
Value: id,
})
if err != nil {
return nil, err
}
return StringValue(string(b)), nil
}
type WindowOrderBy struct {
Value Value `json:"value"`
IsAsc bool `json:"isAsc"`
}
func (w *WindowOrderBy) UnmarshalJSON(b []byte) error {
var v struct {
Value interface{} `json:"value"`
IsAsc bool `json:"isAsc"`
}
if err := json.Unmarshal(b, &v); err != nil {
return err
}
value, err := DecodeValue(v.Value)
if err != nil {
return err
}
w.Value = value
w.IsAsc = v.IsAsc
return nil
}
func WINDOW_ORDER_BY(value Value, isAsc bool) (Value, error) {
v, err := EncodeValue(value)
if err != nil {
return nil, err
}
b, err := json.Marshal(&WindowFuncOption{
Type: WindowFuncOptionOrderBy,
Value: struct {
Value interface{} `json:"value"`
IsAsc bool `json:"isAsc"`
}{
Value: v,
IsAsc: isAsc,
},
})
if err != nil {
return nil, err
}
return StringValue(string(b)), nil
}
type WindowFuncStatus struct {
FrameUnit WindowFrameUnitType
Start *WindowBoundary
End *WindowBoundary
Partitions []Value
RowID int64
OrderBy []*WindowOrderBy
}
func (s *WindowFuncStatus) Partition() (string, error) {
partitions := make([]string, 0, len(s.Partitions))
for _, p := range s.Partitions {
text, err := p.ToString()
if err != nil {
return "", err
}
partitions = append(partitions, text)
}
return strings.Join(partitions, "_"), nil
}
func parseWindowOptions(args ...Value) ([]Value, *WindowFuncStatus, error) {
var (
filteredArgs []Value
opt *WindowFuncStatus = &WindowFuncStatus{}
)
for _, arg := range args {
if arg == nil {
filteredArgs = append(filteredArgs, nil)
continue
}
text, err := arg.ToString()
if err != nil {
filteredArgs = append(filteredArgs, arg)
continue
}
var v WindowFuncOption
if err := json.Unmarshal([]byte(text), &v); err != nil {
filteredArgs = append(filteredArgs, arg)
continue
}
switch v.Type {
case WindowFuncOptionFrameUnit:
opt.FrameUnit = v.Value.(WindowFrameUnitType)
case WindowFuncOptionStart:
opt.Start = v.Value.(*WindowBoundary)
case WindowFuncOptionEnd:
opt.End = v.Value.(*WindowBoundary)
case WindowFuncOptionPartition:
opt.Partitions = append(opt.Partitions, v.Value.(Value))
case WindowFuncOptionRowID:
opt.RowID = v.Value.(int64)
case WindowFuncOptionOrderBy:
opt.OrderBy = append(opt.OrderBy, v.Value.(*WindowOrderBy))
default:
filteredArgs = append(filteredArgs, arg)
continue
}
}
return filteredArgs, opt, nil
}
type WindowOrderedValue struct {
OrderBy []*WindowOrderBy
Value Value
}
type PartitionedValue struct {
Partition string
Value *WindowOrderedValue
}
type WindowFuncAggregatedStatus struct {
FrameUnit WindowFrameUnitType
Start *WindowBoundary
End *WindowBoundary
RowID int64
once sync.Once
PartitionToValuesMap map[string][]*WindowOrderedValue
PartitionedValues []*PartitionedValue
Values []*WindowOrderedValue
SortedValues []*WindowOrderedValue
opt *AggregatorOption
}
func newWindowFuncAggregatedStatus() *WindowFuncAggregatedStatus {
return &WindowFuncAggregatedStatus{
PartitionToValuesMap: map[string][]*WindowOrderedValue{},
}
}
func (s *WindowFuncAggregatedStatus) Step(value Value, status *WindowFuncStatus) error {
s.once.Do(func() {
s.FrameUnit = status.FrameUnit
s.Start = status.Start
s.End = status.End
s.RowID = status.RowID
})
if s.FrameUnit != status.FrameUnit {
return fmt.Errorf("mismatch frame unit type %d != %d", s.FrameUnit, status.FrameUnit)
}
if s.Start != nil {
if s.Start.Type != status.Start.Type {
return fmt.Errorf("mismatch boundary type %d != %d", s.Start.Type, status.Start.Type)
}
}
if s.End != nil {
if s.End.Type != status.End.Type {
return fmt.Errorf("mismatch boundary type %d != %d", s.End.Type, status.End.Type)
}
}
if s.RowID != status.RowID {
return fmt.Errorf("mismatch rowid %d != %d", s.RowID, status.RowID)
}
v := &WindowOrderedValue{
OrderBy: status.OrderBy,
Value: value,
}
if len(status.Partitions) != 0 {
partition, err := status.Partition()
if err != nil {
return fmt.Errorf("failed to get partition: %w", err)
}
s.PartitionToValuesMap[partition] = append(s.PartitionToValuesMap[partition], v)
s.PartitionedValues = append(s.PartitionedValues, &PartitionedValue{
Partition: partition,
Value: v,
})
}
s.Values = append(s.Values, v)
return nil
}
func (s *WindowFuncAggregatedStatus) Done(cb func([]Value, int, int) error) error {
if s.RowID <= 0 {
return fmt.Errorf("invalid rowid. rowid must be greater than zero")
}
values := s.FilteredValues()
sortedValues := make([]*WindowOrderedValue, len(values))
copy(sortedValues, values)
if len(sortedValues) != 0 {
for orderBy := 0; orderBy < len(sortedValues[0].OrderBy); orderBy++ {
isAsc := sortedValues[0].OrderBy[orderBy].IsAsc
if isAsc {
sort.Slice(sortedValues, func(i, j int) bool {
if sortedValues[i].OrderBy[orderBy].Value == nil {
return true
}
if sortedValues[j].OrderBy[orderBy].Value == nil {
return false
}
cond, _ := sortedValues[i].OrderBy[orderBy].Value.LT(sortedValues[j].OrderBy[orderBy].Value)
return cond
})
} else {
sort.Slice(sortedValues, func(i, j int) bool {
if sortedValues[i].OrderBy[orderBy].Value == nil {
return true
}
if sortedValues[j].OrderBy[orderBy].Value == nil {
return false
}
cond, _ := sortedValues[i].OrderBy[orderBy].Value.GT(sortedValues[j].OrderBy[orderBy].Value)
return cond
})
}
}
}
s.SortedValues = sortedValues
start, err := s.getIndexFromBoundary(s.Start)
if err != nil {
return fmt.Errorf("failed to get start index: %w", err)
}
end, err := s.getIndexFromBoundary(s.End)
if err != nil {
return fmt.Errorf("failed to get end index: %w", err)
}
resultValues := make([]Value, 0, len(sortedValues))
for _, value := range sortedValues {
resultValues = append(resultValues, value.Value)
}
if start >= len(resultValues) || end < 0 {
return nil
}
if start < 0 {
start = 0
}
if end >= len(resultValues) {
end = len(resultValues) - 1
}
return cb(resultValues, start, end)
}
func (s *WindowFuncAggregatedStatus) IgnoreNulls() bool {
return s.opt.IgnoreNulls
}
func (s *WindowFuncAggregatedStatus) Distinct() bool {
return s.opt.Distinct
}
func (s *WindowFuncAggregatedStatus) FilteredValues() []*WindowOrderedValue {
if len(s.PartitionedValues) != 0 {
return s.PartitionToValuesMap[s.Partition()]
}
return s.Values
}
func (s *WindowFuncAggregatedStatus) Partition() string {
return s.PartitionedValues[s.RowID-1].Partition
}
func (s *WindowFuncAggregatedStatus) getIndexFromBoundary(boundary *WindowBoundary) (int, error) {
switch s.FrameUnit {
case WindowFrameUnitRows:
return s.getIndexFromBoundaryByRows(boundary)
case WindowFrameUnitRange:
return s.getIndexFromBoundaryByRange(boundary)
default:
return s.currentIndexByRows()
}
}
func (s *WindowFuncAggregatedStatus) getIndexFromBoundaryByRows(boundary *WindowBoundary) (int, error) {
switch boundary.Type {
case WindowUnboundedPrecedingType:
return 0, nil
case WindowCurrentRowType:
return s.currentIndexByRows()
case WindowUnboundedFollowingType:
return len(s.FilteredValues()) - 1, nil
case WindowOffsetPrecedingType:
cur, err := s.currentIndexByRows()
if err != nil {
return 0, err
}
return cur - int(boundary.Offset), nil
case WindowOffsetFollowingType:
cur, err := s.currentIndexByRows()
if err != nil {
return 0, err
}
return cur + int(boundary.Offset), nil
}
return 0, fmt.Errorf("unsupported boundary type %d", boundary.Type)
}
func (s *WindowFuncAggregatedStatus) currentIndexByRows() (int, error) {
if len(s.PartitionedValues) != 0 {
return s.partitionedCurrentIndexByRows()
}
curRowID := int(s.RowID - 1)
curValue := s.Values[curRowID]
for idx, value := range s.SortedValues {
if value == curValue {
return idx, nil
}
}
return 0, fmt.Errorf("failed to find current index")
}
func (s *WindowFuncAggregatedStatus) partitionedCurrentIndexByRows() (int, error) {
curRowID := int(s.RowID - 1)
curValue := s.PartitionedValues[curRowID]
for idx, value := range s.SortedValues {
if value == curValue.Value {
return idx, nil
}
}
return 0, fmt.Errorf("failed to find current index")
}
func (s *WindowFuncAggregatedStatus) getIndexFromBoundaryByRange(boundary *WindowBoundary) (int, error) {
switch boundary.Type {
case WindowUnboundedPrecedingType:
return 0, nil
case WindowUnboundedFollowingType:
return len(s.FilteredValues()) - 1, nil
case WindowCurrentRowType:
value, err := s.currentRangeValue()
if err != nil {
return 0, err
}
return s.lookupMaxIndexFromRangeValue(value)
case WindowOffsetPrecedingType:
value, err := s.currentRangeValue()
if err != nil {
return 0, err
}
sub, err := value.Sub(IntValue(boundary.Offset))
if err != nil {
return 0, err
}
return s.lookupMinIndexFromRangeValue(sub)
case WindowOffsetFollowingType:
value, err := s.currentRangeValue()
if err != nil {
return 0, err
}
add, err := value.Add(IntValue(boundary.Offset))
if err != nil {
return 0, err
}
return s.lookupMaxIndexFromRangeValue(add)
}
return 0, fmt.Errorf("unsupported boundary type %d", boundary.Type)
}
func (s *WindowFuncAggregatedStatus) currentRangeValue() (Value, error) {
if len(s.PartitionedValues) != 0 {
return s.partitionedCurrentRangeValue()
}
curRowID := int(s.RowID - 1)
curValue := s.Values[curRowID]
if len(curValue.OrderBy) == 0 {
return nil, fmt.Errorf("required order by column for analytic range scanning")
}
return curValue.OrderBy[len(curValue.OrderBy)-1].Value, nil
}
func (s *WindowFuncAggregatedStatus) partitionedCurrentRangeValue() (Value, error) {
curRowID := int(s.RowID - 1)
curValue := s.PartitionedValues[curRowID]
if len(curValue.Value.OrderBy) == 0 {
return nil, fmt.Errorf("required order by column for analytic range scanning")
}
return curValue.Value.OrderBy[len(curValue.Value.OrderBy)-1].Value, nil
}
func (s *WindowFuncAggregatedStatus) lookupMinIndexFromRangeValue(rangeValue Value) (int, error) {
minIndex := -1
for idx := len(s.SortedValues) - 1; idx >= 0; idx-- {
value := s.SortedValues[idx]
if len(value.OrderBy) == 0 {
continue
}
target := value.OrderBy[len(value.OrderBy)-1].Value
cond, err := rangeValue.LTE(target)
if err != nil {
return 0, err
}
if cond {
minIndex = idx
}
}
return minIndex, nil
}
func (s *WindowFuncAggregatedStatus) lookupMaxIndexFromRangeValue(rangeValue Value) (int, error) {
maxIndex := -1
for idx := 0; idx < len(s.SortedValues); idx++ {
value := s.SortedValues[idx]
if len(value.OrderBy) == 0 {
continue
}
target := value.OrderBy[len(value.OrderBy)-1].Value
cond, err := rangeValue.GTE(target)
if err != nil {
return 0, err
}
if cond {
maxIndex = idx
}
}
return maxIndex, nil
}