-
Notifications
You must be signed in to change notification settings - Fork 3.8k
/
builtins.go
2282 lines (2072 loc) · 69.1 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.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
// implied. See the License for the specific language governing
// permissions and limitations under the License.
//
// Author: Peter Mattis (peter@cockroachlabs.com)
package parser
import (
"bytes"
"crypto/md5"
"crypto/sha1"
"crypto/sha256"
"errors"
"fmt"
"math"
"math/rand"
"net"
"regexp"
"regexp/syntax"
"strconv"
"strings"
"time"
"unicode"
"unicode/utf8"
"github.com/knz/strtime"
"github.com/cockroachdb/apd"
"github.com/cockroachdb/cockroach/pkg/build"
"github.com/cockroachdb/cockroach/pkg/roachpb"
"github.com/cockroachdb/cockroach/pkg/sql/pgwire/pgerror"
"github.com/cockroachdb/cockroach/pkg/util/duration"
"github.com/cockroachdb/cockroach/pkg/util/log"
"github.com/cockroachdb/cockroach/pkg/util/syncutil"
"github.com/cockroachdb/cockroach/pkg/util/timeutil"
"github.com/cockroachdb/cockroach/pkg/util/uuid"
)
var (
errEmptyInputString = errors.New("the input string must not be empty")
errAbsOfMinInt64 = errors.New("abs of min integer value (-9223372036854775808) not defined")
errSqrtOfNegNumber = errors.New("cannot take square root of a negative number")
errLogOfNegNumber = errors.New("cannot take logarithm of a negative number")
errLogOfZero = errors.New("cannot take logarithm of zero")
errInsufficientArgs = errors.New("unknown signature: concat_ws()")
errZeroIP = errors.New("zero length IP")
)
// FunctionClass specifies the class of the builtin function.
type FunctionClass int
const (
// NormalClass is a standard builtin function.
NormalClass FunctionClass = iota
// AggregateClass is a builtin aggregate function.
AggregateClass
// WindowClass is a builtin window function.
WindowClass
// GeneratorClass is a builtin generator function.
GeneratorClass
)
// Avoid vet warning about unused enum value.
var _ = NormalClass
const (
categoryComparison = "Comparison"
categoryCompatibility = "Compatibility"
categoryDateAndTime = "Date and Time"
categoryIDGeneration = "ID Generation"
categoryMath = "Math and Numeric"
categoryString = "String and Byte"
categorySystemInfo = "System Info"
)
// Builtin is a built-in function.
type Builtin struct {
Types typeList
ReturnType returnTyper
// When multiple overloads are eligible based on types even after all of of
// the heuristics to pick one have been used, if one of the overloads is a
// Builtin with the `preferredOverload` flag set to true it can be selected
// rather than returning a no-such-method error.
// This should generally be avoided -- avoiding introducing ambiguous
// overloads in the first place is a much better solution -- and only done
// after consultation with @knz @nvanbenschoten.
preferredOverload bool
// Set to true when a function potentially returns a different value
// when called in the same statement with the same parameters.
// e.g.: random(), clock_timestamp(). Some functions like now()
// return the same value in the same statement, but different values
// in separate statements, and should not be marked as impure.
impure bool
// Set to true when a function depends on members of the EvalContext that are
// not marshalled by DistSQL (e.g. planner). Currently used for DistSQL to
// determine if expressions can be evaluated on a different node without
// sending over the EvalContext.
//
// TODO(andrei): Get rid of the planner from the EvalContext and then we can
// get rid of this blacklist.
distsqlBlacklist bool
// Set to true when a function may change at every row whether or
// not it is applied to an expression that contains row-dependent
// variables. Used e.g. by `random` and aggregate functions.
needsRepeatedEvaluation bool
// Set to true when the built-in can only be used by security.RootUser.
privileged bool
class FunctionClass
category string
// Info is a description of the function, which is surfaced on the CockroachDB
// docs site on the "Functions and Operators" page. Descriptions typically use
// third-person with the function as an implicit subject (e.g. "Calculates
// infinity"), but should focus more on ease of understanding so other structures
// might be more appropriate.
Info string
AggregateFunc func([]Type, *EvalContext) AggregateFunc
WindowFunc func([]Type, *EvalContext) WindowFunc
fn func(*EvalContext, Datums) (Datum, error)
}
func (b Builtin) params() typeList {
return b.Types
}
func (b Builtin) returnType() returnTyper {
return b.ReturnType
}
func (b Builtin) preferred() bool {
return b.preferredOverload
}
func categorizeType(t Type) string {
switch t {
case TypeDate, TypeInterval, TypeTimestamp, TypeTimestampTZ:
return categoryDateAndTime
case TypeInt, TypeDecimal, TypeFloat:
return categoryMath
case TypeString, TypeBytes:
return categoryString
default:
return strings.ToUpper(t.String())
}
}
// Category is used to categorize a function (for documentation purposes).
func (b Builtin) Category() string {
// If an explicit category is specified, use it.
if b.category != "" {
return b.category
}
// If single argument attempt to categorize by the type of the argument.
switch typ := b.Types.(type) {
case ArgTypes:
if len(typ) == 1 {
return categorizeType(typ[0].Typ)
}
}
// Fall back to categorizing by return type.
if retType := b.FixedReturnType(); retType != nil {
return categorizeType(retType)
}
return ""
}
// Class returns the FunctionClass of this builtin.
func (b Builtin) Class() FunctionClass {
return b.class
}
// Impure returns false if this builtin is a pure function of its inputs.
func (b Builtin) Impure() bool {
return b.impure
}
// DistSQLBlacklist returns true if the builtin is not supported by DistSQL.
// See distsqlBlacklist.
func (b Builtin) DistSQLBlacklist() bool {
return b.distsqlBlacklist
}
// FixedReturnType returns a fixed type that the function returns, returning Any
// if the return type is based on the function's arguments.
func (b Builtin) FixedReturnType() Type {
if b.ReturnType == nil {
return nil
}
return returnTypeToFixedType(b.ReturnType)
}
// Signature returns a human-readable signature.
func (b Builtin) Signature() string {
return fmt.Sprintf("(%s) -> %s", b.Types.String(), b.FixedReturnType())
}
func init() {
initAggregateBuiltins()
initWindowBuiltins()
initGeneratorBuiltins()
initPGBuiltins()
names := make([]string, 0, len(Builtins))
funDefs = make(map[string]*FunctionDefinition)
for name, def := range Builtins {
funDefs[name] = newFunctionDefinition(name, def)
names = append(names, name)
}
// We alias the builtins to uppercase to hasten the lookup in the
// common case.
for _, name := range names {
uname := strings.ToUpper(name)
def := Builtins[name]
Builtins[uname] = def
funDefs[uname] = funDefs[name]
}
}
var digitNames = []string{"zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine"}
// Builtins contains the built-in functions indexed by name.
var Builtins = map[string][]Builtin{
// Keep the list of functions sorted.
// TODO(XisiHuang): support encoding, i.e., length(str, encoding).
"length": {
stringBuiltin1(func(s string) (Datum, error) {
return NewDInt(DInt(utf8.RuneCountInString(s))), nil
}, TypeInt, "Calculates the number of characters in `val`."),
bytesBuiltin1(func(s string) (Datum, error) {
return NewDInt(DInt(len(s))), nil
}, TypeInt, "Calculates the number of bytes in `val`."),
},
"octet_length": {
stringBuiltin1(func(s string) (Datum, error) {
return NewDInt(DInt(len(s))), nil
}, TypeInt, "Calculates the number of bytes used to represent `val`."),
bytesBuiltin1(func(s string) (Datum, error) {
return NewDInt(DInt(len(s))), nil
}, TypeInt, "Calculates the number of bytes in `val`."),
},
// TODO(pmattis): What string functions should also support TypeBytes?
"lower": {stringBuiltin1(func(s string) (Datum, error) {
return NewDString(strings.ToLower(s)), nil
}, TypeString, "Converts all characters in `val`to their lower-case equivalents.")},
"upper": {stringBuiltin1(func(s string) (Datum, error) {
return NewDString(strings.ToUpper(s)), nil
}, TypeString, "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": {
Builtin{
Types: VariadicType{TypeString},
ReturnType: fixedReturnType(TypeString),
fn: func(_ *EvalContext, args Datums) (Datum, error) {
var buffer bytes.Buffer
for _, d := range args {
if d == DNull {
continue
}
buffer.WriteString(string(MustBeDString(d)))
}
return NewDString(buffer.String()), nil
},
Info: "Concatenates a comma-separated list of strings.",
},
},
"concat_ws": {
Builtin{
Types: VariadicType{TypeString},
ReturnType: fixedReturnType(TypeString),
fn: func(_ *EvalContext, args Datums) (Datum, error) {
if len(args) == 0 {
return nil, errInsufficientArgs
}
if args[0] == DNull {
return DNull, nil
}
sep := string(MustBeDString(args[0]))
var buf bytes.Buffer
prefix := ""
for _, d := range args[1:] {
if d == DNull {
continue
}
// 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(MustBeDString(d)))
}
return NewDString(buf.String()), nil
},
Info: "Uses the first argument as a separator between the concatenation of the " +
"subsequent arguments. <br/><br/>For example `concat_ws('!','wow','great')` " +
"returns `wow!great`.",
},
},
"to_uuid": {
Builtin{
Types: ArgTypes{{"val", TypeString}},
ReturnType: fixedReturnType(TypeBytes),
fn: func(_ *EvalContext, args Datums) (Datum, error) {
s := string(MustBeDString(args[0]))
uv, err := uuid.FromString(s)
if err != nil {
return nil, err
}
return NewDBytes(DBytes(uv.GetBytes())), nil
},
Info: "Converts the character string representation of a UUID to its byte string " +
"representation.",
},
},
"from_uuid": {
Builtin{
Types: ArgTypes{{"val", TypeBytes}},
ReturnType: fixedReturnType(TypeString),
fn: func(_ *EvalContext, args Datums) (Datum, error) {
b := []byte(*args[0].(*DBytes))
uv, err := uuid.FromBytes(b)
if err != nil {
return nil, err
}
return NewDString(uv.String()), nil
},
Info: "Converts the byte string representation of a UUID to its character string " +
"representation.",
},
},
"from_ip": {
Builtin{
Types: ArgTypes{{"val", TypeBytes}},
ReturnType: fixedReturnType(TypeString),
fn: func(_ *EvalContext, args Datums) (Datum, error) {
ipstr := args[0].(*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 NewDString(sv), nil
},
Info: "Converts the byte string representation of an IP to its character string " +
"representation.",
},
},
"to_ip": {
Builtin{
Types: ArgTypes{{"val", TypeString}},
ReturnType: fixedReturnType(TypeBytes),
fn: func(_ *EvalContext, args Datums) (Datum, error) {
ipdstr := 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, fmt.Errorf("invalid IP format: %s", ipdstr.String())
}
return NewDBytes(DBytes(ip)), nil
},
Info: "Converts the character string representation of an IP to its byte string " +
"representation.",
},
},
"split_part": {
Builtin{
Types: ArgTypes{
{"input", TypeString},
{"delimiter", TypeString},
{"return_index_pos", TypeInt},
},
ReturnType: fixedReturnType(TypeString),
fn: func(_ *EvalContext, args Datums) (Datum, error) {
text := string(MustBeDString(args[0]))
sep := string(MustBeDString(args[1]))
field := int(MustBeDInt(args[2]))
if field <= 0 {
return nil, fmt.Errorf("field position %d must be greater than zero", field)
}
splits := strings.Split(text, sep)
if field > len(splits) {
return NewDString(""), nil
}
return NewDString(splits[field-1]), nil
},
Info: "Splits `input` on `delimiter` and return the value in the `return_index_pos` " +
"position (starting at 1). <br/><br/>For example, `split_part('123.456.789.0','.',3)`" +
"returns `789`.",
},
},
"repeat": {
Builtin{
Types: ArgTypes{{"input", TypeString}, {"repeat_counter", TypeInt}},
distsqlBlacklist: true,
ReturnType: fixedReturnType(TypeString),
fn: func(_ *EvalContext, args Datums) (_ Datum, err error) {
s := string(MustBeDString(args[0]))
count := int(MustBeDInt(args[1]))
if count < 0 {
count = 0
}
// Repeat can overflow if len(s) * count is very large. The computation
// for the limit about what make can allocate is not trivial, so it's most
// accurate to detect it with a recover.
defer func() {
if r := recover(); r != nil {
err = fmt.Errorf("%s", r)
}
}()
return NewDString(strings.Repeat(s, count)), nil
},
Info: "Concatenates `input` `repeat_counter` number of times.<br/><br/>For example, " +
"`repeat('dog', 2)` returns `dogdog`.",
},
},
"ascii": {stringBuiltin1(func(s string) (Datum, error) {
for _, ch := range s {
return NewDInt(DInt(ch)), nil
}
return nil, errEmptyInputString
}, TypeInt, "Calculates the ASCII value for the first character in `val`.")},
"md5": {stringBuiltin1(func(s string) (Datum, error) {
return NewDString(fmt.Sprintf("%x", md5.Sum([]byte(s)))), nil
}, TypeString, "Calculates the MD5 hash value of `val`.")},
"sha1": {stringBuiltin1(func(s string) (Datum, error) {
return NewDString(fmt.Sprintf("%x", sha1.Sum([]byte(s)))), nil
}, TypeString, "Calculates the SHA1 hash value of `val`.")},
"sha256": {stringBuiltin1(func(s string) (Datum, error) {
return NewDString(fmt.Sprintf("%x", sha256.Sum256([]byte(s)))), nil
}, TypeString, "Calculates the SHA256 hash value of `val`.")},
"to_hex": {
Builtin{
Types: ArgTypes{{"val", TypeInt}},
ReturnType: fixedReturnType(TypeString),
fn: func(_ *EvalContext, args Datums) (Datum, error) {
return NewDString(fmt.Sprintf("%x", int64(MustBeDInt(args[0])))), nil
},
Info: "Converts `val` to its hexadecimal representation.",
},
},
// The SQL parser coerces POSITION to STRPOS.
"strpos": {stringBuiltin2("input", "find", func(s, substring string) (Datum, error) {
index := strings.Index(s, substring)
if index < 0 {
return DZero, nil
}
return NewDInt(DInt(utf8.RuneCountInString(s[:index]) + 1)), nil
}, TypeInt, "Calculates the position where the string `find` begins in `input`. <br/><br/>For"+
" example, `strpos('doggie', 'gie')` returns `4`.")},
"overlay": {
Builtin{
Types: ArgTypes{
{"input", TypeString},
{"overlay_val", TypeString},
{"start_pos", TypeInt},
},
ReturnType: fixedReturnType(TypeString),
fn: func(_ *EvalContext, args Datums) (Datum, error) {
s := string(MustBeDString(args[0]))
to := string(MustBeDString(args[1]))
pos := int(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). <br/><br/>For example, `overlay('doggie', 'CAT', 2)` returns " +
"`dCATie`.",
},
Builtin{
Types: ArgTypes{
{"input", TypeString},
{"overlay_val", TypeString},
{"start_pos", TypeInt},
{"end_pos", TypeInt},
},
ReturnType: fixedReturnType(TypeString),
fn: func(_ *EvalContext, args Datums) (Datum, error) {
s := string(MustBeDString(args[0]))
to := string(MustBeDString(args[1]))
pos := int(MustBeDInt(args[2]))
size := int(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`.",
},
},
// The SQL parser coerces TRIM(...) and TRIM(BOTH ...) to BTRIM(...).
"btrim": {
stringBuiltin2("input", "trim_chars", func(s, chars string) (Datum, error) {
return NewDString(strings.Trim(s, chars)), nil
}, TypeString, "Removes any characters included in `trim_chars` from the beginning or end"+
" of `input` (applies recursively). <br/><br/>For example, `btrim('doggie', 'eod')` "+
"returns `ggi`."),
stringBuiltin1(func(s string) (Datum, error) {
return NewDString(strings.TrimSpace(s)), nil
}, TypeString, "Removes all spaces from the beginning and end of `val`."),
},
// The SQL parser coerces TRIM(LEADING ...) to LTRIM(...).
"ltrim": {
stringBuiltin2("input", "trim_chars", func(s, chars string) (Datum, error) {
return NewDString(strings.TrimLeft(s, chars)), nil
}, TypeString, "Removes any characters included in `trim_chars` from the beginning "+
"(left-hand side) of `input` (applies recursively). <br/><br/>For example, "+
"`ltrim('doggie', 'od')` returns `ggie`."),
stringBuiltin1(func(s string) (Datum, error) {
return NewDString(strings.TrimLeftFunc(s, unicode.IsSpace)), nil
}, TypeString, "Removes all spaces from the beginning (left-hand side) of `val`."),
},
// The SQL parser coerces TRIM(TRAILING ...) to RTRIM(...).
"rtrim": {
stringBuiltin2("input", "trim_chars", func(s, chars string) (Datum, error) {
return NewDString(strings.TrimRight(s, chars)), nil
}, TypeString, "Removes any characters included in `trim_chars` from the end (right-hand "+
"side) of `input` (applies recursively). <br/><br/>For example, `rtrim('doggie', 'ei')` "+
"returns `dogg`."),
stringBuiltin1(func(s string) (Datum, error) {
return NewDString(strings.TrimRightFunc(s, unicode.IsSpace)), nil
}, TypeString, "Removes all spaces from the end (right-hand side) of `val`."),
},
"reverse": {stringBuiltin1(func(s string) (Datum, error) {
runes := []rune(s)
for i, j := 0, len(runes)-1; i < j; i, j = i+1, j-1 {
runes[i], runes[j] = runes[j], runes[i]
}
return NewDString(string(runes)), nil
}, TypeString, "Reverses the order of the string's characters.")},
"replace": {stringBuiltin3(
"input", "find", "replace",
func(input, from, to string) (Datum, error) {
return NewDString(strings.Replace(input, from, to, -1)), nil
},
TypeString,
"Replaces all occurrences of `find` with `replace` in `input`",
)},
"translate": {stringBuiltin3(
"input", "find", "replace",
func(s, from, to string) (Datum, error) {
const deletionRune = utf8.MaxRune + 1
translation := make(map[rune]rune, len(from))
for _, fromRune := range from {
toRune, size := utf8.DecodeRuneInString(to)
if toRune == utf8.RuneError {
toRune = deletionRune
} else {
to = to[size:]
}
translation[fromRune] = toRune
}
runes := make([]rune, 0, len(s))
for _, c := range s {
if t, ok := translation[c]; ok {
if t != deletionRune {
runes = append(runes, t)
}
} else {
runes = append(runes, c)
}
}
return NewDString(string(runes)), nil
}, TypeString, "In `input`, replaces the first character from `find` with the first "+
"character in `replace`; repeat for each character in `find`. <br/><br/>For example, "+
"`translate('doggie', 'dog', '123');` returns `1233ie`.")},
"regexp_extract": {
Builtin{
Types: ArgTypes{{"input", TypeString}, {"regex", TypeString}},
ReturnType: fixedReturnType(TypeString),
fn: func(ctx *EvalContext, args Datums) (Datum, error) {
s := string(MustBeDString(args[0]))
pattern := string(MustBeDString(args[1]))
return regexpExtract(ctx, s, pattern, `\`)
},
Info: "Returns the first match for the Regular Expression `regex` in `input`.",
},
},
"regexp_replace": {
Builtin{
Types: ArgTypes{
{"input", TypeString},
{"regex", TypeString},
{"replace", TypeString},
},
ReturnType: fixedReturnType(TypeString),
fn: func(ctx *EvalContext, args Datums) (Datum, error) {
s := string(MustBeDString(args[0]))
pattern := string(MustBeDString(args[1]))
to := string(MustBeDString(args[2]))
return regexpReplace(ctx, s, pattern, to, "")
},
Info: "Replaces matches for the Regular Expression `regex` in `input` with the " +
"Regular Expression `replace`.",
},
Builtin{
Types: ArgTypes{
{"input", TypeString},
{"regex", TypeString},
{"replace", TypeString},
{"flags", TypeString},
},
ReturnType: fixedReturnType(TypeString),
fn: func(ctx *EvalContext, args Datums) (Datum, error) {
s := string(MustBeDString(args[0]))
pattern := string(MustBeDString(args[1]))
to := string(MustBeDString(args[2]))
sqlFlags := string(MustBeDString(args[3]))
return regexpReplace(ctx, s, pattern, to, sqlFlags)
},
Info: "Replaces matches for the Regular Expression `regex` in `input` with the Regular " +
"Expression `replace` using `flags`.<br/><br/>CockroachDB supports the following " +
"flags:<br/><br/>• **c**: Case-sensitive matching<br/><br/>• **g**: " +
"Global matching (match each substring instead of only the first).<br/><br/>• " +
"**i**: Case-insensitive matching<br/><br/>• **m** or **n**: Newline-sensitive " +
"`.` and negated brackets (`[^...]`) do not match newline characters (preventing " +
"matching: matches from crossing newlines unless explicitly defined to); `^` and " +
"`$` match the space before and after newline characters respectively (so characters " +
"between newline characters are treated as if they're on a separate line).<br/>" +
"<br/>• **p**: Partial newline-sensitive matching: `.` and negated brackets " +
"(`[^...]`) do not match newline characters (preventing matches from crossing " +
"newlines unless explicitly defined to), but `^` and `$` still only match the " +
"beginning and end of `val`.<br/><br/>• **s**: Newline-insensitive " +
"matching *(default)*.<br/><br/>• **w**: Inverse partial newline-sensitive " +
"matching:`.` and negated brackets (`[^...]`) *do* match newline characters, but `^` " +
"and `$` match the space before and after newline characters respectively (so " +
"characters between newline characters are treated as if they're on a separate line).",
},
},
"initcap": {stringBuiltin1(func(s string) (Datum, error) {
return NewDString(strings.Title(strings.ToLower(s))), nil
}, TypeString, "Capitalizes the first letter of `val`.")},
"left": {
Builtin{
Types: ArgTypes{{"input", TypeBytes}, {"return_set", TypeInt}},
ReturnType: fixedReturnType(TypeBytes),
fn: func(_ *EvalContext, args Datums) (Datum, error) {
bytes := []byte(*args[0].(*DBytes))
n := int(MustBeDInt(args[1]))
if n < -len(bytes) {
n = 0
} else if n < 0 {
n = len(bytes) + n
} else if n > len(bytes) {
n = len(bytes)
}
return NewDBytes(DBytes(bytes[:n])), nil
},
Info: "Returns the first `return_set` bytes from `input`.",
},
Builtin{
Types: ArgTypes{{"input", TypeString}, {"return_set", TypeInt}},
ReturnType: fixedReturnType(TypeString),
fn: func(_ *EvalContext, args Datums) (Datum, error) {
runes := []rune(string(MustBeDString(args[0])))
n := int(MustBeDInt(args[1]))
if n < -len(runes) {
n = 0
} else if n < 0 {
n = len(runes) + n
} else if n > len(runes) {
n = len(runes)
}
return NewDString(string(runes[:n])), nil
},
Info: "Returns the first `return_set` characters from `input`.",
},
},
"right": {
Builtin{
Types: ArgTypes{{"input", TypeBytes}, {"return_set", TypeInt}},
ReturnType: fixedReturnType(TypeBytes),
fn: func(_ *EvalContext, args Datums) (Datum, error) {
bytes := []byte(*args[0].(*DBytes))
n := int(MustBeDInt(args[1]))
if n < -len(bytes) {
n = 0
} else if n < 0 {
n = len(bytes) + n
} else if n > len(bytes) {
n = len(bytes)
}
return NewDBytes(DBytes(bytes[len(bytes)-n:])), nil
},
Info: "Returns the last `return_set` bytes from `input`.",
},
Builtin{
Types: ArgTypes{{"input", TypeString}, {"return_set", TypeInt}},
ReturnType: fixedReturnType(TypeString),
fn: func(_ *EvalContext, args Datums) (Datum, error) {
runes := []rune(string(MustBeDString(args[0])))
n := int(MustBeDInt(args[1]))
if n < -len(runes) {
n = 0
} else if n < 0 {
n = len(runes) + n
} else if n > len(runes) {
n = len(runes)
}
return NewDString(string(runes[len(runes)-n:])), nil
},
Info: "Returns the last `return_set` characters from `input`.",
},
},
"random": {
Builtin{
Types: ArgTypes{},
ReturnType: fixedReturnType(TypeFloat),
impure: true,
needsRepeatedEvaluation: true,
fn: func(_ *EvalContext, args Datums) (Datum, error) {
return NewDFloat(DFloat(rand.Float64())), nil
},
Info: "Returns a random float between 0 and 1.",
},
},
"unique_rowid": {
Builtin{
Types: ArgTypes{},
ReturnType: fixedReturnType(TypeInt),
category: categoryIDGeneration,
impure: true,
fn: func(ctx *EvalContext, args Datums) (Datum, error) {
return NewDInt(GenerateUniqueInt(ctx.NodeID)), nil
},
Info: "Returns a unique ID used by CockroachDB to generate unique row IDs if a " +
"Primary Key isn't defined for the table. The value is a combination of the " +
" insert timestamp and the ID of the node executing the statement, which " +
" guarantees this combination is globally unique.",
},
},
"experimental_uuid_v4": {uuidV4Impl},
"uuid_v4": {uuidV4Impl},
"greatest": {
Builtin{
Types: HomogeneousType{},
ReturnType: identityReturnType(0),
category: categoryComparison,
fn: func(ctx *EvalContext, args Datums) (Datum, error) {
return pickFromTuple(ctx, true /* greatest */, args)
},
Info: "Returns the element with the greatest value.",
},
},
"least": {
Builtin{
Types: HomogeneousType{},
ReturnType: identityReturnType(0),
category: categoryComparison,
fn: func(ctx *EvalContext, args Datums) (Datum, error) {
return pickFromTuple(ctx, false /* !greatest */, args)
},
Info: "Returns the element with the lowest value.",
},
},
// Timestamp/Date functions.
"experimental_strftime": {
Builtin{
Types: ArgTypes{{"input", TypeTimestamp}, {"extract_format", TypeString}},
ReturnType: fixedReturnType(TypeString),
fn: func(_ *EvalContext, args Datums) (Datum, error) {
fromTime := args[0].(*DTimestamp).Time
format := string(MustBeDString(args[1]))
t, err := strtime.Strftime(fromTime, format)
if err != nil {
return nil, err
}
return NewDString(t), nil
},
Info: "From `input`, extracts and formats the time as identified in `extract_format` " +
"using standard `strftime` notation (though not all formatting is supported).",
},
Builtin{
Types: ArgTypes{{"input", TypeDate}, {"extract_format", TypeString}},
ReturnType: fixedReturnType(TypeString),
fn: func(_ *EvalContext, args Datums) (Datum, error) {
fromTime := time.Unix(int64(*args[0].(*DDate))*secondsInDay, 0).UTC()
format := string(MustBeDString(args[1]))
t, err := strtime.Strftime(fromTime, format)
if err != nil {
return nil, err
}
return NewDString(t), nil
},
Info: "From `input`, extracts and formats the time as identified in `extract_format` " +
"using standard `strftime` notation (though not all formatting is supported).",
},
Builtin{
Types: ArgTypes{{"input", TypeTimestampTZ}, {"extract_format", TypeString}},
ReturnType: fixedReturnType(TypeString),
fn: func(_ *EvalContext, args Datums) (Datum, error) {
fromTime := args[0].(*DTimestampTZ).Time
format := string(MustBeDString(args[1]))
t, err := strtime.Strftime(fromTime, format)
if err != nil {
return nil, err
}
return NewDString(t), nil
},
Info: "From `input`, extracts and formats the time as identified in `extract_format` " +
"using standard `strftime` notation (though not all formatting is supported).",
},
},
"experimental_strptime": {
Builtin{
Types: ArgTypes{{"input", TypeString}, {"format", TypeString}},
ReturnType: fixedReturnType(TypeTimestampTZ),
fn: func(_ *EvalContext, args Datums) (Datum, error) {
toParse := string(MustBeDString(args[0]))
format := string(MustBeDString(args[1]))
t, err := strtime.Strptime(toParse, format)
if err != nil {
return nil, err
}
return MakeDTimestampTZ(t.UTC(), time.Microsecond), nil
},
Info: "Returns `input` as a timestamptz using `format` (which uses standard " +
"`strptime` formatting).",
},
},
"age": {
Builtin{
Types: ArgTypes{{"val", TypeTimestampTZ}},
ReturnType: fixedReturnType(TypeInterval),
fn: func(ctx *EvalContext, args Datums) (Datum, error) {
return timestampMinusBinOp.fn(ctx, ctx.GetTxnTimestamp(time.Microsecond), args[0])
},
Info: "Calculates the interval between `val` and the current time.",
},
Builtin{
Types: ArgTypes{{"begin", TypeTimestampTZ}, {"end", TypeTimestampTZ}},
ReturnType: fixedReturnType(TypeInterval),
fn: func(ctx *EvalContext, args Datums) (Datum, error) {
return timestampMinusBinOp.fn(ctx, args[0], args[1])
},
Info: "Calculates the interval between `begin` and `end`.",
},
},
"current_date": {
Builtin{
Types: ArgTypes{},
ReturnType: fixedReturnType(TypeDate),
fn: func(ctx *EvalContext, args Datums) (Datum, error) {
t := ctx.GetTxnTimestamp(time.Microsecond).Time
return NewDDateFromTime(t, ctx.GetLocation()), nil
},
Info: "Returns the current date.",
},
},
"now": txnTSImpl,
"current_timestamp": txnTSImpl,
"transaction_timestamp": txnTSImpl,
"statement_timestamp": {
Builtin{
Types: ArgTypes{},
ReturnType: fixedReturnType(TypeTimestampTZ),
preferredOverload: true,
impure: true,
fn: func(ctx *EvalContext, args Datums) (Datum, error) {
return MakeDTimestampTZ(ctx.GetStmtTimestamp(), time.Microsecond), nil
},
Info: "Returns the current statement's timestamp.",
},
Builtin{
Types: ArgTypes{},
ReturnType: fixedReturnType(TypeTimestamp),
impure: true,
fn: func(ctx *EvalContext, args Datums) (Datum, error) {
return MakeDTimestamp(ctx.GetStmtTimestamp(), time.Microsecond), nil
},
Info: "Returns the current statement's timestamp.",
},
},
"cluster_logical_timestamp": {
Builtin{
Types: ArgTypes{},
ReturnType: fixedReturnType(TypeDecimal),
category: categorySystemInfo,
impure: true,
fn: func(ctx *EvalContext, args Datums) (Datum, error) {
return ctx.GetClusterTimestamp(), nil
},
Info: "This function is used only by CockroachDB's developers for testing purposes.",
},
},
"clock_timestamp": {
Builtin{
Types: ArgTypes{},
ReturnType: fixedReturnType(TypeTimestampTZ),
preferredOverload: true,
impure: true,
fn: func(_ *EvalContext, args Datums) (Datum, error) {
return MakeDTimestampTZ(timeutil.Now(), time.Microsecond), nil
},
Info: "Returns the current wallclock time.",
},
Builtin{
Types: ArgTypes{},
ReturnType: fixedReturnType(TypeTimestamp),
impure: true,
fn: func(_ *EvalContext, args Datums) (Datum, error) {
return MakeDTimestamp(timeutil.Now(), time.Microsecond), nil
},
Info: "Returns the current wallclock time.",
},
},
"extract": {
Builtin{
Types: ArgTypes{{"element", TypeString}, {"input", TypeTimestamp}},
ReturnType: fixedReturnType(TypeInt),
category: categoryDateAndTime,
fn: func(ctx *EvalContext, args Datums) (Datum, error) {
// extract timeSpan fromTime.
fromTS := args[1].(*DTimestamp)
timeSpan := strings.ToLower(string(MustBeDString(args[0])))
return extractStringFromTimestamp(ctx, fromTS.Time, timeSpan)
},
Info: "Extracts `element` from `input`. Compatible `elements` are: <br/>• " +
"year<br/>• quarter<br/>• month<br/>• week<br/>• " +
"dayofweek<br/>• dayofyear<br/>• hour<br/>• minute<br/>• " +
"second<br/>• millisecond<br/>• microsecond<br/>• epoch",
},
Builtin{
Types: ArgTypes{{"element", TypeString}, {"input", TypeDate}},
ReturnType: fixedReturnType(TypeInt),
category: categoryDateAndTime,