-
Notifications
You must be signed in to change notification settings - Fork 3.8k
/
structured.go
2842 lines (2618 loc) · 94.4 KB
/
structured.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 2015 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 tabledesc
import (
"context"
"fmt"
"sort"
"strings"
"github.com/cockroachdb/cockroach/pkg/clusterversion"
"github.com/cockroachdb/cockroach/pkg/docs"
"github.com/cockroachdb/cockroach/pkg/keys"
"github.com/cockroachdb/cockroach/pkg/roachpb"
"github.com/cockroachdb/cockroach/pkg/settings"
"github.com/cockroachdb/cockroach/pkg/settings/cluster"
"github.com/cockroachdb/cockroach/pkg/sql/catalog"
"github.com/cockroachdb/cockroach/pkg/sql/catalog/catpb"
"github.com/cockroachdb/cockroach/pkg/sql/catalog/colinfo"
"github.com/cockroachdb/cockroach/pkg/sql/catalog/descpb"
"github.com/cockroachdb/cockroach/pkg/sql/catalog/internal/validate"
"github.com/cockroachdb/cockroach/pkg/sql/catalog/typedesc"
"github.com/cockroachdb/cockroach/pkg/sql/lexbase"
"github.com/cockroachdb/cockroach/pkg/sql/parser"
"github.com/cockroachdb/cockroach/pkg/sql/pgwire/pgcode"
"github.com/cockroachdb/cockroach/pkg/sql/pgwire/pgerror"
"github.com/cockroachdb/cockroach/pkg/sql/rowenc"
"github.com/cockroachdb/cockroach/pkg/sql/schemachanger/scpb"
"github.com/cockroachdb/cockroach/pkg/sql/sem/catid"
"github.com/cockroachdb/cockroach/pkg/sql/sem/tree"
"github.com/cockroachdb/cockroach/pkg/sql/types"
"github.com/cockroachdb/cockroach/pkg/util"
"github.com/cockroachdb/cockroach/pkg/util/errorutil/unimplemented"
"github.com/cockroachdb/cockroach/pkg/util/hlc"
"github.com/cockroachdb/cockroach/pkg/util/iterutil"
"github.com/cockroachdb/cockroach/pkg/util/protoutil"
"github.com/cockroachdb/errors"
"github.com/lib/pq/oid"
)
// Mutable is a custom type for TableDescriptors
// going through schema mutations.
type Mutable struct {
wrapper
// original represents the version of the table descriptor read from the
// store.
original *immutable
}
const (
// LegacyPrimaryKeyIndexName is the pre 22.1 default PRIMARY KEY index name.
LegacyPrimaryKeyIndexName = "primary"
// SequenceColumnID is the ID of the sole column in a sequence.
SequenceColumnID = 1
// SequenceColumnName is the name of the sole column in a sequence.
SequenceColumnName = "value"
)
// ErrMissingColumns indicates a table with no columns.
var ErrMissingColumns = errors.New("table must contain at least 1 column")
// ErrMissingPrimaryKey indicates a table with no primary key.
var ErrMissingPrimaryKey = errors.New("table must contain a primary key")
// UseMVCCCompliantIndexCreation controls whether index additions will
// use the MVCC compliant scheme which requires both temporary indexes
// and a different initial state.
var UseMVCCCompliantIndexCreation = settings.RegisterBoolSetting(
settings.TenantWritable,
"sql.mvcc_compliant_index_creation.enabled",
"if true, schema changes will use the an index backfiller designed for MVCC-compliant bulk operations",
true,
)
// DescriptorType returns the type of this descriptor.
func (desc *wrapper) DescriptorType() catalog.DescriptorType {
return catalog.Table
}
// SetName implements the DescriptorProto interface.
func (desc *Mutable) SetName(name string) {
desc.Name = name
}
// IsPartitionAllBy implements the TableDescriptor interface.
func (desc *wrapper) IsPartitionAllBy() bool {
return desc.PartitionAllBy
}
// GetParentSchemaID returns the ParentSchemaID if the descriptor has
// one. If the descriptor was created before the field was added, then the
// descriptor belongs to a table under the `public` physical schema. The static
// public schema ID is returned in that case.
func (desc *wrapper) GetParentSchemaID() descpb.ID {
parentSchemaID := desc.GetUnexposedParentSchemaID()
// TODO(richardjcai): Remove this case in 22.1.
if parentSchemaID == descpb.InvalidID {
parentSchemaID = keys.PublicSchemaID
}
return parentSchemaID
}
// IndexKeysPerRow implements the TableDescriptor interface.
func (desc *wrapper) IndexKeysPerRow(idx catalog.Index) int {
if desc.PrimaryIndex.ID == idx.GetID() || idx.GetEncodingType() == descpb.PrimaryIndexEncoding {
return len(desc.Families)
}
if idx.NumSecondaryStoredColumns() == 0 || len(desc.Families) == 1 {
return 1
}
// Calculate the number of column families used by the secondary index. We
// only need to look at the stored columns because column families are only
// applicable to the value part of the KV.
//
// 0th family is always present.
numUsedFamilies := 1
storedColumnIDs := idx.CollectSecondaryStoredColumnIDs()
for _, family := range desc.Families[1:] {
for _, columnID := range family.ColumnIDs {
if storedColumnIDs.Contains(columnID) {
numUsedFamilies++
break
}
}
}
return numUsedFamilies
}
// BuildIndexName returns an index name that is not equal to any
// of tableDesc's indexes, roughly following Postgres's conventions for naming
// anonymous indexes. For example:
//
// CREATE INDEX ON t (a)
// => t_a_idx
//
// CREATE UNIQUE INDEX ON t (a, b)
// => t_a_b_key
//
// CREATE INDEX ON t ((a + b), c, lower(d))
// => t_expr_c_expr1_idx
//
func BuildIndexName(tableDesc *Mutable, idx *descpb.IndexDescriptor) (string, error) {
// An index name has a segment for the table name, each key column, and a
// final word (either "idx" or "key").
segments := make([]string, 0, len(idx.KeyColumnNames)+2)
// Add the table name segment.
segments = append(segments, tableDesc.Name)
// Add the key column segments. For inaccessible columns, use "expr" as the
// segment. If there are multiple inaccessible columns, add an incrementing
// integer suffix.
exprCount := 0
for i, n := idx.ExplicitColumnStartIdx(), len(idx.KeyColumnNames); i < n; i++ {
var segmentName string
col, err := tableDesc.FindColumnWithName(tree.Name(idx.KeyColumnNames[i]))
if err != nil {
return "", err
}
if col.IsExpressionIndexColumn() {
if exprCount == 0 {
segmentName = "expr"
} else {
segmentName = fmt.Sprintf("expr%d", exprCount)
}
exprCount++
} else {
segmentName = idx.KeyColumnNames[i]
}
segments = append(segments, segmentName)
}
// Add a segment for delete preserving indexes so that
// temporary indexes used by the index backfiller are easily
// identifiable and so that we don't cause too many changes in
// the index names generated by a series of operations.
if idx.UseDeletePreservingEncoding {
segments = append(segments, "crdb_internal_dpe")
}
// Add the final segment.
if idx.Unique {
segments = append(segments, "key")
} else {
segments = append(segments, "idx")
}
// Append digits to the index name to make it unique, if necessary.
baseName := strings.Join(segments, "_")
name := baseName
for i := 1; ; i++ {
foundIndex, _ := tableDesc.FindIndexWithName(name)
if foundIndex == nil {
break
}
name = fmt.Sprintf("%s%d", baseName, i)
}
return name, nil
}
// AllActiveAndInactiveChecks implements the TableDescriptor interface.
func (desc *wrapper) AllActiveAndInactiveChecks() []*descpb.TableDescriptor_CheckConstraint {
// A check constraint could be both on the table descriptor and in the
// list of mutations while the constraint is validated for existing rows. In
// that case, the constraint is in the Validating state, and we avoid
// including it twice. (Note that even though unvalidated check constraints
// cannot be added as of 19.1, they can still exist if they were created under
// previous versions.)
checks := make([]*descpb.TableDescriptor_CheckConstraint, 0, len(desc.Checks))
for _, c := range desc.Checks {
// While a constraint is being validated for existing rows or being dropped,
// the constraint is present both on the table descriptor and in the
// mutations list in the Validating or Dropping state, so those constraints
// are excluded here to avoid double-counting.
if c.Validity != descpb.ConstraintValidity_Validating &&
c.Validity != descpb.ConstraintValidity_Dropping {
checks = append(checks, c)
}
}
for _, m := range desc.Mutations {
if c := m.GetConstraint(); c != nil && c.ConstraintType == descpb.ConstraintToUpdate_CHECK {
// Any mutations that are dropped should be
// excluded to avoid returning duplicates.
if m.Direction != descpb.DescriptorMutation_DROP {
checks = append(checks, &c.Check)
}
}
}
return checks
}
// GetColumnFamilyForShard returns the column family that a newly added shard column
// should be assigned to, given the set of columns it's computed from.
//
// This is currently the column family of the first column in the set of index columns.
func GetColumnFamilyForShard(desc *Mutable, idxColumns []string) string {
for _, f := range desc.Families {
for _, fCol := range f.ColumnNames {
if fCol == idxColumns[0] {
return f.Name
}
}
}
return ""
}
// AllActiveAndInactiveUniqueWithoutIndexConstraints implements the
// TableDescriptor interface.
func (desc *wrapper) AllActiveAndInactiveUniqueWithoutIndexConstraints() []*descpb.UniqueWithoutIndexConstraint {
ucs := make([]*descpb.UniqueWithoutIndexConstraint, 0, len(desc.UniqueWithoutIndexConstraints))
for i := range desc.UniqueWithoutIndexConstraints {
uc := &desc.UniqueWithoutIndexConstraints[i]
// While a constraint is being validated for existing rows or being dropped,
// the constraint is present both on the table descriptor and in the
// mutations list in the Validating or Dropping state, so those constraints
// are excluded here to avoid double-counting.
if uc.Validity != descpb.ConstraintValidity_Validating &&
uc.Validity != descpb.ConstraintValidity_Dropping {
ucs = append(ucs, uc)
}
}
for i := range desc.Mutations {
if c := desc.Mutations[i].GetConstraint(); c != nil &&
c.ConstraintType == descpb.ConstraintToUpdate_UNIQUE_WITHOUT_INDEX {
ucs = append(ucs, &c.UniqueWithoutIndexConstraint)
}
}
return ucs
}
// AllActiveAndInactiveForeignKeys implements the TableDescriptor interface.
func (desc *wrapper) AllActiveAndInactiveForeignKeys() []*descpb.ForeignKeyConstraint {
fks := make([]*descpb.ForeignKeyConstraint, 0, len(desc.OutboundFKs))
for i := range desc.OutboundFKs {
fk := &desc.OutboundFKs[i]
// While a constraint is being validated for existing rows or being dropped,
// the constraint is present both on the table descriptor and in the
// mutations list in the Validating or Dropping state, so those constraints
// are excluded here to avoid double-counting.
if fk.Validity != descpb.ConstraintValidity_Validating && fk.Validity != descpb.ConstraintValidity_Dropping {
fks = append(fks, fk)
}
}
for i := range desc.Mutations {
if c := desc.Mutations[i].GetConstraint(); c != nil && c.ConstraintType == descpb.ConstraintToUpdate_FOREIGN_KEY {
fks = append(fks, &c.ForeignKey)
}
}
return fks
}
// ForeachDependedOnBy implements the TableDescriptor interface.
func (desc *wrapper) ForeachDependedOnBy(
f func(dep *descpb.TableDescriptor_Reference) error,
) error {
for i := range desc.DependedOnBy {
if err := f(&desc.DependedOnBy[i]); err != nil {
return iterutil.Map(err)
}
}
return nil
}
// ForeachOutboundFK implements the TableDescriptor interface.
func (desc *wrapper) ForeachOutboundFK(
f func(constraint *descpb.ForeignKeyConstraint) error,
) error {
for i := range desc.OutboundFKs {
if err := f(&desc.OutboundFKs[i]); err != nil {
return iterutil.Map(err)
}
}
return nil
}
// ForeachInboundFK calls f for every inbound foreign key in desc until an
// error is returned.
func (desc *wrapper) ForeachInboundFK(f func(fk *descpb.ForeignKeyConstraint) error) error {
for i := range desc.InboundFKs {
if err := f(&desc.InboundFKs[i]); err != nil {
return iterutil.Map(err)
}
}
return nil
}
// NumFamilies implements the TableDescriptor interface.
func (desc *wrapper) NumFamilies() int {
return len(desc.Families)
}
// ForeachFamily implements the TableDescriptor interface.
func (desc *wrapper) ForeachFamily(f func(family *descpb.ColumnFamilyDescriptor) error) error {
for i := range desc.Families {
if err := f(&desc.Families[i]); err != nil {
return iterutil.Map(err)
}
}
return nil
}
func generatedFamilyName(familyID descpb.FamilyID, columnNames []string) string {
var buf strings.Builder
fmt.Fprintf(&buf, "fam_%d", familyID)
for _, n := range columnNames {
buf.WriteString(`_`)
buf.WriteString(n)
}
return buf.String()
}
// ForEachExprStringInTableDesc runs a closure for each expression string
// within a TableDescriptor. The closure takes in a string pointer so that
// it can mutate the TableDescriptor if desired.
func ForEachExprStringInTableDesc(descI catalog.TableDescriptor, f func(expr *string) error) error {
var desc *wrapper
switch descV := descI.(type) {
case *wrapper:
desc = descV
case *immutable:
desc = &descV.wrapper
case *Mutable:
desc = &descV.wrapper
default:
return errors.AssertionFailedf("unexpected type of table %T", descI)
}
// Helpers for each schema element type that can contain an expression.
doCol := func(c *descpb.ColumnDescriptor) error {
if c.HasDefault() {
if err := f(c.DefaultExpr); err != nil {
return err
}
}
if c.IsComputed() {
if err := f(c.ComputeExpr); err != nil {
return err
}
}
if c.HasOnUpdate() {
if err := f(c.OnUpdateExpr); err != nil {
return err
}
}
return nil
}
doIndex := func(i catalog.Index) error {
if i.IsPartial() {
return f(&i.IndexDesc().Predicate)
}
return nil
}
doCheck := func(c *descpb.TableDescriptor_CheckConstraint) error {
return f(&c.Expr)
}
// Process columns.
for i := range desc.Columns {
if err := doCol(&desc.Columns[i]); err != nil {
return err
}
}
// Process all indexes.
if err := catalog.ForEachIndex(descI, catalog.IndexOpts{
NonPhysicalPrimaryIndex: true,
DropMutations: true,
AddMutations: true,
}, doIndex); err != nil {
return err
}
// Process checks.
for i := range desc.Checks {
if err := doCheck(desc.Checks[i]); err != nil {
return err
}
}
// Process all non-index mutations.
for _, mut := range desc.Mutations {
if c := mut.GetColumn(); c != nil {
if err := doCol(c); err != nil {
return err
}
}
if c := mut.GetConstraint(); c != nil &&
c.ConstraintType == descpb.ConstraintToUpdate_CHECK {
if err := doCheck(&c.Check); err != nil {
return err
}
}
}
return nil
}
// GetAllReferencedTypeIDs implements the TableDescriptor interface.
func (desc *wrapper) GetAllReferencedTypeIDs(
dbDesc catalog.DatabaseDescriptor, getType func(descpb.ID) (catalog.TypeDescriptor, error),
) (referencedAnywhere, referencedInColumns descpb.IDs, _ error) {
ids, err := desc.getAllReferencedTypesInTableColumns(getType)
if err != nil {
return nil, nil, err
}
referencedInColumns = make(descpb.IDs, 0, len(ids))
for id := range ids {
referencedInColumns = append(referencedInColumns, id)
}
sort.Sort(referencedInColumns)
// REGIONAL BY TABLE tables may have a dependency with the multi-region enum.
exists := desc.GetMultiRegionEnumDependencyIfExists()
if exists {
regionEnumID, err := dbDesc.MultiRegionEnumID()
if err != nil {
return nil, nil, err
}
ids[regionEnumID] = struct{}{}
}
// Add any other type dependencies that are not
// used in a column (specifically for views).
for _, id := range desc.DependsOnTypes {
ids[id] = struct{}{}
}
// Construct the output.
result := make(descpb.IDs, 0, len(ids))
for id := range ids {
result = append(result, id)
}
// Sort the output so that the order is deterministic.
sort.Sort(result)
return result, referencedInColumns, nil
}
// getAllReferencedTypesInTableColumns returns a map of all user defined
// type descriptor IDs that this table references. Consider using
// GetAllReferencedTypeIDs when constructing the list of type descriptor IDs
// referenced by a table -- being used by a column is a sufficient but not
// necessary condition for a table to reference a type.
// One example of a table having a type descriptor dependency but no column to
// show for it is a REGIONAL BY TABLE table (homed in the non-primary region).
// These use a value from the multi-region enum to denote the homing region, but
// do so in the locality config as opposed to through a column.
// GetAllReferencedTypesByID accounts for this dependency.
func (desc *wrapper) getAllReferencedTypesInTableColumns(
getType func(descpb.ID) (catalog.TypeDescriptor, error),
) (map[descpb.ID]struct{}, error) {
// All serialized expressions within a table descriptor are serialized
// with type annotations as ID's, so this visitor will collect them all.
visitor := &tree.TypeCollectorVisitor{
OIDs: make(map[oid.Oid]struct{}),
}
addOIDsInExpr := func(exprStr *string) error {
expr, err := parser.ParseExpr(*exprStr)
if err != nil {
return err
}
tree.WalkExpr(visitor, expr)
return nil
}
if err := ForEachExprStringInTableDesc(desc, addOIDsInExpr); err != nil {
return nil, err
}
// For each of the collected type IDs in the table descriptor expressions,
// collect the closure of ID's referenced.
ids := make(map[descpb.ID]struct{})
for id := range visitor.OIDs {
uid, err := typedesc.UserDefinedTypeOIDToID(id)
if err != nil {
return nil, err
}
typDesc, err := getType(uid)
if err != nil {
return nil, err
}
children, err := typDesc.GetIDClosure()
if err != nil {
return nil, err
}
for child := range children {
ids[child] = struct{}{}
}
}
// Now add all of the column types in the table.
addIDsInColumn := func(c *descpb.ColumnDescriptor) error {
children, err := typedesc.GetTypeDescriptorClosure(c.Type)
if err != nil {
return err
}
for id := range children {
ids[id] = struct{}{}
}
return nil
}
for i := range desc.Columns {
if err := addIDsInColumn(&desc.Columns[i]); err != nil {
return nil, err
}
}
for _, mut := range desc.Mutations {
if c := mut.GetColumn(); c != nil {
if err := addIDsInColumn(c); err != nil {
return nil, err
}
}
}
return ids, nil
}
func (desc *Mutable) initIDs() {
if desc.NextColumnID == 0 {
desc.NextColumnID = 1
}
if desc.Version == 0 {
desc.Version = 1
}
if desc.NextMutationID == descpb.InvalidMutationID {
desc.NextMutationID = 1
}
if desc.NextConstraintID == 0 {
desc.NextConstraintID = 1
}
}
// MaybeFillColumnID assigns a column ID to the given column if the said column has an ID
// of 0.
func (desc *Mutable) MaybeFillColumnID(
c *descpb.ColumnDescriptor, columnNames map[string]descpb.ColumnID,
) {
desc.initIDs()
columnID := c.ID
if columnID == 0 {
columnID = desc.NextColumnID
desc.NextColumnID++
}
columnNames[c.Name] = columnID
c.ID = columnID
}
// AllocateIDs allocates column, family, and index ids for any column, family,
// or index which has an ID of 0. It's the same as AllocateIDsWithoutValidation,
// but does validation on the table elements.
func (desc *Mutable) AllocateIDs(ctx context.Context, version clusterversion.ClusterVersion) error {
if err := desc.AllocateIDsWithoutValidation(ctx); err != nil {
return err
}
// This is sort of ugly. If the descriptor does not have an ID, we hack one in
// to pass the table ID check. We use a non-reserved ID, reserved ones being set
// before AllocateIDs.
savedID := desc.ID
if desc.ID == 0 {
desc.ID = keys.SystemDatabaseID
}
err := validate.Self(version, desc)
desc.ID = savedID
return err
}
// AllocateIDsWithoutValidation allocates column, family, and index ids for any
// column, family, or index which has an ID of 0.
func (desc *Mutable) AllocateIDsWithoutValidation(ctx context.Context) error {
// Only tables with physical data can have / need a primary key.
if desc.IsPhysicalTable() {
if err := desc.ensurePrimaryKey(); err != nil {
return err
}
}
desc.initIDs()
columnNames := map[string]descpb.ColumnID{}
for i := range desc.Columns {
desc.MaybeFillColumnID(&desc.Columns[i], columnNames)
}
for _, m := range desc.Mutations {
if c := m.GetColumn(); c != nil {
desc.MaybeFillColumnID(c, columnNames)
}
}
// Only tables and materialized views can have / need indexes and column families.
if desc.IsTable() || desc.MaterializedView() {
if err := desc.allocateIndexIDs(columnNames); err != nil {
return err
}
// Virtual tables don't have column families.
if desc.IsPhysicalTable() {
desc.allocateColumnFamilyIDs(columnNames)
}
}
return nil
}
func (desc *Mutable) ensurePrimaryKey() error {
if len(desc.PrimaryIndex.KeyColumnNames) == 0 && desc.IsPhysicalTable() {
// Ensure a Primary Key exists.
nameExists := func(name string) bool {
_, err := desc.FindColumnWithName(tree.Name(name))
return err == nil
}
s := "unique_rowid()"
col := &descpb.ColumnDescriptor{
Name: GenerateUniqueName("rowid", nameExists),
Type: types.Int,
DefaultExpr: &s,
Hidden: true,
Nullable: false,
}
desc.AddColumn(col)
idx := descpb.IndexDescriptor{
Unique: true,
KeyColumnNames: []string{col.Name},
KeyColumnDirections: []catpb.IndexColumn_Direction{catpb.IndexColumn_ASC},
}
if err := desc.AddPrimaryIndex(idx); err != nil {
return err
}
}
return nil
}
func (desc *Mutable) allocateIndexIDs(columnNames map[string]descpb.ColumnID) error {
if desc.NextIndexID == 0 {
desc.NextIndexID = 1
}
if desc.NextConstraintID == 0 {
desc.NextConstraintID = 1
}
// Assign names to unnamed indexes.
err := catalog.ForEachNonPrimaryIndex(desc, func(idx catalog.Index) error {
if len(idx.GetName()) == 0 {
name, err := BuildIndexName(desc, idx.IndexDesc())
if err != nil {
return err
}
idx.IndexDesc().Name = name
}
if idx.GetConstraintID() == 0 && idx.IsUnique() {
idx.IndexDesc().ConstraintID = desc.NextConstraintID
desc.NextConstraintID++
}
return nil
})
if err != nil {
return err
}
var compositeColIDs catalog.TableColSet
for i := range desc.Columns {
col := &desc.Columns[i]
if colinfo.CanHaveCompositeKeyEncoding(col.Type) {
compositeColIDs.Add(col.ID)
}
}
// Populate IDs.
primaryColIDs := desc.GetPrimaryIndex().CollectKeyColumnIDs()
for _, idx := range desc.AllIndexes() {
if !idx.Primary() {
maybeUpgradeSecondaryIndexFormatVersion(idx.IndexDesc())
}
if idx.Primary() && idx.GetConstraintID() == 0 {
idx.IndexDesc().ConstraintID = desc.NextConstraintID
desc.NextConstraintID++
}
if idx.GetID() == 0 {
idx.IndexDesc().ID = desc.NextIndexID
desc.NextIndexID++
} else if !idx.Primary() {
// Nothing to do for this secondary index.
continue
} else if !idx.CollectPrimaryStoredColumnIDs().Contains(0) {
// Nothing to do for this primary index.
continue
}
// Populate KeyColumnIDs to match KeyColumnNames.
for j, colName := range idx.IndexDesc().KeyColumnNames {
if len(idx.IndexDesc().KeyColumnIDs) <= j {
idx.IndexDesc().KeyColumnIDs = append(idx.IndexDesc().KeyColumnIDs, 0)
}
if idx.IndexDesc().KeyColumnIDs[j] == 0 {
idx.IndexDesc().KeyColumnIDs[j] = columnNames[colName]
}
}
// Rebuild KeySuffixColumnIDs, StoreColumnIDs and CompositeColumnIDs.
indexHasOldStoredColumns := idx.HasOldStoredColumns()
idx.IndexDesc().KeySuffixColumnIDs = nil
idx.IndexDesc().StoreColumnIDs = nil
idx.IndexDesc().CompositeColumnIDs = nil
// KeySuffixColumnIDs is only populated for indexes using the secondary
// index encoding. It is the set difference of the primary key minus the
// non-inverted columns in the index's key.
colIDs := idx.CollectKeyColumnIDs()
isInverted := idx.GetType() == descpb.IndexDescriptor_INVERTED
invID := catid.ColumnID(0)
if isInverted {
invID = idx.InvertedColumnID()
}
var extraColumnIDs []descpb.ColumnID
for _, primaryColID := range desc.PrimaryIndex.KeyColumnIDs {
if !colIDs.Contains(primaryColID) {
extraColumnIDs = append(extraColumnIDs, primaryColID)
colIDs.Add(primaryColID)
} else if invID == primaryColID {
// In an inverted index, the inverted column's value is not equal to the
// actual data in the row for that column. As a result, if the inverted
// column happens to also be in the primary key, it's crucial that
// the index key still be suffixed with that full primary key value to
// preserve the index semantics.
// extraColumnIDs = append(extraColumnIDs, primaryColID)
// However, this functionality is not supported by the execution engine,
// so prevent it by returning an error.
col, err := desc.FindColumnWithID(primaryColID)
if err != nil {
return err
}
return unimplemented.NewWithIssuef(84405,
"primary key column %s cannot be present in an inverted index",
col.GetName(),
)
}
}
if idx.GetEncodingType() == descpb.SecondaryIndexEncoding {
idx.IndexDesc().KeySuffixColumnIDs = extraColumnIDs
} else {
colIDs = idx.CollectKeyColumnIDs()
}
// StoreColumnIDs are derived from StoreColumnNames just like KeyColumnIDs
// derives from KeyColumnNames.
// For primary indexes this set of columns is typically defined as the set
// difference of non-virtual columns minus the primary key.
// In the case of secondary indexes, these columns are defined explicitly at
// index creation via the STORING clause. We do some validation checks here
// presumably to guard against user input errors.
//
// TODO(postamar): AllocateIDs should not do user input validation.
// The only errors it should return should be assertion failures.
for _, colName := range idx.IndexDesc().StoreColumnNames {
col, err := desc.FindColumnWithName(tree.Name(colName))
if err != nil {
return err
}
if primaryColIDs.Contains(col.GetID()) && idx.GetEncodingType() == descpb.SecondaryIndexEncoding {
// If the primary index contains a stored column, we don't need to
// store it - it's already part of the index.
err = pgerror.Newf(pgcode.DuplicateColumn,
"index %q already contains column %q", idx.GetName(), col.GetName())
err = errors.WithDetailf(err,
"column %q is part of the primary index and therefore implicit in all indexes", col.GetName())
return err
}
if colIDs.Contains(col.GetID()) {
return pgerror.Newf(
pgcode.DuplicateColumn,
"index %q already contains column %q", idx.GetName(), col.GetName())
}
if indexHasOldStoredColumns {
idx.IndexDesc().KeySuffixColumnIDs = append(idx.IndexDesc().KeySuffixColumnIDs, col.GetID())
} else {
idx.IndexDesc().StoreColumnIDs = append(idx.IndexDesc().StoreColumnIDs, col.GetID())
}
colIDs.Add(col.GetID())
}
// CompositeColumnIDs is defined as the subset of columns in the index key
// or in the primary key whose type has a composite encoding, like DECIMAL
// for instance.
for _, colID := range idx.IndexDesc().KeyColumnIDs {
if compositeColIDs.Contains(colID) {
idx.IndexDesc().CompositeColumnIDs = append(idx.IndexDesc().CompositeColumnIDs, colID)
}
}
for _, colID := range idx.IndexDesc().KeySuffixColumnIDs {
if compositeColIDs.Contains(colID) {
idx.IndexDesc().CompositeColumnIDs = append(idx.IndexDesc().CompositeColumnIDs, colID)
}
}
}
return nil
}
func (desc *Mutable) allocateColumnFamilyIDs(columnNames map[string]descpb.ColumnID) {
if desc.NextFamilyID == 0 {
if len(desc.Families) == 0 {
desc.Families = []descpb.ColumnFamilyDescriptor{
{ID: 0, Name: "primary"},
}
}
desc.NextFamilyID = 1
}
var columnsInFamilies catalog.TableColSet
for i := range desc.Families {
family := &desc.Families[i]
if family.ID == 0 && i != 0 {
family.ID = desc.NextFamilyID
desc.NextFamilyID++
}
for j, colName := range family.ColumnNames {
if len(family.ColumnIDs) <= j {
family.ColumnIDs = append(family.ColumnIDs, 0)
}
if family.ColumnIDs[j] == 0 {
family.ColumnIDs[j] = columnNames[colName]
}
columnsInFamilies.Add(family.ColumnIDs[j])
}
desc.Families[i] = *family
}
var primaryIndexColIDs catalog.TableColSet
for _, colID := range desc.PrimaryIndex.KeyColumnIDs {
primaryIndexColIDs.Add(colID)
}
ensureColumnInFamily := func(col *descpb.ColumnDescriptor) {
if col.Virtual {
// Virtual columns don't need to be part of families.
return
}
if columnsInFamilies.Contains(col.ID) {
return
}
if primaryIndexColIDs.Contains(col.ID) {
// Primary index columns are required to be assigned to family 0.
desc.Families[0].ColumnNames = append(desc.Families[0].ColumnNames, col.Name)
desc.Families[0].ColumnIDs = append(desc.Families[0].ColumnIDs, col.ID)
return
}
var familyID descpb.FamilyID
if desc.ParentID == keys.SystemDatabaseID {
// TODO(dan): This assigns families such that the encoding is exactly the
// same as before column families. It's used for all system tables because
// reads of them don't go through the normal sql layer, which is where the
// knowledge of families lives. Fix that and remove this workaround.
familyID = descpb.FamilyID(col.ID)
desc.Families = append(desc.Families, descpb.ColumnFamilyDescriptor{
ID: familyID,
ColumnNames: []string{col.Name},
ColumnIDs: []descpb.ColumnID{col.ID},
})
} else {
idx, ok := fitColumnToFamily(desc, *col)
if !ok {
idx = len(desc.Families)
desc.Families = append(desc.Families, descpb.ColumnFamilyDescriptor{
ID: desc.NextFamilyID,
ColumnNames: []string{},
ColumnIDs: []descpb.ColumnID{},
})
}
familyID = desc.Families[idx].ID
desc.Families[idx].ColumnNames = append(desc.Families[idx].ColumnNames, col.Name)
desc.Families[idx].ColumnIDs = append(desc.Families[idx].ColumnIDs, col.ID)
}
if familyID >= desc.NextFamilyID {
desc.NextFamilyID = familyID + 1
}
}
for i := range desc.Columns {
ensureColumnInFamily(&desc.Columns[i])
}
for _, m := range desc.Mutations {
if c := m.GetColumn(); c != nil {
ensureColumnInFamily(c)
}
}
for i := range desc.Families {
family := &desc.Families[i]
if len(family.Name) == 0 {
family.Name = generatedFamilyName(family.ID, family.ColumnNames)
}
if family.DefaultColumnID == 0 {
defaultColumnID := descpb.ColumnID(0)
for _, colID := range family.ColumnIDs {
if !primaryIndexColIDs.Contains(colID) {
if defaultColumnID == 0 {
defaultColumnID = colID
} else {
defaultColumnID = descpb.ColumnID(0)
break
}
}
}
family.DefaultColumnID = defaultColumnID
}
desc.Families[i] = *family
}
}
// fitColumnToFamily attempts to fit a new column into the existing column
// families. If the heuristics find a fit, true is returned along with the
// index of the selected family. Otherwise, false is returned and the column
// should be put in a new family.
//
// Current heuristics:
// - Put all columns in family 0.
func fitColumnToFamily(desc *Mutable, col descpb.ColumnDescriptor) (int, bool) {
// Fewer column families means fewer kv entries, which is generally faster.
// On the other hand, an update to any column in a family requires that they
// all are read and rewritten, so large (or numerous) columns that are not
// updated at the same time as other columns in the family make things
// slower.
//
// The initial heuristic used for family assignment tried to pack
// fixed-width columns into families up to a certain size and would put any
// variable-width column into its own family. This was conservative to
// guarantee that we avoid the worst-case behavior of a very large immutable
// blob in the same family as frequently updated columns.
//
// However, our initial customers have revealed that this is backward.
// Repeatedly, they have recreated existing schemas without any tuning and
// found lackluster performance. Each of these has turned out better as a
// single family (sometimes 100% faster or more), the most aggressive tuning
// possible.
//
// Further, as the WideTable benchmark shows, even the worst-case isn't that
// bad (33% slower with an immutable 1MB blob, which is the upper limit of
// what we'd recommend for column size regardless of families). This
// situation also appears less frequent than we feared.
//
// The result is that we put all columns in one family and require the user
// to manually specify family assignments when this is incorrect.
return 0, true
}
// MaybeIncrementVersion implements the MutableDescriptor interface.
func (desc *Mutable) MaybeIncrementVersion() {
// Already incremented, no-op.
if desc.Version == desc.ClusterVersion().Version+1 || desc.ClusterVersion().Version == 0 {
return