forked from cockroachdb/cockroach
-
Notifications
You must be signed in to change notification settings - Fork 0
/
pg_catalog.go
2660 lines (2528 loc) · 84.6 KB
/
pg_catalog.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.
//
// 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.
package sql
import (
"bytes"
"context"
"encoding/binary"
"fmt"
"hash"
"hash/fnv"
"strings"
"unicode"
"github.com/cockroachdb/cockroach/pkg/keys"
"github.com/cockroachdb/cockroach/pkg/security"
"github.com/cockroachdb/cockroach/pkg/sql/pgwire/pgerror"
"github.com/cockroachdb/cockroach/pkg/sql/sem/builtins"
"github.com/cockroachdb/cockroach/pkg/sql/sem/tree"
"github.com/cockroachdb/cockroach/pkg/sql/sqlbase"
"github.com/cockroachdb/cockroach/pkg/sql/types"
"github.com/lib/pq/oid"
"github.com/pkg/errors"
"golang.org/x/text/collate"
)
var (
oidZero = tree.NewDOid(0)
zeroVal = tree.DZero
negOneVal = tree.NewDInt(-1)
passwdStarString = tree.NewDString("********")
)
const (
cockroachIndexEncoding = "prefix"
defaultCollationTag = "en-US"
)
// pgCatalog contains a set of system tables mirroring PostgreSQL's pg_catalog schema.
// This code attempts to comply as closely as possible to the system catalogs documented
// in https://www.postgresql.org/docs/9.6/static/catalogs.html.
var pgCatalog = virtualSchema{
name: pgCatalogName,
allTableNames: buildStringSet(
// Generated with:
// select distinct '"'||table_name||'",' from information_schema.tables
// where table_schema='pg_catalog' order by table_name;
"pg_aggregate",
"pg_am",
"pg_amop",
"pg_amproc",
"pg_attrdef",
"pg_attribute",
"pg_auth_members",
"pg_authid",
"pg_available_extension_versions",
"pg_available_extensions",
"pg_cast",
"pg_class",
"pg_collation",
"pg_config",
"pg_constraint",
"pg_conversion",
"pg_cursors",
"pg_database",
"pg_db_role_setting",
"pg_default_acl",
"pg_depend",
"pg_description",
"pg_enum",
"pg_event_trigger",
"pg_extension",
"pg_file_settings",
"pg_foreign_data_wrapper",
"pg_foreign_server",
"pg_foreign_table",
"pg_group",
"pg_hba_file_rules",
"pg_index",
"pg_indexes",
"pg_inherits",
"pg_init_privs",
"pg_language",
"pg_largeobject",
"pg_largeobject_metadata",
"pg_locks",
"pg_matviews",
"pg_namespace",
"pg_opclass",
"pg_operator",
"pg_opfamily",
"pg_partitioned_table",
"pg_pltemplate",
"pg_policies",
"pg_policy",
"pg_prepared_statements",
"pg_prepared_xacts",
"pg_proc",
"pg_publication",
"pg_publication_rel",
"pg_publication_tables",
"pg_range",
"pg_replication_origin",
"pg_replication_origin_status",
"pg_replication_slots",
"pg_rewrite",
"pg_roles",
"pg_rules",
"pg_seclabel",
"pg_seclabels",
"pg_sequence",
"pg_sequences",
"pg_settings",
"pg_shadow",
"pg_shdepend",
"pg_shdescription",
"pg_shseclabel",
"pg_stat_activity",
"pg_stat_all_indexes",
"pg_stat_all_tables",
"pg_stat_archiver",
"pg_stat_bgwriter",
"pg_stat_database",
"pg_stat_database_conflicts",
"pg_stat_progress_vacuum",
"pg_stat_replication",
"pg_stat_ssl",
"pg_stat_subscription",
"pg_stat_sys_indexes",
"pg_stat_sys_tables",
"pg_stat_user_functions",
"pg_stat_user_indexes",
"pg_stat_user_tables",
"pg_stat_wal_receiver",
"pg_stat_xact_all_tables",
"pg_stat_xact_sys_tables",
"pg_stat_xact_user_functions",
"pg_stat_xact_user_tables",
"pg_statio_all_indexes",
"pg_statio_all_sequences",
"pg_statio_all_tables",
"pg_statio_sys_indexes",
"pg_statio_sys_sequences",
"pg_statio_sys_tables",
"pg_statio_user_indexes",
"pg_statio_user_sequences",
"pg_statio_user_tables",
"pg_statistic",
"pg_statistic_ext",
"pg_stats",
"pg_subscription",
"pg_subscription_rel",
"pg_tables",
"pg_tablespace",
"pg_timezone_abbrevs",
"pg_timezone_names",
"pg_transform",
"pg_trigger",
"pg_ts_config",
"pg_ts_config_map",
"pg_ts_dict",
"pg_ts_parser",
"pg_ts_template",
"pg_type",
"pg_user",
"pg_user_mapping",
"pg_user_mappings",
"pg_views",
),
tableDefs: map[sqlbase.ID]virtualSchemaDef{
sqlbase.PgCatalogAmTableID: pgCatalogAmTable,
sqlbase.PgCatalogAttrDefTableID: pgCatalogAttrDefTable,
sqlbase.PgCatalogAttributeTableID: pgCatalogAttributeTable,
sqlbase.PgCatalogAuthMembersTableID: pgCatalogAuthMembersTable,
sqlbase.PgCatalogClassTableID: pgCatalogClassTable,
sqlbase.PgCatalogCollationTableID: pgCatalogCollationTable,
sqlbase.PgCatalogConstraintTableID: pgCatalogConstraintTable,
sqlbase.PgCatalogDatabaseTableID: pgCatalogDatabaseTable,
sqlbase.PgCatalogDependTableID: pgCatalogDependTable,
sqlbase.PgCatalogDescriptionTableID: pgCatalogDescriptionTable,
sqlbase.PgCatalogSharedDescriptionTableID: pgCatalogSharedDescriptionTable,
sqlbase.PgCatalogEnumTableID: pgCatalogEnumTable,
sqlbase.PgCatalogExtensionTableID: pgCatalogExtensionTable,
sqlbase.PgCatalogForeignDataWrapperTableID: pgCatalogForeignDataWrapperTable,
sqlbase.PgCatalogForeignServerTableID: pgCatalogForeignServerTable,
sqlbase.PgCatalogForeignTableTableID: pgCatalogForeignTableTable,
sqlbase.PgCatalogIndexTableID: pgCatalogIndexTable,
sqlbase.PgCatalogIndexesTableID: pgCatalogIndexesTable,
sqlbase.PgCatalogInheritsTableID: pgCatalogInheritsTable,
sqlbase.PgCatalogLanguageTableID: pgCatalogLanguageTable,
sqlbase.PgCatalogNamespaceTableID: pgCatalogNamespaceTable,
sqlbase.PgCatalogOperatorTableID: pgCatalogOperatorTable,
sqlbase.PgCatalogProcTableID: pgCatalogProcTable,
sqlbase.PgCatalogRangeTableID: pgCatalogRangeTable,
sqlbase.PgCatalogRewriteTableID: pgCatalogRewriteTable,
sqlbase.PgCatalogRolesTableID: pgCatalogRolesTable,
sqlbase.PgCatalogSequencesTableID: pgCatalogSequencesTable,
sqlbase.PgCatalogSettingsTableID: pgCatalogSettingsTable,
sqlbase.PgCatalogUserTableID: pgCatalogUserTable,
sqlbase.PgCatalogUserMappingTableID: pgCatalogUserMappingTable,
sqlbase.PgCatalogTablesTableID: pgCatalogTablesTable,
sqlbase.PgCatalogTablespaceTableID: pgCatalogTablespaceTable,
sqlbase.PgCatalogTriggerTableID: pgCatalogTriggerTable,
sqlbase.PgCatalogTypeTableID: pgCatalogTypeTable,
sqlbase.PgCatalogViewsTableID: pgCatalogViewsTable,
sqlbase.PgCatalogStatActivityTableID: pgCatalogStatActivityTable,
sqlbase.PgCatalogSecurityLabelTableID: pgCatalogSecurityLabelTable,
sqlbase.PgCatalogSharedSecurityLabelTableID: pgCatalogSharedSecurityLabelTable,
},
// Postgres's catalogs are ill-defined when there is no current
// database set. Simply reject any attempts to use them in that
// case.
validWithNoDatabaseContext: false,
}
// The catalog pg_am stores information about relation access methods.
// It's important to note that this table changed drastically between Postgres
// versions 9.5 and 9.6. We currently support both versions of this table.
// See: https://www.postgresql.org/docs/9.5/static/catalog-pg-am.html and
// https://www.postgresql.org/docs/9.6/static/catalog-pg-am.html.
var pgCatalogAmTable = virtualSchemaTable{
comment: `index access methods (incomplete)
https://www.postgresql.org/docs/9.5/catalog-pg-am.html`,
schema: `
CREATE TABLE pg_catalog.pg_am (
oid OID,
amname NAME,
amstrategies INT,
amsupport INT,
amcanorder BOOL,
amcanorderbyop BOOL,
amcanbackward BOOL,
amcanunique BOOL,
amcanmulticol BOOL,
amoptionalkey BOOL,
amsearcharray BOOL,
amsearchnulls BOOL,
amstorage BOOL,
amclusterable BOOL,
ampredlocks BOOL,
amkeytype OID,
aminsert OID,
ambeginscan OID,
amgettuple OID,
amgetbitmap OID,
amrescan OID,
amendscan OID,
ammarkpos OID,
amrestrpos OID,
ambuild OID,
ambuildempty OID,
ambulkdelete OID,
amvacuumcleanup OID,
amcanreturn OID,
amcostestimate OID,
amoptions OID,
amhandler OID,
amtype CHAR
)`,
populate: func(_ context.Context, p *planner, _ *DatabaseDescriptor, addRow func(...tree.Datum) error) error {
h := makeOidHasher()
h.writeStr(cockroachIndexEncoding)
return addRow(
h.getOid(), // oid - all versions
tree.NewDName(cockroachIndexEncoding), // amname - all versions
zeroVal, // amstrategies - < v9.6
zeroVal, // amsupport - < v9.6
tree.DBoolTrue, // amcanorder - < v9.6
tree.DBoolFalse, // amcanorderbyop - < v9.6
tree.DBoolTrue, // amcanbackward - < v9.6
tree.DBoolTrue, // amcanunique - < v9.6
tree.DBoolTrue, // amcanmulticol - < v9.6
tree.DBoolTrue, // amoptionalkey - < v9.6
tree.DBoolTrue, // amsearcharray - < v9.6
tree.DBoolTrue, // amsearchnulls - < v9.6
tree.DBoolFalse, // amstorage - < v9.6
tree.DBoolFalse, // amclusterable - < v9.6
tree.DBoolFalse, // ampredlocks - < v9.6
oidZero, // amkeytype - < v9.6
tree.DNull, // aminsert - < v9.6
tree.DNull, // ambeginscan - < v9.6
oidZero, // amgettuple - < v9.6
oidZero, // amgetbitmap - < v9.6
tree.DNull, // amrescan - < v9.6
tree.DNull, // amendscan - < v9.6
tree.DNull, // ammarkpos - < v9.6
tree.DNull, // amrestrpos - < v9.6
tree.DNull, // ambuild - < v9.6
tree.DNull, // ambuildempty - < v9.6
tree.DNull, // ambulkdelete - < v9.6
tree.DNull, // amvacuumcleanup - < v9.6
tree.DNull, // amcanreturn - < v9.6
tree.DNull, // amcostestimate - < v9.6
tree.DNull, // amoptions - < v9.6
tree.DNull, // amhandler - > v9.6
tree.NewDString("i"), // amtype - > v9.6
)
},
}
var pgCatalogAttrDefTable = virtualSchemaTable{
comment: `column default values
https://www.postgresql.org/docs/9.5/catalog-pg-attrdef.html`,
schema: `
CREATE TABLE pg_catalog.pg_attrdef (
oid OID,
adrelid OID,
adnum INT,
adbin STRING,
adsrc STRING
)`,
populate: func(ctx context.Context, p *planner, dbContext *DatabaseDescriptor, addRow func(...tree.Datum) error) error {
h := makeOidHasher()
return forEachTableDesc(ctx, p, dbContext, virtualMany,
func(db *sqlbase.DatabaseDescriptor, scName string, table *sqlbase.TableDescriptor) error {
colNum := 0
return forEachColumnInTable(table, func(column *sqlbase.ColumnDescriptor) error {
colNum++
if column.DefaultExpr == nil {
// pg_attrdef only expects rows for columns with default values.
return nil
}
defSrc := tree.NewDString(*column.DefaultExpr)
return addRow(
h.ColumnOid(table.ID, column.ID), // oid
defaultOid(table.ID), // adrelid
tree.NewDInt(tree.DInt(colNum)), // adnum
defSrc, // adbin
defSrc, // adsrc
)
})
})
},
}
var pgCatalogAttributeTable = virtualSchemaTable{
comment: `table columns (incomplete - see also information_schema.columns)
https://www.postgresql.org/docs/9.5/catalog-pg-attribute.html`,
schema: `
CREATE TABLE pg_catalog.pg_attribute (
attrelid OID,
attname NAME,
atttypid OID,
attstattarget INT,
attlen INT,
attnum INT,
attndims INT,
attcacheoff INT,
atttypmod INT,
attbyval BOOL,
attstorage CHAR,
attalign CHAR,
attnotnull BOOL,
atthasdef BOOL,
attisdropped BOOL,
attislocal BOOL,
attinhcount INT,
attcollation OID,
attacl STRING[],
attoptions STRING[],
attfdwoptions STRING[]
)`,
populate: func(ctx context.Context, p *planner, dbContext *DatabaseDescriptor, addRow func(...tree.Datum) error) error {
h := makeOidHasher()
return forEachTableDesc(ctx, p, dbContext, virtualMany, func(db *sqlbase.DatabaseDescriptor, scName string, table *sqlbase.TableDescriptor) error {
// addColumn adds adds either a table or a index column to the pg_attribute table.
addColumn := func(column *sqlbase.ColumnDescriptor, attRelID tree.Datum, colID sqlbase.ColumnID) error {
colTyp := &column.Type
attTypMod := int32(-1)
if width := colTyp.Width(); width != 0 {
switch colTyp.Family() {
case types.StringFamily:
// Postgres adds 4 to the attypmod for bounded string types, the
// var header size.
attTypMod = width + 4
case types.BitFamily:
attTypMod = width
case types.DecimalFamily:
// attTypMod is calculated by putting the precision in the upper
// bits and the scale in the lower bits of a 32-bit int, and adding
// 4 (the var header size). We mock this for clients' sake. See
// numeric.c.
attTypMod = ((colTyp.Precision() << 16) | width) + 4
}
}
return addRow(
attRelID, // attrelid
tree.NewDName(column.Name), // attname
typOid(colTyp), // atttypid
zeroVal, // attstattarget
typLen(colTyp), // attlen
tree.NewDInt(tree.DInt(colID)), // attnum
zeroVal, // attndims
negOneVal, // attcacheoff
tree.NewDInt(tree.DInt(attTypMod)), // atttypmod
tree.DNull, // attbyval (see pg_type.typbyval)
tree.DNull, // attstorage
tree.DNull, // attalign
tree.MakeDBool(tree.DBool(!column.Nullable)), // attnotnull
tree.MakeDBool(tree.DBool(column.DefaultExpr != nil)), // atthasdef
tree.DBoolFalse, // attisdropped
tree.DBoolTrue, // attislocal
zeroVal, // attinhcount
typColl(colTyp, h), // attcollation
tree.DNull, // attacl
tree.DNull, // attoptions
tree.DNull, // attfdwoptions
)
}
// Columns for table.
if err := forEachColumnInTable(table, func(column *sqlbase.ColumnDescriptor) error {
tableID := defaultOid(table.ID)
return addColumn(column, tableID, column.ID)
}); err != nil {
return err
}
// Columns for each index.
return forEachIndexInTable(table, func(index *sqlbase.IndexDescriptor) error {
return forEachColumnInIndex(table, index,
func(column *sqlbase.ColumnDescriptor) error {
idxID := h.IndexOid(db, scName, table, index)
return addColumn(column, idxID, column.ID)
},
)
})
})
},
}
var pgCatalogAuthMembersTable = virtualSchemaTable{
comment: `role membership
https://www.postgresql.org/docs/9.5/catalog-pg-auth-members.html`,
schema: `
CREATE TABLE pg_catalog.pg_auth_members (
roleid OID,
member OID,
grantor OID,
admin_option BOOL
)`,
populate: func(ctx context.Context, p *planner, _ *DatabaseDescriptor, addRow func(...tree.Datum) error) error {
h := makeOidHasher()
return forEachRoleMembership(ctx, p,
func(roleName, memberName string, isAdmin bool) error {
return addRow(
h.UserOid(roleName), // roleid
h.UserOid(memberName), // member
tree.DNull, // grantor
tree.MakeDBool(tree.DBool(isAdmin)), // admin_option
)
})
},
}
var (
relKindTable = tree.NewDString("r")
relKindIndex = tree.NewDString("i")
relKindView = tree.NewDString("v")
relKindSequence = tree.NewDString("S")
relPersistencePermanent = tree.NewDString("p")
)
var pgCatalogClassTable = virtualSchemaTable{
comment: `tables and relation-like objects (incomplete - see also information_schema.tables/sequences/views)
https://www.postgresql.org/docs/9.5/catalog-pg-class.html`,
schema: `
CREATE TABLE pg_catalog.pg_class (
oid OID,
relname NAME NOT NULL,
relnamespace OID,
reltype OID,
relowner OID,
relam OID,
relfilenode OID,
reltablespace OID,
relpages INT,
reltuples FLOAT,
relallvisible INT,
reltoastrelid OID,
relhasindex BOOL,
relisshared BOOL,
relpersistence CHAR,
relistemp BOOL,
relkind CHAR,
relnatts INT,
relchecks INT,
relhasoids BOOL,
relhaspkey BOOL,
relhasrules BOOL,
relhastriggers BOOL,
relhassubclass BOOL,
relfrozenxid INT,
relacl STRING[],
reloptions STRING[]
)`,
populate: func(ctx context.Context, p *planner, dbContext *DatabaseDescriptor, addRow func(...tree.Datum) error) error {
h := makeOidHasher()
return forEachTableDesc(ctx, p, dbContext, virtualMany,
func(db *sqlbase.DatabaseDescriptor, scName string, table *sqlbase.TableDescriptor) error {
// The only difference between tables, views and sequences is the relkind column.
relKind := relKindTable
if table.IsView() {
relKind = relKindView
} else if table.IsSequence() {
relKind = relKindSequence
}
namespaceOid := h.NamespaceOid(db, scName)
if err := addRow(
defaultOid(table.ID), // oid
tree.NewDName(table.Name), // relname
namespaceOid, // relnamespace
oidZero, // reltype (PG creates a composite type in pg_type for each table)
tree.DNull, // relowner
tree.DNull, // relam
oidZero, // relfilenode
oidZero, // reltablespace
tree.DNull, // relpages
tree.DNull, // reltuples
zeroVal, // relallvisible
oidZero, // reltoastrelid
tree.MakeDBool(tree.DBool(table.IsPhysicalTable())), // relhasindex
tree.DBoolFalse, // relisshared
relPersistencePermanent, // relPersistence
tree.DBoolFalse, // relistemp
relKind, // relkind
tree.NewDInt(tree.DInt(len(table.Columns))), // relnatts
tree.NewDInt(tree.DInt(len(table.Checks))), // relchecks
tree.DBoolFalse, // relhasoids
tree.MakeDBool(tree.DBool(table.IsPhysicalTable())), // relhaspkey
tree.DBoolFalse, // relhasrules
tree.DBoolFalse, // relhastriggers
tree.DBoolFalse, // relhassubclass
zeroVal, // relfrozenxid
tree.DNull, // relacl
tree.DNull, // reloptions
); err != nil {
return err
}
// Skip adding indexes for sequences (their table descriptors hav a primary
// index to make them comprehensible to backup/restore, but PG doesn't include
// an index in pg_class).
if table.IsSequence() {
return nil
}
// Indexes.
return forEachIndexInTable(table, func(index *sqlbase.IndexDescriptor) error {
return addRow(
h.IndexOid(db, scName, table, index), // oid
tree.NewDName(index.Name), // relname
namespaceOid, // relnamespace
oidZero, // reltype
tree.DNull, // relowner
tree.DNull, // relam
oidZero, // relfilenode
oidZero, // reltablespace
tree.DNull, // relpages
tree.DNull, // reltuples
zeroVal, // relallvisible
oidZero, // reltoastrelid
tree.DBoolFalse, // relhasindex
tree.DBoolFalse, // relisshared
relPersistencePermanent, // relPersistence
tree.DBoolFalse, // relistemp
relKindIndex, // relkind
tree.NewDInt(tree.DInt(len(index.ColumnNames))), // relnatts
zeroVal, // relchecks
tree.DBoolFalse, // relhasoids
tree.DBoolFalse, // relhaspkey
tree.DBoolFalse, // relhasrules
tree.DBoolFalse, // relhastriggers
tree.DBoolFalse, // relhassubclass
zeroVal, // relfrozenxid
tree.DNull, // relacl
tree.DNull, // reloptions
)
})
})
},
}
var pgCatalogCollationTable = virtualSchemaTable{
comment: `available collations (incomplete)
https://www.postgresql.org/docs/9.5/catalog-pg-collation.html`,
schema: `
CREATE TABLE pg_catalog.pg_collation (
oid OID,
collname STRING,
collnamespace OID,
collowner OID,
collencoding INT,
collcollate STRING,
collctype STRING
)`,
populate: func(ctx context.Context, p *planner, dbContext *DatabaseDescriptor, addRow func(...tree.Datum) error) error {
h := makeOidHasher()
return forEachDatabaseDesc(ctx, p, dbContext, func(db *DatabaseDescriptor) error {
namespaceOid := h.NamespaceOid(db, tree.PublicSchema)
for _, tag := range collate.Supported() {
collName := tag.String()
if err := addRow(
h.CollationOid(collName), // oid
tree.NewDString(collName), // collname
namespaceOid, // collnamespace
tree.DNull, // collowner
builtins.DatEncodingUTFId, // collencoding
// It's not clear how to translate a Go collation tag into the format
// required by LC_COLLATE and LC_CTYPE.
tree.DNull, // collcollate
tree.DNull, // collctype
); err != nil {
return err
}
}
return nil
})
},
}
var (
conTypeCheck = tree.NewDString("c")
conTypeFK = tree.NewDString("f")
conTypePKey = tree.NewDString("p")
conTypeUnique = tree.NewDString("u")
conTypeTrigger = tree.NewDString("t")
conTypeExclusion = tree.NewDString("x")
// Avoid unused warning for constants.
_ = conTypeTrigger
_ = conTypeExclusion
fkActionNone = tree.NewDString("a")
fkActionRestrict = tree.NewDString("r")
fkActionCascade = tree.NewDString("c")
fkActionSetNull = tree.NewDString("n")
fkActionSetDefault = tree.NewDString("d")
fkActionMap = map[sqlbase.ForeignKeyReference_Action]tree.Datum{
sqlbase.ForeignKeyReference_NO_ACTION: fkActionNone,
sqlbase.ForeignKeyReference_RESTRICT: fkActionRestrict,
sqlbase.ForeignKeyReference_CASCADE: fkActionCascade,
sqlbase.ForeignKeyReference_SET_NULL: fkActionSetNull,
sqlbase.ForeignKeyReference_SET_DEFAULT: fkActionSetDefault,
}
fkMatchTypeFull = tree.NewDString("f")
fkMatchTypePartial = tree.NewDString("p")
fkMatchTypeSimple = tree.NewDString("s")
fkMatchMap = map[sqlbase.ForeignKeyReference_Match]tree.Datum{
sqlbase.ForeignKeyReference_SIMPLE: fkMatchTypeSimple,
sqlbase.ForeignKeyReference_FULL: fkMatchTypeFull,
sqlbase.ForeignKeyReference_PARTIAL: fkMatchTypePartial,
}
)
var pgCatalogConstraintTable = virtualSchemaTable{
comment: `table constraints (incomplete - see also information_schema.table_constraints)
https://www.postgresql.org/docs/9.5/catalog-pg-constraint.html`,
schema: `
CREATE TABLE pg_catalog.pg_constraint (
oid OID,
conname NAME,
connamespace OID,
contype STRING,
condeferrable BOOL,
condeferred BOOL,
convalidated BOOL,
conrelid OID,
contypid OID,
conindid OID,
confrelid OID,
confupdtype STRING,
confdeltype STRING,
confmatchtype STRING,
conislocal BOOL,
coninhcount INT,
connoinherit BOOL,
conkey INT[],
confkey INT[],
conpfeqop OID[],
conppeqop OID[],
conffeqop OID[],
conexclop OID[],
conbin STRING,
consrc STRING,
-- condef is a CockroachDB extension that provides a SHOW CREATE CONSTRAINT
-- style string, for use by pg_get_constraintdef().
condef STRING
)`,
populate: func(ctx context.Context, p *planner, dbContext *DatabaseDescriptor, addRow func(...tree.Datum) error) error {
h := makeOidHasher()
return forEachTableDescWithTableLookup(ctx, p, dbContext, hideVirtual /*virtual tables have no constraints*/, func(
db *sqlbase.DatabaseDescriptor,
scName string,
table *sqlbase.TableDescriptor,
tableLookup tableLookupFn,
) error {
conInfo, err := table.GetConstraintInfoWithLookup(tableLookup.getTableByID)
if err != nil {
return err
}
namespaceOid := h.NamespaceOid(db, scName)
tblOid := defaultOid(table.ID)
for conName, con := range conInfo {
oid := tree.DNull
contype := tree.DNull
conindid := oidZero
confrelid := oidZero
confupdtype := tree.DNull
confdeltype := tree.DNull
confmatchtype := tree.DNull
conkey := tree.DNull
confkey := tree.DNull
consrc := tree.DNull
conbin := tree.DNull
condef := tree.DNull
// Determine constraint kind-specific fields.
var err error
switch con.Kind {
case sqlbase.ConstraintTypePK:
oid = h.PrimaryKeyConstraintOid(db, scName, table, con.Index)
contype = conTypePKey
conindid = h.IndexOid(db, scName, table, con.Index)
var err error
if conkey, err = colIDArrayToDatum(con.Index.ColumnIDs); err != nil {
return err
}
condef = tree.NewDString(table.PrimaryKeyString())
case sqlbase.ConstraintTypeFK:
referencedDB, err := tableLookup.getDatabaseByID(con.ReferencedTable.ParentID)
if err != nil {
return err
}
oid = h.ForeignKeyConstraintOid(db, tree.PublicSchema, table, con.FK)
contype = conTypeFK
conindid = h.IndexOid(referencedDB, tree.PublicSchema, con.ReferencedTable, con.ReferencedIndex)
confrelid = defaultOid(con.ReferencedTable.ID)
if r, ok := fkActionMap[con.FK.OnUpdate]; ok {
confupdtype = r
}
if r, ok := fkActionMap[con.FK.OnDelete]; ok {
confdeltype = r
}
if r, ok := fkMatchMap[con.FK.Match]; ok {
confmatchtype = r
}
columnIDs := con.Index.ColumnIDs
if int(con.FK.SharedPrefixLen) > len(columnIDs) {
return pgerror.AssertionFailedf(
"foreign key %q's SharedPrefixLen (%d) is greater than the columns in the index (%d)",
con.FK.Name,
con.FK.SharedPrefixLen,
int32(len(columnIDs)),
)
}
sharedPrefixLen := len(columnIDs)
if int(con.FK.SharedPrefixLen) > 0 {
sharedPrefixLen = int(con.FK.SharedPrefixLen)
}
if conkey, err = colIDArrayToDatum(columnIDs[:sharedPrefixLen]); err != nil {
return err
}
if confkey, err = colIDArrayToDatum(con.ReferencedIndex.ColumnIDs); err != nil {
return err
}
var buf bytes.Buffer
if err := printForeignKeyConstraint(ctx, &buf, db.Name, con.Index, tableLookup); err != nil {
return err
}
condef = tree.NewDString(buf.String())
case sqlbase.ConstraintTypeUnique:
oid = h.UniqueConstraintOid(db, scName, table, con.Index)
contype = conTypeUnique
conindid = h.IndexOid(db, scName, table, con.Index)
var err error
if conkey, err = colIDArrayToDatum(con.Index.ColumnIDs); err != nil {
return err
}
f := tree.NewFmtCtx(tree.FmtSimple)
f.WriteString("UNIQUE (")
con.Index.ColNamesFormat(f)
f.WriteByte(')')
condef = tree.NewDString(f.CloseAndGetString())
case sqlbase.ConstraintTypeCheck:
oid = h.CheckConstraintOid(db, scName, table, con.CheckConstraint)
contype = conTypeCheck
if conkey, err = colIDArrayToDatum(con.CheckConstraint.ColumnIDs); err != nil {
return err
}
consrc = tree.NewDString(con.Details)
conbin = consrc
condef = tree.NewDString(fmt.Sprintf("CHECK (%s)", con.Details))
}
if err := addRow(
oid, // oid
dNameOrNull(conName), // conname
namespaceOid, // connamespace
contype, // contype
tree.DBoolFalse, // condeferrable
tree.DBoolFalse, // condeferred
tree.MakeDBool(tree.DBool(!con.Unvalidated)), // convalidated
tblOid, // conrelid
oidZero, // contypid
conindid, // conindid
confrelid, // confrelid
confupdtype, // confupdtype
confdeltype, // confdeltype
confmatchtype, // confmatchtype
tree.DBoolTrue, // conislocal
zeroVal, // coninhcount
tree.DBoolTrue, // connoinherit
conkey, // conkey
confkey, // confkey
tree.DNull, // conpfeqop
tree.DNull, // conppeqop
tree.DNull, // conffeqop
tree.DNull, // conexclop
conbin, // conbin
consrc, // consrc
condef, // condef
); err != nil {
return err
}
}
return nil
})
},
}
// colIDArrayToDatum returns an int[] containing the ColumnIDs, or NULL if there
// are no ColumnIDs.
func colIDArrayToDatum(arr []sqlbase.ColumnID) (tree.Datum, error) {
if len(arr) == 0 {
return tree.DNull, nil
}
d := tree.NewDArray(types.Int)
for _, val := range arr {
if err := d.Append(tree.NewDInt(tree.DInt(val))); err != nil {
return nil, err
}
}
return d, nil
}
// colIDArrayToVector returns an INT2VECTOR containing the ColumnIDs, or NULL if
// there are no ColumnIDs.
func colIDArrayToVector(arr []sqlbase.ColumnID) (tree.Datum, error) {
dArr, err := colIDArrayToDatum(arr)
if err != nil {
return nil, err
}
if dArr == tree.DNull {
return dArr, nil
}
return tree.NewDIntVectorFromDArray(tree.MustBeDArray(dArr)), nil
}
var pgCatalogDatabaseTable = virtualSchemaTable{
comment: `available databases (incomplete)
https://www.postgresql.org/docs/9.5/catalog-pg-database.html`,
schema: `
CREATE TABLE pg_catalog.pg_database (
oid OID,
datname Name,
datdba OID,
encoding INT,
datcollate STRING,
datctype STRING,
datistemplate BOOL,
datallowconn BOOL,
datconnlimit INT,
datlastsysoid OID,
datfrozenxid INT,
datminmxid INT,
dattablespace OID,
datacl STRING[]
)`,
populate: func(ctx context.Context, p *planner, _ *DatabaseDescriptor, addRow func(...tree.Datum) error) error {
return forEachDatabaseDesc(ctx, p, nil /*all databases*/, func(db *sqlbase.DatabaseDescriptor) error {
return addRow(
defaultOid(db.ID), // oid
tree.NewDName(db.Name), // datname
tree.DNull, // datdba
builtins.DatEncodingUTFId, // encoding
builtins.DatEncodingEnUTF8, // datcollate
builtins.DatEncodingEnUTF8, // datctype
tree.DBoolFalse, // datistemplate
tree.DBoolTrue, // datallowconn
negOneVal, // datconnlimit
tree.DNull, // datlastsysoid
tree.DNull, // datfrozenxid
tree.DNull, // datminmxid
oidZero, // dattablespace
tree.DNull, // datacl
)
})
},
}
var (
depTypeNormal = tree.NewDString("n")
depTypeAuto = tree.NewDString("a")
depTypeInternal = tree.NewDString("i")
depTypeExtension = tree.NewDString("e")
depTypeAutoExtension = tree.NewDString("x")
depTypePin = tree.NewDString("p")
// Avoid unused warning for constants.
_ = depTypeAuto
_ = depTypeInternal
_ = depTypeExtension
_ = depTypeAutoExtension
_ = depTypePin
pgConstraintsTableName = tree.MakeTableNameWithSchema("", tree.Name(pgCatalogName), tree.Name("pg_constraint"))
pgClassTableName = tree.MakeTableNameWithSchema("", tree.Name(pgCatalogName), tree.Name("pg_class"))
)
// pg_depend is a fairly complex table that details many different kinds of
// relationships between database objects. We do not implement the vast
// majority of this table, as it is mainly used by pgjdbc to address a
// deficiency in pg_constraint that was removed in postgres v9.0 with the
// addition of the conindid column. To provide backward compatibility with
// pgjdbc drivers before https://github.com/pgjdbc/pgjdbc/pull/689, we
// provide those rows in pg_depend that track the dependency of foreign key
// constraints on their supporting index entries in pg_class.
var pgCatalogDependTable = virtualSchemaTable{
comment: `dependency relationships (incomplete)
https://www.postgresql.org/docs/9.5/catalog-pg-depend.html`,
schema: `
CREATE TABLE pg_catalog.pg_depend (
classid OID,
objid OID,
objsubid INT,
refclassid OID,
refobjid OID,
refobjsubid INT,
deptype CHAR
)`,
populate: func(ctx context.Context, p *planner, dbContext *DatabaseDescriptor, addRow func(...tree.Datum) error) error {
vt := p.getVirtualTabler()
pgConstraintsDesc, err := vt.getVirtualTableDesc(&pgConstraintsTableName)
if err != nil {
return errors.New("could not find pg_catalog.pg_constraint")
}
pgClassDesc, err := vt.getVirtualTableDesc(&pgClassTableName)
if err != nil {
return errors.New("could not find pg_catalog.pg_class")
}
h := makeOidHasher()
return forEachTableDescWithTableLookup(ctx, p, dbContext, hideVirtual /*virtual tables have no constraints*/, func(
db *sqlbase.DatabaseDescriptor,
scName string,
table *sqlbase.TableDescriptor,
tableLookup tableLookupFn,
) error {
conInfo, err := table.GetConstraintInfoWithLookup(tableLookup.getTableByID)
if err != nil {
return err
}
pgConstraintTableOid := defaultOid(pgConstraintsDesc.ID)
pgClassTableOid := defaultOid(pgClassDesc.ID)
for _, con := range conInfo {
if con.Kind != sqlbase.ConstraintTypeFK {
continue
}
referencedDB, err := tableLookup.getDatabaseByID(con.ReferencedTable.ParentID)
if err != nil {
return err
}
constraintOid := h.ForeignKeyConstraintOid(db, tree.PublicSchema, table, con.FK)
refObjID := h.IndexOid(referencedDB, tree.PublicSchema, con.ReferencedTable, con.ReferencedIndex)
if err := addRow(
pgConstraintTableOid, // classid