-
Notifications
You must be signed in to change notification settings - Fork 3.8k
/
pg_builtins.go
2500 lines (2364 loc) · 86.7 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 (
"fmt"
"strings"
"time"
"github.com/cockroachdb/cockroach/pkg/keys"
"github.com/cockroachdb/cockroach/pkg/security"
"github.com/cockroachdb/cockroach/pkg/sql/catalog"
"github.com/cockroachdb/cockroach/pkg/sql/catalog/catconstants"
"github.com/cockroachdb/cockroach/pkg/sql/catalog/descpb"
"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/tree"
"github.com/cockroachdb/cockroach/pkg/sql/sessiondata"
"github.com/cockroachdb/cockroach/pkg/sql/sqlerrors"
"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 builtinDefinition{
props: defProps(),
overloads: []tree.Overload{
{
Types: tree.ArgTypes{},
ReturnType: tree.FixedReturnType(types.Bool),
Fn: func(*tree.EvalContext, tree.Datums) (tree.Datum, error) {
return tree.DBoolFalse, nil
},
Info: notUsableInfo,
Volatility: tree.VolatilityVolatile,
},
},
}
}
// 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.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(): {},
}
// UpdatableCommand matches update operations in postgres.
type UpdatableCommand tree.DInt
// The following constants are the values for UpdatableCommand enumeration.
const (
UpdateCommand UpdatableCommand = 2 + iota
InsertCommand
DeleteCommand
)
var (
nonUpdatableEvents = tree.NewDInt(0)
allUpdatableEvents = tree.NewDInt((1 << UpdateCommand) | (1 << InsertCommand) | (1 << DeleteCommand))
)
// 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 initPGBuiltins() {
for k, v := range pgBuiltins {
if _, exists := builtins[k]; exists {
panic("duplicate builtin: " + k)
}
v.props.Category = categoryCompatibility
builtins[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) {
builtins[name] = builtin
}
}
// Make array type i/o builtins.
for name, builtin := range makeTypeIOBuiltins("array_", types.AnyArray) {
builtins[name] = builtin
}
for name, builtin := range makeTypeIOBuiltins("anyarray_", types.AnyArray) {
builtins[name] = builtin
}
// Make enum type i/o builtins.
for name, builtin := range makeTypeIOBuiltins("enum_", types.AnyEnum) {
builtins[name] = builtin
}
// Make crdb_internal.create_regfoo builtins.
for _, typ := range []*types.T{
types.RegClass,
types.RegNamespace,
types.RegProc,
types.RegProcedure,
types.RegRole,
types.RegType,
} {
typName := typ.SQLStandardName()
builtins["crdb_internal.create_"+typName] = makeCreateRegDef(typ)
}
}
var errUnimplemented = pgerror.New(pgcode.FeatureNotSupported, "unimplemented")
func makeTypeIOBuiltin(argTypes tree.TypeList, returnType *types.T) builtinDefinition {
return builtinDefinition{
props: tree.FunctionProperties{
Category: categoryCompatibility,
},
overloads: []tree.Overload{
{
Types: argTypes,
ReturnType: tree.FixedReturnType(returnType),
Fn: func(_ *tree.EvalContext, _ tree.Datums) (tree.Datum, error) {
return nil, errUnimplemented
},
Info: notUsableInfo,
Volatility: tree.VolatilityVolatile,
// 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.ArgTypes{{typname, 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.ArgTypes{{"input", types.Any}}, typ),
// Note: PG returns 'cstring' for these builtins, but we don't support that.
builtinPrefix + "out": makeTypeIOBuiltin(tree.ArgTypes{{typname, typ}}, types.Bytes),
// Note: PG takes 'cstring' for these builtins, but we don't support that.
builtinPrefix + "in": makeTypeIOBuiltin(tree.ArgTypes{{"input", 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(argTypes tree.ArgTypes) tree.Overload {
return tree.Overload{
Types: argTypes,
ReturnType: tree.FixedReturnType(types.String),
Fn: func(ctx *tree.EvalContext, args tree.Datums) (tree.Datum, error) {
colNumber := *tree.NewDInt(0)
if len(args) == 3 {
colNumber = *args[1].(*tree.DInt)
}
r, err := ctx.Planner.QueryRowEx(
ctx.Ctx(), "pg_get_indexdef",
ctx.Txn,
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 = ctx.Planner.QueryRowEx(
ctx.Ctx(), "pg_get_indexdef",
ctx.Txn,
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: tree.VolatilityStable,
}
}
// Make a pg_get_viewdef function with the given arguments.
func makePGGetViewDef(argTypes tree.ArgTypes) tree.Overload {
return tree.Overload{
Types: argTypes,
ReturnType: tree.FixedReturnType(types.String),
Fn: func(ctx *tree.EvalContext, args tree.Datums) (tree.Datum, error) {
r, err := ctx.Planner.QueryRowEx(
ctx.Ctx(), "pg_get_viewdef",
ctx.Txn,
sessiondata.NoSessionDataOverride,
"SELECT definition FROM pg_catalog.pg_views v JOIN pg_catalog.pg_class c ON "+
"c.relname=v.viewname WHERE oid=$1", args[0])
if err != nil {
return nil, err
}
if len(r) == 0 {
return tree.DNull, nil
}
return r[0], nil
},
Info: notUsableInfo,
Volatility: tree.VolatilityStable,
}
}
// Make a pg_get_constraintdef function with the given arguments.
func makePGGetConstraintDef(argTypes tree.ArgTypes) tree.Overload {
return tree.Overload{
Types: argTypes,
ReturnType: tree.FixedReturnType(types.String),
Fn: func(ctx *tree.EvalContext, args tree.Datums) (tree.Datum, error) {
r, err := ctx.Planner.QueryRowEx(
ctx.Ctx(), "pg_get_constraintdef",
ctx.Txn,
sessiondata.NoSessionDataOverride,
"SELECT condef FROM pg_catalog.pg_constraint WHERE oid=$1", args[0])
if err != nil {
return nil, err
}
if len(r) == 0 {
return nil, pgerror.Newf(pgcode.InvalidParameterValue, "unknown constraint (OID=%s)", args[0])
}
return r[0], nil
},
Info: notUsableInfo,
Volatility: tree.VolatilityStable,
}
}
// argTypeOpts is similar to tree.ArgTypes, but represents arguments that can
// accept multiple types.
type argTypeOpts []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 argTypeOpts,
fn func(ctx *tree.EvalContext, args tree.Datums, user security.SQLUsername) (tree.Datum, 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.
argTypes := []tree.ArgTypes{
{}, // no user
}
for _, typ := range strOrOidTypes {
argTypes = append(argTypes, tree.ArgTypes{{"user", typ}})
}
// 2. variants have one or more object identification arguments, which each
// accept multiple types.
for _, objSpecArg := range objSpecArgs {
prevArgTypes := argTypes
argTypes = make([]tree.ArgTypes, 0, len(argTypes)*len(objSpecArg.Typ))
for _, argType := range prevArgTypes {
for _, typ := range objSpecArg.Typ {
argTypeVariant := append(argType, tree.ArgTypes{{objSpecArg.Name, typ}}...)
argTypes = append(argTypes, argTypeVariant)
}
}
}
// 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, argType := range argTypes {
argTypes[i] = append(argType, tree.ArgTypes{{"privilege", types.String}}...)
}
var variants []tree.Overload
for _, argType := range argTypes {
withUser := argType[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: argType,
ReturnType: tree.FixedReturnType(types.Bool),
Fn: func(ctx *tree.EvalContext, args tree.Datums) (tree.Datum, error) {
var user security.SQLUsername
if withUser {
arg := tree.UnwrapDatum(ctx, args[0])
userS, err := getNameForArg(ctx, 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 = security.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 ctx.SessionData().User().Undefined() {
// Wut... is this possible?
return tree.DNull, nil
}
user = ctx.SessionData().User()
}
return fn(ctx, args, user)
},
Info: fmt.Sprintf(infoFmt, infoDetail),
Volatility: tree.VolatilityStable,
})
}
return builtinDefinition{
props: tree.FunctionProperties{
DistsqlBlocklist: true,
},
overloads: 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 *tree.EvalContext, 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 := ctx.Planner.QueryRowEx(ctx.Ctx(), "get-name-for-arg",
ctx.Txn, 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
// 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) {
argStr := string(tree.MustBeDString(arg))
privStrs := strings.Split(argStr, ",")
res := make([]privilege.Privilege, 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)
// 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
}
// runPrivilegeChecks runs the provided function for each privilege in the list.
// If any of the checks return True or NULL, the function short-circuits with
// that result. Otherwise, it returns False.
func runPrivilegeChecks(
privs []privilege.Privilege, check func(privilege.Privilege) (tree.Datum, error),
) (tree.Datum, error) {
for _, p := range privs {
d, err := check(p)
if err != nil {
return nil, err
}
switch d {
case tree.DBoolFalse:
case tree.DBoolTrue, tree.DNull:
return d, nil
default:
return nil, errors.AssertionFailedf("unexpected privilege check result %v", d)
}
}
return tree.DBoolFalse, nil
}
func makeCreateRegDef(typ *types.T) builtinDefinition {
return makeBuiltin(defProps(),
tree.Overload{
Types: tree.ArgTypes{
{"oid", types.Int},
{"name", types.String},
},
ReturnType: tree.FixedReturnType(typ),
Fn: func(_ *tree.EvalContext, d tree.Datums) (tree.Datum, error) {
return tree.NewDOidWithName(tree.MustBeDInt(d[0]), typ, string(tree.MustBeDString(d[1]))), nil
},
Info: notUsableInfo,
Volatility: tree.VolatilityImmutable,
},
)
}
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.ArgTypes{},
ReturnType: tree.FixedReturnType(types.Int),
Fn: func(_ *tree.EvalContext, _ tree.Datums) (tree.Datum, error) {
return tree.NewDInt(-1), nil
},
Info: notUsableInfo,
Volatility: tree.VolatilityStable,
},
),
// See https://www.postgresql.org/docs/9.3/static/catalog-pg-database.html.
"pg_encoding_to_char": makeBuiltin(defProps(),
tree.Overload{
Types: tree.ArgTypes{
{"encoding_id", types.Int},
},
ReturnType: tree.FixedReturnType(types.String),
Fn: func(ctx *tree.EvalContext, args tree.Datums) (tree.Datum, error) {
if args[0].Compare(ctx, DatEncodingUTFId) == 0 {
return datEncodingUTF8ShortName, nil
}
return tree.DNull, nil
},
Info: notUsableInfo,
Volatility: tree.VolatilityStable,
},
),
// Here getdatabaseencoding just returns UTF8 because,
// CockroachDB supports just UTF8 for now.
"getdatabaseencoding": makeBuiltin(
tree.FunctionProperties{Category: categorySystemInfo},
tree.Overload{
Types: tree.ArgTypes{},
ReturnType: tree.FixedReturnType(types.String),
Fn: func(ctx *tree.EvalContext, 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: tree.VolatilityStable,
},
),
// 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.ArgTypes{
{"pg_node_tree", types.String},
{"relation_oid", types.Oid},
},
ReturnType: tree.FixedReturnType(types.String),
Fn: func(_ *tree.EvalContext, args tree.Datums) (tree.Datum, error) {
return args[0], nil
},
Info: notUsableInfo,
Volatility: tree.VolatilityStable,
},
tree.Overload{
Types: tree.ArgTypes{
{"pg_node_tree", types.String},
{"relation_oid", types.Oid},
{"pretty_bool", types.Bool},
},
ReturnType: tree.FixedReturnType(types.String),
Fn: func(_ *tree.EvalContext, args tree.Datums) (tree.Datum, error) {
return args[0], nil
},
Info: notUsableInfo,
Volatility: tree.VolatilityStable,
},
),
// pg_get_constraintdef functions like SHOW CREATE CONSTRAINT would if we
// supported that statement.
"pg_get_constraintdef": makeBuiltin(tree.FunctionProperties{DistsqlBlocklist: true},
makePGGetConstraintDef(tree.ArgTypes{
{"constraint_oid", types.Oid}, {"pretty_bool", types.Bool}}),
makePGGetConstraintDef(tree.ArgTypes{{"constraint_oid", 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.ArgTypes{{"oid", types.Oid}},
ReturnType: tree.FixedReturnType(types.String),
Fn: func(ctx *tree.EvalContext, args tree.Datums) (tree.Datum, error) {
return tree.DNull, nil
},
Info: notUsableInfo,
Volatility: tree.VolatilityStable,
},
),
// pg_get_function_result returns the types of the result of an 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(defProps(),
tree.Overload{
Types: tree.ArgTypes{{"func_oid", types.Oid}},
ReturnType: tree.FixedReturnType(types.String),
Fn: func(ctx *tree.EvalContext, args tree.Datums) (tree.Datum, error) {
funcOid := tree.MustBeDOid(args[0])
t, err := ctx.Planner.QueryRowEx(
ctx.Ctx(), "pg_get_function_result",
ctx.Txn,
sessiondata.NoSessionDataOverride,
`SELECT prorettype::REGTYPE::TEXT FROM pg_proc WHERE oid=$1`, int(funcOid.DInt))
if err != nil {
return nil, err
}
if len(t) == 0 {
return tree.NewDString(""), nil
}
return t[0], nil
},
Info: notUsableInfo,
Volatility: tree.VolatilityStable,
},
),
// 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(defProps(),
tree.Overload{
Types: tree.ArgTypes{{"func_oid", types.Oid}},
ReturnType: tree.FixedReturnType(types.String),
Fn: func(ctx *tree.EvalContext, args tree.Datums) (tree.Datum, error) {
funcOid := tree.MustBeDOid(args[0])
t, err := ctx.Planner.QueryRowEx(
ctx.Ctx(), "pg_get_function_identity_arguments",
ctx.Txn,
sessiondata.NoSessionDataOverride,
`SELECT array_agg(unnest(proargtypes)::REGTYPE::TEXT) FROM pg_proc WHERE oid=$1`, int(funcOid.DInt))
if err != nil {
return nil, err
}
if len(t) == 0 || t[0] == tree.DNull {
return tree.NewDString(""), nil
}
arr := tree.MustBeDArray(t[0])
var sb strings.Builder
for i, elem := range arr.Array {
if i > 0 {
sb.WriteString(", ")
}
if elem == tree.DNull {
// This shouldn't ever happen, but let's be safe about it.
sb.WriteString("NULL")
continue
}
str, ok := tree.AsDString(elem)
if !ok {
// This also shouldn't happen.
sb.WriteString(elem.String())
continue
}
sb.WriteString(string(str))
}
return tree.NewDString(sb.String()), nil
},
Info: notUsableInfo,
Volatility: tree.VolatilityStable,
},
),
// pg_get_indexdef functions like SHOW CREATE INDEX would if we supported that
// statement.
"pg_get_indexdef": makeBuiltin(tree.FunctionProperties{DistsqlBlocklist: true},
makePGGetIndexDef(tree.ArgTypes{{"index_oid", types.Oid}}),
makePGGetIndexDef(tree.ArgTypes{{"index_oid", types.Oid}, {"column_no", types.Int}, {"pretty_bool", 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{DistsqlBlocklist: true},
makePGGetViewDef(tree.ArgTypes{{"view_oid", types.Oid}}),
makePGGetViewDef(tree.ArgTypes{{"view_oid", types.Oid}, {"pretty_bool", types.Bool}}),
),
"pg_get_serial_sequence": makeBuiltin(
tree.FunctionProperties{
Category: categorySequences,
},
tree.Overload{
Types: tree.ArgTypes{{"table_name", types.String}, {"column_name", types.String}},
ReturnType: tree.FixedReturnType(types.String),
Fn: func(ctx *tree.EvalContext, 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 := ctx.Sequence.GetSerialSequenceNameFromColumn(ctx.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: tree.VolatilityStable,
},
),
// 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(defProps(),
tree.Overload{
Types: tree.ArgTypes{},
ReturnType: tree.FixedReturnType(types.Oid),
Fn: func(ctx *tree.EvalContext, _ tree.Datums) (tree.Datum, error) {
schema := ctx.SessionData().SearchPath.GetTemporarySchemaName()
if schema == "" {
// The session has not yet created a temporary schema.
return tree.NewDOid(0), nil
}
oid, err := ctx.Planner.ResolveOIDFromString(
ctx.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 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: tree.VolatilityStable,
},
),
// 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(defProps(),
tree.Overload{
Types: tree.ArgTypes{{"oid", types.Oid}},
ReturnType: tree.FixedReturnType(types.Bool),
Fn: func(ctx *tree.EvalContext, args tree.Datums) (tree.Datum, error) {
schemaArg := tree.UnwrapDatum(ctx, args[0])
schema, err := getNameForArg(ctx, 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 == ctx.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: tree.VolatilityStable,
},
),
// TODO(bram): Make sure the reported type is correct for tuples. See #25523.
"pg_typeof": makeBuiltin(tree.FunctionProperties{NullableArgs: true},
tree.Overload{
Types: tree.ArgTypes{{"val", types.Any}},
ReturnType: tree.FixedReturnType(types.String),
Fn: func(_ *tree.EvalContext, args tree.Datums) (tree.Datum, error) {
return tree.NewDString(args[0].ResolvedType().SQLStandardName()), nil
},
Info: notUsableInfo,
Volatility: tree.VolatilityStable,
},
),
// https://www.postgresql.org/docs/10/functions-info.html#FUNCTIONS-INFO-CATALOG-TABLE
"pg_collation_for": makeBuiltin(
tree.FunctionProperties{Category: categoryString},
tree.Overload{
Types: tree.ArgTypes{{"str", types.Any}},
ReturnType: tree.FixedReturnType(types.String),
Fn: func(ctx *tree.EvalContext, 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: tree.VolatilityStable,
},
),
"pg_get_userbyid": makeBuiltin(tree.FunctionProperties{DistsqlBlocklist: true},
tree.Overload{
Types: tree.ArgTypes{
{"role_oid", types.Oid},
},
ReturnType: tree.FixedReturnType(types.String),
Fn: func(ctx *tree.EvalContext, args tree.Datums) (tree.Datum, error) {
oid := args[0]
t, err := ctx.Planner.QueryRowEx(
ctx.Ctx(), "pg_get_userbyid",
ctx.Txn,
sessiondata.NoSessionDataOverride,
"SELECT rolname FROM pg_catalog.pg_roles WHERE oid=$1", oid)
if err != nil {
return nil, err
}
if len(t) == 0 {
return tree.NewDString(fmt.Sprintf("unknown (OID=%s)", args[0])), nil
}
return t[0], nil
},
Info: notUsableInfo,
Volatility: tree.VolatilityStable,
},
),
"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.ArgTypes{{"sequence_oid", types.Oid}},
ReturnType: tree.FixedReturnType(types.String),
Fn: func(ctx *tree.EvalContext, args tree.Datums) (tree.Datum, error) {
r, err := ctx.Planner.QueryRowEx(
ctx.Ctx(), "pg_sequence_parameters",
ctx.Txn,
sessiondata.NoSessionDataOverride,
`SELECT seqstart, seqmin, seqmax, seqincrement, seqcycle, seqcache, seqtypid `+
`FROM pg_catalog.pg_sequence WHERE seqrelid=$1`, args[0])
if err != nil {
return nil, err
}
if len(r) == 0 {
return nil, pgerror.Newf(pgcode.UndefinedTable, "unknown sequence (OID=%s)", args[0])
}
seqstart, seqmin, seqmax, seqincrement, seqcycle, seqcache, seqtypid := r[0], r[1], r[2], r[3], r[4], r[5], r[6]
seqcycleStr := "t"
if seqcycle.(*tree.DBool) == tree.DBoolFalse {
seqcycleStr = "f"
}
return tree.NewDString(fmt.Sprintf("(%s,%s,%s,%s,%s,%s,%s)", seqstart, seqmin, seqmax, seqincrement, seqcycleStr, seqcache, seqtypid)), nil
},
Info: notUsableInfo,
Volatility: tree.VolatilityStable,
},
),
"format_type": makeBuiltin(tree.FunctionProperties{NullableArgs: true, DistsqlBlocklist: true},
tree.Overload{
Types: tree.ArgTypes{{"type_oid", types.Oid}, {"typemod", types.Int}},
ReturnType: tree.FixedReturnType(types.String),
Fn: func(ctx *tree.EvalContext, 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 := oid.Oid(oidArg.(*tree.DOid).DInt)
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 = ctx.Planner.ResolveTypeByOID(ctx.Context, 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: tree.VolatilityStable,
},
),
"col_description": makeBuiltin(defProps(),
tree.Overload{
Types: tree.ArgTypes{{"table_oid", types.Oid}, {"column_number", types.Int}},
ReturnType: tree.FixedReturnType(types.String),
Fn: func(ctx *tree.EvalContext, args tree.Datums) (tree.Datum, error) {
if *args[1].(*tree.DInt) == 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
}
// 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 := ctx.Planner.QueryRowEx(
ctx.Ctx(), "pg_get_coldesc",
ctx.Txn,
sessiondata.NoSessionDataOverride,
`
SELECT COALESCE(c.comment, pc.comment) FROM system.comments c
FULL OUTER JOIN crdb_internal.predefined_comments pc
ON pc.object_id=c.object_id AND pc.sub_id=c.sub_id AND pc.type = c.type
WHERE c.type=$1::int AND c.object_id=$2::int AND c.sub_id=$3::int LIMIT 1
`, keys.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: tree.VolatilityStable,
},
),
"obj_description": makeBuiltin(defProps(),
tree.Overload{
Types: tree.ArgTypes{{"object_oid", types.Oid}},