-
Notifications
You must be signed in to change notification settings - Fork 3.8k
/
generator_builtins.go
3035 lines (2694 loc) · 93 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"
gojson "encoding/json"
"math/rand"
"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/kv/kvpb"
"github.com/cockroachdb/cockroach/pkg/roachpb"
"github.com/cockroachdb/cockroach/pkg/sql/lexbase"
"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/builtins/builtinconstants"
"github.com/cockroachdb/cockroach/pkg/sql/sem/eval"
"github.com/cockroachdb/cockroach/pkg/sql/sem/tree"
"github.com/cockroachdb/cockroach/pkg/sql/sem/volatility"
"github.com/cockroachdb/cockroach/pkg/sql/sessiondata"
"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/mon"
"github.com/cockroachdb/cockroach/pkg/util/randident"
"github.com/cockroachdb/cockroach/pkg/util/randident/randidentcfg"
"github.com/cockroachdb/cockroach/pkg/util/randutil"
"github.com/cockroachdb/cockroach/pkg/util/timeutil"
"github.com/cockroachdb/cockroach/pkg/util/tracing"
"github.com/cockroachdb/cockroach/pkg/util/tracing/tracingpb"
"github.com/cockroachdb/errors"
)
// See the comments at the start of generators.go for details about
// this functionality.
var _ eval.ValueGenerator = &seriesValueGenerator{}
var _ eval.ValueGenerator = &arrayValueGenerator{}
func init() {
// Add all windows to the builtins map after a few sanity checks.
for k, v := range generators {
for _, g := range v.overloads {
if g.Class != tree.GeneratorClass {
panic(errors.AssertionFailedf("generator functions should be marked with the tree.GeneratorClass "+
"function class, found %v", v))
}
}
registerBuiltin(k, v)
}
}
func genProps() tree.FunctionProperties {
return tree.FunctionProperties{
Category: builtinconstants.CategoryGenerator,
}
}
func jsonGenPropsWithLabels(returnLabels []string) tree.FunctionProperties {
return tree.FunctionProperties{
Category: builtinconstants.CategoryJSON,
ReturnLabels: returnLabels,
}
}
func recordGenProps() tree.FunctionProperties {
return tree.FunctionProperties{
Category: builtinconstants.CategoryGenerator,
ReturnsRecordType: true,
}
}
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(_ context.Context) {}
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.ParamTypes{{Name: "aclitems", Typ: types.StringArray}},
aclexplodeGeneratorType,
func(_ context.Context, _ *eval.Context, args tree.Datums) (eval.ValueGenerator, error) {
return aclexplodeGenerator{}, nil
},
"Produces a virtual table containing aclitem stuff ("+
"returns no rows as this feature is unsupported in CockroachDB)",
volatility.Stable,
),
),
"crdb_internal.scan": makeBuiltin(genProps(),
makeGeneratorOverload(
tree.ParamTypes{
{Name: "start_key", Typ: types.Bytes},
{Name: "end_key", Typ: types.Bytes},
},
spanKeyIteratorType,
func(ctx context.Context, evalCtx *eval.Context, args tree.Datums) (eval.ValueGenerator, error) {
isAdmin, err := evalCtx.SessionAccessor.HasAdminRole(ctx)
if err != nil {
return nil, err
}
if !isAdmin {
return nil, errors.New("crdb_internal.scan() requires admin privilege")
}
startKey := []byte(tree.MustBeDBytes(args[0]))
endKey := []byte(tree.MustBeDBytes(args[1]))
return newSpanKeyIterator(evalCtx, roachpb.Span{
Key: startKey,
EndKey: endKey,
}), nil
},
"Returns the raw keys and values with their timestamp from the specified span",
volatility.Stable,
),
makeGeneratorOverload(
tree.ParamTypes{
{Name: "span", Typ: types.BytesArray},
},
spanKeyIteratorType,
func(ctx context.Context, evalCtx *eval.Context, args tree.Datums) (eval.ValueGenerator, error) {
isAdmin, err := evalCtx.SessionAccessor.HasAdminRole(ctx)
if err != nil {
return nil, err
}
if !isAdmin {
return nil, errors.New("crdb_internal.scan() requires admin privilege")
}
arr := tree.MustBeDArray(args[0])
if arr.Len() != 2 {
return nil, errors.New("expected an array of two elements")
}
startKey := []byte(tree.MustBeDBytes(arr.Array[0]))
endKey := []byte(tree.MustBeDBytes(arr.Array[1]))
return newSpanKeyIterator(evalCtx, roachpb.Span{
Key: startKey,
EndKey: endKey,
}), nil
},
"Returns the raw keys and values from the specified span",
volatility.Stable,
),
),
"generate_series": makeBuiltin(genProps(),
// See https://www.postgresql.org/docs/current/static/functions-srf.html#FUNCTIONS-SRF-SERIES
makeGeneratorOverload(
tree.ParamTypes{{Name: "start", Typ: types.Int}, {Name: "end", Typ: types.Int}},
seriesValueGeneratorType,
makeSeriesGenerator,
"Produces a virtual table containing the integer values from `start` to `end`, inclusive.",
volatility.Immutable,
),
makeGeneratorOverload(
tree.ParamTypes{{Name: "start", Typ: types.Int}, {Name: "end", Typ: types.Int}, {Name: "step", Typ: types.Int}},
seriesValueGeneratorType,
makeSeriesGenerator,
"Produces a virtual table containing the integer values from `start` to `end`, inclusive, by increment of `step`.",
volatility.Immutable,
),
makeGeneratorOverload(
tree.ParamTypes{{Name: "start", Typ: types.Timestamp}, {Name: "end", Typ: types.Timestamp}, {Name: "step", Typ: types.Interval}},
seriesTSValueGeneratorType,
makeTSSeriesGenerator,
"Produces a virtual table containing the timestamp values from `start` to `end`, inclusive, by increment of `step`.",
volatility.Immutable,
),
makeGeneratorOverload(
tree.ParamTypes{{Name: "start", Typ: types.TimestampTZ}, {Name: "end", Typ: types.TimestampTZ}, {Name: "step", Typ: types.Interval}},
seriesTSTZValueGeneratorType,
makeTSTZSeriesGenerator,
"Produces a virtual table containing the timestampTZ values from `start` to `end`, inclusive, by increment of `step`.",
volatility.Immutable,
),
),
// 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 eval.TestingKnobs.CallbackGenerators.
"crdb_internal.testing_callback": makeBuiltin(genProps(),
makeGeneratorOverload(
tree.ParamTypes{{Name: "name", Typ: types.String}},
types.Int,
func(ctx context.Context, evalCtx *eval.Context, args tree.Datums) (eval.ValueGenerator, error) {
s, ok := tree.AsDString(args[0])
if !ok {
return nil, errors.Newf("expected string value, got %T", args[0])
}
name := string(s)
gen, ok := evalCtx.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.",
volatility.Volatile,
),
),
"pg_get_keywords": makeBuiltin(genProps(),
// See https://www.postgresql.org/docs/10/static/functions-info.html#FUNCTIONS-INFO-CATALOG-TABLE
makeGeneratorOverload(
tree.ParamTypes{},
keywordsValueGeneratorType,
makeKeywordsGenerator,
"Produces a virtual table containing the keywords known to the SQL parser.",
volatility.Immutable,
),
),
`pg_options_to_table`: makeBuiltin(
genProps(),
makeGeneratorOverload(
tree.ParamTypes{
{Name: "options", Typ: types.MakeArray(types.String)},
},
optionsToOverloadGeneratorType,
makeOptionsToTableGenerator,
"Converts the options array format to a table.",
// This is stable in PG, even though it's implemented immutability here.
// It is probably related to character encodings being configurable in PG.
volatility.Stable,
),
),
"regexp_split_to_table": makeBuiltin(
genProps(),
makeGeneratorOverload(
tree.ParamTypes{
{Name: "string", Typ: types.String},
{Name: "pattern", Typ: types.String},
},
types.String,
makeRegexpSplitToTableGeneratorFactory(false /* hasFlags */),
"Split string using a POSIX regular expression as the delimiter.",
volatility.Immutable,
),
makeGeneratorOverload(
tree.ParamTypes{
{Name: "string", Typ: types.String},
{Name: "pattern", Typ: types.String},
{Name: "flags", Typ: types.String},
},
types.String,
makeRegexpSplitToTableGeneratorFactory(true /* hasFlags */),
"Split string using a POSIX regular expression as the delimiter with flags."+regexpFlagInfo,
volatility.Immutable,
),
),
"unnest": makeBuiltin(genProps(),
// See https://www.postgresql.org/docs/current/static/functions-array.html
makeGeneratorOverloadWithReturnType(
tree.ParamTypes{{Name: "input", Typ: 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",
volatility.Immutable,
),
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",
volatility.Immutable,
),
),
"information_schema._pg_expandarray": makeBuiltin(genProps(),
makeGeneratorOverloadWithReturnType(
tree.ParamTypes{{Name: "input", Typ: 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",
volatility.Immutable,
),
),
"crdb_internal.unary_table": makeBuiltin(genProps(),
makeGeneratorOverload(
tree.ParamTypes{},
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.",
volatility.Volatile,
),
),
"generate_subscripts": makeBuiltin(genProps(),
// See https://www.postgresql.org/docs/current/static/functions-srf.html#FUNCTIONS-SRF-SUBSCRIPTS
makeGeneratorOverload(
tree.ParamTypes{{Name: "array", Typ: types.AnyArray}},
subscriptsValueGeneratorType,
makeGenerateSubscriptsGenerator,
"Returns a series comprising the given array's subscripts.",
volatility.Immutable,
),
makeGeneratorOverload(
tree.ParamTypes{{Name: "array", Typ: types.AnyArray}, {Name: "dim", Typ: types.Int}},
subscriptsValueGeneratorType,
makeGenerateSubscriptsGenerator,
"Returns a series comprising the given array's subscripts.",
volatility.Immutable,
),
makeGeneratorOverload(
tree.ParamTypes{{Name: "array", Typ: types.AnyArray}, {Name: "dim", Typ: types.Int}, {Name: "reverse", Typ: 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.",
volatility.Immutable,
),
),
"json_array_elements": makeBuiltin(jsonGenPropsWithLabels(jsonArrayGeneratorLabels), jsonArrayElementsImpl),
"jsonb_array_elements": makeBuiltin(jsonGenPropsWithLabels(jsonArrayGeneratorLabels), jsonArrayElementsImpl),
"json_array_elements_text": makeBuiltin(jsonGenPropsWithLabels(jsonArrayGeneratorLabels), jsonArrayElementsTextImpl),
"jsonb_array_elements_text": makeBuiltin(jsonGenPropsWithLabels(jsonArrayGeneratorLabels), jsonArrayElementsTextImpl),
"json_object_keys": makeBuiltin(genProps(), jsonObjectKeysImpl),
"jsonb_object_keys": makeBuiltin(genProps(), jsonObjectKeysImpl),
"json_each": makeBuiltin(jsonGenPropsWithLabels(jsonEachGeneratorLabels), jsonEachImpl),
"jsonb_each": makeBuiltin(jsonGenPropsWithLabels(jsonEachGeneratorLabels), jsonEachImpl),
"json_each_text": makeBuiltin(jsonGenPropsWithLabels(jsonEachGeneratorLabels), jsonEachTextImpl),
"jsonb_each_text": makeBuiltin(jsonGenPropsWithLabels(jsonEachGeneratorLabels), jsonEachTextImpl),
"json_populate_record": makeBuiltin(jsonPopulateProps, makeJSONPopulateImpl(makeJSONPopulateRecordGenerator,
"Expands the object in from_json to a row whose columns match the record type defined by base.",
)),
"jsonb_populate_record": makeBuiltin(jsonPopulateProps, makeJSONPopulateImpl(makeJSONPopulateRecordGenerator,
"Expands the object in from_json to a row whose columns match the record type defined by base.",
)),
"json_populate_recordset": makeBuiltin(jsonPopulateProps, makeJSONPopulateImpl(makeJSONPopulateRecordSetGenerator,
"Expands the outermost array of objects in from_json to a set of rows whose columns match the record type defined by base")),
"jsonb_populate_recordset": makeBuiltin(jsonPopulateProps, makeJSONPopulateImpl(makeJSONPopulateRecordSetGenerator,
"Expands the outermost array of objects in from_json to a set of rows whose columns match the record type defined by base")),
"json_to_record": makeBuiltin(recordGenProps(), jsonToRecordImpl),
"jsonb_to_record": makeBuiltin(recordGenProps(), jsonToRecordImpl),
"json_to_recordset": makeBuiltin(recordGenProps(), jsonToRecordSetImpl),
"jsonb_to_recordset": makeBuiltin(recordGenProps(), jsonToRecordSetImpl),
"crdb_internal.check_consistency": makeBuiltin(
tree.FunctionProperties{
Category: builtinconstants.CategorySystemInfo,
DistsqlBlocklist: true, // see #88222
},
makeGeneratorOverload(
tree.ParamTypes{
{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\n"+
"`SELECT * FROM crdb_internal.check_consistency(true, b'\\x02', b'\\x04')`",
volatility.Volatile,
),
),
"crdb_internal.list_sql_keys_in_range": makeBuiltin(
tree.FunctionProperties{
Category: builtinconstants.CategorySystemInfo,
},
makeGeneratorOverload(
tree.ParamTypes{
{Name: "range_id", Typ: types.Int},
},
rangeKeyIteratorType,
makeRangeKeyIterator,
"Returns all SQL K/V pairs within the requested range.",
volatility.Volatile,
),
),
"crdb_internal.payloads_for_span": makeBuiltin(
tree.FunctionProperties{
Category: builtinconstants.CategorySystemInfo,
},
makeGeneratorOverload(
tree.ParamTypes{
{Name: "span_id", Typ: types.Int},
},
payloadsForSpanGeneratorType,
makePayloadsForSpanGenerator,
"Returns the payload(s) of the requested span and all its children.",
volatility.Volatile,
),
),
"crdb_internal.payloads_for_trace": makeBuiltin(
tree.FunctionProperties{
Category: builtinconstants.CategorySystemInfo,
},
makeGeneratorOverload(
tree.ParamTypes{
{Name: "trace_id", Typ: types.Int},
},
payloadsForTraceGeneratorType,
makePayloadsForTraceGenerator,
"Returns the payload(s) of the requested trace.",
volatility.Volatile,
),
),
"crdb_internal.show_create_all_schemas": makeBuiltin(
tree.FunctionProperties{},
makeGeneratorOverload(
tree.ParamTypes{
{Name: "database_name", Typ: types.String},
},
showCreateAllSchemasGeneratorType,
makeShowCreateAllSchemasGenerator,
`Returns rows of CREATE schema statements.
The output can be used to recreate a database.'
`,
volatility.Volatile,
),
),
"crdb_internal.show_create_all_tables": makeBuiltin(
tree.FunctionProperties{},
makeGeneratorOverload(
tree.ParamTypes{
{Name: "database_name", Typ: types.String},
},
showCreateAllTablesGeneratorType,
makeShowCreateAllTablesGenerator,
`Returns rows of 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.'
`,
volatility.Volatile,
),
),
"crdb_internal.show_create_all_types": makeBuiltin(
tree.FunctionProperties{},
makeGeneratorOverload(
tree.ParamTypes{
{Name: "database_name", Typ: types.String},
},
showCreateAllTypesGeneratorType,
makeShowCreateAllTypesGenerator,
`Returns rows of CREATE type statements.
The output can be used to recreate a database.'
`,
volatility.Volatile,
),
),
"crdb_internal.decode_plan_gist": makeBuiltin(
tree.FunctionProperties{},
makeGeneratorOverload(
tree.ParamTypes{
{Name: "gist", Typ: types.String},
},
decodePlanGistGeneratorType,
makeDecodePlanGistGenerator,
`Returns rows of output similar to EXPLAIN from a gist such as those found in planGists element of the statistics column of the statement_statistics table.
`,
volatility.Volatile,
),
),
"crdb_internal.decode_external_plan_gist": makeBuiltin(
tree.FunctionProperties{},
makeGeneratorOverload(
tree.ParamTypes{
{Name: "gist", Typ: types.String},
},
decodePlanGistGeneratorType,
makeDecodeExternalPlanGistGenerator,
`Returns rows of output similar to EXPLAIN from a gist such as those found in planGists element of the statistics column of the statement_statistics table without attempting to resolve tables or indexes.
`,
volatility.Volatile,
),
),
"crdb_internal.gen_rand_ident": makeBuiltin(
tree.FunctionProperties{},
makeGeneratorOverload(
tree.ParamTypes{
{Name: "name_pattern", Typ: types.String},
{Name: "count", Typ: types.Int},
},
types.String,
func(ctx context.Context, evalCtx *eval.Context, args tree.Datums,
) (eval.ValueGenerator, error) {
return makeIdentGenerator(ctx, evalCtx, args[0], args[1], nil)
},
`Returns random SQL identifiers.
gen_rand_ident(pattern, count) is an alias for gen_rand_ident(pattern, count, '').
See the documentation of the other gen_rand_ident overload for details.
`,
volatility.Volatile,
),
makeGeneratorOverload(
tree.ParamTypes{
{Name: "name_pattern", Typ: types.String},
{Name: "count", Typ: types.Int},
{Name: "parameters", Typ: types.Jsonb},
},
types.String,
func(ctx context.Context, evalCtx *eval.Context, args tree.Datums,
) (eval.ValueGenerator, error) {
return makeIdentGenerator(ctx, evalCtx, args[0], args[1], args[2])
},
`Returns count random SQL identifiers that resemble the name_pattern.
The last argument is a JSONB object containing the following optional fields:
- "seed": the seed to use for the pseudo-random generator (default: random).`+
randidentcfg.ConfigDoc,
volatility.Volatile,
),
),
"crdb_internal.tenant_span_stats": makeBuiltin(genProps(),
// Tenant overload
makeGeneratorOverload(
tree.ParamTypes{},
tableSpanStatsGeneratorType,
makeTableSpanStatsGenerator,
"Returns statistics (range count, disk size, live range bytes, total range bytes, live range byte percentage) for all of the tenant's tables.",
volatility.Stable,
),
// Database overload
makeGeneratorOverload(
tree.ParamTypes{
{Name: "database_id", Typ: types.Int},
},
tableSpanStatsGeneratorType,
makeTableSpanStatsGenerator,
"Returns statistics (range count, disk size, live range bytes, total range bytes, live range byte percentage) for tables of the provided database id.",
volatility.Stable,
),
// Table overload
makeGeneratorOverload(
tree.ParamTypes{
{Name: "database_id", Typ: types.Int},
{Name: "table_id", Typ: types.Int},
},
tableSpanStatsGeneratorType,
makeTableSpanStatsGenerator,
"Returns statistics (range count, disk size, live range bytes, total range bytes, live range byte percentage) for the provided table id.",
volatility.Stable,
),
),
}
var decodePlanGistGeneratorType = types.String
type gistPlanGenerator struct {
gist string
index int
rows []string
evalCtx *eval.Context
external bool
}
var _ eval.ValueGenerator = &gistPlanGenerator{}
func (g *gistPlanGenerator) ResolvedType() *types.T {
return types.String
}
func (g *gistPlanGenerator) Start(_ context.Context, _ *kv.Txn) error {
rows, err := g.evalCtx.Planner.DecodeGist(g.gist, g.external)
if err != nil {
return err
}
g.rows = rows
g.index = -1
return nil
}
func (g *gistPlanGenerator) Next(context.Context) (bool, error) {
g.index++
return g.index < len(g.rows), nil
}
func (g *gistPlanGenerator) Close(context.Context) {}
// Values implements the tree.ValueGenerator interface.
func (g *gistPlanGenerator) Values() (tree.Datums, error) {
return tree.Datums{tree.NewDString(g.rows[g.index])}, nil
}
func makeDecodePlanGistGenerator(
ctx context.Context, evalCtx *eval.Context, args tree.Datums,
) (eval.ValueGenerator, error) {
gist := string(tree.MustBeDString(args[0]))
return &gistPlanGenerator{gist: gist, evalCtx: evalCtx, external: false}, nil
}
func makeDecodeExternalPlanGistGenerator(
ctx context.Context, evalCtx *eval.Context, args tree.Datums,
) (eval.ValueGenerator, error) {
gist := string(tree.MustBeDString(args[0]))
return &gistPlanGenerator{gist: gist, evalCtx: evalCtx, external: true}, nil
}
func makeGeneratorOverload(
in tree.TypeList, ret *types.T, g eval.GeneratorOverload, info string, volatility volatility.V,
) tree.Overload {
return makeGeneratorOverloadWithReturnType(in, tree.FixedReturnType(ret), g, info, volatility)
}
var unsuitableUseOfGeneratorFn = func(_ context.Context, _ *eval.Context, _ tree.Datums) (tree.Datum, error) {
return nil, errors.AssertionFailedf("generator functions cannot be evaluated as scalars")
}
var unsuitableUseOfGeneratorFnWithExprs eval.FnWithExprsOverload = func(
_ context.Context, _ *eval.Context, _ tree.Exprs,
) (tree.Datum, error) {
return nil, errors.AssertionFailedf("generator functions cannot be evaluated as scalars")
}
func makeGeneratorOverloadWithReturnType(
in tree.TypeList,
retType tree.ReturnTyper,
g eval.GeneratorOverload,
info string,
volatility volatility.V,
) tree.Overload {
return tree.Overload{
Types: in,
ReturnType: retType,
Generator: g,
Class: tree.GeneratorClass,
Info: info,
Volatility: volatility,
}
}
// regexpSplitToTableGenerator supports regexp_split_to_table.
type regexpSplitToTableGenerator struct {
words []string
curr int
}
func makeRegexpSplitToTableGeneratorFactory(hasFlags bool) eval.GeneratorOverload {
return func(
ctx context.Context, evalCtx *eval.Context, args tree.Datums,
) (eval.ValueGenerator, error) {
words, err := regexpSplit(evalCtx, 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(_ context.Context) {}
// 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
}
type optionsToTableGenerator struct {
arr *tree.DArray
idx int
}
func makeOptionsToTableGenerator(
_ context.Context, _ *eval.Context, d tree.Datums,
) (eval.ValueGenerator, error) {
arr := tree.MustBeDArray(d[0])
return &optionsToTableGenerator{arr: arr, idx: -1}, nil
}
var optionsToOverloadGeneratorType = types.MakeLabeledTuple(
[]*types.T{types.String, types.String},
[]string{"option_name", "option_value"},
)
// ResolvedType implements the tree.ValueGenerator interface.
func (*optionsToTableGenerator) ResolvedType() *types.T {
return optionsToOverloadGeneratorType
}
// Close implements the tree.ValueGenerator interface.
func (*optionsToTableGenerator) Close(_ context.Context) {}
// Start implements the tree.ValueGenerator interface.
func (g *optionsToTableGenerator) Start(_ context.Context, _ *kv.Txn) error {
return nil
}
// Next implements the tree.ValueGenerator interface.
func (g *optionsToTableGenerator) Next(_ context.Context) (bool, error) {
g.idx++
if g.idx >= g.arr.Len() {
return false, nil
}
return true, nil
}
// Values implements the tree.ValueGenerator interface.
func (g *optionsToTableGenerator) Values() (tree.Datums, error) {
elem := g.arr.Array[g.idx]
if elem == tree.DNull {
return nil, pgerror.Newf(
pgcode.InvalidParameterValue,
"null array element not allowed in this context",
)
}
s := string(tree.MustBeDString(elem))
split := strings.SplitN(s, "=", 2)
ret := make(tree.Datums, 2)
ret[0] = tree.NewDString(split[0])
if len(split) == 2 {
ret[1] = tree.NewDString(split[1])
} else {
ret[1] = tree.DNull
}
return ret, 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(
_ context.Context, _ *eval.Context, _ tree.Datums,
) (eval.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(_ context.Context) {}
// 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(lexbase.KeywordNames), nil
}
// Values implements the tree.ValueGenerator interface.
func (k *keywordsValueGenerator) Values() (tree.Datums, error) {
kw := lexbase.KeywordNames[k.curKeyword]
cat := lexbase.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 seriesTSTZValueGeneratorType = types.TimestampTZ
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 seriesGenTSTZValue(s *seriesValueGenerator) (tree.Datums, error) {
ts, err := tree.MakeDTimestampTZ(s.value.(time.Time), time.Microsecond)
if err != nil {
return nil, err
}
return tree.Datums{ts}, nil
}
func makeSeriesGenerator(
_ context.Context, _ *eval.Context, args tree.Datums,
) (eval.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(
_ context.Context, _ *eval.Context, args tree.Datums,
) (eval.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
}
func makeTSTZSeriesGenerator(
_ context.Context, _ *eval.Context, args tree.Datums,
) (eval.ValueGenerator, error) {
start := args[0].(*tree.DTimestampTZ).Time
stop := args[1].(*tree.DTimestampTZ).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: seriesTSTZValueGeneratorType,
genValue: seriesGenTSTZValue,
next: seriesTSNext,
}, nil
}
// ResolvedType implements the tree.ValueGenerator interface.
func (s *seriesValueGenerator) ResolvedType() *types.T {
return s.genType
}