-
Notifications
You must be signed in to change notification settings - Fork 3.8k
/
pg_catalog.go
3357 lines (3188 loc) · 109 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.
//
// 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 sql
import (
"bytes"
"context"
"encoding/binary"
"fmt"
"hash"
"hash/fnv"
"strings"
"time"
"unicode"
"github.com/cockroachdb/cockroach/pkg/keys"
"github.com/cockroachdb/cockroach/pkg/security"
"github.com/cockroachdb/cockroach/pkg/sql/catalog/resolver"
"github.com/cockroachdb/cockroach/pkg/sql/parser"
"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/cockroachdb/cockroach/pkg/util/log"
"github.com/cockroachdb/errors"
"github.com/lib/pq/oid"
"golang.org/x/text/collate"
)
var (
oidZero = tree.NewDOid(0)
zeroVal = tree.DZero
negOneVal = tree.NewDInt(-1)
passwdStarString = tree.NewDString("********")
)
const (
indexTypeForwardIndex = "prefix"
indexTypeInvertedIndex = "inverted"
defaultCollationTag = "en-US"
)
// Bitmasks for pg_index.indoption. Each column in the index has a bitfield
// indicating how the columns are indexed. The constants below are the same as
// the ones in Postgres:
// https://github.com/postgres/postgres/blob/b6423e92abfadaa1ed9642319872aa1654403cd6/src/include/catalog/pg_index.h#L70-L76
const (
// indoptionDesc indicates that the values in the index are in reverse order.
indoptionDesc = 0x01
// indoptionNullsFirst indicates that NULLs appear first in the index.
indoptionNullsFirst = 0x02
)
var forwardIndexOid = stringOid(indexTypeForwardIndex)
var invertedIndexOid = stringOid(indexTypeInvertedIndex)
// 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.PgCatalogAuthIDTableID: pgCatalogAuthIDTable,
sqlbase.PgCatalogAuthMembersTableID: pgCatalogAuthMembersTable,
sqlbase.PgCatalogAvailableExtensionsTableID: pgCatalogAvailableExtensionsTable,
sqlbase.PgCatalogCastTableID: pgCatalogCastTable,
sqlbase.PgCatalogClassTableID: pgCatalogClassTable,
sqlbase.PgCatalogCollationTableID: pgCatalogCollationTable,
sqlbase.PgCatalogConstraintTableID: pgCatalogConstraintTable,
sqlbase.PgCatalogConversionTableID: pgCatalogConversionTable,
sqlbase.PgCatalogDatabaseTableID: pgCatalogDatabaseTable,
sqlbase.PgCatalogDefaultACLTableID: pgCatalogDefaultACLTable,
sqlbase.PgCatalogDependTableID: pgCatalogDependTable,
sqlbase.PgCatalogDescriptionTableID: pgCatalogDescriptionTable,
sqlbase.PgCatalogSharedDescriptionTableID: pgCatalogSharedDescriptionTable,
sqlbase.PgCatalogEnumTableID: pgCatalogEnumTable,
sqlbase.PgCatalogEventTriggerTableID: pgCatalogEventTriggerTable,
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.PgCatalogLocksTableID: pgCatalogLocksTable,
sqlbase.PgCatalogMatViewsTableID: pgCatalogMatViewsTable,
sqlbase.PgCatalogNamespaceTableID: pgCatalogNamespaceTable,
sqlbase.PgCatalogOperatorTableID: pgCatalogOperatorTable,
sqlbase.PgCatalogPreparedStatementsTableID: pgCatalogPreparedStatementsTable,
sqlbase.PgCatalogPreparedXactsTableID: pgCatalogPreparedXactsTable,
sqlbase.PgCatalogProcTableID: pgCatalogProcTable,
sqlbase.PgCatalogAggregateTableID: pgCatalogAggregateTable,
sqlbase.PgCatalogRangeTableID: pgCatalogRangeTable,
sqlbase.PgCatalogRewriteTableID: pgCatalogRewriteTable,
sqlbase.PgCatalogRolesTableID: pgCatalogRolesTable,
sqlbase.PgCatalogSecLabelsTableID: pgCatalogSecLabelsTable,
sqlbase.PgCatalogSequencesTableID: pgCatalogSequencesTable,
sqlbase.PgCatalogSettingsTableID: pgCatalogSettingsTable,
sqlbase.PgCatalogShdependTableID: pgCatalogShdependTable,
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,
containsTypes: true,
}
// 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 INT2,
amsupport INT2,
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, _ *sqlbase.ImmutableDatabaseDescriptor, addRow func(...tree.Datum) error) error {
// add row for forward indexes
if err := addRow(
forwardIndexOid, // oid - all versions
tree.NewDName(indexTypeForwardIndex), // 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
); err != nil {
return err
}
// add row for inverted indexes
if err := addRow(
invertedIndexOid, // oid - all versions
tree.NewDName(indexTypeInvertedIndex), // amname - all versions
zeroVal, // amstrategies - < v9.6
zeroVal, // amsupport - < v9.6
tree.DBoolFalse, // amcanorder - < v9.6
tree.DBoolFalse, // amcanorderbyop - < v9.6
tree.DBoolFalse, // amcanbackward - < v9.6
tree.DBoolFalse, // amcanunique - < v9.6
tree.DBoolFalse, // amcanmulticol - < v9.6
tree.DBoolFalse, // amoptionalkey - < v9.6
tree.DBoolFalse, // 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
); err != nil {
return err
}
return nil
},
}
var pgCatalogAttrDefTable = makeAllRelationsVirtualTableWithDescriptorIDIndex(
`column default values
https://www.postgresql.org/docs/9.5/catalog-pg-attrdef.html`,
`
CREATE TABLE pg_catalog.pg_attrdef (
oid OID,
adrelid OID NOT NULL,
adnum INT2,
adbin STRING,
adsrc STRING,
INDEX(adrelid)
)`,
virtualMany, false, /* includesIndexEntries */
func(ctx context.Context, p *planner, h oidHasher, db *sqlbase.ImmutableDatabaseDescriptor, scName string,
table *sqlbase.ImmutableTableDescriptor,
lookup simpleSchemaResolver,
addRow func(...tree.Datum) error) 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
}
var defSrc *tree.DString
expr, err := parser.ParseExpr(*column.DefaultExpr)
if err != nil {
defSrc = tree.NewDString(*column.DefaultExpr)
} else {
// Use type check to resolve types in expr. We don't use
// DeserializeTableDescExpr here because that returns a typed
// expression under the hood. Since typed expressions don't contain
// type annotations, we wouldn't format some defaults as intended.
if _, err := expr.TypeCheck(ctx, &p.semaCtx, types.Any); err != nil {
return err
}
ctx := tree.NewFmtCtx(tree.FmtPGAttrdefAdbin)
ctx.FormatNode(expr)
defSrc = tree.NewDString(ctx.String())
}
return addRow(
h.ColumnOid(table.ID, column.ID), // oid
tableOid(table.ID), // adrelid
tree.NewDInt(tree.DInt(column.GetLogicalColumnID())), // adnum
defSrc, // adbin
defSrc, // adsrc
)
})
})
var pgCatalogAttributeTable = makeAllRelationsVirtualTableWithDescriptorIDIndex(
`table columns (incomplete - see also information_schema.columns)
https://www.postgresql.org/docs/9.5/catalog-pg-attribute.html`,
`
CREATE TABLE pg_catalog.pg_attribute (
attrelid OID NOT NULL,
attname NAME,
atttypid OID,
attstattarget INT4,
attlen INT2,
attnum INT2,
attndims INT4,
attcacheoff INT4,
atttypmod INT4,
attbyval BOOL,
attstorage CHAR,
attalign CHAR,
attnotnull BOOL,
atthasdef BOOL,
attisdropped BOOL,
attislocal BOOL,
attinhcount INT4,
attcollation OID,
attacl STRING[],
attoptions STRING[],
attfdwoptions STRING[],
INDEX(attrelid)
)`,
virtualMany, true, /* includesIndexEntries */
func(ctx context.Context, p *planner, h oidHasher, db *sqlbase.ImmutableDatabaseDescriptor, scName string,
table *sqlbase.ImmutableTableDescriptor,
lookup simpleSchemaResolver,
addRow func(...tree.Datum) error) 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
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(colTyp.TypeModifier())), // 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 := tableOid(table.ID)
return addColumn(column, tableID, column.GetLogicalColumnID())
}); 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(table.ID, index.ID)
return addColumn(column, idxID, column.GetLogicalColumnID())
},
)
})
})
var pgCatalogCastTable = virtualSchemaTable{
comment: `casts (empty - needs filling out)
https://www.postgresql.org/docs/9.6/catalog-pg-cast.html`,
schema: `
CREATE TABLE pg_catalog.pg_cast (
oid OID,
castsource OID,
casttarget OID,
castfunc OID,
castcontext CHAR,
castmethod CHAR
)`,
populate: func(ctx context.Context, p *planner, _ *sqlbase.ImmutableDatabaseDescriptor, addRow func(...tree.Datum) error) error {
// TODO(someone): to populate this, we should split up the big PerformCast
// method in tree/eval.go into entries in a list. Then, this virtual table
// can simply range over the list. This would probably be better for
// maintainability anyway.
return nil
},
}
var pgCatalogAuthIDTable = virtualSchemaTable{
comment: `authorization identifiers - differs from postgres as we do not display passwords,
and thus do not require admin privileges for access.
https://www.postgresql.org/docs/9.5/catalog-pg-authid.html`,
schema: `
CREATE TABLE pg_catalog.pg_authid (
oid OID,
rolname NAME,
rolsuper BOOL,
rolinherit BOOL,
rolcreaterole BOOL,
rolcreatedb BOOL,
rolcanlogin BOOL,
rolreplication BOOL,
rolbypassrls BOOL,
rolconnlimit INT4,
rolpassword TEXT,
rolvaliduntil TIMESTAMPTZ
)`,
populate: func(ctx context.Context, p *planner, _ *sqlbase.ImmutableDatabaseDescriptor, addRow func(...tree.Datum) error) error {
h := makeOidHasher()
return forEachRole(ctx, p, func(username string, isRole bool, noLogin bool, rolValidUntil *time.Time) error {
isRoot := tree.DBool(username == security.RootUser || username == sqlbase.AdminRole)
isRoleDBool := tree.DBool(isRole)
roleCanLogin := tree.DBool(!noLogin)
roleValidUntilValue := tree.DNull
if rolValidUntil != nil {
var err error
roleValidUntilValue, err = tree.MakeDTimestampTZ(*rolValidUntil, time.Second)
if err != nil {
return err
}
}
return addRow(
h.UserOid(username), // oid
tree.NewDName(username), // rolname
tree.MakeDBool(isRoot), // rolsuper
tree.MakeDBool(isRoleDBool), // rolinherit. Roles inherit by default.
tree.MakeDBool(isRoot), // rolcreaterole
tree.MakeDBool(isRoot), // rolcreatedb
tree.MakeDBool(roleCanLogin), // rolcanlogin.
tree.DBoolFalse, // rolreplication
tree.DBoolFalse, // rolbypassrls
negOneVal, // rolconnlimit
passwdStarString, // rolpassword
roleValidUntilValue, // rolvaliduntil
)
})
},
}
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, _ *sqlbase.ImmutableDatabaseDescriptor, 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 pgCatalogAvailableExtensionsTable = virtualSchemaTable{
comment: `available extensions
https://www.postgresql.org/docs/9.6/view-pg-available-extensions.html`,
schema: `
CREATE TABLE pg_catalog.pg_available_extensions (
name NAME,
default_version TEXT,
installed_version TEXT,
comment TEXT
)`,
populate: func(ctx context.Context, p *planner, _ *sqlbase.ImmutableDatabaseDescriptor, addRow func(...tree.Datum) error) error {
// We support no extensions.
return nil
},
}
var (
relKindTable = tree.NewDString("r")
relKindIndex = tree.NewDString("i")
relKindView = tree.NewDString("v")
relKindSequence = tree.NewDString("S")
relPersistencePermanent = tree.NewDString("p")
)
var pgCatalogClassTable = makeAllRelationsVirtualTableWithDescriptorIDIndex(
`tables and relation-like objects (incomplete - see also information_schema.tables/sequences/views)
https://www.postgresql.org/docs/9.5/catalog-pg-class.html`,
`
CREATE TABLE pg_catalog.pg_class (
oid OID NOT NULL,
relname NAME NOT NULL,
relnamespace OID,
reltype OID,
reloftype OID,
relowner OID,
relam OID,
relfilenode OID,
reltablespace OID,
relpages INT4,
reltuples FLOAT4,
relallvisible INT4,
reltoastrelid OID,
relhasindex BOOL,
relisshared BOOL,
relpersistence CHAR,
relistemp BOOL,
relkind CHAR,
relnatts INT2,
relchecks INT2,
relhasoids BOOL,
relhaspkey BOOL,
relhasrules BOOL,
relhastriggers BOOL,
relhassubclass BOOL,
relfrozenxid INT,
relacl STRING[],
reloptions STRING[],
INDEX (oid)
)`,
virtualMany, true, /* includesIndexEntries */
func(ctx context.Context, p *planner, h oidHasher, db *sqlbase.ImmutableDatabaseDescriptor, scName string,
table *sqlbase.ImmutableTableDescriptor, _ simpleSchemaResolver, addRow func(...tree.Datum) error) error {
// The only difference between tables, views and sequences are the relkind and relam columns.
relKind := relKindTable
relAm := forwardIndexOid
if table.IsView() {
relKind = relKindView
relAm = oidZero
} else if table.IsSequence() {
relKind = relKindSequence
relAm = oidZero
}
namespaceOid := h.NamespaceOid(db, scName)
if err := addRow(
tableOid(table.ID), // oid
tree.NewDName(table.Name), // relname
namespaceOid, // relnamespace
oidZero, // reltype (PG creates a composite type in pg_type for each table)
oidZero, // reloftype (PG creates a composite type in pg_type for each table)
tree.DNull, // relowner
relAm, // 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 {
indexType := forwardIndexOid
if index.Type == sqlbase.IndexDescriptor_INVERTED {
indexType = invertedIndexOid
}
return addRow(
h.IndexOid(table.ID, index.ID), // oid
tree.NewDName(index.Name), // relname
namespaceOid, // relnamespace
oidZero, // reltype
oidZero, // reloftype
tree.DNull, // relowner
indexType, // 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 INT4,
collcollate STRING,
collctype STRING
)`,
populate: func(ctx context.Context, p *planner, dbContext *sqlbase.ImmutableDatabaseDescriptor, addRow func(...tree.Datum) error) error {
h := makeOidHasher()
return forEachDatabaseDesc(ctx, p, dbContext, false /* requiresPrivileges */, func(db *sqlbase.ImmutableDatabaseDescriptor) error {
namespaceOid := h.NamespaceOid(db, pgCatalogName)
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,
}
)
func populateTableConstraints(
ctx context.Context,
p *planner,
h oidHasher,
db *sqlbase.ImmutableDatabaseDescriptor,
scName string,
table *sqlbase.ImmutableTableDescriptor,
tableLookup simpleSchemaResolver,
addRow func(...tree.Datum) error,
) error {
conInfo, err := table.GetConstraintInfoWithLookup(tableLookup.getTableByID)
if err != nil {
return err
}
namespaceOid := h.NamespaceOid(db, scName)
tblOid := tableOid(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.TableDesc(), con.Index)
contype = conTypePKey
conindid = h.IndexOid(table.ID, con.Index.ID)
var err error
if conkey, err = colIDArrayToDatum(con.Index.ColumnIDs); err != nil {
return err
}
condef = tree.NewDString(table.PrimaryKeyString())
case sqlbase.ConstraintTypeFK:
oid = h.ForeignKeyConstraintOid(db, scName, table.TableDesc(), con.FK)
contype = conTypeFK
// Foreign keys don't have a single linked index. Pick the first one
// that matches on the referenced table.
referencedTable, err := tableLookup.getTableByID(con.FK.ReferencedTableID)
if err != nil {
return err
}
if idx, err := sqlbase.FindFKReferencedIndex(referencedTable, con.FK.ReferencedColumnIDs); err != nil {
// We couldn't find an index that matched. This shouldn't happen.
log.Warningf(ctx, "broken fk reference: %v", err)
} else {
conindid = h.IndexOid(con.ReferencedTable.ID, idx.ID)
}
confrelid = tableOid(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
}
if conkey, err = colIDArrayToDatum(con.FK.OriginColumnIDs); err != nil {
return err
}
if confkey, err = colIDArrayToDatum(con.FK.ReferencedColumnIDs); err != nil {
return err
}
var buf bytes.Buffer
if err := showForeignKeyConstraint(&buf, db.GetName(), table, con.FK, tableLookup); err != nil {
return err
}
condef = tree.NewDString(buf.String())
case sqlbase.ConstraintTypeUnique:
oid = h.UniqueConstraintOid(db, scName, table.TableDesc(), con.Index)
contype = conTypeUnique
conindid = h.IndexOid(table.ID, con.Index.ID)
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.TableDesc(), con.CheckConstraint)
contype = conTypeCheck
if conkey, err = colIDArrayToDatum(con.CheckConstraint.ColumnIDs); err != nil {
return err
}
consrc = tree.NewDString(fmt.Sprintf("(%s)", 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
}
type oneAtATimeSchemaResolver struct {
ctx context.Context
p *planner
}
func (r oneAtATimeSchemaResolver) getDatabaseByID(
id sqlbase.ID,
) (*sqlbase.ImmutableDatabaseDescriptor, error) {
return r.p.Tables().DatabaseCache().GetDatabaseDescByID(r.ctx, r.p.txn, id)
}
func (r oneAtATimeSchemaResolver) getTableByID(id sqlbase.ID) (*TableDescriptor, error) {
table, err := r.p.LookupTableByID(r.ctx, id)
if err != nil {
return nil, err
}
return table.Desc.TableDesc(), nil
}
// makeAllRelationsVirtualTableWithDescriptorIDIndex creates a virtual table that searches through
// all table descriptors in the system. It automatically adds a virtual index implementation to the
// table id column as well. The input schema must have a single INDEX definition
// with a single column, which must be the column that contains the table id.