-
Notifications
You must be signed in to change notification settings - Fork 3.9k
/
Copy pathopt_catalog.go
1973 lines (1693 loc) · 58.6 KB
/
opt_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 2018 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"
"math"
"time"
"github.com/cockroachdb/cockroach/pkg/config"
"github.com/cockroachdb/cockroach/pkg/config/zonepb"
"github.com/cockroachdb/cockroach/pkg/geo/geoindex"
"github.com/cockroachdb/cockroach/pkg/keys"
"github.com/cockroachdb/cockroach/pkg/kv"
"github.com/cockroachdb/cockroach/pkg/roachpb"
"github.com/cockroachdb/cockroach/pkg/sql/catalog"
"github.com/cockroachdb/cockroach/pkg/sql/catalog/catalogkv"
"github.com/cockroachdb/cockroach/pkg/sql/catalog/colinfo"
"github.com/cockroachdb/cockroach/pkg/sql/catalog/dbdesc"
"github.com/cockroachdb/cockroach/pkg/sql/catalog/descpb"
"github.com/cockroachdb/cockroach/pkg/sql/catalog/resolver"
"github.com/cockroachdb/cockroach/pkg/sql/catalog/tabledesc"
"github.com/cockroachdb/cockroach/pkg/sql/opt/cat"
"github.com/cockroachdb/cockroach/pkg/sql/pgwire/pgcode"
"github.com/cockroachdb/cockroach/pkg/sql/pgwire/pgerror"
"github.com/cockroachdb/cockroach/pkg/sql/privilege"
"github.com/cockroachdb/cockroach/pkg/sql/roleoption"
"github.com/cockroachdb/cockroach/pkg/sql/rowenc"
"github.com/cockroachdb/cockroach/pkg/sql/sem/tree"
"github.com/cockroachdb/cockroach/pkg/sql/sqlerrors"
"github.com/cockroachdb/cockroach/pkg/sql/stats"
"github.com/cockroachdb/cockroach/pkg/sql/types"
"github.com/cockroachdb/cockroach/pkg/util"
"github.com/cockroachdb/errors"
"github.com/lib/pq/oid"
)
// optCatalog implements the cat.Catalog interface over the SchemaResolver
// interface for the use of the new optimizer. The interfaces are simplified to
// only include what the optimizer needs, and certain common lookups are cached
// for faster performance.
type optCatalog struct {
// planner needs to be set via a call to init before calling other methods.
planner *planner
// cfg is the gossiped and cached system config. It may be nil if the node
// does not yet have it available.
cfg *config.SystemConfig
// dataSources is a cache of table and view objects that's used to satisfy
// repeated calls for the same data source.
// Note that the data source object might still need to be recreated if
// something outside of the descriptor has changed (e.g. table stats).
dataSources map[*tabledesc.Immutable]cat.DataSource
// tn is a temporary name used during resolution to avoid heap allocation.
tn tree.TableName
}
var _ cat.Catalog = &optCatalog{}
// init initializes an optCatalog instance (which the caller can pre-allocate).
// The instance can be used across multiple queries, but reset() should be
// called for each query.
func (oc *optCatalog) init(planner *planner) {
oc.planner = planner
oc.dataSources = make(map[*tabledesc.Immutable]cat.DataSource)
}
// reset prepares the optCatalog to be used for a new query.
func (oc *optCatalog) reset() {
// If we have accumulated too many tables in our map, throw everything away.
// This deals with possible edge cases where we do a lot of DDL in a
// long-lived session.
if len(oc.dataSources) > 100 {
oc.dataSources = make(map[*tabledesc.Immutable]cat.DataSource)
}
oc.cfg = oc.planner.execCfg.SystemConfig.GetSystemConfig()
}
// optSchema represents the parent database and schema for an object. It
// implements the cat.Object and cat.Schema interfaces.
type optSchema struct {
planner *planner
database *dbdesc.Immutable
schema catalog.ResolvedSchema
name cat.SchemaName
}
// ID is part of the cat.Object interface.
func (os *optSchema) ID() cat.StableID {
switch os.schema.Kind {
case catalog.SchemaUserDefined, catalog.SchemaTemporary:
// User defined schemas and the temporary schema have real ID's, so use
// them here.
return cat.StableID(os.schema.ID)
default:
// Virtual schemas and the public schema don't, so just fall back to the
// parent database's ID.
return cat.StableID(os.database.GetID())
}
}
// PostgresDescriptorID is part of the cat.Object interface.
func (os *optSchema) PostgresDescriptorID() cat.StableID {
return os.ID()
}
// Equals is part of the cat.Object interface.
func (os *optSchema) Equals(other cat.Object) bool {
otherSchema, ok := other.(*optSchema)
return ok && os.ID() == otherSchema.ID()
}
// Name is part of the cat.Schema interface.
func (os *optSchema) Name() *cat.SchemaName {
return &os.name
}
// GetDataSourceNames is part of the cat.Schema interface.
func (os *optSchema) GetDataSourceNames(ctx context.Context) ([]cat.DataSourceName, error) {
return resolver.GetObjectNames(
ctx,
os.planner.Txn(),
os.planner,
os.planner.ExecCfg().Codec,
os.database,
os.name.Schema(),
true, /* explicitPrefix */
)
}
func (os *optSchema) getDescriptorForPermissionsCheck() catalog.Descriptor {
// If the schema is backed by a descriptor, then return it.
if os.schema.Kind == catalog.SchemaUserDefined {
return os.schema.Desc
}
// Otherwise, just return the database descriptor.
return os.database
}
// ResolveSchema is part of the cat.Catalog interface.
func (oc *optCatalog) ResolveSchema(
ctx context.Context, flags cat.Flags, name *cat.SchemaName,
) (cat.Schema, cat.SchemaName, error) {
if flags.AvoidDescriptorCaches {
defer func(prev bool) {
oc.planner.avoidCachedDescriptors = prev
}(oc.planner.avoidCachedDescriptors)
oc.planner.avoidCachedDescriptors = true
}
oc.tn.ObjectNamePrefix = *name
found, prefixI, err := oc.tn.ObjectNamePrefix.Resolve(
ctx,
oc.planner,
oc.planner.CurrentDatabase(),
oc.planner.CurrentSearchPath(),
)
if err != nil {
return nil, cat.SchemaName{}, err
}
if !found {
if !name.ExplicitSchema && !name.ExplicitCatalog {
return nil, cat.SchemaName{}, pgerror.New(
pgcode.InvalidName, "no database or schema specified",
)
}
return nil, cat.SchemaName{}, pgerror.Newf(
pgcode.InvalidSchemaName, "target database or schema does not exist",
)
}
prefix := prefixI.(*catalog.ResolvedObjectPrefix)
return &optSchema{
planner: oc.planner,
database: prefix.Database.(*dbdesc.Immutable),
schema: prefix.Schema,
name: oc.tn.ObjectNamePrefix,
}, oc.tn.ObjectNamePrefix, nil
}
// ResolveDataSource is part of the cat.Catalog interface.
func (oc *optCatalog) ResolveDataSource(
ctx context.Context, flags cat.Flags, name *cat.DataSourceName,
) (cat.DataSource, cat.DataSourceName, error) {
if flags.AvoidDescriptorCaches {
defer func(prev bool) {
oc.planner.avoidCachedDescriptors = prev
}(oc.planner.avoidCachedDescriptors)
oc.planner.avoidCachedDescriptors = true
}
oc.tn = *name
lflags := tree.ObjectLookupFlagsWithRequiredTableKind(tree.ResolveAnyTableKind)
desc, err := resolver.ResolveExistingTableObject(ctx, oc.planner, &oc.tn, lflags)
if err != nil {
return nil, cat.DataSourceName{}, err
}
// Ensure that the current user can access the target schema.
if err := oc.planner.canResolveDescUnderSchema(ctx, desc.GetParentSchemaID(), desc); err != nil {
return nil, cat.DataSourceName{}, err
}
ds, err := oc.dataSourceForDesc(ctx, flags, desc, &oc.tn)
if err != nil {
return nil, cat.DataSourceName{}, err
}
return ds, oc.tn, nil
}
// ResolveDataSourceByID is part of the cat.Catalog interface.
func (oc *optCatalog) ResolveDataSourceByID(
ctx context.Context, flags cat.Flags, dataSourceID cat.StableID,
) (_ cat.DataSource, isAdding bool, _ error) {
if flags.AvoidDescriptorCaches {
defer func(prev bool) {
oc.planner.avoidCachedDescriptors = prev
}(oc.planner.avoidCachedDescriptors)
oc.planner.avoidCachedDescriptors = true
}
tableLookup, err := oc.planner.LookupTableByID(ctx, descpb.ID(dataSourceID))
if err != nil {
isAdding := catalog.HasAddingTableError(err)
if errors.Is(err, catalog.ErrDescriptorNotFound) || isAdding {
return nil, isAdding, sqlerrors.NewUndefinedRelationError(&tree.TableRef{TableID: int64(dataSourceID)})
}
return nil, false, err
}
// The name is only used for virtual tables, which can't be looked up by ID.
ds, err := oc.dataSourceForDesc(ctx, cat.Flags{}, tableLookup, &tree.TableName{})
return ds, false, err
}
// ResolveTypeByOID is part of the cat.Catalog interface.
func (oc *optCatalog) ResolveTypeByOID(ctx context.Context, oid oid.Oid) (*types.T, error) {
return oc.planner.ResolveTypeByOID(ctx, oid)
}
// ResolveType is part of the cat.Catalog interface.
func (oc *optCatalog) ResolveType(
ctx context.Context, name *tree.UnresolvedObjectName,
) (*types.T, error) {
return oc.planner.ResolveType(ctx, name)
}
func getDescFromCatalogObjectForPermissions(o cat.Object) (catalog.Descriptor, error) {
switch t := o.(type) {
case *optSchema:
return t.getDescriptorForPermissionsCheck(), nil
case *optTable:
return t.desc, nil
case *optVirtualTable:
return t.desc, nil
case *optView:
return t.desc, nil
case *optSequence:
return t.desc, nil
default:
return nil, errors.AssertionFailedf("invalid object type: %T", o)
}
}
func getDescForDataSource(o cat.DataSource) (*tabledesc.Immutable, error) {
switch t := o.(type) {
case *optTable:
return t.desc, nil
case *optVirtualTable:
return t.desc, nil
case *optView:
return t.desc, nil
case *optSequence:
return t.desc, nil
default:
return nil, errors.AssertionFailedf("invalid object type: %T", o)
}
}
// CheckPrivilege is part of the cat.Catalog interface.
func (oc *optCatalog) CheckPrivilege(ctx context.Context, o cat.Object, priv privilege.Kind) error {
desc, err := getDescFromCatalogObjectForPermissions(o)
if err != nil {
return err
}
return oc.planner.CheckPrivilege(ctx, desc, priv)
}
// CheckAnyPrivilege is part of the cat.Catalog interface.
func (oc *optCatalog) CheckAnyPrivilege(ctx context.Context, o cat.Object) error {
desc, err := getDescFromCatalogObjectForPermissions(o)
if err != nil {
return err
}
return oc.planner.CheckAnyPrivilege(ctx, desc)
}
// HasAdminRole is part of the cat.Catalog interface.
func (oc *optCatalog) HasAdminRole(ctx context.Context) (bool, error) {
return oc.planner.HasAdminRole(ctx)
}
// RequireAdminRole is part of the cat.Catalog interface.
func (oc *optCatalog) RequireAdminRole(ctx context.Context, action string) error {
return oc.planner.RequireAdminRole(ctx, action)
}
// HasRoleOption is part of the cat.Catalog interface.
func (oc *optCatalog) HasRoleOption(
ctx context.Context, roleOption roleoption.Option,
) (bool, error) {
return oc.planner.HasRoleOption(ctx, roleOption)
}
// FullyQualifiedName is part of the cat.Catalog interface.
func (oc *optCatalog) FullyQualifiedName(
ctx context.Context, ds cat.DataSource,
) (cat.DataSourceName, error) {
return oc.fullyQualifiedNameWithTxn(ctx, ds, oc.planner.Txn())
}
func (oc *optCatalog) fullyQualifiedNameWithTxn(
ctx context.Context, ds cat.DataSource, txn *kv.Txn,
) (cat.DataSourceName, error) {
if vt, ok := ds.(*optVirtualTable); ok {
// Virtual tables require special handling, because they can have multiple
// effective instances that utilize the same descriptor.
return vt.name, nil
}
desc, err := getDescForDataSource(ds)
if err != nil {
return cat.DataSourceName{}, err
}
dbID := desc.ParentID
dbDesc, err := catalogkv.MustGetDatabaseDescByID(ctx, txn, oc.codec(), dbID)
if err != nil {
return cat.DataSourceName{}, err
}
return tree.MakeTableName(tree.Name(dbDesc.GetName()), tree.Name(desc.Name)), nil
}
// dataSourceForDesc returns a data source wrapper for the given descriptor.
// The wrapper might come from the cache, or it may be created now.
func (oc *optCatalog) dataSourceForDesc(
ctx context.Context, flags cat.Flags, desc *tabledesc.Immutable, name *cat.DataSourceName,
) (cat.DataSource, error) {
// Because they are backed by physical data, we treat materialized views
// as tables for the purposes of planning.
if desc.IsTable() || desc.MaterializedView() {
// Tables require invalidation logic for cached wrappers.
return oc.dataSourceForTable(ctx, flags, desc, name)
}
ds, ok := oc.dataSources[desc]
if ok {
return ds, nil
}
switch {
case desc.IsView():
ds = newOptView(desc)
case desc.IsSequence():
ds = newOptSequence(desc)
default:
return nil, errors.AssertionFailedf("unexpected table descriptor: %+v", desc)
}
oc.dataSources[desc] = ds
return ds, nil
}
// dataSourceForTable returns a table data source wrapper for the given descriptor.
// The wrapper might come from the cache, or it may be created now.
func (oc *optCatalog) dataSourceForTable(
ctx context.Context, flags cat.Flags, desc *tabledesc.Immutable, name *cat.DataSourceName,
) (cat.DataSource, error) {
if desc.IsVirtualTable() {
// Virtual tables can have multiple effective instances that utilize the
// same descriptor, so we can't cache them (see the comment for
// optVirtualTable.id for more information).
return newOptVirtualTable(ctx, oc, desc, name)
}
// Even if we have a cached data source, we still have to cross-check that
// statistics and the zone config haven't changed.
var tableStats []*stats.TableStatistic
if !flags.NoTableStats {
var err error
tableStats, err = oc.planner.execCfg.TableStatsCache.GetTableStats(context.TODO(), desc.ID)
if err != nil {
// Ignore any error. We still want to be able to run queries even if we lose
// access to the statistics table.
// TODO(radu): at least log the error.
tableStats = nil
}
}
zoneConfig, err := oc.getZoneConfig(desc)
if err != nil {
return nil, err
}
// Check to see if there's already a data source wrapper for this descriptor,
// and it was created with the same stats and zone config.
if ds, ok := oc.dataSources[desc]; ok && !ds.(*optTable).isStale(desc, tableStats, zoneConfig) {
return ds, nil
}
ds, err := newOptTable(desc, oc.codec(), tableStats, zoneConfig)
if err != nil {
return nil, err
}
oc.dataSources[desc] = ds
return ds, nil
}
var emptyZoneConfig = &zonepb.ZoneConfig{}
// getZoneConfig returns the ZoneConfig data structure for the given table.
// ZoneConfigs are stored in protobuf binary format in the SystemConfig, which
// is gossiped around the cluster. Note that the returned ZoneConfig might be
// somewhat stale, since it's taken from the gossiped SystemConfig.
func (oc *optCatalog) getZoneConfig(desc *tabledesc.Immutable) (*zonepb.ZoneConfig, error) {
// Lookup table's zone if system config is available (it may not be as node
// is starting up and before it's received the gossiped config). If it is
// not available, use an empty config that has no zone constraints.
if oc.cfg == nil || desc.IsVirtualTable() {
return emptyZoneConfig, nil
}
zone, err := oc.cfg.GetZoneConfigForObject(oc.codec(), uint32(desc.ID))
if err != nil {
return nil, err
}
if zone == nil {
// This can happen with tests that override the hook.
zone = emptyZoneConfig
}
return zone, err
}
func (oc *optCatalog) codec() keys.SQLCodec {
return oc.planner.ExecCfg().Codec
}
// optView is a wrapper around sqlbase.Immutable that implements
// the cat.Object, cat.DataSource, and cat.View interfaces.
type optView struct {
desc *tabledesc.Immutable
}
var _ cat.View = &optView{}
func newOptView(desc *tabledesc.Immutable) *optView {
return &optView{desc: desc}
}
// ID is part of the cat.Object interface.
func (ov *optView) ID() cat.StableID {
return cat.StableID(ov.desc.ID)
}
// PostgresDescriptorID is part of the cat.Object interface.
func (ov *optView) PostgresDescriptorID() cat.StableID {
return cat.StableID(ov.desc.ID)
}
// Equals is part of the cat.Object interface.
func (ov *optView) Equals(other cat.Object) bool {
otherView, ok := other.(*optView)
if !ok {
return false
}
return ov.desc.ID == otherView.desc.ID && ov.desc.Version == otherView.desc.Version
}
// Name is part of the cat.View interface.
func (ov *optView) Name() tree.Name {
return tree.Name(ov.desc.Name)
}
// IsSystemView is part of the cat.View interface.
func (ov *optView) IsSystemView() bool {
return ov.desc.IsVirtualTable()
}
// Query is part of the cat.View interface.
func (ov *optView) Query() string {
return ov.desc.ViewQuery
}
// ColumnNameCount is part of the cat.View interface.
func (ov *optView) ColumnNameCount() int {
return len(ov.desc.Columns)
}
// ColumnName is part of the cat.View interface.
func (ov *optView) ColumnName(i int) tree.Name {
return tree.Name(ov.desc.Columns[i].Name)
}
// optSequence is a wrapper around sqlbase.Immutable that
// implements the cat.Object and cat.DataSource interfaces.
type optSequence struct {
desc *tabledesc.Immutable
}
var _ cat.DataSource = &optSequence{}
var _ cat.Sequence = &optSequence{}
func newOptSequence(desc *tabledesc.Immutable) *optSequence {
return &optSequence{desc: desc}
}
// ID is part of the cat.Object interface.
func (os *optSequence) ID() cat.StableID {
return cat.StableID(os.desc.ID)
}
// PostgresDescriptorID is part of the cat.Object interface.
func (os *optSequence) PostgresDescriptorID() cat.StableID {
return cat.StableID(os.desc.ID)
}
// Equals is part of the cat.Object interface.
func (os *optSequence) Equals(other cat.Object) bool {
otherSeq, ok := other.(*optSequence)
if !ok {
return false
}
return os.desc.ID == otherSeq.desc.ID && os.desc.Version == otherSeq.desc.Version
}
// Name is part of the cat.Sequence interface.
func (os *optSequence) Name() tree.Name {
return tree.Name(os.desc.Name)
}
// SequenceMarker is part of the cat.Sequence interface.
func (os *optSequence) SequenceMarker() {}
// optTable is a wrapper around sqlbase.Immutable that caches
// index wrappers and maintains a ColumnID => Column mapping for fast lookup.
type optTable struct {
desc *tabledesc.Immutable
// columns contains all the columns presented to the catalog. This includes:
// - ordinary table columns (those in the table descriptor)
// - MVCC timestamp system column
// - virtual columns (for inverted indexes).
// They are stored in this order, though we shouldn't rely on that anywhere.
columns []cat.Column
// indexes are the inlined wrappers for the table's primary and secondary
// indexes.
indexes []optIndex
// codec is capable of encoding sql table keys.
codec keys.SQLCodec
// rawStats stores the original table statistics slice. Used for a fast-path
// check that the statistics haven't changed.
rawStats []*stats.TableStatistic
// stats are the inlined wrappers for table statistics.
stats []optTableStat
zone *zonepb.ZoneConfig
// family is the inlined wrapper for the table's primary family. The primary
// family is the first family explicitly specified by the user. If no families
// were explicitly specified, then the primary family is synthesized.
primaryFamily optFamily
// families are the inlined wrappers for the table's non-primary families,
// which are all the families specified by the user after the first. The
// primary family is kept separate since the common case is that there's just
// one family.
families []optFamily
outboundFKs []optForeignKeyConstraint
inboundFKs []optForeignKeyConstraint
// checkConstraints is the set of check constraints for this table. It
// can be different from desc's constraints because of synthesized
// constraints for user defined types.
checkConstraints []cat.CheckConstraint
// colMap is a mapping from unique ColumnID to column ordinal within the
// table. This is a common lookup that needs to be fast.
colMap map[descpb.ColumnID]int
}
var _ cat.Table = &optTable{}
func newOptTable(
desc *tabledesc.Immutable,
codec keys.SQLCodec,
stats []*stats.TableStatistic,
tblZone *zonepb.ZoneConfig,
) (*optTable, error) {
ot := &optTable{
desc: desc,
codec: codec,
rawStats: stats,
zone: tblZone,
}
// First, determine how many columns we will potentially need.
colDescs := ot.desc.DeletableColumns()
numCols := len(colDescs) + len(colinfo.AllSystemColumnDescs)
// One for each inverted index virtual column.
secondaryIndexes := ot.desc.DeletableIndexes()
for i := range secondaryIndexes {
if secondaryIndexes[i].Type == descpb.IndexDescriptor_INVERTED {
numCols++
}
}
ot.columns = make([]cat.Column, len(colDescs), numCols)
numOrdinary := len(ot.desc.Columns)
numWritable := len(ot.desc.WritableColumns())
for i := range colDescs {
desc := colDescs[i]
var kind cat.ColumnKind
switch {
case i < numOrdinary:
kind = cat.Ordinary
case i < numWritable:
kind = cat.WriteOnly
default:
kind = cat.DeleteOnly
}
ot.columns[i].InitNonVirtual(
i,
cat.StableID(desc.ID),
tree.Name(desc.Name),
kind,
desc.Type,
desc.Nullable,
desc.Hidden,
desc.DefaultExpr,
desc.ComputeExpr,
)
}
newColumn := func() (col *cat.Column, ordinal int) {
ordinal = len(ot.columns)
ot.columns = ot.columns[:ordinal+1]
return &ot.columns[ordinal], ordinal
}
// Set up any registered system columns. However, we won't add the column
// in case a column with the same name already exists in the table.
// Note that the column does not exist when err != nil. This check is done
// for migration purposes. We need to avoid adding the system column if the
// table has a column with this name for some reason.
for i := range colinfo.AllSystemColumnDescs {
sysCol := &colinfo.AllSystemColumnDescs[i]
if _, _, err := desc.FindColumnByName(tree.Name(sysCol.Name)); err != nil {
col, ord := newColumn()
col.InitNonVirtual(
ord,
cat.StableID(sysCol.ID),
tree.Name(sysCol.Name),
cat.System,
sysCol.Type,
sysCol.Nullable,
sysCol.Hidden,
sysCol.DefaultExpr,
sysCol.ComputeExpr,
)
}
}
// Create the table's column mapping from descpb.ColumnID to column ordinal.
ot.colMap = make(map[descpb.ColumnID]int, ot.ColumnCount())
for i := range ot.columns {
ot.colMap[descpb.ColumnID(ot.columns[i].ColID())] = i
}
// Build the indexes.
ot.indexes = make([]optIndex, 1+len(secondaryIndexes))
for i := range ot.indexes {
var idxDesc *descpb.IndexDescriptor
if i == 0 {
idxDesc = &desc.PrimaryIndex
} else {
idxDesc = &secondaryIndexes[i-1]
}
// If there is a subzone that applies to the entire index, use that,
// else use the table zone. Skip subzones that apply to partitions,
// since they apply only to a subset of the index.
idxZone := tblZone
for j := range tblZone.Subzones {
subzone := &tblZone.Subzones[j]
if subzone.IndexID == uint32(idxDesc.ID) && subzone.PartitionName == "" {
copyZone := subzone.Config
copyZone.InheritFromParent(tblZone)
idxZone = ©Zone
}
}
if idxDesc.Type == descpb.IndexDescriptor_INVERTED {
// The first column of an inverted index is special: in the descriptors,
// it looks as if the table column is part of the index; in fact the key
// contains values *derived* from that column. In the catalog, we refer to
// this key as a separate, virtual column.
invertedSourceColOrdinal, _ := ot.lookupColumnOrdinal(idxDesc.ColumnIDs[0])
// Add a virtual column that refers to the inverted index key.
virtualCol, virtualColOrd := newColumn()
// TODO(radu, mjibson): figure out what the type should be here. Geo is
// Int, but JSON isn't anything decodable (including Bytes). The disk
// fetecher will need to be taught about inverted indexes and dump the
// read data directly into a DBytes (i.e., don't call
// encoding.DecodeBytesAscending).
typ := ot.Column(invertedSourceColOrdinal).DatumType()
virtualCol.InitVirtual(
virtualColOrd,
tree.Name(string(ot.Column(invertedSourceColOrdinal).ColName())+"_inverted_key"),
typ,
false, /* nullable */
invertedSourceColOrdinal,
)
ot.indexes[i].init(ot, i, idxDesc, idxZone, virtualColOrd)
} else {
ot.indexes[i].init(ot, i, idxDesc, idxZone, -1 /* virtualColOrd */)
}
}
for i := range ot.desc.OutboundFKs {
fk := &ot.desc.OutboundFKs[i]
ot.outboundFKs = append(ot.outboundFKs, optForeignKeyConstraint{
name: fk.Name,
originTable: ot.ID(),
originColumns: fk.OriginColumnIDs,
referencedTable: cat.StableID(fk.ReferencedTableID),
referencedColumns: fk.ReferencedColumnIDs,
validity: fk.Validity,
match: fk.Match,
deleteAction: fk.OnDelete,
updateAction: fk.OnUpdate,
})
}
for i := range ot.desc.InboundFKs {
fk := &ot.desc.InboundFKs[i]
ot.inboundFKs = append(ot.inboundFKs, optForeignKeyConstraint{
name: fk.Name,
originTable: cat.StableID(fk.OriginTableID),
originColumns: fk.OriginColumnIDs,
referencedTable: ot.ID(),
referencedColumns: fk.ReferencedColumnIDs,
validity: fk.Validity,
match: fk.Match,
deleteAction: fk.OnDelete,
updateAction: fk.OnUpdate,
})
}
ot.primaryFamily.init(ot, &desc.Families[0])
ot.families = make([]optFamily, len(desc.Families)-1)
for i := range ot.families {
ot.families[i].init(ot, &desc.Families[i+1])
}
// Synthesize any check constraints for user defined types.
var synthesizedChecks []cat.CheckConstraint
for i := 0; i < ot.ColumnCount(); i++ {
col := ot.Column(i)
if col.IsMutation() {
// We do not synthesize check constraints for mutation columns.
continue
}
colType := col.DatumType()
if colType.UserDefined() {
switch colType.Family() {
case types.EnumFamily:
// We synthesize an (x IN (v1, v2, v3...)) check for enum types.
expr := &tree.ComparisonExpr{
Operator: tree.In,
Left: &tree.ColumnItem{ColumnName: col.ColName()},
Right: tree.NewDTuple(colType, tree.MakeAllDEnumsInType(colType)...),
}
synthesizedChecks = append(synthesizedChecks, cat.CheckConstraint{
Constraint: tree.Serialize(expr),
Validated: true,
})
}
}
}
// Move all existing and synthesized checks into the opt table.
activeChecks := desc.ActiveChecks()
ot.checkConstraints = make([]cat.CheckConstraint, 0, len(activeChecks)+len(synthesizedChecks))
for i := range activeChecks {
ot.checkConstraints = append(ot.checkConstraints, cat.CheckConstraint{
Constraint: activeChecks[i].Expr,
Validated: activeChecks[i].Validity == descpb.ConstraintValidity_Validated,
})
}
ot.checkConstraints = append(ot.checkConstraints, synthesizedChecks...)
// Add stats last, now that other metadata is initialized.
if stats != nil {
ot.stats = make([]optTableStat, len(stats))
n := 0
for i := range stats {
// We skip any stats that have columns that don't exist in the table anymore.
if ok, err := ot.stats[n].init(ot, stats[i]); err != nil {
return nil, err
} else if ok {
n++
}
}
ot.stats = ot.stats[:n]
}
return ot, nil
}
// ID is part of the cat.Object interface.
func (ot *optTable) ID() cat.StableID {
return cat.StableID(ot.desc.ID)
}
// PostgresDescriptorID is part of the cat.Object interface.
func (ot *optTable) PostgresDescriptorID() cat.StableID {
return cat.StableID(ot.desc.ID)
}
// isStale checks if the optTable object needs to be refreshed because the stats,
// zone config, or used types have changed. False positives are ok.
func (ot *optTable) isStale(
rawDesc *tabledesc.Immutable, tableStats []*stats.TableStatistic, zone *zonepb.ZoneConfig,
) bool {
// Fast check to verify that the statistics haven't changed: we check the
// length and the address of the underlying array. This is not a perfect
// check (in principle, the stats could have left the cache and then gotten
// regenerated), but it works in the common case.
if len(tableStats) != len(ot.rawStats) {
return true
}
if len(tableStats) > 0 && &tableStats[0] != &ot.rawStats[0] {
return true
}
if !zone.Equal(ot.zone) {
return true
}
// Check if any of the version of column types have changed.
if !ot.desc.UserDefinedTypeColsHaveSameVersion(rawDesc) {
return true
}
return false
}
// Equals is part of the cat.Object interface.
func (ot *optTable) Equals(other cat.Object) bool {
otherTable, ok := other.(*optTable)
if !ok {
return false
}
if ot == otherTable {
// Fast path when it is the same object.
return true
}
if ot.desc.ID != otherTable.desc.ID || ot.desc.Version != otherTable.desc.Version {
return false
}
// Verify the stats are identical.
if len(ot.stats) != len(otherTable.stats) {
return false
}
for i := range ot.stats {
if !ot.stats[i].equals(&otherTable.stats[i]) {
return false
}
}
// Verify that all of the user defined types in the table are the same.
if !ot.desc.UserDefinedTypeColsHaveSameVersion(otherTable.desc) {
return false
}
// Verify that indexes are in same zones. For performance, skip deep equality
// check if it's the same as the previous index (common case).
var prevLeftZone, prevRightZone *zonepb.ZoneConfig
for i := range ot.indexes {
leftZone := ot.indexes[i].zone
rightZone := otherTable.indexes[i].zone
if leftZone == prevLeftZone && rightZone == prevRightZone {
continue
}
if !leftZone.Equal(rightZone) {
return false
}
prevLeftZone = leftZone
prevRightZone = rightZone
}
return true
}
// Name is part of the cat.Table interface.
func (ot *optTable) Name() tree.Name {
return tree.Name(ot.desc.Name)
}
// IsVirtualTable is part of the cat.Table interface.
func (ot *optTable) IsVirtualTable() bool {
return false
}
// IsMaterializedView implements the cat.Table interface.
func (ot *optTable) IsMaterializedView() bool {
return ot.desc.MaterializedView()
}
// ColumnCount is part of the cat.Table interface.
func (ot *optTable) ColumnCount() int {
return len(ot.columns)
}
// Column is part of the cat.Table interface.
func (ot *optTable) Column(i int) *cat.Column {
return &ot.columns[i]
}
// getColDesc is part of optCatalogTableInterface.
func (ot *optTable) getColDesc(i int) *descpb.ColumnDescriptor {
if i < len(ot.desc.DeletableColumns()) {
return &ot.desc.DeletableColumns()[i]
}
// Check if the column matches any registered system columns.
for j := range colinfo.AllSystemColumnDescs {
colDesc := &colinfo.AllSystemColumnDescs[j]
if descpb.ColumnID(ot.columns[i].ColID()) == colDesc.ID {
return colDesc
}
}
return nil
}
// IndexCount is part of the cat.Table interface.
func (ot *optTable) IndexCount() int {
// Primary index is always present, so count is always >= 1.
return 1 + len(ot.desc.Indexes)
}
// WritableIndexCount is part of the cat.Table interface.
func (ot *optTable) WritableIndexCount() int {
// Primary index is always present, so count is always >= 1.
return 1 + len(ot.desc.WritableIndexes())
}
// DeletableIndexCount is part of the cat.Table interface.
func (ot *optTable) DeletableIndexCount() int {
// Primary index is always present, so count is always >= 1.
return 1 + len(ot.desc.DeletableIndexes())
}
// Index is part of the cat.Table interface.
func (ot *optTable) Index(i cat.IndexOrdinal) cat.Index {
return &ot.indexes[i]
}
// StatisticCount is part of the cat.Table interface.
func (ot *optTable) StatisticCount() int {
return len(ot.stats)
}
// Statistic is part of the cat.Table interface.
func (ot *optTable) Statistic(i int) cat.TableStatistic {
return &ot.stats[i]
}
// CheckCount is part of the cat.Table interface.
func (ot *optTable) CheckCount() int {
return len(ot.checkConstraints)