-
Notifications
You must be signed in to change notification settings - Fork 3.8k
/
pg_catalog.go
1847 lines (1735 loc) · 57.3 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 (
"encoding/binary"
"fmt"
"hash"
"hash/fnv"
"reflect"
"strconv"
"strings"
"unicode"
"github.com/lib/pq/oid"
"github.com/pkg/errors"
"golang.org/x/net/context"
"golang.org/x/text/collate"
"github.com/cockroachdb/cockroach/pkg/security"
"github.com/cockroachdb/cockroach/pkg/sql/parser"
"github.com/cockroachdb/cockroach/pkg/sql/sqlbase"
)
var (
oidZero = parser.NewDOid(0)
zeroVal = parser.DZero
negOneVal = parser.NewDInt(-1)
)
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,
tables: []virtualSchemaTable{
pgCatalogAmTable,
pgCatalogAttrDefTable,
pgCatalogAttributeTable,
pgCatalogClassTable,
pgCatalogCollationTable,
pgCatalogConstraintTable,
pgCatalogDatabaseTable,
pgCatalogDependTable,
pgCatalogDescriptionTable,
pgCatalogEnumTable,
pgCatalogExtensionTable,
pgCatalogForeignServerTable,
pgCatalogForeignTableTable,
pgCatalogIndexTable,
pgCatalogIndexesTable,
pgCatalogInheritsTable,
pgCatalogNamespaceTable,
pgCatalogProcTable,
pgCatalogRangeTable,
pgCatalogRolesTable,
pgCatalogSettingsTable,
pgCatalogTablesTable,
pgCatalogTypeTable,
pgCatalogViewsTable,
},
}
// See: https://www.postgresql.org/docs/current/static/catalog-pg-am.html.
var pgCatalogAmTable = virtualSchemaTable{
schema: `
CREATE TABLE pg_catalog.pg_am (
oid OID,
amname NAME,
amhandler OID,
amtype CHAR
);
`,
populate: func(_ context.Context, p *planner, _ string, addRow func(...parser.Datum) error) error {
h := makeOidHasher()
h.writeStr(cockroachIndexEncoding)
return addRow(
h.getOid(),
parser.NewDName(cockroachIndexEncoding),
parser.DNull,
parser.NewDString("i"),
)
},
}
// See: https://www.postgresql.org/docs/9.6/static/catalog-pg-attrdef.html.
var pgCatalogAttrDefTable = virtualSchemaTable{
schema: `
CREATE TABLE pg_catalog.pg_attrdef (
oid OID,
adrelid OID,
adnum INT,
adbin STRING,
adsrc STRING
);
`,
populate: func(ctx context.Context, p *planner, prefix string, addRow func(...parser.Datum) error) error {
h := makeOidHasher()
return forEachTableDesc(ctx, p, prefix, func(db *sqlbase.DatabaseDescriptor, 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 := parser.NewDString(*column.DefaultExpr)
return addRow(
h.ColumnOid(db, table, column), // oid
h.TableOid(db, table), // adrelid
parser.NewDInt(parser.DInt(colNum)), // adnum
defSrc, // adbin
defSrc, // adsrc
)
})
})
},
}
// See: https://www.postgresql.org/docs/9.6/static/catalog-pg-attribute.html.
var pgCatalogAttributeTable = virtualSchemaTable{
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, prefix string, addRow func(...parser.Datum) error) error {
h := makeOidHasher()
return forEachTableDesc(ctx, p, prefix, func(db *sqlbase.DatabaseDescriptor, 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 parser.Datum, colNum int) error {
colTyp := column.Type.ToDatumType()
return addRow(
attRelID, // attrelid
parser.NewDName(column.Name), // attname
typOid(colTyp), // atttypid
zeroVal, // attstattarget
typLen(colTyp), // attlen
parser.NewDInt(parser.DInt(colNum)), // attnum
zeroVal, // attndims
negOneVal, // attcacheoff
negOneVal, // atttypmod
parser.DNull, // attbyval (see pg_type.typbyval)
parser.DNull, // attstorage
parser.DNull, // attalign
parser.MakeDBool(parser.DBool(!column.Nullable)), // attnotnull
parser.MakeDBool(parser.DBool(column.DefaultExpr != nil)), // atthasdef
parser.MakeDBool(false), // attisdropped
parser.MakeDBool(true), // attislocal
zeroVal, // attinhcount
typColl(colTyp, h), // attcollation
parser.DNull, // attacl
parser.DNull, // attoptions
parser.DNull, // attfdwoptions
)
}
// Columns for table.
colNum := 0
if err := forEachColumnInTable(table, func(column *sqlbase.ColumnDescriptor) error {
colNum++
tableID := h.TableOid(db, table)
return addColumn(column, tableID, colNum)
}); err != nil {
return err
}
// Columns for each index.
return forEachIndexInTable(table, func(index *sqlbase.IndexDescriptor) error {
colNum := 0
return forEachColumnInIndex(table, index,
func(column *sqlbase.ColumnDescriptor) error {
colNum++
idxID := h.IndexOid(db, table, index)
return addColumn(column, idxID, colNum)
},
)
})
})
},
}
var (
relKindTable = parser.NewDString("r")
relKindIndex = parser.NewDString("i")
relKindView = parser.NewDString("v")
)
// See: https://www.postgresql.org/docs/9.6/static/catalog-pg-class.html.
var pgCatalogClassTable = virtualSchemaTable{
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,
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, prefix string, addRow func(...parser.Datum) error) error {
h := makeOidHasher()
return forEachTableDesc(ctx, p, prefix, func(db *sqlbase.DatabaseDescriptor, table *sqlbase.TableDescriptor) error {
// Table.
relKind := relKindTable
if table.IsView() {
// The only difference between tables and views is the relkind column.
relKind = relKindView
}
if err := addRow(
h.TableOid(db, table), // oid
parser.NewDName(table.Name), // relname
pgNamespaceForDB(db, h).Oid, // relnamespace
oidZero, // reltype (PG creates a composite type in pg_type for each table)
parser.DNull, // relowner
parser.DNull, // relam
oidZero, // relfilenode
oidZero, // reltablespace
parser.DNull, // relpages
parser.DNull, // reltuples
zeroVal, // relallvisible
oidZero, // reltoastrelid
parser.MakeDBool(parser.DBool(table.IsPhysicalTable())), // relhasindex
parser.MakeDBool(false), // relisshared
parser.MakeDBool(false), // relistemp
relKind, // relkind
parser.NewDInt(parser.DInt(len(table.Columns))), // relnatts
parser.NewDInt(parser.DInt(len(table.Checks))), // relchecks
parser.MakeDBool(false), // relhasoids
parser.MakeDBool(parser.DBool(table.IsPhysicalTable())), // relhaspkey
parser.MakeDBool(false), // relhasrules
parser.MakeDBool(false), // relhastriggers
parser.MakeDBool(false), // relhassubclass
zeroVal, // relfrozenxid
parser.DNull, // relacl
parser.DNull, // reloptions
); err != nil {
return err
}
// Indexes.
return forEachIndexInTable(table, func(index *sqlbase.IndexDescriptor) error {
return addRow(
h.IndexOid(db, table, index), // oid
parser.NewDName(index.Name), // relname
pgNamespaceForDB(db, h).Oid, // relnamespace
oidZero, // reltype
parser.DNull, // relowner
parser.DNull, // relam
oidZero, // relfilenode
oidZero, // reltablespace
parser.DNull, // relpages
parser.DNull, // reltuples
zeroVal, // relallvisible
oidZero, // reltoastrelid
parser.MakeDBool(false), // relhasindex
parser.MakeDBool(false), // relisshared
parser.MakeDBool(false), // relistemp
relKindIndex, // relkind
parser.NewDInt(parser.DInt(len(index.ColumnNames))), // relnatts
zeroVal, // relchecks
parser.MakeDBool(false), // relhasoids
parser.MakeDBool(false), // relhaspkey
parser.MakeDBool(false), // relhasrules
parser.MakeDBool(false), // relhastriggers
parser.MakeDBool(false), // relhassubclass
zeroVal, // relfrozenxid
parser.DNull, // relacl
parser.DNull, // reloptions
)
})
})
},
}
// See: https://www.postgresql.org/docs/9.6/static/catalog-pg-collation.html.
var pgCatalogCollationTable = virtualSchemaTable{
schema: `
CREATE TABLE pg_catalog.pg_collation (
oid OID,
collname STRING,
collnamespace OID,
collowner OID,
collencoding INT,
collcollate STRING,
collctype STRING
);
`,
populate: func(_ context.Context, p *planner, _ string, addRow func(...parser.Datum) error) error {
h := makeOidHasher()
for _, tag := range collate.Supported() {
collName := tag.String()
if err := addRow(
h.CollationOid(collName), // oid
parser.NewDString(collName), // collname
pgNamespacePGCatalog.Oid, // collnamespace
parser.DNull, // collowner
datEncodingUTFId, // collencoding
// It's not clear how to translate a Go collation tag into the format
// required by LC_COLLATE and LC_CTYPE.
parser.DNull, // collcollate
parser.DNull, // collctype
); err != nil {
return err
}
}
return nil
},
}
var (
conTypeCheck = parser.NewDString("c")
conTypeFK = parser.NewDString("f")
conTypePKey = parser.NewDString("p")
conTypeUnique = parser.NewDString("u")
conTypeTrigger = parser.NewDString("t")
conTypeExclusion = parser.NewDString("x")
// Avoid unused warning for constants.
_ = conTypeTrigger
_ = conTypeExclusion
fkActionNone = parser.NewDString("a")
fkActionRestrict = parser.NewDString("r")
fkActionCascade = parser.NewDString("c")
fkActionSetNull = parser.NewDString("n")
fkActionSetDefault = parser.NewDString("d")
// Avoid unused warning for constants.
_ = fkActionRestrict
_ = fkActionCascade
_ = fkActionSetNull
_ = fkActionSetDefault
fkMatchTypeFull = parser.NewDString("f")
fkMatchTypePartial = parser.NewDString("p")
fkMatchTypeSimple = parser.NewDString("s")
// Avoid unused warning for constants.
_ = fkMatchTypeFull
_ = fkMatchTypePartial
)
// See: https://www.postgresql.org/docs/9.6/static/catalog-pg-constraint.html.
var pgCatalogConstraintTable = virtualSchemaTable{
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 STRING,
conppeqop STRING,
conffeqop STRING,
conexclop STRING,
conbin STRING,
consrc STRING
);
`,
populate: func(ctx context.Context, p *planner, prefix string, addRow func(...parser.Datum) error) error {
h := makeOidHasher()
return forEachTableDescWithTableLookup(ctx, p, prefix, func(
db *sqlbase.DatabaseDescriptor,
table *sqlbase.TableDescriptor,
tableLookup tableLookupFn,
) error {
info, err := table.GetConstraintInfoWithLookup(tableLookup.tableOrErr)
if err != nil {
return err
}
for name, c := range info {
oid := parser.DNull
contype := parser.DNull
conindid := oidZero
confrelid := oidZero
confupdtype := parser.DNull
confdeltype := parser.DNull
confmatchtype := parser.DNull
conkey := parser.DNull
confkey := parser.DNull
consrc := parser.DNull
// Determine constraint kind-specific fields.
switch c.Kind {
case sqlbase.ConstraintTypePK:
oid = h.PrimaryKeyConstraintOid(db, table, c.Index)
contype = conTypePKey
conindid = h.IndexOid(db, table, c.Index)
var err error
conkey, err = colIDArrayToDatum(c.Index.ColumnIDs)
if err != nil {
return err
}
case sqlbase.ConstraintTypeFK:
referencedDB, _ := tableLookup(c.ReferencedTable.ID)
if referencedDB == nil {
panic(fmt.Sprintf("could not find database of %+v", c.ReferencedTable))
}
oid = h.ForeignKeyConstraintOid(db, table, c.FK)
contype = conTypeFK
conindid = h.IndexOid(referencedDB, c.ReferencedTable, c.ReferencedIndex)
confrelid = h.TableOid(referencedDB, c.ReferencedTable)
confupdtype = fkActionNone
confdeltype = fkActionNone
confmatchtype = fkMatchTypeSimple
var err error
conkey, err = colIDArrayToDatum(c.Index.ColumnIDs)
if err != nil {
return err
}
confkey, err = colIDArrayToDatum(c.ReferencedIndex.ColumnIDs)
if err != nil {
return err
}
case sqlbase.ConstraintTypeUnique:
oid = h.UniqueConstraintOid(db, table, c.Index)
contype = conTypeUnique
conindid = h.IndexOid(db, table, c.Index)
var err error
conkey, err = colIDArrayToDatum(c.Index.ColumnIDs)
if err != nil {
return err
}
case sqlbase.ConstraintTypeCheck:
oid = h.CheckConstraintOid(db, table, c.CheckConstraint)
contype = conTypeCheck
// TODO(nvanbenschoten): We currently do not store the referenced columns for a check
// constraint. We should add an array of column indexes to
// sqlbase.TableDescriptor_CheckConstraint and use that here.
consrc = parser.NewDString(c.Details)
}
if err := addRow(
oid, // oid
dNameOrNull(name), // conname
pgNamespaceForDB(db, h).Oid, // connamespace
contype, // contype
parser.MakeDBool(false), // condeferrable
parser.MakeDBool(false), // condeferred
parser.MakeDBool(parser.DBool(!c.Unvalidated)), // convalidated
h.TableOid(db, table), // conrelid
oidZero, // contypid
conindid, // conindid
confrelid, // confrelid
confupdtype, // confupdtype
confdeltype, // confdeltype
confmatchtype, // confmatchtype
parser.MakeDBool(true), // conislocal
zeroVal, // coninhcount
parser.MakeDBool(true), // connoinherit
conkey, // conkey
confkey, // confkey
parser.DNull, // conpfeqop
parser.DNull, // conppeqop
parser.DNull, // conffeqop
parser.DNull, // conexclop
consrc, // conbin
consrc, // consrc
); 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) (parser.Datum, error) {
if len(arr) == 0 {
return parser.DNull, nil
}
d := parser.NewDArray(parser.TypeInt)
for _, val := range arr {
if err := d.Append(parser.NewDInt(parser.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) (parser.Datum, error) {
dArr, err := colIDArrayToDatum(arr)
if err != nil {
return nil, err
}
if dArr == parser.DNull {
return dArr, nil
}
return parser.NewDIntVectorFromDArray(parser.MustBeDArray(dArr)), nil
}
var (
// http://doxygen.postgresql.org/pg__wchar_8h.html#a22e0c8b9f59f6e226a5968620b4bb6a9aac3b065b882d3231ba59297524da2f23
datEncodingUTFId = parser.NewDInt(6)
datEncodingEnUTF8 = parser.NewDString("en_US.utf8")
)
// See https://www.postgresql.org/docs/9.6/static/catalog-pg-database.html.
var pgCatalogDatabaseTable = virtualSchemaTable{
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, _ string, addRow func(...parser.Datum) error) error {
h := makeOidHasher()
return forEachDatabaseDesc(ctx, p, func(db *sqlbase.DatabaseDescriptor) error {
return addRow(
h.DBOid(db), // oid
parser.NewDName(db.Name), // datname
parser.DNull, // datdba
datEncodingUTFId, // encoding
datEncodingEnUTF8, // datcollate
datEncodingEnUTF8, // datctype
parser.MakeDBool(false), // datistemplate
parser.MakeDBool(true), // datallowconn
negOneVal, // datconnlimit
parser.DNull, // datlastsysoid
parser.DNull, // datfrozenxid
parser.DNull, // datminmxid
parser.DNull, // dattablespace
parser.DNull, // datacl
)
})
},
}
var (
depTypeNormal = parser.NewDString("n")
depTypeAuto = parser.NewDString("a")
depTypeInternal = parser.NewDString("i")
depTypeExtension = parser.NewDString("e")
depTypeAutoExtension = parser.NewDString("x")
depTypePin = parser.NewDString("p")
// Avoid unused warning for constants.
_ = depTypeAuto
_ = depTypeInternal
_ = depTypeExtension
_ = depTypeAutoExtension
_ = depTypePin
)
// See https://www.postgresql.org/docs/9.6/static/catalog-pg-depend.html.
//
// 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{
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, prefix string, addRow func(...parser.Datum) error) error {
h := makeOidHasher()
db, err := getDatabaseDesc(ctx, p.txn, p.getVirtualTabler(), pgCatalogName)
if err != nil {
return errors.New("could not find pg_catalog")
}
pgConstraintDesc, err := getTableDesc(
ctx,
p.txn,
p.getVirtualTabler(),
&parser.TableName{
DatabaseName: pgCatalogName,
TableName: "pg_constraint"},
)
if err != nil {
return errors.New("could not find pg_catalog.pg_constraint")
}
pgConstraintTableOid := h.TableOid(db, pgConstraintDesc)
pgClassDesc, err := getTableDesc(
ctx,
p.txn,
p.getVirtualTabler(),
&parser.TableName{
DatabaseName: pgCatalogName,
TableName: "pg_class"},
)
if err != nil {
return errors.New("could not find pg_catalog.pg_class")
}
pgClassTableOid := h.TableOid(db, pgClassDesc)
return forEachTableDescWithTableLookup(ctx, p, prefix, func(
db *sqlbase.DatabaseDescriptor,
table *sqlbase.TableDescriptor,
tableLookup tableLookupFn,
) error {
info, err := table.GetConstraintInfoWithLookup(tableLookup.tableOrErr)
if err != nil {
return err
}
for _, c := range info {
if c.Kind != sqlbase.ConstraintTypeFK {
continue
}
referencedDB, _ := tableLookup(c.ReferencedTable.ID)
if referencedDB == nil {
panic(fmt.Sprintf("could not find database of %+v", c.ReferencedTable))
}
constraintOid := h.ForeignKeyConstraintOid(db, table, c.FK)
refObjID := h.IndexOid(referencedDB, c.ReferencedTable, c.ReferencedIndex)
if err := addRow(
pgConstraintTableOid, // classid
constraintOid, // objid
zeroVal, // objsubid
pgClassTableOid, // refclassid
refObjID, // refobjid
zeroVal, // refobjsubid
depTypeNormal, // deptype
); err != nil {
return err
}
}
return nil
})
},
}
// See: https://www.postgresql.org/docs/9.6/static/catalog-pg-description.html.
var pgCatalogDescriptionTable = virtualSchemaTable{
schema: `
CREATE TABLE pg_catalog.pg_description (
objoid OID,
classoid OID,
objsubid INT,
description STRING
);
`,
populate: func(_ context.Context, p *planner, _ string, addRow func(...parser.Datum) error) error {
// Comments on database objects are not currently supported.
return nil
},
}
// See: https://www.postgresql.org/docs/9.6/static/catalog-pg-enum.html.
var pgCatalogEnumTable = virtualSchemaTable{
schema: `
CREATE TABLE pg_catalog.pg_enum (
oid OID,
enumtypid OID,
enumsortorder FLOAT,
enumlabel STRING
);
`,
populate: func(_ context.Context, p *planner, _ string, addRow func(...parser.Datum) error) error {
// Enum types are not currently supported.
return nil
},
}
// See: https://www.postgresql.org/docs/9.6/static/catalog-pg-extension.html.
var pgCatalogExtensionTable = virtualSchemaTable{
schema: `
CREATE TABLE pg_catalog.pg_extension (
extname NAME,
extowner OID,
extnamespace OID,
extrelocatable BOOL,
extversion STRING,
extconfig STRING,
extcondition STRING
);
`,
populate: func(_ context.Context, p *planner, _ string, addRow func(...parser.Datum) error) error {
// Extensions are not supported.
return nil
},
}
// See: https://www.postgresql.org/docs/9.6/static/catalog-pg-foreign-server.html.
var pgCatalogForeignServerTable = virtualSchemaTable{
schema: `
CREATE TABLE pg_catalog.pg_foreign_server (
oid OID,
srvname NAME,
srvowner OID,
srvfdw OID,
srvtype STRING,
srvversion STRING,
srvacl STRING,
srvoptions STRING
);
`,
populate: func(_ context.Context, p *planner, _ string, addRow func(...parser.Datum) error) error {
// Foreign servers are not supported.
return nil
},
}
// See: https://www.postgresql.org/docs/9.6/static/catalog-pg-foreign-table.html.
var pgCatalogForeignTableTable = virtualSchemaTable{
schema: `
CREATE TABLE pg_catalog.pg_foreign_table (
ftrelid OID,
ftserver OID,
ftoptions STRING
);
`,
populate: func(_ context.Context, p *planner, _ string, addRow func(...parser.Datum) error) error {
// Foreign tables are not supported.
return nil
},
}
// See: https://www.postgresql.org/docs/9.6/static/catalog-pg-index.html.
var pgCatalogIndexTable = virtualSchemaTable{
schema: `
CREATE TABLE pg_catalog.pg_index (
indexrelid OID,
indrelid OID,
indnatts INT,
indisunique BOOL,
indisprimary BOOL,
indisexclusion BOOL,
indimmediate BOOL,
indisclustered BOOL,
indisvalid BOOL,
indcheckxmin BOOL,
indisready BOOL,
indislive BOOL,
indisreplident BOOL,
indkey INT2VECTOR,
indcollation INT,
indclass INT,
indoption INT,
indexprs STRING,
indpred STRING
);
`,
populate: func(ctx context.Context, p *planner, prefix string, addRow func(...parser.Datum) error) error {
h := makeOidHasher()
return forEachTableDesc(ctx, p, prefix, func(db *sqlbase.DatabaseDescriptor, table *sqlbase.TableDescriptor) error {
tableOid := h.TableOid(db, table)
return forEachIndexInTable(table, func(index *sqlbase.IndexDescriptor) error {
isMutation, isWriteOnly :=
table.GetIndexMutationCapabilities(index.ID)
isReady := isMutation && isWriteOnly
indkey, err := colIDArrayToVector(index.ColumnIDs)
if err != nil {
return err
}
return addRow(
h.IndexOid(db, table, index), // indexrelid
tableOid, // indrelid
parser.NewDInt(parser.DInt(len(index.ColumnNames))), // indnatts
parser.MakeDBool(parser.DBool(index.Unique)), // indisunique
parser.MakeDBool(parser.DBool(table.IsPhysicalTable() && index.ID == table.PrimaryIndex.ID)), // indisprimary
parser.MakeDBool(false), // indisexclusion
parser.MakeDBool(parser.DBool(index.Unique)), // indimmediate
parser.MakeDBool(false), // indisclustered
parser.MakeDBool(parser.DBool(!isMutation)), // indisvalid
parser.MakeDBool(false), // indcheckxmin
parser.MakeDBool(parser.DBool(isReady)), // indisready
parser.MakeDBool(true), // indislive
parser.MakeDBool(false), // indisreplident
indkey, // indkey
zeroVal, // indcollation
zeroVal, // indclass
zeroVal, // indoption
parser.DNull, // indexprs
parser.DNull, // indpred
)
})
})
},
}
// See: https://www.postgresql.org/docs/9.6/static/view-pg-indexes.html.
//
// Note that crdb_oid is an extension of the schema to much more easily map
// index OIDs to the corresponding index definition.
var pgCatalogIndexesTable = virtualSchemaTable{
schema: `
CREATE TABLE pg_catalog.pg_indexes (
crdb_oid OID,
schemaname NAME,
tablename NAME,
indexname NAME,
tablespace NAME,
indexdef STRING
);
`,
populate: func(ctx context.Context, p *planner, prefix string, addRow func(...parser.Datum) error) error {
h := makeOidHasher()
return forEachTableDesc(ctx, p, prefix, func(db *sqlbase.DatabaseDescriptor, table *sqlbase.TableDescriptor) error {
return forEachIndexInTable(table, func(index *sqlbase.IndexDescriptor) error {
def, err := indexDefFromDescriptor(ctx, p, db, table, index)
if err != nil {
return err
}
return addRow(
h.IndexOid(db, table, index), // oid
pgNamespaceForDB(db, h).NameStr, // schemaname
parser.NewDName(table.Name), // tablename
parser.NewDName(index.Name), // indexname
parser.DNull, // tablespace
parser.NewDString(def), // indexdef
)
})
})
},
}
// indexDefFromDescriptor creates an index definition (`CREATE INDEX ... ON (...)`) from
// and index descriptor by reconstructing a CreateIndex parser node and calling its
// String method.
func indexDefFromDescriptor(
ctx context.Context,
p *planner,
db *sqlbase.DatabaseDescriptor,
table *sqlbase.TableDescriptor,
index *sqlbase.IndexDescriptor,
) (string, error) {
indexDef := parser.CreateIndex{
Name: parser.Name(index.Name),
Table: parser.NormalizableTableName{
TableNameReference: &parser.TableName{
DatabaseName: parser.Name(db.Name),
TableName: parser.Name(table.Name),
},
},
Unique: index.Unique,
Columns: make(parser.IndexElemList, len(index.ColumnNames)),
Storing: make(parser.NameList, len(index.StoreColumnNames)),
}
for i, name := range index.ColumnNames {
elem := parser.IndexElem{
Column: parser.Name(name),
Direction: parser.Ascending,
}
if index.ColumnDirections[i] == sqlbase.IndexDescriptor_DESC {
elem.Direction = parser.Descending
}
indexDef.Columns[i] = elem
}
for i, name := range index.StoreColumnNames {
indexDef.Storing[i] = parser.Name(name)
}
if len(index.Interleave.Ancestors) > 0 {
intl := index.Interleave
parentTable, err := sqlbase.GetTableDescFromID(ctx, p.txn, intl.Ancestors[len(intl.Ancestors)-1].TableID)
if err != nil {
return "", err
}
parentDb, err := sqlbase.GetDatabaseDescFromID(ctx, p.txn, parentTable.ParentID)
if err != nil {
return "", err
}
var sharedPrefixLen int
for _, ancestor := range intl.Ancestors {
sharedPrefixLen += int(ancestor.SharedPrefixLen)
}
fields := index.ColumnNames[:sharedPrefixLen]
intlDef := &parser.InterleaveDef{
Parent: &parser.NormalizableTableName{
TableNameReference: &parser.TableName{
DatabaseName: parser.Name(parentDb.Name),
TableName: parser.Name(parentTable.Name),
},
},
Fields: make(parser.NameList, len(fields)),
}
for i, field := range fields {
intlDef.Fields[i] = parser.Name(field)
}
indexDef.Interleave = intlDef
}
return indexDef.String(), nil
}
// See: https://www.postgresql.org/docs/9.6/static/catalog-pg-inherits.html.
var pgCatalogInheritsTable = virtualSchemaTable{
schema: `
CREATE TABLE pg_catalog.pg_inherits (
inhrelid OID,
inhparent OID,
inhseqno INT
);
`,
populate: func(_ context.Context, p *planner, _ string, addRow func(...parser.Datum) error) error {
// Table inheritance is not supported.
return nil
},
}
// See: https://www.postgresql.org/docs/9.6/static/catalog-pg-namespace.html.
var pgCatalogNamespaceTable = virtualSchemaTable{
schema: `
CREATE TABLE pg_catalog.pg_namespace (