-
Notifications
You must be signed in to change notification settings - Fork 3.8k
/
information_schema.go
executable file
·2714 lines (2538 loc) · 105 KB
/
information_schema.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 (
"context"
"fmt"
"sort"
"strconv"
"strings"
"time"
"unicode/utf8"
"github.com/cockroachdb/cockroach/pkg/clusterversion"
"github.com/cockroachdb/cockroach/pkg/docs"
"github.com/cockroachdb/cockroach/pkg/keys"
"github.com/cockroachdb/cockroach/pkg/kv"
"github.com/cockroachdb/cockroach/pkg/security"
"github.com/cockroachdb/cockroach/pkg/sql/catalog"
"github.com/cockroachdb/cockroach/pkg/sql/catalog/catconstants"
"github.com/cockroachdb/cockroach/pkg/sql/catalog/catpb"
"github.com/cockroachdb/cockroach/pkg/sql/catalog/descpb"
"github.com/cockroachdb/cockroach/pkg/sql/catalog/nstree"
"github.com/cockroachdb/cockroach/pkg/sql/catalog/schemadesc"
"github.com/cockroachdb/cockroach/pkg/sql/catalog/schemaexpr"
"github.com/cockroachdb/cockroach/pkg/sql/catalog/tabledesc"
"github.com/cockroachdb/cockroach/pkg/sql/privilege"
"github.com/cockroachdb/cockroach/pkg/sql/sem/tree"
"github.com/cockroachdb/cockroach/pkg/sql/sqlutil"
"github.com/cockroachdb/cockroach/pkg/sql/types"
"github.com/cockroachdb/cockroach/pkg/sql/vtable"
"github.com/cockroachdb/cockroach/pkg/util/timeutil/pgdate"
"github.com/cockroachdb/errors"
"github.com/lib/pq/oid"
"golang.org/x/text/collate"
)
const (
pgCatalogName = catconstants.PgCatalogName
)
var pgCatalogNameDString = tree.NewDString(pgCatalogName)
// informationSchema lists all the table definitions for
// information_schema.
var informationSchema = virtualSchema{
name: catconstants.InformationSchemaName,
undefinedTables: buildStringSet(
// Generated with:
// select distinct '"'||table_name||'",' from information_schema.tables
// where table_schema='information_schema' order by table_name;
"_pg_foreign_data_wrappers",
"_pg_foreign_servers",
"_pg_foreign_table_columns",
"_pg_foreign_tables",
"_pg_user_mappings",
"sql_languages",
"sql_packages",
"sql_sizing_profiles",
),
tableDefs: map[descpb.ID]virtualSchemaDef{
catconstants.InformationSchemaAdministrableRoleAuthorizationsID: informationSchemaAdministrableRoleAuthorizations,
catconstants.InformationSchemaApplicableRolesID: informationSchemaApplicableRoles,
catconstants.InformationSchemaAttributesTableID: informationSchemaAttributesTable,
catconstants.InformationSchemaCharacterSets: informationSchemaCharacterSets,
catconstants.InformationSchemaCheckConstraintRoutineUsageTableID: informationSchemaCheckConstraintRoutineUsageTable,
catconstants.InformationSchemaCheckConstraints: informationSchemaCheckConstraints,
catconstants.InformationSchemaCollationCharacterSetApplicability: informationSchemaCollationCharacterSetApplicability,
catconstants.InformationSchemaCollations: informationSchemaCollations,
catconstants.InformationSchemaColumnColumnUsageTableID: informationSchemaColumnColumnUsageTable,
catconstants.InformationSchemaColumnDomainUsageTableID: informationSchemaColumnDomainUsageTable,
catconstants.InformationSchemaColumnOptionsTableID: informationSchemaColumnOptionsTable,
catconstants.InformationSchemaColumnPrivilegesID: informationSchemaColumnPrivileges,
catconstants.InformationSchemaColumnStatisticsTableID: informationSchemaColumnStatisticsTable,
catconstants.InformationSchemaColumnUDTUsageID: informationSchemaColumnUDTUsage,
catconstants.InformationSchemaColumnsExtensionsTableID: informationSchemaColumnsExtensionsTable,
catconstants.InformationSchemaColumnsTableID: informationSchemaColumnsTable,
catconstants.InformationSchemaConstraintColumnUsageTableID: informationSchemaConstraintColumnUsageTable,
catconstants.InformationSchemaConstraintTableUsageTableID: informationSchemaConstraintTableUsageTable,
catconstants.InformationSchemaDataTypePrivilegesTableID: informationSchemaDataTypePrivilegesTable,
catconstants.InformationSchemaDomainConstraintsTableID: informationSchemaDomainConstraintsTable,
catconstants.InformationSchemaDomainUdtUsageTableID: informationSchemaDomainUdtUsageTable,
catconstants.InformationSchemaDomainsTableID: informationSchemaDomainsTable,
catconstants.InformationSchemaElementTypesTableID: informationSchemaElementTypesTable,
catconstants.InformationSchemaEnabledRolesID: informationSchemaEnabledRoles,
catconstants.InformationSchemaEnginesTableID: informationSchemaEnginesTable,
catconstants.InformationSchemaEventsTableID: informationSchemaEventsTable,
catconstants.InformationSchemaFilesTableID: informationSchemaFilesTable,
catconstants.InformationSchemaForeignDataWrapperOptionsTableID: informationSchemaForeignDataWrapperOptionsTable,
catconstants.InformationSchemaForeignDataWrappersTableID: informationSchemaForeignDataWrappersTable,
catconstants.InformationSchemaForeignServerOptionsTableID: informationSchemaForeignServerOptionsTable,
catconstants.InformationSchemaForeignServersTableID: informationSchemaForeignServersTable,
catconstants.InformationSchemaForeignTableOptionsTableID: informationSchemaForeignTableOptionsTable,
catconstants.InformationSchemaForeignTablesTableID: informationSchemaForeignTablesTable,
catconstants.InformationSchemaInformationSchemaCatalogNameTableID: informationSchemaInformationSchemaCatalogNameTable,
catconstants.InformationSchemaKeyColumnUsageTableID: informationSchemaKeyColumnUsageTable,
catconstants.InformationSchemaKeywordsTableID: informationSchemaKeywordsTable,
catconstants.InformationSchemaOptimizerTraceTableID: informationSchemaOptimizerTraceTable,
catconstants.InformationSchemaParametersTableID: informationSchemaParametersTable,
catconstants.InformationSchemaPartitionsTableID: informationSchemaPartitionsTable,
catconstants.InformationSchemaPluginsTableID: informationSchemaPluginsTable,
catconstants.InformationSchemaProcesslistTableID: informationSchemaProcesslistTable,
catconstants.InformationSchemaProfilingTableID: informationSchemaProfilingTable,
catconstants.InformationSchemaReferentialConstraintsTableID: informationSchemaReferentialConstraintsTable,
catconstants.InformationSchemaResourceGroupsTableID: informationSchemaResourceGroupsTable,
catconstants.InformationSchemaRoleColumnGrantsTableID: informationSchemaRoleColumnGrantsTable,
catconstants.InformationSchemaRoleRoutineGrantsTableID: informationSchemaRoleRoutineGrantsTable,
catconstants.InformationSchemaRoleTableGrantsID: informationSchemaRoleTableGrants,
catconstants.InformationSchemaRoleUdtGrantsTableID: informationSchemaRoleUdtGrantsTable,
catconstants.InformationSchemaRoleUsageGrantsTableID: informationSchemaRoleUsageGrantsTable,
catconstants.InformationSchemaRoutinePrivilegesTableID: informationSchemaRoutinePrivilegesTable,
catconstants.InformationSchemaRoutineTableID: informationSchemaRoutineTable,
catconstants.InformationSchemaSQLFeaturesTableID: informationSchemaSQLFeaturesTable,
catconstants.InformationSchemaSQLImplementationInfoTableID: informationSchemaSQLImplementationInfoTable,
catconstants.InformationSchemaSQLPartsTableID: informationSchemaSQLPartsTable,
catconstants.InformationSchemaSQLSizingTableID: informationSchemaSQLSizingTable,
catconstants.InformationSchemaSchemataExtensionsTableID: informationSchemaSchemataExtensionsTable,
catconstants.InformationSchemaSchemataTableID: informationSchemaSchemataTable,
catconstants.InformationSchemaSchemataTablePrivilegesID: informationSchemaSchemataTablePrivileges,
catconstants.InformationSchemaSequencesID: informationSchemaSequences,
catconstants.InformationSchemaSessionVariables: informationSchemaSessionVariables,
catconstants.InformationSchemaStGeometryColumnsTableID: informationSchemaStGeometryColumnsTable,
catconstants.InformationSchemaStSpatialReferenceSystemsTableID: informationSchemaStSpatialReferenceSystemsTable,
catconstants.InformationSchemaStUnitsOfMeasureTableID: informationSchemaStUnitsOfMeasureTable,
catconstants.InformationSchemaStatisticsTableID: informationSchemaStatisticsTable,
catconstants.InformationSchemaTableConstraintTableID: informationSchemaTableConstraintTable,
catconstants.InformationSchemaTableConstraintsExtensionsTableID: informationSchemaTableConstraintsExtensionsTable,
catconstants.InformationSchemaTablePrivilegesID: informationSchemaTablePrivileges,
catconstants.InformationSchemaTablesExtensionsTableID: informationSchemaTablesExtensionsTable,
catconstants.InformationSchemaTablesTableID: informationSchemaTablesTable,
catconstants.InformationSchemaTablespacesExtensionsTableID: informationSchemaTablespacesExtensionsTable,
catconstants.InformationSchemaTablespacesTableID: informationSchemaTablespacesTable,
catconstants.InformationSchemaTransformsTableID: informationSchemaTransformsTable,
catconstants.InformationSchemaTriggeredUpdateColumnsTableID: informationSchemaTriggeredUpdateColumnsTable,
catconstants.InformationSchemaTriggersTableID: informationSchemaTriggersTable,
catconstants.InformationSchemaTypePrivilegesID: informationSchemaTypePrivilegesTable,
catconstants.InformationSchemaUdtPrivilegesTableID: informationSchemaUdtPrivilegesTable,
catconstants.InformationSchemaUsagePrivilegesTableID: informationSchemaUsagePrivilegesTable,
catconstants.InformationSchemaUserAttributesTableID: informationSchemaUserAttributesTable,
catconstants.InformationSchemaUserDefinedTypesTableID: informationSchemaUserDefinedTypesTable,
catconstants.InformationSchemaUserMappingOptionsTableID: informationSchemaUserMappingOptionsTable,
catconstants.InformationSchemaUserMappingsTableID: informationSchemaUserMappingsTable,
catconstants.InformationSchemaUserPrivilegesID: informationSchemaUserPrivileges,
catconstants.InformationSchemaViewColumnUsageTableID: informationSchemaViewColumnUsageTable,
catconstants.InformationSchemaViewRoutineUsageTableID: informationSchemaViewRoutineUsageTable,
catconstants.InformationSchemaViewTableUsageTableID: informationSchemaViewTableUsageTable,
catconstants.InformationSchemaViewsTableID: informationSchemaViewsTable,
},
tableValidator: validateInformationSchemaTable,
validWithNoDatabaseContext: true,
}
func buildStringSet(ss ...string) map[string]struct{} {
m := map[string]struct{}{}
for _, s := range ss {
m[s] = struct{}{}
}
return m
}
var (
emptyString = tree.NewDString("")
// information_schema was defined before the BOOLEAN data type was added to
// the SQL specification. Because of this, boolean values are represented as
// STRINGs. The BOOLEAN data type should NEVER be used in information_schema
// tables. Instead, define columns as STRINGs and map bools to STRINGs using
// yesOrNoDatum.
yesString = tree.NewDString("YES")
noString = tree.NewDString("NO")
)
func yesOrNoDatum(b bool) tree.Datum {
if b {
return yesString
}
return noString
}
func dNameOrNull(s string) tree.Datum {
if s == "" {
return tree.DNull
}
return tree.NewDName(s)
}
func dIntFnOrNull(fn func() (int32, bool)) tree.Datum {
if n, ok := fn(); ok {
return tree.NewDInt(tree.DInt(n))
}
return tree.DNull
}
func validateInformationSchemaTable(table *descpb.TableDescriptor) error {
// Make sure no tables have boolean columns.
for i := range table.Columns {
if table.Columns[i].Type.Family() == types.BoolFamily {
return errors.Errorf("information_schema tables should never use BOOL columns. "+
"See the comment about yesOrNoDatum. Found BOOL column in %s.", table.Name)
}
}
return nil
}
var informationSchemaAdministrableRoleAuthorizations = virtualSchemaTable{
comment: `roles for which the current user has admin option
` + docs.URL("information-schema.html#administrable_role_authorizations") + `
https://www.postgresql.org/docs/9.5/infoschema-administrable-role-authorizations.html`,
schema: vtable.InformationSchemaAdministrableRoleAuthorizations,
populate: func(
ctx context.Context, p *planner, _ catalog.DatabaseDescriptor, addRow func(...tree.Datum) error,
) error {
return populateRoleHierarchy(ctx, p, addRow, true /* onlyIsAdmin */)
},
}
var informationSchemaApplicableRoles = virtualSchemaTable{
comment: `roles available to the current user
` + docs.URL("information-schema.html#applicable_roles") + `
https://www.postgresql.org/docs/9.5/infoschema-applicable-roles.html`,
schema: vtable.InformationSchemaApplicableRoles,
populate: func(
ctx context.Context, p *planner, _ catalog.DatabaseDescriptor, addRow func(...tree.Datum) error,
) error {
return populateRoleHierarchy(ctx, p, addRow, false /* onlyIsAdmin */)
},
}
func populateRoleHierarchy(
ctx context.Context, p *planner, addRow func(...tree.Datum) error, onlyIsAdmin bool,
) error {
allRoles, err := p.MemberOfWithAdminOption(ctx, p.User())
if err != nil {
return err
}
return forEachRoleMembership(
ctx, p.ExecCfg().InternalExecutor, p.Txn(),
func(role, member security.SQLUsername, isAdmin bool) error {
// The ADMIN OPTION is inherited through the role hierarchy, and grantee
// is supposed to be the role that has the ADMIN OPTION. The current user
// inherits all the ADMIN OPTIONs of its ancestors.
isRole := member == p.User()
_, hasRole := allRoles[member]
if (hasRole || isRole) && (!onlyIsAdmin || isAdmin) {
if err := addRow(
tree.NewDString(member.Normalized()), // grantee
tree.NewDString(role.Normalized()), // role_name
yesOrNoDatum(isAdmin), // is_grantable
); err != nil {
return err
}
}
return nil
},
)
}
var informationSchemaCharacterSets = virtualSchemaTable{
comment: `character sets available in the current database
` + docs.URL("information-schema.html#character_sets") + `
https://www.postgresql.org/docs/9.5/infoschema-character-sets.html`,
schema: vtable.InformationSchemaCharacterSets,
populate: func(ctx context.Context, p *planner, dbContext catalog.DatabaseDescriptor, addRow func(...tree.Datum) error) error {
return forEachDatabaseDesc(ctx, p, nil /* all databases */, true, /* requiresPrivileges */
func(db catalog.DatabaseDescriptor) error {
return addRow(
tree.DNull, // character_set_catalog
tree.DNull, // character_set_schema
tree.NewDString("UTF8"), // character_set_name: UTF8 is the only available encoding
tree.NewDString("UCS"), // character_repertoire: UCS for UTF8 encoding
tree.NewDString("UTF8"), // form_of_use: same as the database encoding
tree.NewDString(db.GetName()), // default_collate_catalog
tree.DNull, // default_collate_schema
tree.DNull, // default_collate_name
)
})
},
}
var informationSchemaCheckConstraints = virtualSchemaTable{
comment: `check constraints
` + docs.URL("information-schema.html#check_constraints") + `
https://www.postgresql.org/docs/9.5/infoschema-check-constraints.html`,
schema: vtable.InformationSchemaCheckConstraints,
populate: func(ctx context.Context, p *planner, dbContext catalog.DatabaseDescriptor, addRow func(...tree.Datum) error) error {
h := makeOidHasher()
return forEachTableDescWithTableLookup(ctx, p, dbContext, hideVirtual /* no constraints in virtual tables */, func(
db catalog.DatabaseDescriptor,
scName string,
table catalog.TableDescriptor,
tableLookup tableLookupFn,
) error {
conInfo, err := table.GetConstraintInfoWithLookup(tableLookup.getTableByID)
if err != nil {
return err
}
dbNameStr := tree.NewDString(db.GetName())
scNameStr := tree.NewDString(scName)
for conName, con := range conInfo {
// Only Check constraints are included.
if con.Kind != descpb.ConstraintTypeCheck {
continue
}
conNameStr := tree.NewDString(conName)
// Like with pg_catalog.pg_constraint, Postgres wraps the check
// constraint expression in two pairs of parentheses.
chkExprStr := tree.NewDString(fmt.Sprintf("((%s))", con.Details))
if err := addRow(
dbNameStr, // constraint_catalog
scNameStr, // constraint_schema
conNameStr, // constraint_name
chkExprStr, // check_clause
); err != nil {
return err
}
}
// Unlike with pg_catalog.pg_constraint, Postgres also includes NOT
// NULL column constraints in information_schema.check_constraints.
// Cockroach doesn't track these constraints as check constraints,
// but we can pull them off of the table's column descriptors.
for _, column := range table.PublicColumns() {
// Only visible, non-nullable columns are included.
if column.IsHidden() || column.IsNullable() {
continue
}
// Generate a unique name for each NOT NULL constraint. Postgres
// uses the format <namespace_oid>_<table_oid>_<col_idx>_not_null.
// We might as well do the same.
conNameStr := tree.NewDString(fmt.Sprintf(
"%s_%s_%d_not_null", h.NamespaceOid(db.GetID(), scName), tableOid(table.GetID()), column.Ordinal()+1,
))
chkExprStr := tree.NewDString(fmt.Sprintf(
"%s IS NOT NULL", column.GetName(),
))
if err := addRow(
dbNameStr, // constraint_catalog
scNameStr, // constraint_schema
conNameStr, // constraint_name
chkExprStr, // check_clause
); err != nil {
return err
}
}
return nil
})
},
}
var informationSchemaColumnPrivileges = virtualSchemaTable{
comment: `column privilege grants (incomplete)
` + docs.URL("information-schema.html#column_privileges") + `
https://www.postgresql.org/docs/9.5/infoschema-column-privileges.html`,
schema: vtable.InformationSchemaColumnPrivileges,
populate: func(ctx context.Context, p *planner, dbContext catalog.DatabaseDescriptor, addRow func(...tree.Datum) error) error {
return forEachTableDesc(ctx, p, dbContext, virtualMany, func(
db catalog.DatabaseDescriptor, scName string, table catalog.TableDescriptor,
) error {
dbNameStr := tree.NewDString(db.GetName())
scNameStr := tree.NewDString(scName)
columndata := privilege.List{privilege.SELECT, privilege.INSERT, privilege.UPDATE} // privileges for column level granularity
for _, u := range table.GetPrivileges().Users {
for _, priv := range columndata {
if priv.Mask()&u.Privileges != 0 {
for _, cd := range table.PublicColumns() {
if err := addRow(
tree.DNull, // grantor
tree.NewDString(u.User().Normalized()), // grantee
dbNameStr, // table_catalog
scNameStr, // table_schema
tree.NewDString(table.GetName()), // table_name
tree.NewDString(cd.GetName()), // column_name
tree.NewDString(priv.String()), // privilege_type
tree.DNull, // is_grantable
); err != nil {
return err
}
}
}
}
}
return nil
})
},
}
var informationSchemaColumnsTable = virtualSchemaTable{
comment: `table and view columns (incomplete)
` + docs.URL("information-schema.html#columns") + `
https://www.postgresql.org/docs/9.5/infoschema-columns.html`,
schema: vtable.InformationSchemaColumns,
populate: func(ctx context.Context, p *planner, dbContext catalog.DatabaseDescriptor, addRow func(...tree.Datum) error) error {
// Get the collations for all comments of current database.
comments, err := getComments(ctx, p)
if err != nil {
return err
}
// Push all comments of columns into map.
commentMap := make(map[tree.DInt]map[tree.DInt]string)
for _, comment := range comments {
objID := tree.MustBeDInt(comment[0])
objSubID := tree.MustBeDInt(comment[1])
description := comment[2].String()
commentType := tree.MustBeDInt(comment[3])
if commentType == 2 {
if commentMap[objID] == nil {
commentMap[objID] = make(map[tree.DInt]string)
}
commentMap[objID][objSubID] = description
}
}
return forEachTableDesc(ctx, p, dbContext, virtualMany, func(
db catalog.DatabaseDescriptor, scName string, table catalog.TableDescriptor,
) error {
dbNameStr := tree.NewDString(db.GetName())
scNameStr := tree.NewDString(scName)
for _, column := range table.AccessibleColumns() {
collationCatalog := tree.DNull
collationSchema := tree.DNull
collationName := tree.DNull
if locale := column.GetType().Locale(); locale != "" {
collationCatalog = dbNameStr
collationSchema = pgCatalogNameDString
collationName = tree.NewDString(locale)
}
colDefault := tree.DNull
if column.HasDefault() {
colExpr, err := schemaexpr.FormatExprForDisplay(
ctx, table, column.GetDefaultExpr(), &p.semaCtx, p.SessionData(), tree.FmtParsable,
)
if err != nil {
return err
}
colDefault = tree.NewDString(colExpr)
}
colComputed := emptyString
if column.IsComputed() {
colExpr, err := schemaexpr.FormatExprForDisplay(
ctx, table, column.GetComputeExpr(), &p.semaCtx, p.SessionData(), tree.FmtSimple,
)
if err != nil {
return err
}
colComputed = tree.NewDString(colExpr)
}
colGeneratedAsIdentity := emptyString
if column.IsGeneratedAsIdentity() {
if column.IsGeneratedAlwaysAsIdentity() {
colGeneratedAsIdentity = tree.NewDString("ALWAYS")
} else if column.IsGeneratedByDefaultAsIdentity() {
colGeneratedAsIdentity = tree.NewDString("BY DEFAULT")
} else {
return errors.AssertionFailedf(
"column %s is of wrong generated as identity type (neither ALWAYS nor BY DEFAULT)",
column.GetName(),
)
}
}
// Match the comment belonging to current column from map,using table id and column id
tableID := tree.DInt(table.GetID())
columnID := tree.DInt(column.GetID())
description := commentMap[tableID][columnID]
// udt_schema is set to pg_catalog for builtin types. If, however, the
// type is a user defined type, then we should fill this value based on
// the schema it is under.
udtSchema := pgCatalogNameDString
typeMetaName := column.GetType().TypeMeta.Name
if typeMetaName != nil {
udtSchema = tree.NewDString(typeMetaName.Schema)
}
err := addRow(
dbNameStr, // table_catalog
scNameStr, // table_schema
tree.NewDString(table.GetName()), // table_name
tree.NewDString(column.GetName()), // column_name
tree.NewDString(description), // column_comment
tree.NewDInt(tree.DInt(column.GetPGAttributeNum())), // ordinal_position
colDefault, // column_default
yesOrNoDatum(column.IsNullable()), // is_nullable
tree.NewDString(column.GetType().InformationSchemaName()), // data_type
characterMaximumLength(column.GetType()), // character_maximum_length
characterOctetLength(column.GetType()), // character_octet_length
numericPrecision(column.GetType()), // numeric_precision
numericPrecisionRadix(column.GetType()), // numeric_precision_radix
numericScale(column.GetType()), // numeric_scale
datetimePrecision(column.GetType()), // datetime_precision
tree.DNull, // interval_type
tree.DNull, // interval_precision
tree.DNull, // character_set_catalog
tree.DNull, // character_set_schema
tree.DNull, // character_set_name
collationCatalog, // collation_catalog
collationSchema, // collation_schema
collationName, // collation_name
tree.DNull, // domain_catalog
tree.DNull, // domain_schema
tree.DNull, // domain_name
dbNameStr, // udt_catalog
udtSchema, // udt_schema
tree.NewDString(column.GetType().PGName()), // udt_name
tree.DNull, // scope_catalog
tree.DNull, // scope_schema
tree.DNull, // scope_name
tree.DNull, // maximum_cardinality
tree.DNull, // dtd_identifier
tree.DNull, // is_self_referencing
yesOrNoDatum(column.IsGeneratedAsIdentity()), // is_identity
colGeneratedAsIdentity, // identity_generation
// TODO(janexing): parse the GeneratedAsIdentitySequenceOption to
// fill out these "identity_x" columns.
tree.DNull, // identity_start
tree.DNull, // identity_increment
tree.DNull, // identity_maximum
tree.DNull, // identity_minimum
tree.DNull, // identity_cycle
yesOrNoDatum(column.IsComputed()), // is_generated
colComputed, // generation_expression
yesOrNoDatum(table.IsTable() &&
!table.IsVirtualTable() &&
!column.IsComputed(),
), // is_updatable
yesOrNoDatum(column.IsHidden()), // is_hidden
tree.NewDString(column.GetType().SQLString()), // crdb_sql_type
)
if err != nil {
return err
}
}
return nil
})
},
}
var informationSchemaColumnUDTUsage = virtualSchemaTable{
comment: `columns with user defined types
` + docs.URL("information-schema.html#column_udt_usage") + `
https://www.postgresql.org/docs/current/infoschema-column-udt-usage.html`,
schema: vtable.InformationSchemaColumnUDTUsage,
populate: func(ctx context.Context, p *planner, dbContext catalog.DatabaseDescriptor, addRow func(...tree.Datum) error) error {
return forEachTableDesc(ctx, p, dbContext, hideVirtual,
func(db catalog.DatabaseDescriptor, scName string, table catalog.TableDescriptor) error {
dbNameStr := tree.NewDString(db.GetName())
scNameStr := tree.NewDString(scName)
tbNameStr := tree.NewDString(table.GetName())
for _, col := range table.PublicColumns() {
if !col.GetType().UserDefined() {
continue
}
if err := addRow(
tree.NewDString(col.GetType().TypeMeta.Name.Catalog), // UDT_CATALOG
tree.NewDString(col.GetType().TypeMeta.Name.Schema), // UDT_SCHEMA
tree.NewDString(col.GetType().TypeMeta.Name.Name), // UDT_NAME
dbNameStr, // TABLE_CATALOG
scNameStr, // TABLE_SCHEMA
tbNameStr, // TABLE_NAME
tree.NewDString(col.GetName()), // COLUMN_NAME
); err != nil {
return err
}
}
return nil
},
)
},
}
var informationSchemaEnabledRoles = virtualSchemaTable{
comment: `roles for the current user
` + docs.URL("information-schema.html#enabled_roles") + `
https://www.postgresql.org/docs/9.5/infoschema-enabled-roles.html`,
schema: vtable.InformationSchemaEnabledRoles,
populate: func(ctx context.Context, p *planner, _ catalog.DatabaseDescriptor, addRow func(...tree.Datum) error) error {
currentUser := p.SessionData().User()
memberMap, err := p.MemberOfWithAdminOption(ctx, currentUser)
if err != nil {
return err
}
// The current user is always listed.
if err := addRow(
tree.NewDString(currentUser.Normalized()), // role_name: the current user
); err != nil {
return err
}
for roleName := range memberMap {
if err := addRow(
tree.NewDString(roleName.Normalized()), // role_name
); err != nil {
return err
}
}
return nil
},
}
// characterMaximumLength returns the declared maximum length of
// characters if the type is a character or bit string data
// type. Returns false if the data type is not a character or bit
// string, or if the string's length is not bounded.
func characterMaximumLength(colType *types.T) tree.Datum {
return dIntFnOrNull(func() (int32, bool) {
// "char" columns have a width of 1, but should report a NULL maximum
// character length.
if colType.Oid() == oid.T_char {
return 0, false
}
switch colType.Family() {
case types.StringFamily, types.CollatedStringFamily, types.BitFamily:
if colType.Width() > 0 {
return colType.Width(), true
}
}
return 0, false
})
}
// characterOctetLength returns the maximum possible length in
// octets of a datum if the T is a character string. Returns
// false if the data type is not a character string, or if the
// string's length is not bounded.
func characterOctetLength(colType *types.T) tree.Datum {
return dIntFnOrNull(func() (int32, bool) {
// "char" columns have a width of 1, but should report a NULL octet
// length.
if colType.Oid() == oid.T_char {
return 0, false
}
switch colType.Family() {
case types.StringFamily, types.CollatedStringFamily:
if colType.Width() > 0 {
return colType.Width() * utf8.UTFMax, true
}
}
return 0, false
})
}
// numericPrecision returns the declared or implicit precision of numeric
// data types. Returns false if the data type is not numeric, or if the precision
// of the numeric type is not bounded.
func numericPrecision(colType *types.T) tree.Datum {
return dIntFnOrNull(func() (int32, bool) {
switch colType.Family() {
case types.IntFamily:
return colType.Width(), true
case types.FloatFamily:
if colType.Width() == 32 {
return 24, true
}
return 53, true
case types.DecimalFamily:
if colType.Precision() > 0 {
return colType.Precision(), true
}
}
return 0, false
})
}
// numericPrecisionRadix returns the implicit precision radix of
// numeric data types. Returns false if the data type is not numeric.
func numericPrecisionRadix(colType *types.T) tree.Datum {
return dIntFnOrNull(func() (int32, bool) {
switch colType.Family() {
case types.IntFamily:
return 2, true
case types.FloatFamily:
return 2, true
case types.DecimalFamily:
return 10, true
}
return 0, false
})
}
// NumericScale returns the declared or implicit precision of exact numeric
// data types. Returns false if the data type is not an exact numeric, or if the
// scale of the exact numeric type is not bounded.
func numericScale(colType *types.T) tree.Datum {
return dIntFnOrNull(func() (int32, bool) {
switch colType.Family() {
case types.IntFamily:
return 0, true
case types.DecimalFamily:
if colType.Precision() > 0 {
return colType.Width(), true
}
}
return 0, false
})
}
// datetimePrecision returns the declared or implicit precision of Time,
// Timestamp or Interval data types. Returns false if the data type is not
// a Time, Timestamp or Interval.
func datetimePrecision(colType *types.T) tree.Datum {
return dIntFnOrNull(func() (int32, bool) {
switch colType.Family() {
case types.TimeFamily, types.TimeTZFamily, types.TimestampFamily, types.TimestampTZFamily, types.IntervalFamily:
return colType.Precision(), true
}
return 0, false
})
}
var informationSchemaConstraintColumnUsageTable = virtualSchemaTable{
comment: `columns usage by constraints
https://www.postgresql.org/docs/9.5/infoschema-constraint-column-usage.html`,
schema: vtable.InformationSchemaConstraintColumnUsage,
populate: func(ctx context.Context, p *planner, dbContext catalog.DatabaseDescriptor, addRow func(...tree.Datum) error) error {
return forEachTableDescWithTableLookup(ctx, p, dbContext, hideVirtual /* no constraints in virtual tables */, func(
db catalog.DatabaseDescriptor,
scName string,
table catalog.TableDescriptor,
tableLookup tableLookupFn,
) error {
conInfo, err := table.GetConstraintInfoWithLookup(tableLookup.getTableByID)
if err != nil {
return err
}
scNameStr := tree.NewDString(scName)
dbNameStr := tree.NewDString(db.GetName())
for conName, con := range conInfo {
conTable := table
conCols := con.Columns
conNameStr := tree.NewDString(conName)
if con.Kind == descpb.ConstraintTypeFK {
// For foreign key constraint, constraint_column_usage
// identifies the table/columns that the foreign key
// references.
conTable = tabledesc.NewBuilder(con.ReferencedTable).BuildImmutableTable()
conCols, err = conTable.NamesForColumnIDs(con.FK.ReferencedColumnIDs)
if err != nil {
return err
}
}
tableNameStr := tree.NewDString(conTable.GetName())
for _, col := range conCols {
if err := addRow(
dbNameStr, // table_catalog
scNameStr, // table_schema
tableNameStr, // table_name
tree.NewDString(col), // column_name
dbNameStr, // constraint_catalog
scNameStr, // constraint_schema
conNameStr, // constraint_name
); err != nil {
return err
}
}
}
return nil
})
},
}
// MySQL: https://dev.mysql.com/doc/refman/5.7/en/key-column-usage-table.html
var informationSchemaKeyColumnUsageTable = virtualSchemaTable{
comment: `column usage by indexes and key constraints
` + docs.URL("information-schema.html#key_column_usage") + `
https://www.postgresql.org/docs/9.5/infoschema-key-column-usage.html`,
schema: vtable.InformationSchemaKeyColumnUsage,
populate: func(ctx context.Context, p *planner, dbContext catalog.DatabaseDescriptor, addRow func(...tree.Datum) error) error {
return forEachTableDescWithTableLookup(ctx, p, dbContext, hideVirtual /* no constraints in virtual tables */, func(
db catalog.DatabaseDescriptor,
scName string,
table catalog.TableDescriptor,
tableLookup tableLookupFn,
) error {
conInfo, err := table.GetConstraintInfoWithLookup(tableLookup.getTableByID)
if err != nil {
return err
}
dbNameStr := tree.NewDString(db.GetName())
scNameStr := tree.NewDString(scName)
tbNameStr := tree.NewDString(table.GetName())
for conName, con := range conInfo {
// Only Primary Key, Foreign Key, and Unique constraints are included.
switch con.Kind {
case descpb.ConstraintTypePK:
case descpb.ConstraintTypeFK:
case descpb.ConstraintTypeUnique:
default:
continue
}
cstNameStr := tree.NewDString(conName)
for pos, col := range con.Columns {
ordinalPos := tree.NewDInt(tree.DInt(pos + 1))
uniquePos := tree.DNull
if con.Kind == descpb.ConstraintTypeFK {
uniquePos = ordinalPos
}
if err := addRow(
dbNameStr, // constraint_catalog
scNameStr, // constraint_schema
cstNameStr, // constraint_name
dbNameStr, // table_catalog
scNameStr, // table_schema
tbNameStr, // table_name
tree.NewDString(col), // column_name
ordinalPos, // ordinal_position, 1-indexed
uniquePos, // position_in_unique_constraint
); err != nil {
return err
}
}
}
return nil
})
},
}
// Postgres: https://www.postgresql.org/docs/9.6/static/infoschema-parameters.html
// MySQL: https://dev.mysql.com/doc/refman/5.7/en/parameters-table.html
var informationSchemaParametersTable = virtualSchemaTable{
comment: `built-in function parameters (empty - introspection not yet supported)
https://www.postgresql.org/docs/9.5/infoschema-parameters.html`,
schema: vtable.InformationSchemaParameters,
populate: func(ctx context.Context, p *planner, dbContext catalog.DatabaseDescriptor, addRow func(...tree.Datum) error) error {
return nil
},
unimplemented: true,
}
var (
matchOptionFull = tree.NewDString("FULL")
matchOptionPartial = tree.NewDString("PARTIAL")
matchOptionNone = tree.NewDString("NONE")
matchOptionMap = map[descpb.ForeignKeyReference_Match]tree.Datum{
descpb.ForeignKeyReference_SIMPLE: matchOptionNone,
descpb.ForeignKeyReference_FULL: matchOptionFull,
descpb.ForeignKeyReference_PARTIAL: matchOptionPartial,
}
refConstraintRuleNoAction = tree.NewDString("NO ACTION")
refConstraintRuleRestrict = tree.NewDString("RESTRICT")
refConstraintRuleSetNull = tree.NewDString("SET NULL")
refConstraintRuleSetDefault = tree.NewDString("SET DEFAULT")
refConstraintRuleCascade = tree.NewDString("CASCADE")
)
func dStringForFKAction(action catpb.ForeignKeyAction) tree.Datum {
switch action {
case catpb.ForeignKeyAction_NO_ACTION:
return refConstraintRuleNoAction
case catpb.ForeignKeyAction_RESTRICT:
return refConstraintRuleRestrict
case catpb.ForeignKeyAction_SET_NULL:
return refConstraintRuleSetNull
case catpb.ForeignKeyAction_SET_DEFAULT:
return refConstraintRuleSetDefault
case catpb.ForeignKeyAction_CASCADE:
return refConstraintRuleCascade
}
panic(errors.Errorf("unexpected ForeignKeyReference_Action: %v", action))
}
// MySQL: https://dev.mysql.com/doc/refman/5.7/en/referential-constraints-table.html
var informationSchemaReferentialConstraintsTable = virtualSchemaTable{
comment: `foreign key constraints
` + docs.URL("information-schema.html#referential_constraints") + `
https://www.postgresql.org/docs/9.5/infoschema-referential-constraints.html`,
schema: vtable.InformationSchemaReferentialConstraints,
populate: func(ctx context.Context, p *planner, dbContext catalog.DatabaseDescriptor, addRow func(...tree.Datum) error) error {
return forEachTableDescWithTableLookup(ctx, p, dbContext, hideVirtual /* no constraints in virtual tables */, func(
db catalog.DatabaseDescriptor,
scName string,
table catalog.TableDescriptor,
tableLookup tableLookupFn,
) error {
dbNameStr := tree.NewDString(db.GetName())
scNameStr := tree.NewDString(scName)
tbNameStr := tree.NewDString(table.GetName())
return table.ForeachOutboundFK(func(fk *descpb.ForeignKeyConstraint) error {
refTable, err := tableLookup.getTableByID(fk.ReferencedTableID)
if err != nil {
return err
}
var matchType = tree.DNull
if r, ok := matchOptionMap[fk.Match]; ok {
matchType = r
}
refConstraint, err := tabledesc.FindFKReferencedUniqueConstraint(
refTable, fk.ReferencedColumnIDs,
)
if err != nil {
return err
}
return addRow(
dbNameStr, // constraint_catalog
scNameStr, // constraint_schema
tree.NewDString(fk.Name), // constraint_name
dbNameStr, // unique_constraint_catalog
scNameStr, // unique_constraint_schema
tree.NewDString(refConstraint.GetName()), // unique_constraint_name
matchType, // match_option
dStringForFKAction(fk.OnUpdate), // update_rule
dStringForFKAction(fk.OnDelete), // delete_rule
tbNameStr, // table_name
tree.NewDString(refTable.GetName()), // referenced_table_name
)
})
})
},
}
// Postgres: https://www.postgresql.org/docs/9.6/static/infoschema-role-table-grants.html
// MySQL: missing
var informationSchemaRoleTableGrants = virtualSchemaTable{
comment: `privileges granted on table or views (incomplete; see also information_schema.table_privileges; may contain excess users or roles)
` + docs.URL("information-schema.html#role_table_grants") + `
https://www.postgresql.org/docs/9.5/infoschema-role-table-grants.html`,
schema: vtable.InformationSchemaRoleTableGrants,
// This is the same as information_schema.table_privileges. In postgres, this virtual table does
// not show tables with grants provided through PUBLIC, but table_privileges does.
// Since we don't have the PUBLIC concept, the two virtual tables are identical.
populate: populateTablePrivileges,
}
// MySQL: https://dev.mysql.com/doc/mysql-infoschema-excerpt/5.7/en/routines-table.html
var informationSchemaRoutineTable = virtualSchemaTable{
comment: `built-in functions (empty - introspection not yet supported)
https://www.postgresql.org/docs/9.5/infoschema-routines.html`,
schema: vtable.InformationSchemaRoutines,
populate: func(ctx context.Context, p *planner, dbContext catalog.DatabaseDescriptor, addRow func(...tree.Datum) error) error {
return nil
},
unimplemented: true,
}
// MySQL: https://dev.mysql.com/doc/refman/5.7/en/schemata-table.html
var informationSchemaSchemataTable = virtualSchemaTable{
comment: `database schemas (may contain schemata without permission)
` + docs.URL("information-schema.html#schemata") + `
https://www.postgresql.org/docs/9.5/infoschema-schemata.html`,
schema: vtable.InformationSchemaSchemata,
populate: func(ctx context.Context, p *planner, dbContext catalog.DatabaseDescriptor, addRow func(...tree.Datum) error) error {
return forEachDatabaseDesc(ctx, p, dbContext, true, /* requiresPrivileges */
func(db catalog.DatabaseDescriptor) error {
return forEachSchema(ctx, p, db, func(sc catalog.SchemaDescriptor) error {
return addRow(
tree.NewDString(db.GetName()), // catalog_name
tree.NewDString(sc.GetName()), // schema_name
tree.DNull, // default_character_set_name
tree.DNull, // sql_path
yesOrNoDatum(sc.SchemaKind() == catalog.SchemaUserDefined), // crdb_is_user_defined
)
})
})
},
}
var builtinTypePrivileges = []struct {
grantee *tree.DString
kind *tree.DString
}{
{tree.NewDString(security.RootUser), tree.NewDString(privilege.ALL.String())},
{tree.NewDString(security.AdminRole), tree.NewDString(privilege.ALL.String())},
{tree.NewDString(security.PublicRole), tree.NewDString(privilege.USAGE.String())},
}
// Custom; PostgreSQL has data_type_privileges, which only shows one row per type,
// which may result in confusing semantics for the user compared to this table
// which has one row for each grantee.
var informationSchemaTypePrivilegesTable = virtualSchemaTable{
comment: `type privileges (incomplete; may contain excess users or roles)
` + docs.URL("information-schema.html#type_privileges"),
schema: vtable.InformationSchemaTypePrivileges,
populate: func(ctx context.Context, p *planner, dbContext catalog.DatabaseDescriptor, addRow func(...tree.Datum) error) error {
return forEachDatabaseDesc(ctx, p, dbContext, true, /* requiresPrivileges */
func(db catalog.DatabaseDescriptor) error {
dbNameStr := tree.NewDString(db.GetName())
pgCatalogStr := tree.NewDString("pg_catalog")
populateGrantOption := p.ExecCfg().Settings.Version.IsActive(ctx, clusterversion.ValidateGrantOption)
var isGrantable tree.Datum
if populateGrantOption {
isGrantable = noString
} else {
isGrantable = tree.DNull
}
// Generate one for each existing type.
for _, typ := range types.OidToType {
typeNameStr := tree.NewDString(typ.Name())