-
Notifications
You must be signed in to change notification settings - Fork 3.8k
/
generator_builtins.go
1696 lines (1486 loc) · 50.9 KB
/
generator_builtins.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
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2016 The Cockroach Authors.
//
// Use of this software is governed by the Business Source License
// included in the file licenses/BSL.txt.
//
// As of the Change Date specified in that file, in accordance with
// the Business Source License, use of this software will be governed
// by the Apache License, Version 2.0, included in the file
// licenses/APL.txt.
package builtins
import (
"bytes"
"context"
"fmt"
"strings"
"time"
"github.com/cockroachdb/cockroach/pkg/keys"
"github.com/cockroachdb/cockroach/pkg/kv"
"github.com/cockroachdb/cockroach/pkg/kv/kvclient"
"github.com/cockroachdb/cockroach/pkg/roachpb"
"github.com/cockroachdb/cockroach/pkg/sql/lex"
"github.com/cockroachdb/cockroach/pkg/sql/pgwire/pgcode"
"github.com/cockroachdb/cockroach/pkg/sql/pgwire/pgerror"
"github.com/cockroachdb/cockroach/pkg/sql/protoreflect"
"github.com/cockroachdb/cockroach/pkg/sql/sem/tree"
"github.com/cockroachdb/cockroach/pkg/sql/sqlutil"
"github.com/cockroachdb/cockroach/pkg/sql/types"
"github.com/cockroachdb/cockroach/pkg/util/arith"
"github.com/cockroachdb/cockroach/pkg/util/duration"
"github.com/cockroachdb/cockroach/pkg/util/errorutil"
"github.com/cockroachdb/cockroach/pkg/util/json"
"github.com/cockroachdb/cockroach/pkg/util/timeutil"
"github.com/cockroachdb/cockroach/pkg/util/tracing"
"github.com/cockroachdb/errors"
pbtypes "github.com/gogo/protobuf/types"
)
// See the comments at the start of generators.go for details about
// this functionality.
var _ tree.ValueGenerator = &seriesValueGenerator{}
var _ tree.ValueGenerator = &arrayValueGenerator{}
func initGeneratorBuiltins() {
// Add all windows to the Builtins map after a few sanity checks.
for k, v := range generators {
if _, exists := builtins[k]; exists {
panic("duplicate builtin: " + k)
}
if v.props.Class != tree.GeneratorClass {
panic(errors.AssertionFailedf("generator functions should be marked with the tree.GeneratorClass "+
"function class, found %v", v))
}
builtins[k] = v
}
}
func genProps() tree.FunctionProperties {
return tree.FunctionProperties{
Class: tree.GeneratorClass,
Category: categoryGenerator,
}
}
func genPropsWithLabels(returnLabels []string) tree.FunctionProperties {
return tree.FunctionProperties{
Class: tree.GeneratorClass,
Category: categoryGenerator,
ReturnLabels: returnLabels,
}
}
var aclexplodeGeneratorType = types.MakeLabeledTuple(
[]*types.T{types.Oid, types.Oid, types.String, types.Bool},
[]string{"grantor", "grantee", "privilege_type", "is_grantable"},
)
// aclExplodeGenerator supports the execution of aclexplode.
type aclexplodeGenerator struct{}
func (aclexplodeGenerator) ResolvedType() *types.T { return aclexplodeGeneratorType }
func (aclexplodeGenerator) Start(_ context.Context, _ *kv.Txn) error { return nil }
func (aclexplodeGenerator) Close() {}
func (aclexplodeGenerator) Next(_ context.Context) (bool, error) { return false, nil }
func (aclexplodeGenerator) Values() (tree.Datums, error) { return nil, nil }
// generators is a map from name to slice of Builtins for all built-in
// generators.
//
// These functions are identified with Class == tree.GeneratorClass.
// The properties are reachable via tree.FunctionDefinition.
var generators = map[string]builtinDefinition{
// See https://www.postgresql.org/docs/9.6/static/functions-info.html.
"aclexplode": makeBuiltin(genProps(),
makeGeneratorOverload(
tree.ArgTypes{{"aclitems", types.StringArray}},
aclexplodeGeneratorType,
func(ctx *tree.EvalContext, args tree.Datums) (tree.ValueGenerator, error) {
return aclexplodeGenerator{}, nil
},
"Produces a virtual table containing aclitem stuff ("+
"returns no rows as this feature is unsupported in CockroachDB)",
tree.VolatilityStable,
),
),
"generate_series": makeBuiltin(genProps(),
// See https://www.postgresql.org/docs/current/static/functions-srf.html#FUNCTIONS-SRF-SERIES
makeGeneratorOverload(
tree.ArgTypes{{"start", types.Int}, {"end", types.Int}},
seriesValueGeneratorType,
makeSeriesGenerator,
"Produces a virtual table containing the integer values from `start` to `end`, inclusive.",
tree.VolatilityImmutable,
),
makeGeneratorOverload(
tree.ArgTypes{{"start", types.Int}, {"end", types.Int}, {"step", types.Int}},
seriesValueGeneratorType,
makeSeriesGenerator,
"Produces a virtual table containing the integer values from `start` to `end`, inclusive, by increment of `step`.",
tree.VolatilityImmutable,
),
makeGeneratorOverload(
tree.ArgTypes{{"start", types.Timestamp}, {"end", types.Timestamp}, {"step", types.Interval}},
seriesTSValueGeneratorType,
makeTSSeriesGenerator,
"Produces a virtual table containing the timestamp values from `start` to `end`, inclusive, by increment of `step`.",
tree.VolatilityImmutable,
),
),
// crdb_internal.testing_callback is a generator function intended for internal unit tests.
// You give it a name and it calls a callback that had to have been installed
// on a TestServer through its EvalContextTestingKnobs.CallbackGenerators.
"crdb_internal.testing_callback": makeBuiltin(genProps(),
makeGeneratorOverload(
tree.ArgTypes{{"name", types.String}},
types.Int,
func(ctx *tree.EvalContext, args tree.Datums) (tree.ValueGenerator, error) {
name := string(*args[0].(*tree.DString))
gen, ok := ctx.TestingKnobs.CallbackGenerators[name]
if !ok {
return nil, errors.Errorf("callback %q not registered", name)
}
return gen, nil
},
"For internal CRDB testing only. "+
"The function calls a callback identified by `name` registered with the server by "+
"the test.",
tree.VolatilityVolatile,
),
),
"pg_get_keywords": makeBuiltin(genProps(),
// See https://www.postgresql.org/docs/10/static/functions-info.html#FUNCTIONS-INFO-CATALOG-TABLE
makeGeneratorOverload(
tree.ArgTypes{},
keywordsValueGeneratorType,
makeKeywordsGenerator,
"Produces a virtual table containing the keywords known to the SQL parser.",
tree.VolatilityImmutable,
),
),
"regexp_split_to_table": makeBuiltin(
genProps(),
makeGeneratorOverload(
tree.ArgTypes{
{"string", types.String},
{"pattern", types.String},
},
types.String,
makeRegexpSplitToTableGeneratorFactory(false /* hasFlags */),
"Split string using a POSIX regular expression as the delimiter.",
tree.VolatilityImmutable,
),
makeGeneratorOverload(
tree.ArgTypes{
{"string", types.String},
{"pattern", types.String},
{"flags", types.String},
},
types.String,
makeRegexpSplitToTableGeneratorFactory(true /* hasFlags */),
"Split string using a POSIX regular expression as the delimiter with flags."+regexpFlagInfo,
tree.VolatilityImmutable,
),
),
"unnest": makeBuiltin(genProps(),
// See https://www.postgresql.org/docs/current/static/functions-array.html
makeGeneratorOverloadWithReturnType(
tree.ArgTypes{{"input", types.AnyArray}},
func(args []tree.TypedExpr) *types.T {
if len(args) == 0 || args[0].ResolvedType().Family() == types.UnknownFamily {
return tree.UnknownReturnType
}
return args[0].ResolvedType().ArrayContents()
},
makeArrayGenerator,
"Returns the input array as a set of rows",
tree.VolatilityImmutable,
),
makeGeneratorOverloadWithReturnType(
tree.VariadicType{
FixedTypes: []*types.T{types.AnyArray, types.AnyArray},
VarType: types.AnyArray,
},
// TODO(rafiss): update this or docgen so that functions.md shows the
// return type as variadic.
func(args []tree.TypedExpr) *types.T {
returnTypes := make([]*types.T, len(args))
labels := make([]string, len(args))
for i, arg := range args {
if arg.ResolvedType().Family() == types.UnknownFamily {
return tree.UnknownReturnType
}
returnTypes[i] = arg.ResolvedType().ArrayContents()
labels[i] = "unnest"
}
return types.MakeLabeledTuple(returnTypes, labels)
},
makeVariadicUnnestGenerator,
"Returns the input arrays as a set of rows",
tree.VolatilityImmutable,
),
),
"information_schema._pg_expandarray": makeBuiltin(genProps(),
makeGeneratorOverloadWithReturnType(
tree.ArgTypes{{"input", types.AnyArray}},
func(args []tree.TypedExpr) *types.T {
if len(args) == 0 || args[0].ResolvedType().Family() == types.UnknownFamily {
return tree.UnknownReturnType
}
t := args[0].ResolvedType().ArrayContents()
return types.MakeLabeledTuple([]*types.T{t, types.Int}, expandArrayValueGeneratorLabels)
},
makeExpandArrayGenerator,
"Returns the input array as a set of rows with an index",
tree.VolatilityImmutable,
),
),
"crdb_internal.unary_table": makeBuiltin(genProps(),
makeGeneratorOverload(
tree.ArgTypes{},
unaryValueGeneratorType,
makeUnaryGenerator,
"Produces a virtual table containing a single row with no values.\n\n"+
"This function is used only by CockroachDB's developers for testing purposes.",
tree.VolatilityVolatile,
),
),
"generate_subscripts": makeBuiltin(genProps(),
// See https://www.postgresql.org/docs/current/static/functions-srf.html#FUNCTIONS-SRF-SUBSCRIPTS
makeGeneratorOverload(
tree.ArgTypes{{"array", types.AnyArray}},
subscriptsValueGeneratorType,
makeGenerateSubscriptsGenerator,
"Returns a series comprising the given array's subscripts.",
tree.VolatilityImmutable,
),
makeGeneratorOverload(
tree.ArgTypes{{"array", types.AnyArray}, {"dim", types.Int}},
subscriptsValueGeneratorType,
makeGenerateSubscriptsGenerator,
"Returns a series comprising the given array's subscripts.",
tree.VolatilityImmutable,
),
makeGeneratorOverload(
tree.ArgTypes{{"array", types.AnyArray}, {"dim", types.Int}, {"reverse", types.Bool}},
subscriptsValueGeneratorType,
makeGenerateSubscriptsGenerator,
"Returns a series comprising the given array's subscripts.\n\n"+
"When reverse is true, the series is returned in reverse order.",
tree.VolatilityImmutable,
),
),
"json_array_elements": makeBuiltin(genPropsWithLabels(jsonArrayGeneratorLabels), jsonArrayElementsImpl),
"jsonb_array_elements": makeBuiltin(genPropsWithLabels(jsonArrayGeneratorLabels), jsonArrayElementsImpl),
"json_array_elements_text": makeBuiltin(genPropsWithLabels(jsonArrayGeneratorLabels), jsonArrayElementsTextImpl),
"jsonb_array_elements_text": makeBuiltin(genPropsWithLabels(jsonArrayGeneratorLabels), jsonArrayElementsTextImpl),
"json_object_keys": makeBuiltin(genProps(), jsonObjectKeysImpl),
"jsonb_object_keys": makeBuiltin(genProps(), jsonObjectKeysImpl),
"json_each": makeBuiltin(genPropsWithLabels(jsonEachGeneratorLabels), jsonEachImpl),
"jsonb_each": makeBuiltin(genPropsWithLabels(jsonEachGeneratorLabels), jsonEachImpl),
"json_each_text": makeBuiltin(genPropsWithLabels(jsonEachGeneratorLabels), jsonEachTextImpl),
"jsonb_each_text": makeBuiltin(genPropsWithLabels(jsonEachGeneratorLabels), jsonEachTextImpl),
"crdb_internal.check_consistency": makeBuiltin(
tree.FunctionProperties{
Class: tree.GeneratorClass,
Category: categorySystemInfo,
},
makeGeneratorOverload(
tree.ArgTypes{
{Name: "stats_only", Typ: types.Bool},
{Name: "start_key", Typ: types.Bytes},
{Name: "end_key", Typ: types.Bytes},
},
checkConsistencyGeneratorType,
makeCheckConsistencyGenerator,
"Runs a consistency check on ranges touching the specified key range. "+
"an empty start or end key is treated as the minimum and maximum possible, "+
"respectively. stats_only should only be set to false when targeting a "+
"small number of ranges to avoid overloading the cluster. Each returned row "+
"contains the range ID, the status (a roachpb.CheckConsistencyResponse_Status), "+
"and verbose detail.\n\n"+
"Example usage:\n"+
"SELECT * FROM crdb_internal.check_consistency(true, '\\x02', '\\x04')",
tree.VolatilityVolatile,
),
),
"crdb_internal.list_sql_keys_in_range": makeBuiltin(
tree.FunctionProperties{
Class: tree.GeneratorClass,
Category: categorySystemInfo,
},
makeGeneratorOverload(
tree.ArgTypes{
{Name: "range_id", Typ: types.Int},
},
rangeKeyIteratorType,
makeRangeKeyIterator,
"Returns all SQL K/V pairs within the requested range.",
tree.VolatilityVolatile,
),
),
"crdb_internal.payloads_for_span": makeBuiltin(
tree.FunctionProperties{
Class: tree.GeneratorClass,
Category: categorySystemInfo,
},
makeGeneratorOverload(
tree.ArgTypes{
{Name: "span_id", Typ: types.Int},
},
payloadsForSpanGeneratorType,
makePayloadsForSpanGenerator,
"Returns the payload(s) of the requested span.",
tree.VolatilityVolatile,
),
),
"crdb_internal.show_create_all_tables": makeBuiltin(
tree.FunctionProperties{
Class: tree.GeneratorClass,
},
makeGeneratorOverload(
tree.ArgTypes{
{"dbName", types.String},
},
showCreateAllTablesGeneratorType,
makeShowCreateAllTablesGenerator,
`Returns a rows CREATE table statements followed by
ALTER table statements that add table constraints. The rows are ordered
by dependencies. All foreign keys are added after the creation of the table
in the alter statements.
It is not recommended to perform this operation on a database with many
tables.
The output can be used to recreate a database.'
`,
tree.VolatilityVolatile,
),
),
}
func makeGeneratorOverload(
in tree.TypeList, ret *types.T, g tree.GeneratorFactory, info string, volatility tree.Volatility,
) tree.Overload {
return makeGeneratorOverloadWithReturnType(in, tree.FixedReturnType(ret), g, info, volatility)
}
func newUnsuitableUseOfGeneratorError() error {
return errors.AssertionFailedf("generator functions cannot be evaluated as scalars")
}
func makeGeneratorOverloadWithReturnType(
in tree.TypeList,
retType tree.ReturnTyper,
g tree.GeneratorFactory,
info string,
volatility tree.Volatility,
) tree.Overload {
return tree.Overload{
Types: in,
ReturnType: retType,
Generator: g,
Fn: func(ctx *tree.EvalContext, args tree.Datums) (tree.Datum, error) {
return nil, newUnsuitableUseOfGeneratorError()
},
Info: info,
Volatility: volatility,
}
}
// regexpSplitToTableGenerator supports regexp_split_to_table.
type regexpSplitToTableGenerator struct {
words []string
curr int
}
func makeRegexpSplitToTableGeneratorFactory(hasFlags bool) tree.GeneratorFactory {
return func(
ctx *tree.EvalContext, args tree.Datums,
) (tree.ValueGenerator, error) {
words, err := regexpSplit(ctx, args, hasFlags)
if err != nil {
return nil, err
}
return ®expSplitToTableGenerator{
words: words,
curr: -1,
}, nil
}
}
// ResolvedType implements the tree.ValueGenerator interface.
func (*regexpSplitToTableGenerator) ResolvedType() *types.T { return types.String }
// Close implements the tree.ValueGenerator interface.
func (*regexpSplitToTableGenerator) Close() {}
// Start implements the tree.ValueGenerator interface.
func (g *regexpSplitToTableGenerator) Start(_ context.Context, _ *kv.Txn) error {
g.curr = -1
return nil
}
// Next implements the tree.ValueGenerator interface.
func (g *regexpSplitToTableGenerator) Next(_ context.Context) (bool, error) {
g.curr++
return g.curr < len(g.words), nil
}
// Values implements the tree.ValueGenerator interface.
func (g *regexpSplitToTableGenerator) Values() (tree.Datums, error) {
return tree.Datums{tree.NewDString(g.words[g.curr])}, nil
}
// keywordsValueGenerator supports the execution of pg_get_keywords().
type keywordsValueGenerator struct {
curKeyword int
}
var keywordsValueGeneratorType = types.MakeLabeledTuple(
[]*types.T{types.String, types.String, types.String},
[]string{"word", "catcode", "catdesc"},
)
func makeKeywordsGenerator(_ *tree.EvalContext, _ tree.Datums) (tree.ValueGenerator, error) {
return &keywordsValueGenerator{}, nil
}
// ResolvedType implements the tree.ValueGenerator interface.
func (*keywordsValueGenerator) ResolvedType() *types.T { return keywordsValueGeneratorType }
// Close implements the tree.ValueGenerator interface.
func (*keywordsValueGenerator) Close() {}
// Start implements the tree.ValueGenerator interface.
func (k *keywordsValueGenerator) Start(_ context.Context, _ *kv.Txn) error {
k.curKeyword = -1
return nil
}
// Next implements the tree.ValueGenerator interface.
func (k *keywordsValueGenerator) Next(_ context.Context) (bool, error) {
k.curKeyword++
return k.curKeyword < len(lex.KeywordNames), nil
}
// Values implements the tree.ValueGenerator interface.
func (k *keywordsValueGenerator) Values() (tree.Datums, error) {
kw := lex.KeywordNames[k.curKeyword]
cat := lex.KeywordsCategories[kw]
desc := keywordCategoryDescriptions[cat]
return tree.Datums{tree.NewDString(kw), tree.NewDString(cat), tree.NewDString(desc)}, nil
}
var keywordCategoryDescriptions = map[string]string{
"R": "reserved",
"C": "unreserved (cannot be function or type name)",
"T": "reserved (can be function or type name)",
"U": "unreserved",
}
// seriesValueGenerator supports the execution of generate_series()
// with integer bounds.
type seriesValueGenerator struct {
origStart, value, start, stop, step interface{}
nextOK bool
genType *types.T
next func(*seriesValueGenerator) (bool, error)
genValue func(*seriesValueGenerator) (tree.Datums, error)
}
var seriesValueGeneratorType = types.Int
var seriesTSValueGeneratorType = types.Timestamp
var errStepCannotBeZero = pgerror.New(pgcode.InvalidParameterValue, "step cannot be 0")
func seriesIntNext(s *seriesValueGenerator) (bool, error) {
step := s.step.(int64)
start := s.start.(int64)
stop := s.stop.(int64)
if !s.nextOK {
return false, nil
}
if step < 0 && (start < stop) {
return false, nil
}
if step > 0 && (stop < start) {
return false, nil
}
s.value = start
s.start, s.nextOK = arith.AddWithOverflow(start, step)
return true, nil
}
func seriesGenIntValue(s *seriesValueGenerator) (tree.Datums, error) {
return tree.Datums{tree.NewDInt(tree.DInt(s.value.(int64)))}, nil
}
// seriesTSNext performs calendar-aware math.
func seriesTSNext(s *seriesValueGenerator) (bool, error) {
step := s.step.(duration.Duration)
start := s.start.(time.Time)
stop := s.stop.(time.Time)
if !s.nextOK {
return false, nil
}
stepForward := step.Compare(duration.Duration{}) > 0
if !stepForward && (start.Before(stop)) {
return false, nil
}
if stepForward && (stop.Before(start)) {
return false, nil
}
s.value = start
s.start = duration.Add(start, step)
return true, nil
}
func seriesGenTSValue(s *seriesValueGenerator) (tree.Datums, error) {
ts, err := tree.MakeDTimestamp(s.value.(time.Time), time.Microsecond)
if err != nil {
return nil, err
}
return tree.Datums{ts}, nil
}
func makeSeriesGenerator(_ *tree.EvalContext, args tree.Datums) (tree.ValueGenerator, error) {
start := int64(tree.MustBeDInt(args[0]))
stop := int64(tree.MustBeDInt(args[1]))
step := int64(1)
if len(args) > 2 {
step = int64(tree.MustBeDInt(args[2]))
}
if step == 0 {
return nil, errStepCannotBeZero
}
return &seriesValueGenerator{
origStart: start,
stop: stop,
step: step,
genType: seriesValueGeneratorType,
genValue: seriesGenIntValue,
next: seriesIntNext,
}, nil
}
func makeTSSeriesGenerator(_ *tree.EvalContext, args tree.Datums) (tree.ValueGenerator, error) {
start := args[0].(*tree.DTimestamp).Time
stop := args[1].(*tree.DTimestamp).Time
step := args[2].(*tree.DInterval).Duration
if step.Compare(duration.Duration{}) == 0 {
return nil, errStepCannotBeZero
}
return &seriesValueGenerator{
origStart: start,
stop: stop,
step: step,
genType: seriesTSValueGeneratorType,
genValue: seriesGenTSValue,
next: seriesTSNext,
}, nil
}
// ResolvedType implements the tree.ValueGenerator interface.
func (s *seriesValueGenerator) ResolvedType() *types.T {
return s.genType
}
// Start implements the tree.ValueGenerator interface.
func (s *seriesValueGenerator) Start(_ context.Context, _ *kv.Txn) error {
s.nextOK = true
s.start = s.origStart
s.value = s.origStart
return nil
}
// Close implements the tree.ValueGenerator interface.
func (s *seriesValueGenerator) Close() {}
// Next implements the tree.ValueGenerator interface.
func (s *seriesValueGenerator) Next(_ context.Context) (bool, error) {
return s.next(s)
}
// Values implements the tree.ValueGenerator interface.
func (s *seriesValueGenerator) Values() (tree.Datums, error) {
return s.genValue(s)
}
func makeVariadicUnnestGenerator(
_ *tree.EvalContext, args tree.Datums,
) (tree.ValueGenerator, error) {
var arrays []*tree.DArray
for _, a := range args {
arrays = append(arrays, tree.MustBeDArray(a))
}
g := &multipleArrayValueGenerator{arrays: arrays}
return g, nil
}
// multipleArrayValueGenerator is a value generator that returns each element of a
// list of arrays.
type multipleArrayValueGenerator struct {
arrays []*tree.DArray
nextIndex int
datums tree.Datums
}
// ResolvedType implements the tree.ValueGenerator interface.
func (s *multipleArrayValueGenerator) ResolvedType() *types.T {
arraysN := len(s.arrays)
returnTypes := make([]*types.T, arraysN)
labels := make([]string, arraysN)
for i, arr := range s.arrays {
returnTypes[i] = arr.ParamTyp
labels[i] = "unnest"
}
return types.MakeLabeledTuple(returnTypes, labels)
}
// Start implements the tree.ValueGenerator interface.
func (s *multipleArrayValueGenerator) Start(_ context.Context, _ *kv.Txn) error {
s.datums = make(tree.Datums, len(s.arrays))
s.nextIndex = -1
return nil
}
// Close implements the tree.ValueGenerator interface.
func (s *multipleArrayValueGenerator) Close() {}
// Next implements the tree.ValueGenerator interface.
func (s *multipleArrayValueGenerator) Next(_ context.Context) (bool, error) {
s.nextIndex++
for _, arr := range s.arrays {
if s.nextIndex < arr.Len() {
return true, nil
}
}
return false, nil
}
// Values implements the tree.ValueGenerator interface.
func (s *multipleArrayValueGenerator) Values() (tree.Datums, error) {
for i, arr := range s.arrays {
if s.nextIndex < arr.Len() {
s.datums[i] = arr.Array[s.nextIndex]
} else {
s.datums[i] = tree.DNull
}
}
return s.datums, nil
}
func makeArrayGenerator(_ *tree.EvalContext, args tree.Datums) (tree.ValueGenerator, error) {
arr := tree.MustBeDArray(args[0])
return &arrayValueGenerator{array: arr}, nil
}
// arrayValueGenerator is a value generator that returns each element of an
// array.
type arrayValueGenerator struct {
array *tree.DArray
nextIndex int
}
// ResolvedType implements the tree.ValueGenerator interface.
func (s *arrayValueGenerator) ResolvedType() *types.T {
return s.array.ParamTyp
}
// Start implements the tree.ValueGenerator interface.
func (s *arrayValueGenerator) Start(_ context.Context, _ *kv.Txn) error {
s.nextIndex = -1
return nil
}
// Close implements the tree.ValueGenerator interface.
func (s *arrayValueGenerator) Close() {}
// Next implements the tree.ValueGenerator interface.
func (s *arrayValueGenerator) Next(_ context.Context) (bool, error) {
s.nextIndex++
if s.nextIndex >= s.array.Len() {
return false, nil
}
return true, nil
}
// Values implements the tree.ValueGenerator interface.
func (s *arrayValueGenerator) Values() (tree.Datums, error) {
return tree.Datums{s.array.Array[s.nextIndex]}, nil
}
func makeExpandArrayGenerator(
evalCtx *tree.EvalContext, args tree.Datums,
) (tree.ValueGenerator, error) {
arr := tree.MustBeDArray(args[0])
g := &expandArrayValueGenerator{avg: arrayValueGenerator{array: arr}}
g.buf[1] = tree.NewDInt(tree.DInt(-1))
return g, nil
}
// expandArrayValueGenerator is a value generator that returns each element of
// an array and an index for it.
type expandArrayValueGenerator struct {
avg arrayValueGenerator
buf [2]tree.Datum
}
var expandArrayValueGeneratorLabels = []string{"x", "n"}
// ResolvedType implements the tree.ValueGenerator interface.
func (s *expandArrayValueGenerator) ResolvedType() *types.T {
return types.MakeLabeledTuple(
[]*types.T{s.avg.array.ParamTyp, types.Int},
expandArrayValueGeneratorLabels,
)
}
// Start implements the tree.ValueGenerator interface.
func (s *expandArrayValueGenerator) Start(_ context.Context, _ *kv.Txn) error {
s.avg.nextIndex = -1
return nil
}
// Close implements the tree.ValueGenerator interface.
func (s *expandArrayValueGenerator) Close() {}
// Next implements the tree.ValueGenerator interface.
func (s *expandArrayValueGenerator) Next(_ context.Context) (bool, error) {
s.avg.nextIndex++
return s.avg.nextIndex < s.avg.array.Len(), nil
}
// Values implements the tree.ValueGenerator interface.
func (s *expandArrayValueGenerator) Values() (tree.Datums, error) {
// Expand array's index is 1 based.
s.buf[0] = s.avg.array.Array[s.avg.nextIndex]
s.buf[1] = tree.NewDInt(tree.DInt(s.avg.nextIndex + 1))
return s.buf[:], nil
}
func makeGenerateSubscriptsGenerator(
evalCtx *tree.EvalContext, args tree.Datums,
) (tree.ValueGenerator, error) {
var arr *tree.DArray
dim := 1
if len(args) > 1 {
dim = int(tree.MustBeDInt(args[1]))
}
// We sadly only support 1D arrays right now.
if dim == 1 {
arr = tree.MustBeDArray(args[0])
} else {
arr = &tree.DArray{}
}
var reverse bool
if len(args) == 3 {
reverse = bool(tree.MustBeDBool(args[2]))
}
g := &subscriptsValueGenerator{
avg: arrayValueGenerator{array: arr},
reverse: reverse,
}
g.buf[0] = tree.NewDInt(tree.DInt(-1))
return g, nil
}
// subscriptsValueGenerator is a value generator that returns a series
// comprising the given array's subscripts.
type subscriptsValueGenerator struct {
avg arrayValueGenerator
buf [1]tree.Datum
// firstIndex is normally 1, since arrays are normally 1-indexed. But the
// special Postgres vector types are 0-indexed.
firstIndex int
reverse bool
}
var subscriptsValueGeneratorType = types.Int
// ResolvedType implements the tree.ValueGenerator interface.
func (s *subscriptsValueGenerator) ResolvedType() *types.T {
return subscriptsValueGeneratorType
}
// Start implements the tree.ValueGenerator interface.
func (s *subscriptsValueGenerator) Start(_ context.Context, _ *kv.Txn) error {
if s.reverse {
s.avg.nextIndex = s.avg.array.Len()
} else {
s.avg.nextIndex = -1
}
// Most arrays are 1-indexed, but not all.
s.firstIndex = s.avg.array.FirstIndex()
return nil
}
// Close implements the tree.ValueGenerator interface.
func (s *subscriptsValueGenerator) Close() {}
// Next implements the tree.ValueGenerator interface.
func (s *subscriptsValueGenerator) Next(_ context.Context) (bool, error) {
if s.reverse {
s.avg.nextIndex--
return s.avg.nextIndex >= 0, nil
}
s.avg.nextIndex++
return s.avg.nextIndex < s.avg.array.Len(), nil
}
// Values implements the tree.ValueGenerator interface.
func (s *subscriptsValueGenerator) Values() (tree.Datums, error) {
s.buf[0] = tree.NewDInt(tree.DInt(s.avg.nextIndex + s.firstIndex))
return s.buf[:], nil
}
// EmptyGenerator returns a new, empty generator. Used when a SRF
// evaluates to NULL.
func EmptyGenerator() tree.ValueGenerator {
return &arrayValueGenerator{array: tree.NewDArray(types.Any)}
}
// unaryValueGenerator supports the execution of crdb_internal.unary_table().
type unaryValueGenerator struct {
done bool
}
var unaryValueGeneratorType = types.EmptyTuple
func makeUnaryGenerator(_ *tree.EvalContext, args tree.Datums) (tree.ValueGenerator, error) {
return &unaryValueGenerator{}, nil
}
// ResolvedType implements the tree.ValueGenerator interface.
func (*unaryValueGenerator) ResolvedType() *types.T { return unaryValueGeneratorType }
// Start implements the tree.ValueGenerator interface.
func (s *unaryValueGenerator) Start(_ context.Context, _ *kv.Txn) error {
s.done = false
return nil
}
// Close implements the tree.ValueGenerator interface.
func (s *unaryValueGenerator) Close() {}
// Next implements the tree.ValueGenerator interface.
func (s *unaryValueGenerator) Next(_ context.Context) (bool, error) {
if !s.done {
s.done = true
return true, nil
}
return false, nil
}
var noDatums tree.Datums
// Values implements the tree.ValueGenerator interface.
func (s *unaryValueGenerator) Values() (tree.Datums, error) { return noDatums, nil }
func jsonAsText(j json.JSON) (tree.Datum, error) {
text, err := j.AsText()
if err != nil {
return nil, err
}
if text == nil {
return tree.DNull, nil
}
return tree.NewDString(*text), nil
}
var (
errJSONObjectKeysOnArray = pgerror.New(pgcode.InvalidParameterValue, "cannot call json_object_keys on an array")
errJSONObjectKeysOnScalar = pgerror.Newf(pgcode.InvalidParameterValue, "cannot call json_object_keys on a scalar")
errJSONDeconstructArrayAsObject = pgerror.New(pgcode.InvalidParameterValue, "cannot deconstruct an array as an object")
errJSONDeconstructScalarAsObject = pgerror.Newf(pgcode.InvalidParameterValue, "cannot deconstruct a scalar")
)
var jsonArrayElementsImpl = makeGeneratorOverload(
tree.ArgTypes{{"input", types.Jsonb}},
jsonArrayGeneratorType,
makeJSONArrayAsJSONGenerator,
"Expands a JSON array to a set of JSON values.",
tree.VolatilityImmutable,
)
var jsonArrayElementsTextImpl = makeGeneratorOverload(
tree.ArgTypes{{"input", types.Jsonb}},
jsonArrayTextGeneratorType,
makeJSONArrayAsTextGenerator,
"Expands a JSON array to a set of text values.",
tree.VolatilityImmutable,
)
var jsonArrayGeneratorLabels = []string{"value"}
var jsonArrayGeneratorType = types.Jsonb
var jsonArrayTextGeneratorType = types.String
type jsonArrayGenerator struct {
json tree.DJSON
nextIndex int
asText bool
buf [1]tree.Datum
}
var errJSONCallOnNonArray = pgerror.New(pgcode.InvalidParameterValue,
"cannot be called on a non-array")
func makeJSONArrayAsJSONGenerator(
_ *tree.EvalContext, args tree.Datums,
) (tree.ValueGenerator, error) {
return makeJSONArrayGenerator(args, false)
}
func makeJSONArrayAsTextGenerator(
_ *tree.EvalContext, args tree.Datums,
) (tree.ValueGenerator, error) {
return makeJSONArrayGenerator(args, true)
}
func makeJSONArrayGenerator(args tree.Datums, asText bool) (tree.ValueGenerator, error) {
target := tree.MustBeDJSON(args[0])
if target.Type() != json.ArrayJSONType {
return nil, errJSONCallOnNonArray
}
return &jsonArrayGenerator{
json: target,
asText: asText,
}, nil
}
// ResolvedType implements the tree.ValueGenerator interface.
func (g *jsonArrayGenerator) ResolvedType() *types.T {
if g.asText {
return jsonArrayTextGeneratorType
}
return jsonArrayGeneratorType
}
// Start implements the tree.ValueGenerator interface.
func (g *jsonArrayGenerator) Start(_ context.Context, _ *kv.Txn) error {
g.nextIndex = -1
g.json.JSON = g.json.JSON.MaybeDecode()
g.buf[0] = nil
return nil
}
// Close implements the tree.ValueGenerator interface.
func (g *jsonArrayGenerator) Close() {}
// Next implements the tree.ValueGenerator interface.
func (g *jsonArrayGenerator) Next(_ context.Context) (bool, error) {
g.nextIndex++
next, err := g.json.FetchValIdx(g.nextIndex)
if err != nil || next == nil {
return false, err
}
if g.asText {