-
Notifications
You must be signed in to change notification settings - Fork 3.8k
/
pg_builtins.go
2307 lines (2173 loc) · 84.3 KB
/
pg_builtins.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2016 The Cockroach Authors.
//
// Use of this software is governed by the Business Source License
// included in the file licenses/BSL.txt.
//
// As of the Change Date specified in that file, in accordance with
// the Business Source License, use of this software will be governed
// by the Apache License, Version 2.0, included in the file
// licenses/APL.txt.
package builtins
import (
"context"
"fmt"
"strconv"
"strings"
"time"
"github.com/cockroachdb/cockroach/pkg/security/username"
"github.com/cockroachdb/cockroach/pkg/sql/catalog"
"github.com/cockroachdb/cockroach/pkg/sql/catalog/catalogkeys"
"github.com/cockroachdb/cockroach/pkg/sql/oidext"
"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/privilege"
"github.com/cockroachdb/cockroach/pkg/sql/rowenc/valueside"
"github.com/cockroachdb/cockroach/pkg/sql/sem/builtins/builtinconstants"
"github.com/cockroachdb/cockroach/pkg/sql/sem/catconstants"
"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/types"
"github.com/cockroachdb/cockroach/pkg/util/ipaddr"
"github.com/cockroachdb/errors"
"github.com/lib/pq/oid"
)
// This file contains builtin functions that we implement primarily for
// compatibility with Postgres.
const notUsableInfo = "Not usable; exposed only for compatibility with PostgreSQL."
// makeNotUsableFalseBuiltin creates a builtin that takes no arguments and
// always returns a boolean with the value false.
func makeNotUsableFalseBuiltin() builtinDefinition {
return makeBuiltin(
defProps(),
tree.Overload{
Types: tree.ParamTypes{},
ReturnType: tree.FixedReturnType(types.Bool),
Fn: func(context.Context, *eval.Context, tree.Datums) (tree.Datum, error) {
return tree.DBoolFalse, nil
},
Info: notUsableInfo,
Volatility: volatility.Volatile,
},
)
}
// typeBuiltinsHaveUnderscore is a map to keep track of which types have i/o
// builtins with underscores in between their type name and the i/o builtin
// name, like date_in vs int8in. There seems to be no other way to
// programmatically determine whether or not this underscore is present, hence
// the existence of this map.
var typeBuiltinsHaveUnderscore = map[oid.Oid]struct{}{
types.Any.Oid(): {},
types.AnyArray.Oid(): {},
types.Date.Oid(): {},
types.Time.Oid(): {},
types.TimeTZ.Oid(): {},
types.Decimal.Oid(): {},
types.Interval.Oid(): {},
types.Json.Oid(): {},
types.Jsonb.Oid(): {},
types.Uuid.Oid(): {},
types.VarBit.Oid(): {},
types.Geometry.Oid(): {},
types.Geography.Oid(): {},
types.Box2D.Oid(): {},
oid.T_bit: {},
types.Timestamp.Oid(): {},
types.TimestampTZ.Oid(): {},
types.AnyTuple.Oid(): {},
}
// PGIOBuiltinPrefix returns the string prefix to a type's IO functions. This
// is either the type's postgres display name or the type's postgres display
// name plus an underscore, depending on the type.
func PGIOBuiltinPrefix(typ *types.T) string {
builtinPrefix := typ.PGName()
if _, ok := typeBuiltinsHaveUnderscore[typ.Oid()]; ok {
return builtinPrefix + "_"
}
return builtinPrefix
}
// initPGBuiltins adds all of the postgres builtins to the builtins map.
func init() {
for k, v := range pgBuiltins {
v.props.Category = builtinconstants.CategoryCompatibility
registerBuiltin(k, v)
}
// Make non-array type i/o builtins.
for _, typ := range types.OidToType {
// Skip most array types. We're doing them separately below.
switch typ.Oid() {
case oid.T_int2vector, oid.T_oidvector:
default:
if typ.Family() == types.ArrayFamily {
continue
}
}
builtinPrefix := PGIOBuiltinPrefix(typ)
for name, builtin := range makeTypeIOBuiltins(builtinPrefix, typ) {
registerBuiltin(name, builtin)
}
}
// Make array type i/o builtins.
for name, builtin := range makeTypeIOBuiltins("array_", types.AnyArray) {
registerBuiltin(name, builtin)
}
for name, builtin := range makeTypeIOBuiltins("anyarray_", types.AnyArray) {
registerBuiltin(name, builtin)
}
// Make enum type i/o builtins.
for name, builtin := range makeTypeIOBuiltins("enum_", types.AnyEnum) {
registerBuiltin(name, builtin)
}
// Make crdb_internal.create_regfoo and to_regfoo builtins.
for _, b := range []struct {
toRegOverloadHelpText string
typ *types.T
}{
{"Translates a textual relation name to its OID", types.RegClass},
{"Translates a textual schema name to its OID", types.RegNamespace},
{"Translates a textual function or procedure name to its OID", types.RegProc},
{"Translates a textual function or procedure name(with argument types) to its OID", types.RegProcedure},
{"Translates a textual role name to its OID", types.RegRole},
{"Translates a textual type name to its OID", types.RegType},
} {
typName := b.typ.SQLStandardName()
registerBuiltin("crdb_internal.create_"+typName, makeCreateRegDef(b.typ))
registerBuiltin("to_"+typName, makeToRegOverload(b.typ, b.toRegOverloadHelpText))
}
}
var errUnimplemented = pgerror.New(pgcode.FeatureNotSupported, "unimplemented")
func makeTypeIOBuiltin(paramTypes tree.TypeList, returnType *types.T) builtinDefinition {
return makeBuiltin(
tree.FunctionProperties{
Category: builtinconstants.CategoryCompatibility,
},
tree.Overload{
Types: paramTypes,
ReturnType: tree.FixedReturnType(returnType),
Fn: func(_ context.Context, _ *eval.Context, _ tree.Datums) (tree.Datum, error) {
return nil, errUnimplemented
},
Info: notUsableInfo,
Volatility: volatility.Volatile,
// Ignore validity checks for typeio builtins. We don't
// implement these anyway, and they are very hard to special
// case.
IgnoreVolatilityCheck: true,
},
)
}
// makeTypeIOBuiltins generates the 4 i/o builtins that Postgres implements for
// every type: typein, typeout, typerecv, and typsend. All 4 builtins are no-op,
// and only supported because ORMs sometimes use their names to form a map for
// client-side type encoding and decoding. See issue #12526 for more details.
func makeTypeIOBuiltins(builtinPrefix string, typ *types.T) map[string]builtinDefinition {
typname := typ.String()
return map[string]builtinDefinition{
builtinPrefix + "send": makeTypeIOBuiltin(tree.ParamTypes{{Name: typname, Typ: typ}}, types.Bytes),
// Note: PG takes type 2281 "internal" for these builtins, which we don't
// provide. We won't implement these functions anyway, so it shouldn't
// matter.
builtinPrefix + "recv": makeTypeIOBuiltin(tree.ParamTypes{{Name: "input", Typ: types.Any}}, typ),
// Note: PG returns 'cstring' for these builtins, but we don't support that.
builtinPrefix + "out": makeTypeIOBuiltin(tree.ParamTypes{{Name: typname, Typ: typ}}, types.Bytes),
// Note: PG takes 'cstring' for these builtins, but we don't support that.
builtinPrefix + "in": makeTypeIOBuiltin(tree.ParamTypes{{Name: "input", Typ: types.Any}}, typ),
}
}
// http://doxygen.postgresql.org/pg__wchar_8h.html#a22e0c8b9f59f6e226a5968620b4bb6a9aac3b065b882d3231ba59297524da2f23
var (
// DatEncodingUTFId is the encoding ID for our only supported database
// encoding, UTF8.
DatEncodingUTFId = tree.NewDInt(6)
// DatEncodingEnUTF8 is the encoding name for our only supported database
// encoding, UTF8.
DatEncodingEnUTF8 = tree.NewDString("en_US.utf8")
datEncodingUTF8ShortName = tree.NewDString("UTF8")
)
// Make a pg_get_indexdef function with the given arguments.
func makePGGetIndexDef(paramTypes tree.ParamTypes) tree.Overload {
return tree.Overload{
Types: paramTypes,
ReturnType: tree.FixedReturnType(types.String),
Fn: func(ctx context.Context, evalCtx *eval.Context, args tree.Datums) (tree.Datum, error) {
colNumber := *tree.NewDInt(0)
if len(args) == 3 {
colNumber = *args[1].(*tree.DInt)
}
r, err := evalCtx.Planner.QueryRowEx(
ctx, "pg_get_indexdef",
sessiondata.NoSessionDataOverride,
"SELECT indexdef FROM pg_catalog.pg_indexes WHERE crdb_oid = $1", args[0])
if err != nil {
return nil, err
}
// If the index does not exist we return null.
if len(r) == 0 {
return tree.DNull, nil
}
// The 1 argument and 3 argument variants are equivalent when column number 0 is passed.
if colNumber == 0 {
return r[0], nil
}
// The 3 argument variant for column number other than 0 returns the column name.
r, err = evalCtx.Planner.QueryRowEx(
ctx, "pg_get_indexdef",
sessiondata.NoSessionDataOverride,
`SELECT ischema.column_name as pg_get_indexdef
FROM information_schema.statistics AS ischema
INNER JOIN pg_catalog.pg_indexes AS pgindex
ON ischema.table_schema = pgindex.schemaname
AND ischema.table_name = pgindex.tablename
AND ischema.index_name = pgindex.indexname
AND pgindex.crdb_oid = $1
AND ischema.seq_in_index = $2`, args[0], args[1])
if err != nil {
return nil, err
}
// If the column number does not exist in the index we return an empty string.
if len(r) == 0 {
return tree.NewDString(""), nil
}
if len(r) > 1 {
return nil, errors.AssertionFailedf("pg_get_indexdef query has more than 1 result row: %+v", r)
}
return r[0], nil
},
Info: notUsableInfo,
Volatility: volatility.Stable,
}
}
// Make a pg_get_viewdef function with the given arguments.
func makePGGetViewDef(paramTypes tree.ParamTypes) tree.Overload {
return tree.Overload{
Types: paramTypes,
ReturnType: tree.FixedReturnType(types.String),
IsUDF: true,
Body: `SELECT definition
FROM pg_catalog.pg_views v
JOIN pg_catalog.pg_class c ON c.relname=v.viewname
WHERE c.oid=$1
UNION ALL
SELECT definition
FROM pg_catalog.pg_matviews v
JOIN pg_catalog.pg_class c ON c.relname=v.matviewname
WHERE c.oid=$1`,
Info: "Returns the CREATE statement for an existing view.",
Volatility: volatility.Stable,
}
}
// Make a pg_get_constraintdef function with the given arguments.
func makePGGetConstraintDef(paramTypes tree.ParamTypes) tree.Overload {
return tree.Overload{
Types: paramTypes,
ReturnType: tree.FixedReturnType(types.String),
IsUDF: true,
Body: `SELECT condef FROM pg_catalog.pg_constraint WHERE oid=$1 LIMIT 1`,
Info: notUsableInfo,
Volatility: volatility.Stable,
}
}
// paramTypeOpts is similar to tree.ParamTypes, but represents parameters that
// can accept multiple types.
type paramTypeOpts []struct {
Name string
Typ []*types.T
}
var strOrOidTypes = []*types.T{types.String, types.Oid}
// makePGPrivilegeInquiryDef constructs all variations of a specific PG access
// privilege inquiry function. Each variant has a different signature.
//
// The function takes a list of "object specification" arguments options. Each
// of these options can specify one or more valid types that it can accept. This
// is *not* the full list of arguments, but is only the list of arguments that
// differs between each privilege inquiry function. It also takes an info string
// that is used to construct the full function description.
func makePGPrivilegeInquiryDef(
infoDetail string,
objSpecArgs paramTypeOpts,
fn func(ctx context.Context, evalCtx *eval.Context, args tree.Datums, user username.SQLUsername) (eval.HasAnyPrivilegeResult, error),
) builtinDefinition {
// Collect the different argument type variations.
//
// 1. variants can begin with an optional "user" argument, which if used
// can be specified using a STRING or an OID. Postgres also allows the
// 'public' pseudo-role to be used, but this is not supported here. If
// the argument omitted, the value of current_user is assumed.
paramTypes := []tree.ParamTypes{
{}, // no user
}
for _, typ := range strOrOidTypes {
paramTypes = append(paramTypes, tree.ParamTypes{{Name: "user", Typ: typ}})
}
// 2. variants have one or more object identification arguments, which each
// accept multiple types.
for _, objSpecArg := range objSpecArgs {
prevParamTypes := paramTypes
paramTypes = make([]tree.ParamTypes, 0, len(paramTypes)*len(objSpecArg.Typ))
for _, paramType := range prevParamTypes {
for _, typ := range objSpecArg.Typ {
paramTypeVariant := append(paramType, tree.ParamTypes{{Name: objSpecArg.Name, Typ: typ}}...)
paramTypes = append(paramTypes, paramTypeVariant)
}
}
}
// 3. variants all end with a "privilege" argument which can only
// be a string. See parsePrivilegeStr for details on how this
// argument is parsed and used.
for i, paramType := range paramTypes {
paramTypes[i] = append(paramType, tree.ParamTypes{{Name: "privilege", Typ: types.String}}...)
}
var variants []tree.Overload
for _, paramType := range paramTypes {
withUser := paramType[0].Name == "user"
infoFmt := "Returns whether or not the current user has privileges for %s."
if withUser {
infoFmt = "Returns whether or not the user has privileges for %s."
}
variants = append(variants, tree.Overload{
Types: paramType,
ReturnType: tree.FixedReturnType(types.Bool),
Fn: func(ctx context.Context, evalCtx *eval.Context, args tree.Datums) (tree.Datum, error) {
var user username.SQLUsername
if withUser {
arg := eval.UnwrapDatum(ctx, evalCtx, args[0])
userS, err := getNameForArg(ctx, evalCtx, arg, "pg_roles", "rolname")
if err != nil {
return nil, err
}
// Note: the username in pg_roles is already normalized, so
// we can safely turn it into a SQLUsername without
// re-normalization.
user = username.MakeSQLUsernameFromPreNormalizedString(userS)
if user.Undefined() {
if _, ok := arg.(*tree.DOid); ok {
// Postgres returns falseifn no matching user is
// found when given an OID.
return tree.DBoolFalse, nil
}
return nil, pgerror.Newf(pgcode.UndefinedObject,
"role %s does not exist", arg)
}
// Remove the first argument.
args = args[1:]
} else {
if evalCtx.SessionData().User().Undefined() {
// Wut... is this possible?
return tree.DNull, nil
}
user = evalCtx.SessionData().User()
}
ret, err := fn(ctx, evalCtx, args, user)
if err != nil {
return nil, err
}
switch ret {
case eval.HasPrivilege:
return tree.DBoolTrue, nil
case eval.HasNoPrivilege:
return tree.DBoolFalse, nil
case eval.ObjectNotFound:
return tree.DNull, nil
default:
panic(fmt.Sprintf("unrecognized HasAnyPrivilegeResult %d", ret))
}
},
Info: fmt.Sprintf(infoFmt, infoDetail),
Volatility: volatility.Stable,
})
}
return makeBuiltin(
tree.FunctionProperties{
DistsqlBlocklist: true,
},
variants...,
)
}
// getNameForArg determines the object name for the specified argument, which
// should be either an unwrapped STRING or an OID. If the object is not found,
// the returned string will be empty.
func getNameForArg(
ctx context.Context, evalCtx *eval.Context, arg tree.Datum, pgTable, pgCol string,
) (string, error) {
var query string
switch t := arg.(type) {
case *tree.DString:
query = fmt.Sprintf("SELECT %s FROM pg_catalog.%s WHERE %s = $1 LIMIT 1", pgCol, pgTable, pgCol)
case *tree.DOid:
query = fmt.Sprintf("SELECT %s FROM pg_catalog.%s WHERE oid = $1 LIMIT 1", pgCol, pgTable)
default:
return "", errors.AssertionFailedf("unexpected arg type %T", t)
}
r, err := evalCtx.Planner.QueryRowEx(ctx, "get-name-for-arg",
sessiondata.NoSessionDataOverride, query, arg)
if err != nil || r == nil {
return "", err
}
return string(tree.MustBeDString(r[0])), nil
}
// privMap maps a privilege string to a Privilege.
type privMap map[string]privilege.Privilege
func normalizePrivilegeStr(arg tree.Datum) []string {
argStr := string(tree.MustBeDString(arg))
privStrs := strings.Split(argStr, ",")
res := make([]string, len(privStrs))
for i, privStr := range privStrs {
// Privileges are case-insensitive.
privStr = strings.ToUpper(privStr)
// Extra whitespace is allowed between but not within privilege names.
privStr = strings.TrimSpace(privStr)
res[i] = privStr
}
return res
}
// parsePrivilegeStr recognizes privilege strings for has_foo_privilege
// builtins, which are known as Access Privilege Inquiry Functions.
//
// The function accept a comma-separated list of case-insensitive privilege
// names, producing a list of privileges. It is liberal about whitespace between
// items, not so much about whitespace within items. The allowed privilege names
// and their corresponding privileges are given as a privMap.
func parsePrivilegeStr(arg tree.Datum, m privMap) ([]privilege.Privilege, error) {
privStrs := normalizePrivilegeStr(arg)
res := make([]privilege.Privilege, len(privStrs))
for i, privStr := range privStrs {
// Check the privilege map.
p, ok := m[privStr]
if !ok {
return nil, pgerror.Newf(pgcode.InvalidParameterValue,
"unrecognized privilege type: %q", privStr)
}
res[i] = p
}
return res, nil
}
func makeCreateRegDef(typ *types.T) builtinDefinition {
return makeBuiltin(defProps(),
tree.Overload{
Types: tree.ParamTypes{
{Name: "oid", Typ: types.Oid},
{Name: "name", Typ: types.String},
},
ReturnType: tree.FixedReturnType(typ),
Fn: func(_ context.Context, _ *eval.Context, d tree.Datums) (tree.Datum, error) {
return tree.NewDOidWithName(tree.MustBeDOid(d[0]).Oid, typ, string(tree.MustBeDString(d[1]))), nil
},
Info: notUsableInfo,
Volatility: volatility.Immutable,
},
)
}
func makeToRegOverload(typ *types.T, helpText string) builtinDefinition {
return makeBuiltin(tree.FunctionProperties{Category: builtinconstants.CategorySystemInfo},
tree.Overload{
Types: tree.ParamTypes{
{Name: "text", Typ: types.String},
},
ReturnType: tree.FixedReturnType(types.RegType),
Fn: func(ctx context.Context, evalCtx *eval.Context, args tree.Datums) (tree.Datum, error) {
typName := tree.MustBeDString(args[0])
int, _ := strconv.Atoi(strings.TrimSpace(string(typName)))
if int > 0 {
return tree.DNull, nil
}
typOid, err := eval.ParseDOid(ctx, evalCtx, string(typName), typ)
if err != nil {
//nolint:returnerrcheck
return tree.DNull, nil
}
return typOid, nil
},
Info: helpText,
Volatility: volatility.Stable,
},
)
}
// Format the array {type,othertype} as type, othertype.
// If there are no args, output the empty string.
const getFunctionArgStringQuery = `SELECT
COALESCE(
(SELECT trim('{}' FROM replace(
array_agg(unnest(proargtypes)::REGTYPE::TEXT)::TEXT,
',', ', ')))
, '')
FROM pg_catalog.pg_proc
WHERE oid=$1
GROUP BY oid, proargtypes
LIMIT 1`
var pgBuiltins = map[string]builtinDefinition{
// See https://www.postgresql.org/docs/9.6/static/functions-info.html.
"pg_backend_pid": makeBuiltin(defProps(),
tree.Overload{
Types: tree.ParamTypes{},
ReturnType: tree.FixedReturnType(types.Int),
Fn: func(ctx context.Context, evalCtx *eval.Context, _ tree.Datums) (tree.Datum, error) {
pid := evalCtx.QueryCancelKey.GetPGBackendPID()
return tree.NewDInt(tree.DInt(pid)), nil
},
Info: "Returns a numerical ID attached to this session. This ID is " +
"part of the query cancellation key used by the wire protocol. This " +
"function was only added for compatibility, and unlike in Postgres, the " +
"returned value does not correspond to a real process ID.",
Volatility: volatility.Stable,
},
),
// See https://www.postgresql.org/docs/9.3/static/catalog-pg-database.html.
"pg_encoding_to_char": makeBuiltin(defProps(),
tree.Overload{
Types: tree.ParamTypes{
{Name: "encoding_id", Typ: types.Int},
},
ReturnType: tree.FixedReturnType(types.String),
Fn: func(ctx context.Context, evalCtx *eval.Context, args tree.Datums) (tree.Datum, error) {
if args[0].Compare(evalCtx, DatEncodingUTFId) == 0 {
return datEncodingUTF8ShortName, nil
}
return tree.DNull, nil
},
Info: notUsableInfo,
Volatility: volatility.Stable,
},
),
// Here getdatabaseencoding just returns UTF8 because,
// CockroachDB supports just UTF8 for now.
"getdatabaseencoding": makeBuiltin(
tree.FunctionProperties{Category: builtinconstants.CategorySystemInfo},
tree.Overload{
Types: tree.ParamTypes{},
ReturnType: tree.FixedReturnType(types.String),
Fn: func(_ context.Context, _ *eval.Context, args tree.Datums) (tree.Datum, error) {
// We only support UTF-8 right now.
// If we allow more encodings, we must also change the virtual schema
// entry for pg_catalog.pg_database.
return datEncodingUTF8ShortName, nil
},
Info: "Returns the current encoding name used by the database.",
Volatility: volatility.Stable,
},
),
// Postgres defines pg_get_expr as a function that "decompiles the internal form
// of an expression", which is provided in the pg_node_tree type. In Cockroach's
// pg_catalog implementation, we populate all pg_node_tree columns with the
// corresponding expression as a string, which means that this function can simply
// return the first argument directly. It also means we can ignore the second and
// optional third argument.
"pg_get_expr": makeBuiltin(defProps(),
tree.Overload{
Types: tree.ParamTypes{
{Name: "pg_node_tree", Typ: types.String},
{Name: "relation_oid", Typ: types.Oid},
},
ReturnType: tree.FixedReturnType(types.String),
Fn: func(_ context.Context, _ *eval.Context, args tree.Datums) (tree.Datum, error) {
return args[0], nil
},
Info: notUsableInfo,
Volatility: volatility.Stable,
},
tree.Overload{
Types: tree.ParamTypes{
{Name: "pg_node_tree", Typ: types.String},
{Name: "relation_oid", Typ: types.Oid},
{Name: "pretty_bool", Typ: types.Bool},
},
ReturnType: tree.FixedReturnType(types.String),
Fn: func(_ context.Context, _ *eval.Context, args tree.Datums) (tree.Datum, error) {
return args[0], nil
},
Info: notUsableInfo,
Volatility: volatility.Stable,
},
),
// pg_get_constraintdef functions like SHOW CREATE CONSTRAINT would if we
// supported that statement.
"pg_get_constraintdef": makeBuiltin(tree.FunctionProperties{DistsqlBlocklist: true},
makePGGetConstraintDef(tree.ParamTypes{
{Name: "constraint_oid", Typ: types.Oid}, {Name: "pretty_bool", Typ: types.Bool}}),
makePGGetConstraintDef(tree.ParamTypes{{Name: "constraint_oid", Typ: types.Oid}}),
),
// pg_get_partkeydef is only provided for compatibility and always returns
// NULL. It is supposed to return the PARTITION BY clause of a table's
// CREATE statement.
"pg_get_partkeydef": makeBuiltin(defProps(),
tree.Overload{
Types: tree.ParamTypes{{Name: "oid", Typ: types.Oid}},
ReturnType: tree.FixedReturnType(types.String),
Fn: func(_ context.Context, _ *eval.Context, args tree.Datums) (tree.Datum, error) {
return tree.DNull, nil
},
Info: notUsableInfo,
Volatility: volatility.Stable,
},
),
"pg_get_functiondef": makeBuiltin(
tree.FunctionProperties{Category: builtinconstants.CategorySystemInfo},
tree.Overload{
Types: tree.ParamTypes{{Name: "func_oid", Typ: types.Oid}},
ReturnType: tree.FixedReturnType(types.String),
IsUDF: true,
Body: fmt.Sprintf(
`SELECT COALESCE(create_statement, prosrc)
FROM pg_catalog.pg_proc
LEFT JOIN crdb_internal.create_function_statements
ON schema_id=pronamespace
AND function_id=oid::int-%d
WHERE oid=$1
LIMIT 1`, oidext.CockroachPredefinedOIDMax),
Info: "For user-defined functions, returns the definition of the specified function. " +
"For builtin functions, returns the name of the function.",
Volatility: volatility.Stable,
},
),
"pg_get_function_arguments": makeBuiltin(
tree.FunctionProperties{Category: builtinconstants.CategorySystemInfo},
tree.Overload{
Types: tree.ParamTypes{{Name: "func_oid", Typ: types.Oid}},
ReturnType: tree.FixedReturnType(types.String),
IsUDF: true,
Body: getFunctionArgStringQuery,
Info: "Returns the argument list (with defaults) necessary to identify a function, " +
"in the form it would need to appear in within CREATE FUNCTION.",
Volatility: volatility.Stable,
},
),
// pg_get_function_result returns the types of the result of a builtin
// function. Multi-return builtins currently are returned as anyelement, which
// is a known incompatibility with Postgres.
// https://www.postgresql.org/docs/11/functions-info.html
"pg_get_function_result": makeBuiltin(
tree.FunctionProperties{Category: builtinconstants.CategorySystemInfo},
tree.Overload{
Types: tree.ParamTypes{{Name: "func_oid", Typ: types.Oid}},
ReturnType: tree.FixedReturnType(types.String),
IsUDF: true,
Body: `SELECT t.typname
FROM pg_catalog.pg_proc p
JOIN pg_catalog.pg_type t
ON prorettype=t.oid
WHERE p.oid=$1 LIMIT 1`,
Info: "Returns the types of the result of the specified function.",
Volatility: volatility.Stable,
},
),
// pg_get_function_identity_arguments returns the argument list necessary to
// identify a function, in the form it would need to appear in within ALTER
// FUNCTION, for instance. This form omits default values.
// https://www.postgresql.org/docs/11/functions-info.html
"pg_get_function_identity_arguments": makeBuiltin(
tree.FunctionProperties{Category: builtinconstants.CategorySystemInfo},
tree.Overload{
Types: tree.ParamTypes{{Name: "func_oid", Typ: types.Oid}},
ReturnType: tree.FixedReturnType(types.String),
IsUDF: true,
Body: getFunctionArgStringQuery,
Info: "Returns the argument list (without defaults) necessary to identify a function, " +
"in the form it would need to appear in within ALTER FUNCTION, for instance.",
Volatility: volatility.Stable,
},
),
// pg_get_indexdef functions like SHOW CREATE INDEX would if we supported that
// statement.
"pg_get_indexdef": makeBuiltin(
tree.FunctionProperties{Category: builtinconstants.CategorySystemInfo, DistsqlBlocklist: true},
makePGGetIndexDef(tree.ParamTypes{{Name: "index_oid", Typ: types.Oid}}),
makePGGetIndexDef(tree.ParamTypes{{Name: "index_oid", Typ: types.Oid}, {Name: "column_no", Typ: types.Int}, {Name: "pretty_bool", Typ: types.Bool}}),
),
// pg_get_viewdef functions like SHOW CREATE VIEW but returns the same format as
// PostgreSQL leaving out the actual 'CREATE VIEW table_name AS' portion of the statement.
"pg_get_viewdef": makeBuiltin(
tree.FunctionProperties{Category: builtinconstants.CategorySystemInfo, DistsqlBlocklist: true},
makePGGetViewDef(tree.ParamTypes{{Name: "view_oid", Typ: types.Oid}}),
makePGGetViewDef(tree.ParamTypes{{Name: "view_oid", Typ: types.Oid}, {Name: "pretty_bool", Typ: types.Bool}}),
),
"pg_get_serial_sequence": makeBuiltin(
tree.FunctionProperties{
Category: builtinconstants.CategorySequences,
},
tree.Overload{
Types: tree.ParamTypes{{Name: "table_name", Typ: types.String}, {Name: "column_name", Typ: types.String}},
ReturnType: tree.FixedReturnType(types.String),
Fn: func(ctx context.Context, evalCtx *eval.Context, args tree.Datums) (tree.Datum, error) {
tableName := tree.MustBeDString(args[0])
columnName := tree.MustBeDString(args[1])
qualifiedName, err := parser.ParseQualifiedTableName(string(tableName))
if err != nil {
return nil, err
}
res, err := evalCtx.Sequence.GetSerialSequenceNameFromColumn(ctx, qualifiedName, tree.Name(columnName))
if err != nil {
return nil, err
}
if res == nil {
return tree.DNull, nil
}
res.ExplicitCatalog = false
return tree.NewDString(fmt.Sprintf(`%s.%s`, res.Schema(), res.Object())), nil
},
Info: "Returns the name of the sequence used by the given column_name in the table table_name.",
Volatility: volatility.Stable,
},
),
// pg_my_temp_schema returns the OID of session's temporary schema, or 0 if
// none.
// https://www.postgresql.org/docs/11/functions-info.html
"pg_my_temp_schema": makeBuiltin(
tree.FunctionProperties{Category: builtinconstants.CategorySystemInfo},
tree.Overload{
Types: tree.ParamTypes{},
ReturnType: tree.FixedReturnType(types.Oid),
Fn: func(ctx context.Context, evalCtx *eval.Context, _ tree.Datums) (tree.Datum, error) {
schema := evalCtx.SessionData().SearchPath.GetTemporarySchemaName()
if schema == "" {
// The session has not yet created a temporary schema.
return tree.NewDOid(0), nil
}
oid, errSafeToIgnore, err := evalCtx.Planner.ResolveOIDFromString(
ctx, types.RegNamespace, tree.NewDString(schema))
if err != nil {
// If the OID lookup returns an UndefinedObject error, return 0
// instead. We can hit this path if the session created a temporary
// schema in one database and then changed databases.
if errSafeToIgnore && pgerror.GetPGCode(err) == pgcode.UndefinedObject {
return tree.NewDOid(0), nil
}
return nil, err
}
return oid, nil
},
Info: "Returns the OID of the current session's temporary schema, " +
"or zero if it has none (because it has not created any temporary tables).",
Volatility: volatility.Stable,
},
),
// pg_is_other_temp_schema returns true if the given OID is the OID of another
// session's temporary schema.
// https://www.postgresql.org/docs/11/functions-info.html
"pg_is_other_temp_schema": makeBuiltin(
tree.FunctionProperties{Category: builtinconstants.CategorySystemInfo},
tree.Overload{
Types: tree.ParamTypes{{Name: "oid", Typ: types.Oid}},
ReturnType: tree.FixedReturnType(types.Bool),
Fn: func(ctx context.Context, evalCtx *eval.Context, args tree.Datums) (tree.Datum, error) {
schemaArg := eval.UnwrapDatum(ctx, evalCtx, args[0])
schema, err := getNameForArg(ctx, evalCtx, schemaArg, "pg_namespace", "nspname")
if err != nil {
return nil, err
}
if schema == "" {
// OID does not exist.
return tree.DBoolFalse, nil
}
if !strings.HasPrefix(schema, catconstants.PgTempSchemaName) {
// OID is not a reference to a temporary schema.
//
// This string matching is what Postgres does too. See isAnyTempNamespace.
return tree.DBoolFalse, nil
}
if schema == evalCtx.SessionData().SearchPath.GetTemporarySchemaName() {
// OID is a reference to this session's temporary schema.
return tree.DBoolFalse, nil
}
return tree.DBoolTrue, nil
},
Info: "Returns true if the given OID is the OID of another session's temporary schema. (This can be useful, for example, to exclude other sessions' temporary tables from a catalog display.)",
Volatility: volatility.Stable,
},
),
// TODO(bram): Make sure the reported type is correct for tuples. See #25523.
"pg_typeof": makeBuiltin(defProps(),
tree.Overload{
Types: tree.ParamTypes{{Name: "val", Typ: types.Any}},
ReturnType: tree.FixedReturnType(types.String),
Fn: func(_ context.Context, _ *eval.Context, args tree.Datums) (tree.Datum, error) {
return tree.NewDString(args[0].ResolvedType().SQLStandardName()), nil
},
Info: notUsableInfo,
Volatility: volatility.Stable,
CalledOnNullInput: true,
},
),
// https://www.postgresql.org/docs/10/functions-info.html#FUNCTIONS-INFO-CATALOG-TABLE
"pg_collation_for": makeBuiltin(
tree.FunctionProperties{Category: builtinconstants.CategoryString},
tree.Overload{
Types: tree.ParamTypes{{Name: "str", Typ: types.Any}},
ReturnType: tree.FixedReturnType(types.String),
Fn: func(_ context.Context, _ *eval.Context, args tree.Datums) (tree.Datum, error) {
var collation string
switch t := args[0].(type) {
case *tree.DString:
collation = "default"
case *tree.DCollatedString:
collation = t.Locale
default:
return tree.DNull, pgerror.Newf(pgcode.DatatypeMismatch,
"collations are not supported by type: %s", t.ResolvedType())
}
return tree.NewDString(fmt.Sprintf(`"%s"`, collation)), nil
},
Info: "Returns the collation of the argument",
Volatility: volatility.Stable,
},
),
"pg_get_userbyid": makeBuiltin(tree.FunctionProperties{DistsqlBlocklist: true},
tree.Overload{
Types: tree.ParamTypes{
{Name: "role_oid", Typ: types.Oid},
},
ReturnType: tree.FixedReturnType(types.String),
IsUDF: true,
Body: `SELECT COALESCE((SELECT rolname FROM pg_catalog.pg_roles WHERE oid=$1 LIMIT 1), 'unknown (OID=' || $1 || ')')`,
Info: notUsableInfo,
Volatility: volatility.Stable,
},
),
"pg_sequence_parameters": makeBuiltin(tree.FunctionProperties{DistsqlBlocklist: true},
// pg_sequence_parameters is an undocumented Postgres builtin that returns
// information about a sequence given its OID. It's nevertheless used by
// at least one UI tool, so we provide an implementation for compatibility.
// The real implementation returns a record; we fake it by returning a
// comma-delimited string enclosed by parentheses.
// TODO(jordan): convert this to return a record type once we support that.
tree.Overload{
Types: tree.ParamTypes{{Name: "sequence_oid", Typ: types.Oid}},
ReturnType: tree.FixedReturnType(types.MakeLabeledTuple(
[]*types.T{types.Int, types.Int, types.Int, types.Int, types.Bool, types.Int, types.Oid},
[]string{"start_value", "minimum_value", "maxmimum_value", "increment", "cycle_option", "cache_size", "data_type"},
)),
IsUDF: true,
Body: `SELECT COALESCE ((SELECT (seqstart, seqmin, seqmax, seqincrement, seqcycle, seqcache, seqtypid)
FROM pg_catalog.pg_sequence WHERE seqrelid=$1 LIMIT 1),
CASE WHEN crdb_internal.force_error('42P01', 'relation with OID ' || $1 || ' does not exist') > 0 THEN NULL ELSE NULL END)`,
Info: notUsableInfo,
Volatility: volatility.Stable,
},
),
"format_type": makeBuiltin(tree.FunctionProperties{DistsqlBlocklist: true},
tree.Overload{
Types: tree.ParamTypes{{Name: "type_oid", Typ: types.Oid}, {Name: "typemod", Typ: types.Int}},
ReturnType: tree.FixedReturnType(types.String),
Fn: func(ctx context.Context, evalCtx *eval.Context, args tree.Datums) (tree.Datum, error) {
// See format_type.c in Postgres.
oidArg := args[0]
if oidArg == tree.DNull {
return tree.DNull, nil
}
maybeTypmod := args[1]
oid := oidArg.(*tree.DOid).Oid
typ, ok := types.OidToType[oid]
if !ok {
// If the type wasn't statically known, try looking it up as a user
// defined type.
var err error
typ, err = evalCtx.Planner.ResolveTypeByOID(ctx, oid)
if err != nil {
// If the error is a descriptor does not exist error, then swallow it.
unknown := tree.NewDString(fmt.Sprintf("unknown (OID=%s)", oidArg))
switch {
case errors.Is(err, catalog.ErrDescriptorNotFound):
return unknown, nil
case pgerror.GetPGCode(err) == pgcode.UndefinedObject:
return unknown, nil
default:
return nil, err
}
}
}
var hasTypmod bool
var typmod int
if maybeTypmod != tree.DNull {
hasTypmod = true
typmod = int(tree.MustBeDInt(maybeTypmod))
}
return tree.NewDString(typ.SQLStandardNameWithTypmod(hasTypmod, typmod)), nil
},
Info: "Returns the SQL name of a data type that is " +
"identified by its type OID and possibly a type modifier. " +
"Currently, the type modifier is ignored.",
Volatility: volatility.Stable,
CalledOnNullInput: true,
},
),
"col_description": makeBuiltin(defProps(),
tree.Overload{
Types: tree.ParamTypes{{Name: "table_oid", Typ: types.Oid}, {Name: "column_number", Typ: types.Int}},
ReturnType: tree.FixedReturnType(types.String),
Fn: func(ctx context.Context, evalCtx *eval.Context, args tree.Datums) (tree.Datum, error) {
if args[0] == tree.DNull || args[1] == tree.DNull {
return tree.DNull, nil
}
if colID := *args[1].(*tree.DInt); colID == 0 {
// column ID 0 never exists, and we don't want the query
// below to pick up the table comment by accident.
return tree.DNull, nil
}
if tabOID := *args[0].(*tree.DOid); tabOID.Oid >= catconstants.MinVirtualID {
// Virtual table columns do not have descriptions.
return tree.DNull, nil
}
// Note: the following is equivalent to:
//
// SELECT description FROM pg_catalog.pg_description
// WHERE objoid=$1 AND objsubid=$2 LIMIT 1
//
// TODO(jordanlewis): Really we'd like to query this directly
// on pg_description and let predicate push-down do its job.
r, err := evalCtx.Planner.QueryRowEx(
ctx, "pg_get_coldesc",
sessiondata.NoSessionDataOverride,
`
SELECT comment FROM system.comments c
WHERE c.type=$1::int AND c.object_id=$2::int AND c.sub_id=$3::int LIMIT 1
`, catalogkeys.ColumnCommentType, args[0], args[1])
if err != nil {
return nil, err
}
if len(r) == 0 {
return tree.DNull, nil
}
return r[0], nil
},
Info: notUsableInfo,
Volatility: volatility.Stable,
},
),
"obj_description": makeBuiltin(defProps(),
tree.Overload{
Types: tree.ParamTypes{{Name: "object_oid", Typ: types.Oid}},
ReturnType: tree.FixedReturnType(types.String),
IsUDF: true,
Body: `SELECT description