-
Notifications
You must be signed in to change notification settings - Fork 3.8k
/
builtins.go
4755 lines (4360 loc) · 159 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"
"crypto/md5"
"crypto/sha1"
"crypto/sha256"
"crypto/sha512"
"fmt"
"hash"
"hash/crc32"
"hash/fnv"
"math"
"math/rand"
"net"
"regexp/syntax"
"strconv"
"strings"
"time"
"unicode"
"unicode/utf8"
"github.com/cockroachdb/apd"
"github.com/cockroachdb/cockroach/pkg/build"
"github.com/cockroachdb/cockroach/pkg/internal/client"
"github.com/cockroachdb/cockroach/pkg/roachpb"
"github.com/cockroachdb/cockroach/pkg/security"
"github.com/cockroachdb/cockroach/pkg/settings/cluster"
"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/sem/tree"
"github.com/cockroachdb/cockroach/pkg/sql/sessiondata"
"github.com/cockroachdb/cockroach/pkg/sql/sqlbase"
"github.com/cockroachdb/cockroach/pkg/sql/types"
"github.com/cockroachdb/cockroach/pkg/util/duration"
"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/syncutil"
"github.com/cockroachdb/cockroach/pkg/util/timeofday"
"github.com/cockroachdb/cockroach/pkg/util/timeutil"
"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")
errAbsOfMinInt64 = pgerror.New(pgcode.NumericValueOutOfRange, "abs of min integer value (-9223372036854775808) not defined")
errSqrtOfNegNumber = pgerror.New(pgcode.InvalidArgumentForPowerFunction, "cannot take square root of a negative number")
errLogOfNegNumber = pgerror.New(pgcode.InvalidArgumentForLogarithm, "cannot take logarithm of a negative number")
errLogOfZero = pgerror.New(pgcode.InvalidArgumentForLogarithm, "cannot take logarithm of zero")
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,
fmt.Sprintf("requested length too large, exceeds %s", humanizeutil.IBytes(maxAllocatedStringSize)))
)
const maxAllocatedStringSize = 128 * 1024 * 1024
const errInsufficientArgsFmtString = "unknown signature: %s()"
const (
categoryComparison = "Comparison"
categoryCompatibility = "Compatibility"
categoryDateAndTime = "Date and time"
categoryIDGeneration = "ID generation"
categorySequences = "Sequence"
categoryMath = "Math and numeric"
categoryString = "String and byte"
categoryArray = "Array"
categorySystemInfo = "System info"
categoryGenerator = "Set-returning"
categoryJSON = "JSONB"
)
func categorizeType(t *types.T) string {
switch t.Family() {
case types.DateFamily, types.IntervalFamily, types.TimestampFamily, types.TimestampTZFamily:
return categoryDateAndTime
case types.IntFamily, types.DecimalFamily, types.FloatFamily:
return categoryMath
case types.StringFamily, types.BytesFamily:
return categoryString
default:
return strings.ToUpper(t.String())
}
}
var digitNames = []string{"zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine"}
// 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)
}
// 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,
"char_length": lengthImpls,
"character_length": lengthImpls,
"bit_length": makeBuiltin(tree.FunctionProperties{Category: categoryString},
stringOverload1(func(_ *tree.EvalContext, 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`."),
bytesOverload1(func(_ *tree.EvalContext, s string) (tree.Datum, error) {
return tree.NewDInt(tree.DInt(len(s) * 8)), nil
}, types.Int, "Calculates the number of bits in `val`."),
),
"octet_length": makeBuiltin(tree.FunctionProperties{Category: categoryString},
stringOverload1(func(_ *tree.EvalContext, s string) (tree.Datum, error) {
return tree.NewDInt(tree.DInt(len(s))), nil
}, types.Int, "Calculates the number of bytes used to represent `val`."),
bytesOverload1(func(_ *tree.EvalContext, s string) (tree.Datum, error) {
return tree.NewDInt(tree.DInt(len(s))), nil
}, types.Int, "Calculates the number of bytes in `val`."),
),
// TODO(pmattis): What string functions should also support types.Bytes?
"lower": makeBuiltin(tree.FunctionProperties{Category: categoryString},
stringOverload1(func(evalCtx *tree.EvalContext, s string) (tree.Datum, error) {
return tree.NewDString(strings.ToLower(s)), nil
}, types.String, "Converts all characters in `val` to their lower-case equivalents.")),
"upper": makeBuiltin(tree.FunctionProperties{Category: categoryString},
stringOverload1(func(evalCtx *tree.EvalContext, 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.")),
"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(evalCtx *tree.EvalContext, 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.",
},
),
"concat_ws": makeBuiltin(tree.FunctionProperties{NullableArgs: true},
tree.Overload{
Types: tree.VariadicType{VarType: types.String},
ReturnType: tree.FixedReturnType(types.String),
Fn: func(evalCtx *tree.EvalContext, 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`.",
},
),
// 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(evalCtx *tree.EvalContext, 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'.",
}),
// 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(evalCtx *tree.EvalContext, 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'.",
}),
"gen_random_uuid": makeBuiltin(
tree.FunctionProperties{
Category: categoryIDGeneration,
Impure: true,
},
tree.Overload{
Types: tree.ArgTypes{},
ReturnType: tree.FixedReturnType(types.Uuid),
Fn: func(_ *tree.EvalContext, _ tree.Datums) (tree.Datum, error) {
uv := uuid.MakeV4()
return tree.NewDUuid(tree.DUuid{UUID: uv}), nil
},
Info: "Generates a random UUID and returns it as a value of UUID type.",
},
),
"to_uuid": makeBuiltin(defProps(),
tree.Overload{
Types: tree.ArgTypes{{"val", types.String}},
ReturnType: tree.FixedReturnType(types.Bytes),
Fn: func(_ *tree.EvalContext, args tree.Datums) (tree.Datum, error) {
s := string(tree.MustBeDString(args[0]))
uv, err := uuid.FromString(s)
if err != nil {
return nil, err
}
return tree.NewDBytes(tree.DBytes(uv.GetBytes())), nil
},
Info: "Converts the character string representation of a UUID to its byte string " +
"representation.",
},
),
"from_uuid": makeBuiltin(defProps(),
tree.Overload{
Types: tree.ArgTypes{{"val", types.Bytes}},
ReturnType: tree.FixedReturnType(types.String),
Fn: func(_ *tree.EvalContext, 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.",
},
),
// 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(_ *tree.EvalContext, 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'`",
},
),
"broadcast": makeBuiltin(defProps(),
tree.Overload{
Types: tree.ArgTypes{{"val", types.INet}},
ReturnType: tree.FixedReturnType(types.INet),
Fn: func(_ *tree.EvalContext, 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'`",
},
),
"family": makeBuiltin(defProps(),
tree.Overload{
Types: tree.ArgTypes{{"val", types.INet}},
ReturnType: tree.FixedReturnType(types.Int),
Fn: func(_ *tree.EvalContext, 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`",
},
),
"host": makeBuiltin(defProps(),
tree.Overload{
Types: tree.ArgTypes{{"val", types.INet}},
ReturnType: tree.FixedReturnType(types.String),
Fn: func(_ *tree.EvalContext, 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'`",
},
),
"hostmask": makeBuiltin(defProps(),
tree.Overload{
Types: tree.ArgTypes{{"val", types.INet}},
ReturnType: tree.FixedReturnType(types.INet),
Fn: func(_ *tree.EvalContext, 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'`",
},
),
"masklen": makeBuiltin(defProps(),
tree.Overload{
Types: tree.ArgTypes{{"val", types.INet}},
ReturnType: tree.FixedReturnType(types.Int),
Fn: func(_ *tree.EvalContext, 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`",
},
),
"netmask": makeBuiltin(defProps(),
tree.Overload{
Types: tree.ArgTypes{{"val", types.INet}},
ReturnType: tree.FixedReturnType(types.INet),
Fn: func(_ *tree.EvalContext, 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." +
"\n\nFor example, `netmask('192.168.1.2/16')` returns `'255.255.0.0'`",
},
),
"set_masklen": makeBuiltin(defProps(),
tree.Overload{
Types: tree.ArgTypes{
{"val", types.INet},
{"prefixlen", types.Int},
},
ReturnType: tree.FixedReturnType(types.INet),
Fn: func(_ *tree.EvalContext, args tree.Datums) (tree.Datum, error) {
dIPAddr := tree.MustBeDIPAddr(args[0])
mask := int(tree.MustBeDInt(args[1]))
if !(dIPAddr.Family == ipaddr.IPv4family && mask >= 0 && mask <= 32) && !(dIPAddr.Family == ipaddr.IPv6family && mask >= 0 && mask <= 128) {
return nil, pgerror.Newf(
pgcode.InvalidParameterValue, "invalid mask length: %d", mask)
}
return &tree.DIPAddr{IPAddr: ipaddr.IPAddr{Family: dIPAddr.Family, Addr: dIPAddr.Addr, Mask: byte(mask)}}, nil
},
Info: "Sets the prefix length of `val` to `prefixlen`.\n\n" +
"For example, `set_masklen('192.168.1.2', 16)` returns `'192.168.1.2/16'`.",
},
),
"text": makeBuiltin(defProps(),
tree.Overload{
Types: tree.ArgTypes{{"val", types.INet}},
ReturnType: tree.FixedReturnType(types.String),
Fn: func(_ *tree.EvalContext, args tree.Datums) (tree.Datum, error) {
dIPAddr := tree.MustBeDIPAddr(args[0])
s := dIPAddr.IPAddr.String()
// Ensure the string has a "/mask" suffix.
if strings.IndexByte(s, '/') == -1 {
s += "/" + strconv.Itoa(int(dIPAddr.Mask))
}
return tree.NewDString(s), nil
},
Info: "Converts the IP address and prefix length to text.",
},
),
"inet_same_family": makeBuiltin(defProps(),
tree.Overload{
Types: tree.ArgTypes{
{"val", types.INet},
{"val", types.INet},
},
ReturnType: tree.FixedReturnType(types.Bool),
Fn: func(_ *tree.EvalContext, args tree.Datums) (tree.Datum, error) {
first := tree.MustBeDIPAddr(args[0])
other := tree.MustBeDIPAddr(args[1])
return tree.MakeDBool(tree.DBool(first.Family == other.Family)), nil
},
Info: "Checks if two IP addresses are of the same IP family.",
},
),
"inet_contained_by_or_equals": makeBuiltin(defProps(),
tree.Overload{
Types: tree.ArgTypes{
{"val", types.INet},
{"container", types.INet},
},
ReturnType: tree.FixedReturnType(types.Bool),
Fn: func(_ *tree.EvalContext, args tree.Datums) (tree.Datum, error) {
ipAddr := tree.MustBeDIPAddr(args[0]).IPAddr
other := tree.MustBeDIPAddr(args[1]).IPAddr
return tree.MakeDBool(tree.DBool(ipAddr.ContainedByOrEquals(&other))), nil
},
Info: "Test for subnet inclusion or equality, using only the network parts of the addresses. " +
"The host part of the addresses is ignored.",
},
),
"inet_contains_or_contained_by": makeBuiltin(defProps(),
tree.Overload{
Types: tree.ArgTypes{
{"val", types.INet},
{"val", types.INet},
},
ReturnType: tree.FixedReturnType(types.Bool),
Fn: func(_ *tree.EvalContext, args tree.Datums) (tree.Datum, error) {
ipAddr := tree.MustBeDIPAddr(args[0]).IPAddr
other := tree.MustBeDIPAddr(args[1]).IPAddr
return tree.MakeDBool(tree.DBool(ipAddr.ContainsOrContainedBy(&other))), nil
},
Info: "Test for subnet inclusion, using only the network parts of the addresses. " +
"The host part of the addresses is ignored.",
},
),
"inet_contains_or_equals": makeBuiltin(defProps(),
tree.Overload{
Types: tree.ArgTypes{
{"container", types.INet},
{"val", types.INet},
},
ReturnType: tree.FixedReturnType(types.Bool),
Fn: func(_ *tree.EvalContext, args tree.Datums) (tree.Datum, error) {
ipAddr := tree.MustBeDIPAddr(args[0]).IPAddr
other := tree.MustBeDIPAddr(args[1]).IPAddr
return tree.MakeDBool(tree.DBool(ipAddr.ContainsOrEquals(&other))), nil
},
Info: "Test for subnet inclusion or equality, using only the network parts of the addresses. " +
"The host part of the addresses is ignored.",
},
),
"from_ip": makeBuiltin(defProps(),
tree.Overload{
Types: tree.ArgTypes{{"val", types.Bytes}},
ReturnType: tree.FixedReturnType(types.String),
Fn: func(_ *tree.EvalContext, args tree.Datums) (tree.Datum, error) {
ipstr := args[0].(*tree.DBytes)
nboip := net.IP(*ipstr)
sv := nboip.String()
// if nboip has a length of 0, sv will be "<nil>"
if sv == "<nil>" {
return nil, errZeroIP
}
return tree.NewDString(sv), nil
},
Info: "Converts the byte string representation of an IP to its character string " +
"representation.",
},
),
"to_ip": makeBuiltin(defProps(),
tree.Overload{
Types: tree.ArgTypes{{"val", types.String}},
ReturnType: tree.FixedReturnType(types.Bytes),
Fn: func(_ *tree.EvalContext, args tree.Datums) (tree.Datum, error) {
ipdstr := tree.MustBeDString(args[0])
ip := net.ParseIP(string(ipdstr))
// If ipdstr could not be parsed to a valid IP,
// ip will be nil.
if ip == nil {
return nil, pgerror.Newf(
pgcode.InvalidParameterValue, "invalid IP format: %s", ipdstr.String())
}
return tree.NewDBytes(tree.DBytes(ip)), nil
},
Info: "Converts the character string representation of an IP to its byte string " +
"representation.",
},
),
"split_part": makeBuiltin(defProps(),
tree.Overload{
Types: tree.ArgTypes{
{"input", types.String},
{"delimiter", types.String},
{"return_index_pos", types.Int},
},
ReturnType: tree.FixedReturnType(types.String),
Fn: func(_ *tree.EvalContext, args tree.Datums) (tree.Datum, error) {
text := string(tree.MustBeDString(args[0]))
sep := string(tree.MustBeDString(args[1]))
field := int(tree.MustBeDInt(args[2]))
if field <= 0 {
return nil, pgerror.Newf(
pgcode.InvalidParameterValue, "field position %d must be greater than zero", field)
}
splits := strings.Split(text, sep)
if field > len(splits) {
return tree.NewDString(""), nil
}
return tree.NewDString(splits[field-1]), nil
},
Info: "Splits `input` on `delimiter` and return the value in the `return_index_pos` " +
"position (starting at 1). \n\nFor example, `split_part('123.456.789.0','.',3)`" +
"returns `789`.",
},
),
"repeat": makeBuiltin(defProps(),
tree.Overload{
Types: tree.ArgTypes{{"input", types.String}, {"repeat_counter", types.Int}},
ReturnType: tree.FixedReturnType(types.String),
Fn: func(evalCtx *tree.EvalContext, args tree.Datums) (_ tree.Datum, err error) {
s := string(tree.MustBeDString(args[0]))
count := int(tree.MustBeDInt(args[1]))
ln := len(s) * count
// Use <= here instead of < to prevent a possible divide-by-zero in the next
// if block.
if count <= 0 {
count = 0
} else if ln/count != len(s) {
// Detect overflow and trigger an error.
return nil, errStringTooLarge
} else if ln > maxAllocatedStringSize {
return nil, errStringTooLarge
}
return tree.NewDString(strings.Repeat(s, count)), nil
},
Info: "Concatenates `input` `repeat_counter` number of times.\n\nFor example, " +
"`repeat('dog', 2)` returns `dogdog`.",
},
),
// https://www.postgresql.org/docs/10/static/functions-binarystring.html
"encode": makeBuiltin(defProps(),
tree.Overload{
Types: tree.ArgTypes{{"data", types.Bytes}, {"format", types.String}},
ReturnType: tree.FixedReturnType(types.String),
Fn: func(evalCtx *tree.EvalContext, args tree.Datums) (_ tree.Datum, err error) {
data, format := *args[0].(*tree.DBytes), string(tree.MustBeDString(args[1]))
be, ok := sessiondata.BytesEncodeFormatFromString(format)
if !ok {
return nil, pgerror.New(pgcode.InvalidParameterValue,
"only 'hex', 'escape', and 'base64' formats are supported for encode()")
}
return tree.NewDString(lex.EncodeByteArrayToRawBytes(
string(data), be, true /* skipHexPrefix */)), nil
},
Info: "Encodes `data` using `format` (`hex` / `escape` / `base64`).",
},
),
"decode": makeBuiltin(defProps(),
tree.Overload{
Types: tree.ArgTypes{{"text", types.String}, {"format", types.String}},
ReturnType: tree.FixedReturnType(types.Bytes),
Fn: func(evalCtx *tree.EvalContext, args tree.Datums) (_ tree.Datum, err error) {
data, format := string(tree.MustBeDString(args[0])), string(tree.MustBeDString(args[1]))
be, ok := sessiondata.BytesEncodeFormatFromString(format)
if !ok {
return nil, pgerror.New(pgcode.InvalidParameterValue,
"only 'hex', 'escape', and 'base64' formats are supported for decode()")
}
res, err := lex.DecodeRawBytesToByteArray(data, be)
if err != nil {
return nil, err
}
return tree.NewDBytes(tree.DBytes(res)), nil
},
Info: "Decodes `data` using `format` (`hex` / `escape` / `base64`).",
},
),
"ascii": makeBuiltin(tree.FunctionProperties{Category: categoryString},
stringOverload1(func(_ *tree.EvalContext, s string) (tree.Datum, error) {
for _, ch := range s {
return tree.NewDInt(tree.DInt(ch)), nil
}
return nil, errEmptyInputString
}, types.Int, "Returns the character code of the first character in `val`. Despite the name, the function supports Unicode too.")),
"chr": makeBuiltin(tree.FunctionProperties{Category: categoryString},
tree.Overload{
Types: tree.ArgTypes{{"val", types.Int}},
ReturnType: tree.FixedReturnType(types.String),
Fn: func(_ *tree.EvalContext, args tree.Datums) (tree.Datum, error) {
x := tree.MustBeDInt(args[0])
var answer string
switch {
case x < 0:
return nil, errChrValueTooSmall
case x > utf8.MaxRune:
return nil, errChrValueTooLarge
default:
answer = string(rune(x))
}
return tree.NewDString(answer), nil
},
Info: "Returns the character with the code given in `val`. Inverse function of `ascii()`.",
},
),
"md5": hashBuiltin(
func() hash.Hash { return md5.New() },
"Calculates the MD5 hash value of a set of values.",
),
"sha1": hashBuiltin(
func() hash.Hash { return sha1.New() },
"Calculates the SHA1 hash value of a set of values.",
),
"sha256": hashBuiltin(
func() hash.Hash { return sha256.New() },
"Calculates the SHA256 hash value of a set of values.",
),
"sha512": hashBuiltin(
func() hash.Hash { return sha512.New() },
"Calculates the SHA512 hash value of a set of values.",
),
"fnv32": hash32Builtin(
func() hash.Hash32 { return fnv.New32() },
"Calculates the 32-bit FNV-1 hash value of a set of values.",
),
"fnv32a": hash32Builtin(
func() hash.Hash32 { return fnv.New32a() },
"Calculates the 32-bit FNV-1a hash value of a set of values.",
),
"fnv64": hash64Builtin(
func() hash.Hash64 { return fnv.New64() },
"Calculates the 64-bit FNV-1 hash value of a set of values.",
),
"fnv64a": hash64Builtin(
func() hash.Hash64 { return fnv.New64a() },
"Calculates the 64-bit FNV-1a hash value of a set of values.",
),
"crc32ieee": hash32Builtin(
func() hash.Hash32 { return crc32.New(crc32.IEEETable) },
"Calculates the CRC-32 hash using the IEEE polynomial.",
),
"crc32c": hash32Builtin(
func() hash.Hash32 { return crc32.New(crc32.MakeTable(crc32.Castagnoli)) },
"Calculates the CRC-32 hash using the Castagnoli polynomial.",
),
"to_hex": makeBuiltin(
tree.FunctionProperties{Category: categoryString},
tree.Overload{
Types: tree.ArgTypes{{"val", types.Int}},
ReturnType: tree.FixedReturnType(types.String),
Fn: func(_ *tree.EvalContext, args tree.Datums) (tree.Datum, error) {
return tree.NewDString(fmt.Sprintf("%x", int64(tree.MustBeDInt(args[0])))), nil
},
Info: "Converts `val` to its hexadecimal representation.",
},
tree.Overload{
Types: tree.ArgTypes{{"val", types.Bytes}},
ReturnType: tree.FixedReturnType(types.String),
Fn: func(_ *tree.EvalContext, args tree.Datums) (tree.Datum, error) {
bytes := *(args[0].(*tree.DBytes))
return tree.NewDString(fmt.Sprintf("%x", []byte(bytes))), nil
},
Info: "Converts `val` to its hexadecimal representation.",
},
),
"to_english": makeBuiltin(
tree.FunctionProperties{Category: categoryString},
tree.Overload{
Types: tree.ArgTypes{{"val", types.Int}},
ReturnType: tree.FixedReturnType(types.String),
Fn: func(_ *tree.EvalContext, args tree.Datums) (tree.Datum, error) {
val := int(*args[0].(*tree.DInt))
var buf bytes.Buffer
if val < 0 {
buf.WriteString("minus-")
val = -val
}
var digits []string
digits = append(digits, digitNames[val%10])
for val > 9 {
val /= 10
digits = append(digits, digitNames[val%10])
}
for i := len(digits) - 1; i >= 0; i-- {
if i < len(digits)-1 {
buf.WriteByte('-')
}
buf.WriteString(digits[i])
}
return tree.NewDString(buf.String()), nil
},
Info: "This function enunciates the value of its argument using English cardinals.",
},
),
// The SQL parser coerces POSITION to STRPOS.
"strpos": makeBuiltin(
tree.FunctionProperties{Category: categoryString},
stringOverload2("input", "find", func(_ *tree.EvalContext, s, substring string) (tree.Datum, error) {
index := strings.Index(s, substring)
if index < 0 {
return tree.DZero, nil
}
return tree.NewDInt(tree.DInt(utf8.RuneCountInString(s[:index]) + 1)), nil
}, types.Int, "Calculates the position where the string `find` begins in `input`. \n\nFor"+
" example, `strpos('doggie', 'gie')` returns `4`.")),
"overlay": makeBuiltin(defProps(),
tree.Overload{
Types: tree.ArgTypes{
{"input", types.String},
{"overlay_val", types.String},
{"start_pos", types.Int},
},
ReturnType: tree.FixedReturnType(types.String),
Fn: func(_ *tree.EvalContext, args tree.Datums) (tree.Datum, error) {
s := string(tree.MustBeDString(args[0]))
to := string(tree.MustBeDString(args[1]))
pos := int(tree.MustBeDInt(args[2]))
size := utf8.RuneCountInString(to)
return overlay(s, to, pos, size)
},
Info: "Replaces characters in `input` with `overlay_val` starting at `start_pos` " +
"(begins at 1). \n\nFor example, `overlay('doggie', 'CAT', 2)` returns " +
"`dCATie`.",
},
tree.Overload{
Types: tree.ArgTypes{
{"input", types.String},
{"overlay_val", types.String},
{"start_pos", types.Int},
{"end_pos", types.Int},
},
ReturnType: tree.FixedReturnType(types.String),
Fn: func(_ *tree.EvalContext, args tree.Datums) (tree.Datum, error) {
s := string(tree.MustBeDString(args[0]))
to := string(tree.MustBeDString(args[1]))
pos := int(tree.MustBeDInt(args[2]))
size := int(tree.MustBeDInt(args[3]))
return overlay(s, to, pos, size)
},
Info: "Deletes the characters in `input` between `start_pos` and `end_pos` (count " +
"starts at 1), and then insert `overlay_val` at `start_pos`.",
},
),
"lpad": makeBuiltin(
tree.FunctionProperties{Category: categoryString},
tree.Overload{
Types: tree.ArgTypes{{"string", types.String}, {"length", types.Int}},
ReturnType: tree.FixedReturnType(types.String),
Fn: func(evalCtx *tree.EvalContext, args tree.Datums) (tree.Datum, error) {
s := string(tree.MustBeDString(args[0]))
length := int(tree.MustBeDInt(args[1]))
ret, err := lpad(s, length, " ")
if err != nil {
return nil, err
}
return tree.NewDString(ret), nil
},
Info: "Pads `string` to `length` by adding ' ' to the left of `string`." +
"If `string` is longer than `length` it is truncated.",
},
tree.Overload{
Types: tree.ArgTypes{{"string", types.String}, {"length", types.Int}, {"fill", types.String}},
ReturnType: tree.FixedReturnType(types.String),
Fn: func(evalCtx *tree.EvalContext, args tree.Datums) (tree.Datum, error) {
s := string(tree.MustBeDString(args[0]))
length := int(tree.MustBeDInt(args[1]))
fill := string(tree.MustBeDString(args[2]))
ret, err := lpad(s, length, fill)
if err != nil {
return nil, err
}
return tree.NewDString(ret), nil
},
Info: "Pads `string` by adding `fill` to the left of `string` to make it `length`. " +
"If `string` is longer than `length` it is truncated.",
},
),
"rpad": makeBuiltin(
tree.FunctionProperties{Category: categoryString},
tree.Overload{
Types: tree.ArgTypes{{"string", types.String}, {"length", types.Int}},
ReturnType: tree.FixedReturnType(types.String),
Fn: func(evalCtx *tree.EvalContext, args tree.Datums) (tree.Datum, error) {
s := string(tree.MustBeDString(args[0]))
length := int(tree.MustBeDInt(args[1]))
ret, err := rpad(s, length, " ")
if err != nil {
return nil, err
}
return tree.NewDString(ret), nil
},
Info: "Pads `string` to `length` by adding ' ' to the right of string. " +
"If `string` is longer than `length` it is truncated.",
},
tree.Overload{
Types: tree.ArgTypes{{"string", types.String}, {"length", types.Int}, {"fill", types.String}},
ReturnType: tree.FixedReturnType(types.String),
Fn: func(evalCtx *tree.EvalContext, args tree.Datums) (tree.Datum, error) {
s := string(tree.MustBeDString(args[0]))
length := int(tree.MustBeDInt(args[1]))
fill := string(tree.MustBeDString(args[2]))
ret, err := rpad(s, length, fill)
if err != nil {
return nil, err
}
return tree.NewDString(ret), nil
},
Info: "Pads `string` to `length` by adding `fill` to the right of `string`. " +
"If `string` is longer than `length` it is truncated.",
},
),
// The SQL parser coerces TRIM(...) and TRIM(BOTH ...) to BTRIM(...).
"btrim": makeBuiltin(defProps(),
stringOverload2("input", "trim_chars", func(_ *tree.EvalContext, s, chars string) (tree.Datum, error) {
return tree.NewDString(strings.Trim(s, chars)), nil
}, types.String, "Removes any characters included in `trim_chars` from the beginning or end"+
" of `input` (applies recursively). \n\nFor example, `btrim('doggie', 'eod')` "+
"returns `ggi`."),
stringOverload1(func(_ *tree.EvalContext, s string) (tree.Datum, error) {
return tree.NewDString(strings.TrimSpace(s)), nil
}, types.String, "Removes all spaces from the beginning and end of `val`."),
),
// The SQL parser coerces TRIM(LEADING ...) to LTRIM(...).
"ltrim": makeBuiltin(defProps(),
stringOverload2("input", "trim_chars", func(_ *tree.EvalContext, s, chars string) (tree.Datum, error) {
return tree.NewDString(strings.TrimLeft(s, chars)), nil
}, types.String, "Removes any characters included in `trim_chars` from the beginning "+
"(left-hand side) of `input` (applies recursively). \n\nFor example, "+
"`ltrim('doggie', 'od')` returns `ggie`."),
stringOverload1(func(_ *tree.EvalContext, s string) (tree.Datum, error) {
return tree.NewDString(strings.TrimLeftFunc(s, unicode.IsSpace)), nil