-
Notifications
You must be signed in to change notification settings - Fork 3.8k
/
builtins.go
9508 lines (8916 loc) · 320 KB
/
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 2015 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"
"compress/gzip"
"context"
"crypto/md5"
cryptorand "crypto/rand"
"crypto/sha1"
"crypto/sha256"
"crypto/sha512"
gojson "encoding/json"
"fmt"
"hash"
"hash/crc32"
"hash/fnv"
"io/ioutil"
"math"
"math/bits"
"math/rand"
"net"
"regexp/syntax"
"strconv"
"strings"
"time"
"unicode"
"unicode/utf8"
"github.com/cockroachdb/cockroach/pkg/base"
"github.com/cockroachdb/cockroach/pkg/build"
"github.com/cockroachdb/cockroach/pkg/clusterversion"
"github.com/cockroachdb/cockroach/pkg/config/zonepb"
"github.com/cockroachdb/cockroach/pkg/keys"
"github.com/cockroachdb/cockroach/pkg/kv"
"github.com/cockroachdb/cockroach/pkg/kv/kvserver/kvserverbase"
"github.com/cockroachdb/cockroach/pkg/roachpb"
"github.com/cockroachdb/cockroach/pkg/security/password"
"github.com/cockroachdb/cockroach/pkg/server/telemetry"
"github.com/cockroachdb/cockroach/pkg/settings"
"github.com/cockroachdb/cockroach/pkg/settings/cluster"
"github.com/cockroachdb/cockroach/pkg/sql/catalog/catalogkeys"
"github.com/cockroachdb/cockroach/pkg/sql/catalog/descpb"
"github.com/cockroachdb/cockroach/pkg/sql/colexecerror"
"github.com/cockroachdb/cockroach/pkg/sql/lex"
"github.com/cockroachdb/cockroach/pkg/sql/lexbase"
"github.com/cockroachdb/cockroach/pkg/sql/parser"
"github.com/cockroachdb/cockroach/pkg/sql/pgwire/pgcode"
"github.com/cockroachdb/cockroach/pkg/sql/pgwire/pgerror"
"github.com/cockroachdb/cockroach/pkg/sql/pgwire/pgnotice"
"github.com/cockroachdb/cockroach/pkg/sql/protoreflect"
"github.com/cockroachdb/cockroach/pkg/sql/roleoption"
"github.com/cockroachdb/cockroach/pkg/sql/rowenc"
"github.com/cockroachdb/cockroach/pkg/sql/rowenc/keyside"
"github.com/cockroachdb/cockroach/pkg/sql/sem/asof"
"github.com/cockroachdb/cockroach/pkg/sql/sem/catid"
"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/sessiondatapb"
"github.com/cockroachdb/cockroach/pkg/sql/sqlliveness"
"github.com/cockroachdb/cockroach/pkg/sql/sqlstats/persistedsqlstats/sqlstatsutil"
"github.com/cockroachdb/cockroach/pkg/sql/sqltelemetry"
"github.com/cockroachdb/cockroach/pkg/sql/types"
"github.com/cockroachdb/cockroach/pkg/util"
"github.com/cockroachdb/cockroach/pkg/util/duration"
"github.com/cockroachdb/cockroach/pkg/util/encoding"
"github.com/cockroachdb/cockroach/pkg/util/errorutil/unimplemented"
"github.com/cockroachdb/cockroach/pkg/util/fuzzystrmatch"
"github.com/cockroachdb/cockroach/pkg/util/humanizeutil"
"github.com/cockroachdb/cockroach/pkg/util/ipaddr"
"github.com/cockroachdb/cockroach/pkg/util/json"
"github.com/cockroachdb/cockroach/pkg/util/log"
"github.com/cockroachdb/cockroach/pkg/util/timeofday"
"github.com/cockroachdb/cockroach/pkg/util/timetz"
"github.com/cockroachdb/cockroach/pkg/util/timeutil"
"github.com/cockroachdb/cockroach/pkg/util/timeutil/pgdate"
"github.com/cockroachdb/cockroach/pkg/util/tracing"
"github.com/cockroachdb/cockroach/pkg/util/tracing/tracingpb"
"github.com/cockroachdb/cockroach/pkg/util/trigram"
"github.com/cockroachdb/cockroach/pkg/util/ulid"
"github.com/cockroachdb/cockroach/pkg/util/unaccent"
"github.com/cockroachdb/cockroach/pkg/util/uuid"
"github.com/cockroachdb/errors"
"github.com/knz/strtime"
)
var (
errEmptyInputString = pgerror.New(pgcode.InvalidParameterValue, "the input string must not be empty")
errZeroIP = pgerror.New(pgcode.InvalidParameterValue, "zero length IP")
errChrValueTooSmall = pgerror.New(pgcode.InvalidParameterValue, "input value must be >= 0")
errChrValueTooLarge = pgerror.Newf(pgcode.InvalidParameterValue,
"input value must be <= %d (maximum Unicode code point)", utf8.MaxRune)
errStringTooLarge = pgerror.Newf(pgcode.ProgramLimitExceeded,
"requested length too large, exceeds %s", humanizeutil.IBytes(maxAllocatedStringSize))
errInvalidNull = pgerror.New(pgcode.InvalidParameterValue, "input cannot be NULL")
// SequenceNameArg represents the name of sequence (string) arguments in
// builtin functions.
SequenceNameArg = "sequence_name"
)
const defaultFollowerReadDuration = -4800 * time.Millisecond
const maxAllocatedStringSize = 128 * 1024 * 1024
const errInsufficientArgsFmtString = "unknown signature: %s()"
const (
categoryArray = "Array"
categoryComparison = "Comparison"
categoryCompatibility = "Compatibility"
categoryCrypto = "Cryptographic"
categoryDateAndTime = "Date and time"
categoryEnum = "Enum"
categoryFullTextSearch = "Full Text Search"
categoryGenerator = "Set-returning"
categoryTrigram = "Trigrams"
categoryFuzzyStringMatching = "Fuzzy String Matching"
categoryIDGeneration = "ID generation"
categoryJSON = "JSONB"
categoryMultiRegion = "Multi-region"
categoryMultiTenancy = "Multi-tenancy"
categorySequences = "Sequence"
categorySpatial = "Spatial"
categoryString = "String and byte"
categorySystemInfo = "System info"
categorySystemRepair = "System repair"
categoryStreamIngestion = "Stream Ingestion"
)
func categorizeType(t *types.T) string {
switch t.Family() {
case types.DateFamily, types.IntervalFamily, types.TimestampFamily, types.TimestampTZFamily:
return categoryDateAndTime
case types.StringFamily, types.BytesFamily:
return categoryString
default:
return strings.ToUpper(t.String())
}
}
const (
// GatewayRegionBuiltinName is the name for the builtin that returns the gateway
// region of the current node.
GatewayRegionBuiltinName = "gateway_region"
// DefaultToDatabasePrimaryRegionBuiltinName is the name for the builtin that
// takes in a region and returns it if it is a valid region on the database.
// Otherwise, it returns the primary region.
DefaultToDatabasePrimaryRegionBuiltinName = "default_to_database_primary_region"
// RehomeRowBuiltinName is the name for the builtin that rehomes a row to the
// user's gateway region, defaulting to the database primary region.
RehomeRowBuiltinName = "rehome_row"
)
var digitNames = [...]string{"zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine"}
const regexpFlagInfo = `
CockroachDB supports the following flags:
| Flag | Description |
|----------------|-------------------------------------------------------------------|
| **c** | Case-sensitive matching |
| **g** | Global matching (match each substring instead of only the first) |
| **i** | Case-insensitive matching |
| **m** or **n** | Newline-sensitive (see below) |
| **p** | Partial newline-sensitive matching (see below) |
| **s** | Newline-insensitive (default) |
| **w** | Inverse partial newline-sensitive matching (see below) |
| Mode | ` + "`.` and `[^...]` match newlines | `^` and `$` match line boundaries" + `|
|------|----------------------------------|--------------------------------------|
| s | yes | no |
| w | yes | yes |
| p | no | no |
| m/n | no | yes |`
// builtinDefinition represents a built-in function before it becomes
// a tree.FunctionDefinition.
type builtinDefinition struct {
props tree.FunctionProperties
overloads []tree.Overload
}
// GetBuiltinProperties provides low-level access to a built-in function's properties.
// For a better, semantic-rich interface consider using tree.FunctionDefinition
// instead, and resolve function names via ResolvableFunctionReference.Resolve().
func GetBuiltinProperties(name string) (*tree.FunctionProperties, []tree.Overload) {
def, ok := builtins[name]
if !ok {
return nil, nil
}
return &def.props, def.overloads
}
// defProps is used below to define built-in functions with default properties.
func defProps() tree.FunctionProperties { return tree.FunctionProperties{} }
// arrayProps is used below for array functions.
func arrayProps() tree.FunctionProperties { return tree.FunctionProperties{Category: categoryArray} }
// arrayPropsNullableArgs is used below for array functions that accept NULLs as arguments.
func arrayPropsNullableArgs() tree.FunctionProperties {
p := arrayProps()
p.NullableArgs = true
return p
}
func makeBuiltin(props tree.FunctionProperties, overloads ...tree.Overload) builtinDefinition {
return builtinDefinition{
props: props,
overloads: overloads,
}
}
func newDecodeError(enc string) error {
return pgerror.Newf(pgcode.CharacterNotInRepertoire,
"invalid byte sequence for encoding %q", enc)
}
func newEncodeError(c rune, enc string) error {
return pgerror.Newf(pgcode.UntranslatableCharacter,
"character %q has no representation in encoding %q", c, enc)
}
func mustBeDIntInTenantRange(e tree.Expr) (tree.DInt, error) {
tenID := tree.MustBeDInt(e)
if int64(tenID) <= 0 {
return 0, pgerror.New(pgcode.InvalidParameterValue, "tenant ID must be positive")
}
return tenID, nil
}
// builtins contains the built-in functions indexed by name.
//
// For use in other packages, see AllBuiltinNames and GetBuiltinProperties().
var builtins = map[string]builtinDefinition{
// TODO(XisiHuang): support encoding, i.e., length(str, encoding).
"length": lengthImpls(true /* includeBitOverload */),
"char_length": lengthImpls(false /* includeBitOverload */),
"character_length": lengthImpls(false /* includeBitOverload */),
"bit_length": makeBuiltin(tree.FunctionProperties{Category: categoryString},
stringOverload1(
func(_ *eval.Context, s string) (tree.Datum, error) {
return tree.NewDInt(tree.DInt(len(s) * 8)), nil
},
types.Int,
"Calculates the number of bits used to represent `val`.",
volatility.Immutable,
),
bytesOverload1(
func(_ *eval.Context, s string) (tree.Datum, error) {
return tree.NewDInt(tree.DInt(len(s) * 8)), nil
},
types.Int,
"Calculates the number of bits used to represent `val`.",
volatility.Immutable,
),
bitsOverload1(
func(_ *eval.Context, s *tree.DBitArray) (tree.Datum, error) {
return tree.NewDInt(tree.DInt(s.BitArray.BitLen())), nil
},
types.Int,
"Calculates the number of bits used to represent `val`.",
volatility.Immutable,
),
),
"octet_length": makeBuiltin(tree.FunctionProperties{Category: categoryString},
stringOverload1(
func(_ *eval.Context, s string) (tree.Datum, error) {
return tree.NewDInt(tree.DInt(len(s))), nil
},
types.Int,
"Calculates the number of bytes used to represent `val`.",
volatility.Immutable,
),
bytesOverload1(
func(_ *eval.Context, s string) (tree.Datum, error) {
return tree.NewDInt(tree.DInt(len(s))), nil
},
types.Int,
"Calculates the number of bytes used to represent `val`.",
volatility.Immutable,
),
bitsOverload1(
func(_ *eval.Context, s *tree.DBitArray) (tree.Datum, error) {
return tree.NewDInt(tree.DInt((s.BitArray.BitLen() + 7) / 8)), nil
},
types.Int,
"Calculates the number of bits used to represent `val`.",
volatility.Immutable,
),
),
// TODO(pmattis): What string functions should also support types.Bytes?
"lower": makeBuiltin(tree.FunctionProperties{Category: categoryString},
stringOverload1(
func(evalCtx *eval.Context, s string) (tree.Datum, error) {
return tree.NewDString(strings.ToLower(s)), nil
},
types.String,
"Converts all characters in `val` to their lower-case equivalents.",
volatility.Immutable,
),
),
"unaccent": makeBuiltin(tree.FunctionProperties{Category: categoryString},
stringOverload1(
func(evalCtx *eval.Context, s string) (tree.Datum, error) {
var b strings.Builder
for _, ch := range s {
v, ok := unaccent.Dictionary[ch]
if ok {
b.WriteString(v)
} else {
b.WriteRune(ch)
}
}
return tree.NewDString(b.String()), nil
},
types.String,
"Removes accents (diacritic signs) from the text provided in `val`.",
volatility.Immutable,
),
),
"upper": makeBuiltin(tree.FunctionProperties{Category: categoryString},
stringOverload1(
func(evalCtx *eval.Context, s string) (tree.Datum, error) {
return tree.NewDString(strings.ToUpper(s)), nil
},
types.String,
"Converts all characters in `val` to their to their upper-case equivalents.",
volatility.Immutable,
),
),
"prettify_statement": makeBuiltin(tree.FunctionProperties{Category: categoryString},
stringOverload1(
func(evalCtx *eval.Context, s string) (tree.Datum, error) {
formattedStmt, err := prettyStatement(tree.DefaultPrettyCfg(), s)
if err != nil {
return nil, err
}
return tree.NewDString(formattedStmt), nil
},
types.String,
"Prettifies a statement using a the default pretty-printing config.",
volatility.Immutable,
),
tree.Overload{
Types: tree.ArgTypes{
{"statement", types.String},
{"line_width", types.Int},
{"align_mode", types.Int},
{"case_mode", types.Int},
},
ReturnType: tree.FixedReturnType(types.String),
Fn: func(_ *eval.Context, args tree.Datums) (tree.Datum, error) {
stmt := string(tree.MustBeDString(args[0]))
lineWidth := int(tree.MustBeDInt(args[1]))
alignMode := int(tree.MustBeDInt(args[2]))
caseMode := int(tree.MustBeDInt(args[3]))
formattedStmt, err := prettyStatementCustomConfig(stmt, lineWidth, alignMode, caseMode)
if err != nil {
return nil, err
}
return tree.NewDString(formattedStmt), nil
},
Info: "Prettifies a statement using a user-configured pretty-printing config.\n" +
"Align mode values range from 0 - 3, representing no, partial, full, and extra alignment respectively.\n" +
"Case mode values range between 0 - 1, representing lower casing and upper casing respectively.",
Volatility: volatility.Immutable,
},
),
"substr": substringImpls,
"substring": substringImpls,
// concat concatenates the text representations of all the arguments.
// NULL arguments are ignored.
"concat": makeBuiltin(
tree.FunctionProperties{
NullableArgs: true,
},
tree.Overload{
Types: tree.VariadicType{VarType: types.String},
ReturnType: tree.FixedReturnType(types.String),
Fn: func(_ *eval.Context, args tree.Datums) (tree.Datum, error) {
var buffer bytes.Buffer
length := 0
for _, d := range args {
if d == tree.DNull {
continue
}
length += len(string(tree.MustBeDString(d)))
if length > maxAllocatedStringSize {
return nil, errStringTooLarge
}
buffer.WriteString(string(tree.MustBeDString(d)))
}
return tree.NewDString(buffer.String()), nil
},
Info: "Concatenates a comma-separated list of strings.",
Volatility: volatility.Immutable,
// In Postgres concat can take any arguments, converting them to
// their text representation. Since the text representation can
// depend on the context (e.g. timezone), the function is Stable. In
// our case, we only take String inputs so our version is ImmutableCopy.
IgnoreVolatilityCheck: true,
},
),
"concat_ws": makeBuiltin(
tree.FunctionProperties{
NullableArgs: true,
},
tree.Overload{
Types: tree.VariadicType{VarType: types.String},
ReturnType: tree.FixedReturnType(types.String),
Fn: func(_ *eval.Context, args tree.Datums) (tree.Datum, error) {
if len(args) == 0 {
return nil, pgerror.Newf(pgcode.UndefinedFunction, errInsufficientArgsFmtString, "concat_ws")
}
if args[0] == tree.DNull {
return tree.DNull, nil
}
sep := string(tree.MustBeDString(args[0]))
var buf bytes.Buffer
prefix := ""
length := 0
for _, d := range args[1:] {
if d == tree.DNull {
continue
}
length += len(prefix) + len(string(tree.MustBeDString(d)))
if length > maxAllocatedStringSize {
return nil, errStringTooLarge
}
// Note: we can't use the range index here because that
// would break when the 2nd argument is NULL.
buf.WriteString(prefix)
prefix = sep
buf.WriteString(string(tree.MustBeDString(d)))
}
return tree.NewDString(buf.String()), nil
},
Info: "Uses the first argument as a separator between the concatenation of the " +
"subsequent arguments. \n\nFor example `concat_ws('!','wow','great')` " +
"returns `wow!great`.",
Volatility: volatility.Immutable,
// In Postgres concat_ws can take any arguments, converting them to
// their text representation. Since the text representation can
// depend on the context (e.g. timezone), the function is Stable. In
// our case, we only take String inputs so our version is ImmutableCopy.
IgnoreVolatilityCheck: true,
},
),
// https://www.postgresql.org/docs/10/static/functions-string.html#FUNCTIONS-STRING-OTHER
"convert_from": makeBuiltin(tree.FunctionProperties{Category: categoryString},
tree.Overload{
Types: tree.ArgTypes{{"str", types.Bytes}, {"enc", types.String}},
ReturnType: tree.FixedReturnType(types.String),
Fn: func(_ *eval.Context, args tree.Datums) (tree.Datum, error) {
str := []byte(tree.MustBeDBytes(args[0]))
enc := CleanEncodingName(string(tree.MustBeDString(args[1])))
switch enc {
// All the following are aliases to each other in PostgreSQL.
case "utf8", "unicode", "cp65001":
if !utf8.Valid(str) {
return nil, newDecodeError("UTF8")
}
return tree.NewDString(string(str)), nil
// All the following are aliases to each other in PostgreSQL.
case "latin1", "iso88591", "cp28591":
var buf strings.Builder
for _, c := range str {
buf.WriteRune(rune(c))
}
return tree.NewDString(buf.String()), nil
}
return nil, pgerror.Newf(pgcode.InvalidParameterValue,
"invalid source encoding name %q", enc)
},
Info: "Decode the bytes in `str` into a string using encoding `enc`. " +
"Supports encodings 'UTF8' and 'LATIN1'.",
Volatility: volatility.Immutable,
IgnoreVolatilityCheck: true,
}),
// https://www.postgresql.org/docs/10/static/functions-string.html#FUNCTIONS-STRING-OTHER
"convert_to": makeBuiltin(tree.FunctionProperties{Category: categoryString},
tree.Overload{
Types: tree.ArgTypes{{"str", types.String}, {"enc", types.String}},
ReturnType: tree.FixedReturnType(types.Bytes),
Fn: func(_ *eval.Context, args tree.Datums) (tree.Datum, error) {
str := string(tree.MustBeDString(args[0]))
enc := CleanEncodingName(string(tree.MustBeDString(args[1])))
switch enc {
// All the following are aliases to each other in PostgreSQL.
case "utf8", "unicode", "cp65001":
return tree.NewDBytes(tree.DBytes([]byte(str))), nil
// All the following are aliases to each other in PostgreSQL.
case "latin1", "iso88591", "cp28591":
res := make([]byte, 0, len(str))
for _, c := range str {
if c > 255 {
return nil, newEncodeError(c, "LATIN1")
}
res = append(res, byte(c))
}
return tree.NewDBytes(tree.DBytes(res)), nil
}
return nil, pgerror.Newf(pgcode.InvalidParameterValue,
"invalid destination encoding name %q", enc)
},
Info: "Encode the string `str` as a byte array using encoding `enc`. " +
"Supports encodings 'UTF8' and 'LATIN1'.",
Volatility: volatility.Immutable,
IgnoreVolatilityCheck: true,
}),
// https://www.postgresql.org/docs/9.0/functions-binarystring.html#FUNCTIONS-BINARYSTRING-OTHER
"get_bit": makeBuiltin(tree.FunctionProperties{Category: categoryString},
tree.Overload{
Types: tree.ArgTypes{{"bit_string", types.VarBit}, {"index", types.Int}},
ReturnType: tree.FixedReturnType(types.Int),
Fn: func(_ *eval.Context, args tree.Datums) (tree.Datum, error) {
bitString := tree.MustBeDBitArray(args[0])
index := int(tree.MustBeDInt(args[1]))
bit, err := bitString.GetBitAtIndex(index)
if err != nil {
return nil, err
}
return tree.NewDInt(tree.DInt(bit)), nil
},
Info: "Extracts a bit at given index in the bit array.",
Volatility: volatility.Immutable,
},
tree.Overload{
Types: tree.ArgTypes{{"byte_string", types.Bytes}, {"index", types.Int}},
ReturnType: tree.FixedReturnType(types.Int),
Fn: func(_ *eval.Context, args tree.Datums) (tree.Datum, error) {
byteString := []byte(*args[0].(*tree.DBytes))
index := int(tree.MustBeDInt(args[1]))
// Check whether index asked is inside ByteArray.
if index < 0 || index >= 8*len(byteString) {
return nil, pgerror.Newf(pgcode.ArraySubscript,
"bit index %d out of valid range (0..%d)", index, 8*len(byteString)-1)
}
// To extract a bit at the given index, we have to determine the
// position within byte array, i.e. index/8 after that checked
// the bit at residual index.
if byteString[index/8]&(byte(1)<<(byte(index)%8)) != 0 {
return tree.NewDInt(tree.DInt(1)), nil
}
return tree.NewDInt(tree.DInt(0)), nil
},
Info: "Extracts a bit at the given index in the byte array.",
Volatility: volatility.Immutable,
}),
// https://www.postgresql.org/docs/9.0/functions-binarystring.html#FUNCTIONS-BINARYSTRING-OTHER
"get_byte": makeBuiltin(tree.FunctionProperties{Category: categoryString},
tree.Overload{
Types: tree.ArgTypes{{"byte_string", types.Bytes}, {"index", types.Int}},
ReturnType: tree.FixedReturnType(types.Int),
Fn: func(_ *eval.Context, args tree.Datums) (tree.Datum, error) {
byteString := []byte(*args[0].(*tree.DBytes))
index := int(tree.MustBeDInt(args[1]))
// Check whether index asked is inside ByteArray.
if index < 0 || index >= len(byteString) {
return nil, pgerror.Newf(pgcode.ArraySubscript,
"byte index %d out of valid range (0..%d)", index, len(byteString)-1)
}
return tree.NewDInt(tree.DInt(byteString[index])), nil
},
Info: "Extracts a byte at the given index in the byte array.",
Volatility: volatility.Immutable,
}),
// https://www.postgresql.org/docs/9.0/functions-binarystring.html#FUNCTIONS-BINARYSTRING-OTHER
"set_bit": makeBuiltin(tree.FunctionProperties{Category: categoryString},
tree.Overload{
Types: tree.ArgTypes{
{"bit_string", types.VarBit},
{"index", types.Int},
{"to_set", types.Int},
},
ReturnType: tree.FixedReturnType(types.VarBit),
Fn: func(_ *eval.Context, args tree.Datums) (tree.Datum, error) {
bitString := tree.MustBeDBitArray(args[0])
index := int(tree.MustBeDInt(args[1]))
toSet := int(tree.MustBeDInt(args[2]))
// Value of bit can only be set to 1 or 0.
if toSet != 0 && toSet != 1 {
return nil, pgerror.Newf(pgcode.InvalidParameterValue,
"new bit must be 0 or 1.")
}
updatedBitString, err := bitString.SetBitAtIndex(index, toSet)
if err != nil {
return nil, err
}
return &tree.DBitArray{BitArray: updatedBitString}, nil
},
Info: "Updates a bit at given index in the bit array.",
Volatility: volatility.Immutable,
},
tree.Overload{
Types: tree.ArgTypes{
{"byte_string", types.Bytes},
{"index", types.Int},
{"to_set", types.Int},
},
ReturnType: tree.FixedReturnType(types.Bytes),
Fn: func(_ *eval.Context, args tree.Datums) (tree.Datum, error) {
byteString := []byte(*args[0].(*tree.DBytes))
index := int(tree.MustBeDInt(args[1]))
toSet := int(tree.MustBeDInt(args[2]))
// Value of bit can only be set to 1 or 0.
if toSet != 0 && toSet != 1 {
return nil, pgerror.Newf(pgcode.InvalidParameterValue,
"new bit must be 0 or 1")
}
// Check whether index asked is inside ByteArray.
if index < 0 || index >= 8*len(byteString) {
return nil, pgerror.Newf(pgcode.ArraySubscript,
"bit index %d out of valid range (0..%d)", index, 8*len(byteString)-1)
}
// To update a bit at the given index, we have to determine the
// position within byte array, i.e. index/8 after that checked
// the bit at residual index.
// Forcefully making bit at the index to 0.
byteString[index/8] &= ^(byte(1) << (byte(index) % 8))
// Updating value at the index to toSet.
byteString[index/8] |= byte(toSet) << (byte(index) % 8)
return tree.NewDBytes(tree.DBytes(byteString)), nil
},
Info: "Updates a bit at the given index in the byte array.",
Volatility: volatility.Immutable,
}),
// https://www.postgresql.org/docs/9.0/functions-binarystring.html#FUNCTIONS-BINARYSTRING-OTHER
"set_byte": makeBuiltin(tree.FunctionProperties{Category: categoryString},
tree.Overload{
Types: tree.ArgTypes{
{"byte_string", types.Bytes},
{"index", types.Int},
{"to_set", types.Int},
},
ReturnType: tree.FixedReturnType(types.Bytes),
Fn: func(_ *eval.Context, args tree.Datums) (tree.Datum, error) {
byteString := []byte(*args[0].(*tree.DBytes))
index := int(tree.MustBeDInt(args[1]))
toSet := int(tree.MustBeDInt(args[2]))
// Check whether index asked is inside ByteArray.
if index < 0 || index >= len(byteString) {
return nil, pgerror.Newf(pgcode.ArraySubscript,
"byte index %d out of valid range (0..%d)", index, len(byteString)-1)
}
byteString[index] = byte(toSet)
return tree.NewDBytes(tree.DBytes(byteString)), nil
},
Info: "Updates a byte at the given index in the byte array.",
Volatility: volatility.Immutable,
}),
"uuid_generate_v4": generateRandomUUID4Impl,
"uuid_nil": generateConstantUUIDImpl(
uuid.Nil, "Returns a nil UUID constant.",
),
"uuid_ns_dns": generateConstantUUIDImpl(
uuid.NamespaceDNS, "Returns a constant designating the DNS namespace for UUIDs.",
),
"uuid_ns_url": generateConstantUUIDImpl(
uuid.NamespaceURL, "Returns a constant designating the URL namespace for UUIDs.",
),
"uuid_ns_oid": generateConstantUUIDImpl(
uuid.NamespaceOID,
"Returns a constant designating the ISO object identifier (OID) namespace for UUIDs. "+
"These are unrelated to the OID type used internally in the database.",
),
"uuid_ns_x500": generateConstantUUIDImpl(
uuid.NamespaceX500, "Returns a constant designating the X.500 distinguished name (DN) namespace for UUIDs.",
),
"uuid_generate_v1": makeBuiltin(
tree.FunctionProperties{
Category: categoryIDGeneration,
},
tree.Overload{
Types: tree.ArgTypes{},
ReturnType: tree.FixedReturnType(types.Uuid),
Fn: func(_ *eval.Context, _ tree.Datums) (tree.Datum, error) {
gen := uuid.NewGenWithHWAF(uuid.RandomHardwareAddrFunc)
uv, err := gen.NewV1()
if err != nil {
return nil, err
}
return tree.NewDUuid(tree.DUuid{UUID: uv}), nil
},
Info: "Generates a version 1 UUID, and returns it as a value of UUID type. " +
"To avoid exposing the server's real MAC address, " +
"this uses a random MAC address and a timestamp. " +
"Essentially, this is an alias for uuid_generate_v1mc.",
Volatility: volatility.Volatile,
},
),
"uuid_generate_v1mc": makeBuiltin(
tree.FunctionProperties{
Category: categoryIDGeneration,
},
tree.Overload{
Types: tree.ArgTypes{},
ReturnType: tree.FixedReturnType(types.Uuid),
Fn: func(_ *eval.Context, _ tree.Datums) (tree.Datum, error) {
gen := uuid.NewGenWithHWAF(uuid.RandomHardwareAddrFunc)
uv, err := gen.NewV1()
if err != nil {
return nil, err
}
return tree.NewDUuid(tree.DUuid{UUID: uv}), nil
},
Info: "Generates a version 1 UUID, and returns it as a value of UUID type. " +
"This uses a random MAC address and a timestamp.",
Volatility: volatility.Volatile,
},
),
"uuid_generate_v3": makeBuiltin(
tree.FunctionProperties{
Category: categoryIDGeneration,
},
tree.Overload{
Types: tree.ArgTypes{{"namespace", types.Uuid}, {"name", types.String}},
ReturnType: tree.FixedReturnType(types.Uuid),
Fn: func(_ *eval.Context, args tree.Datums) (tree.Datum, error) {
namespace := tree.MustBeDUuid(args[0])
name := tree.MustBeDString(args[1])
uv := uuid.NewV3(namespace.UUID, string(name))
return tree.NewDUuid(tree.DUuid{UUID: uv}), nil
},
Info: "Generates a version 3 UUID in the given namespace using the specified input name, " +
"with md5 as the hashing method. " +
"The namespace should be one of the special constants produced by the uuid_ns_*() functions.",
Volatility: volatility.Immutable,
},
),
"uuid_generate_v5": makeBuiltin(
tree.FunctionProperties{
Category: categoryIDGeneration,
},
tree.Overload{
Types: tree.ArgTypes{{"namespace", types.Uuid}, {"name", types.String}},
ReturnType: tree.FixedReturnType(types.Uuid),
Fn: func(_ *eval.Context, args tree.Datums) (tree.Datum, error) {
namespace := tree.MustBeDUuid(args[0])
name := tree.MustBeDString(args[1])
uv := uuid.NewV5(namespace.UUID, string(name))
return tree.NewDUuid(tree.DUuid{UUID: uv}), nil
},
Info: "Generates a version 5 UUID in the given namespace using the specified input name. " +
"This is similar to a version 3 UUID, except it uses SHA-1 for hashing.",
Volatility: volatility.Immutable,
},
),
"to_uuid": makeBuiltin(defProps(),
tree.Overload{
Types: tree.ArgTypes{{"val", types.String}},
ReturnType: tree.FixedReturnType(types.Bytes),
Fn: func(_ *eval.Context, args tree.Datums) (tree.Datum, error) {
s := string(tree.MustBeDString(args[0]))
uv, err := uuid.FromString(s)
if err != nil {
return nil, pgerror.Wrap(err, pgcode.InvalidParameterValue, "invalid UUID")
}
return tree.NewDBytes(tree.DBytes(uv.GetBytes())), nil
},
Info: "Converts the character string representation of a UUID to its byte string " +
"representation.",
Volatility: volatility.Immutable,
},
),
"from_uuid": makeBuiltin(defProps(),
tree.Overload{
Types: tree.ArgTypes{{"val", types.Bytes}},
ReturnType: tree.FixedReturnType(types.String),
Fn: func(_ *eval.Context, args tree.Datums) (tree.Datum, error) {
b := []byte(*args[0].(*tree.DBytes))
uv, err := uuid.FromBytes(b)
if err != nil {
return nil, err
}
return tree.NewDString(uv.String()), nil
},
Info: "Converts the byte string representation of a UUID to its character string " +
"representation.",
Volatility: volatility.Immutable,
},
),
"gen_random_ulid": makeBuiltin(
tree.FunctionProperties{
Category: categoryIDGeneration,
},
tree.Overload{
Types: tree.ArgTypes{},
ReturnType: tree.FixedReturnType(types.Uuid),
Fn: func(_ *eval.Context, _ tree.Datums) (tree.Datum, error) {
entropy := ulid.Monotonic(cryptorand.Reader, 0)
uv := ulid.MustNew(ulid.Now(), entropy)
return tree.NewDUuid(tree.DUuid{UUID: uuid.UUID(uv)}), nil
},
Info: "Generates a random ULID and returns it as a value of UUID type.",
Volatility: volatility.Volatile,
},
),
"uuid_to_ulid": makeBuiltin(defProps(),
tree.Overload{
Types: tree.ArgTypes{{"val", types.Uuid}},
ReturnType: tree.FixedReturnType(types.String),
Fn: func(_ *eval.Context, args tree.Datums) (tree.Datum, error) {
b := (*args[0].(*tree.DUuid)).GetBytes()
var ul ulid.ULID
if err := ul.UnmarshalBinary(b); err != nil {
return nil, err
}
return tree.NewDString(ul.String()), nil
},
Info: "Converts a UUID-encoded ULID to its string representation.",
Volatility: volatility.Immutable,
},
),
"ulid_to_uuid": makeBuiltin(defProps(),
tree.Overload{
Types: tree.ArgTypes{{"val", types.String}},
ReturnType: tree.FixedReturnType(types.Uuid),
Fn: func(_ *eval.Context, args tree.Datums) (tree.Datum, error) {
s := tree.MustBeDString(args[0])
u, err := ulid.Parse(string(s))
if err != nil {
return nil, pgerror.Wrap(err, pgcode.InvalidParameterValue, "invalid ULID")
}
b, err := u.MarshalBinary()
if err != nil {
return nil, err
}
uv, err := uuid.FromBytes(b)
if err != nil {
return nil, err
}
return tree.NewDUuid(tree.DUuid{UUID: uv}), nil
},
Info: "Converts a ULID string to its UUID-encoded representation.",
Volatility: volatility.Immutable,
},
),
// The following functions are all part of the NET address functions. They can
// be found in the postgres reference at https://www.postgresql.org/docs/9.6/static/functions-net.html#CIDR-INET-FUNCTIONS-TABLE
// This includes:
// - abbrev
// - broadcast
// - family
// - host
// - hostmask
// - masklen
// - netmask
// - set_masklen
// - text(inet)
// - inet_same_family
"abbrev": makeBuiltin(defProps(),
tree.Overload{
Types: tree.ArgTypes{{"val", types.INet}},
ReturnType: tree.FixedReturnType(types.String),
Fn: func(_ *eval.Context, args tree.Datums) (tree.Datum, error) {
dIPAddr := tree.MustBeDIPAddr(args[0])
return tree.NewDString(dIPAddr.IPAddr.String()), nil
},
Info: "Converts the combined IP address and prefix length to an abbreviated display format as text." +
"For INET types, this will omit the prefix length if it's not the default (32 or IPv4, 128 for IPv6)" +
"\n\nFor example, `abbrev('192.168.1.2/24')` returns `'192.168.1.2/24'`",
Volatility: volatility.Immutable,
},
),
"broadcast": makeBuiltin(defProps(),
tree.Overload{
Types: tree.ArgTypes{{"val", types.INet}},
ReturnType: tree.FixedReturnType(types.INet),
Fn: func(_ *eval.Context, args tree.Datums) (tree.Datum, error) {
dIPAddr := tree.MustBeDIPAddr(args[0])
broadcastIPAddr := dIPAddr.IPAddr.Broadcast()
return &tree.DIPAddr{IPAddr: broadcastIPAddr}, nil
},
Info: "Gets the broadcast address for the network address represented by the value." +
"\n\nFor example, `broadcast('192.168.1.2/24')` returns `'192.168.1.255/24'`",
Volatility: volatility.Immutable,
},
),
"family": makeBuiltin(defProps(),
tree.Overload{
Types: tree.ArgTypes{{"val", types.INet}},
ReturnType: tree.FixedReturnType(types.Int),
Fn: func(_ *eval.Context, args tree.Datums) (tree.Datum, error) {
dIPAddr := tree.MustBeDIPAddr(args[0])
if dIPAddr.Family == ipaddr.IPv4family {
return tree.NewDInt(tree.DInt(4)), nil
}
return tree.NewDInt(tree.DInt(6)), nil
},
Info: "Extracts the IP family of the value; 4 for IPv4, 6 for IPv6." +
"\n\nFor example, `family('::1')` returns `6`",
Volatility: volatility.Immutable,
},
),
"host": makeBuiltin(defProps(),
tree.Overload{
Types: tree.ArgTypes{{"val", types.INet}},
ReturnType: tree.FixedReturnType(types.String),
Fn: func(_ *eval.Context, args tree.Datums) (tree.Datum, error) {
dIPAddr := tree.MustBeDIPAddr(args[0])
s := dIPAddr.IPAddr.String()
if i := strings.IndexByte(s, '/'); i != -1 {
return tree.NewDString(s[:i]), nil
}
return tree.NewDString(s), nil
},
Info: "Extracts the address part of the combined address/prefixlen value as text." +
"\n\nFor example, `host('192.168.1.2/16')` returns `'192.168.1.2'`",
Volatility: volatility.Immutable,
},
),
"hostmask": makeBuiltin(defProps(),
tree.Overload{
Types: tree.ArgTypes{{"val", types.INet}},
ReturnType: tree.FixedReturnType(types.INet),
Fn: func(_ *eval.Context, args tree.Datums) (tree.Datum, error) {
dIPAddr := tree.MustBeDIPAddr(args[0])
ipAddr := dIPAddr.IPAddr.Hostmask()
return &tree.DIPAddr{IPAddr: ipAddr}, nil
},
Info: "Creates an IP host mask corresponding to the prefix length in the value." +
"\n\nFor example, `hostmask('192.168.1.2/16')` returns `'0.0.255.255'`",
Volatility: volatility.Immutable,
},
),
"masklen": makeBuiltin(defProps(),
tree.Overload{
Types: tree.ArgTypes{{"val", types.INet}},
ReturnType: tree.FixedReturnType(types.Int),
Fn: func(_ *eval.Context, args tree.Datums) (tree.Datum, error) {
dIPAddr := tree.MustBeDIPAddr(args[0])
return tree.NewDInt(tree.DInt(dIPAddr.Mask)), nil
},
Info: "Retrieves the prefix length stored in the value." +
"\n\nFor example, `masklen('192.168.1.2/16')` returns `16`",
Volatility: volatility.Immutable,
},
),
"netmask": makeBuiltin(defProps(),
tree.Overload{
Types: tree.ArgTypes{{"val", types.INet}},
ReturnType: tree.FixedReturnType(types.INet),
Fn: func(_ *eval.Context, args tree.Datums) (tree.Datum, error) {
dIPAddr := tree.MustBeDIPAddr(args[0])
ipAddr := dIPAddr.IPAddr.Netmask()
return &tree.DIPAddr{IPAddr: ipAddr}, nil
},
Info: "Creates an IP network mask corresponding to the prefix length in the value." +