-
Notifications
You must be signed in to change notification settings - Fork 3.8k
/
structured.go
3892 lines (3523 loc) · 129 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 sqlbase
import (
"context"
"fmt"
"sort"
"strconv"
"strings"
"github.com/cockroachdb/cockroach/pkg/internal/client"
"github.com/cockroachdb/cockroach/pkg/keys"
"github.com/cockroachdb/cockroach/pkg/roachpb"
"github.com/cockroachdb/cockroach/pkg/settings/cluster"
"github.com/cockroachdb/cockroach/pkg/sql/opt/cat"
"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/sem/tree"
"github.com/cockroachdb/cockroach/pkg/sql/types"
"github.com/cockroachdb/cockroach/pkg/util/encoding"
"github.com/cockroachdb/cockroach/pkg/util/errorutil/unimplemented"
"github.com/cockroachdb/cockroach/pkg/util/hlc"
"github.com/cockroachdb/cockroach/pkg/util/interval"
"github.com/cockroachdb/cockroach/pkg/util/log"
"github.com/cockroachdb/cockroach/pkg/util/protoutil"
"github.com/cockroachdb/errors"
)
// ID, ColumnID, FamilyID, and IndexID are all uint32, but are each given a
// type alias to prevent accidental use of one of the types where
// another is expected.
// ID is a custom type for {Database,Table}Descriptor IDs.
type ID tree.ID
// InvalidID is the uninitialised descriptor id.
const InvalidID ID = 0
// IDs is a sortable list of IDs.
type IDs []ID
func (ids IDs) Len() int { return len(ids) }
func (ids IDs) Less(i, j int) bool { return ids[i] < ids[j] }
func (ids IDs) Swap(i, j int) { ids[i], ids[j] = ids[j], ids[i] }
// TableDescriptors is a sortable list of *TableDescriptors.
type TableDescriptors []*TableDescriptor
// TablesByID is a shorthand for the common map of tables keyed by ID.
type TablesByID map[ID]*TableDescriptor
func (t TableDescriptors) Len() int { return len(t) }
func (t TableDescriptors) Less(i, j int) bool { return t[i].ID < t[j].ID }
func (t TableDescriptors) Swap(i, j int) { t[i], t[j] = t[j], t[i] }
// ColumnID is a custom type for ColumnDescriptor IDs.
type ColumnID tree.ColumnID
// ColumnIDs is a slice of ColumnDescriptor IDs.
type ColumnIDs []ColumnID
func (c ColumnIDs) Len() int { return len(c) }
func (c ColumnIDs) Swap(i, j int) { c[i], c[j] = c[j], c[i] }
func (c ColumnIDs) Less(i, j int) bool { return c[i] < c[j] }
// HasPrefix returns true if the input list is a prefix of this list.
func (c ColumnIDs) HasPrefix(input ColumnIDs) bool {
if len(input) > len(c) {
return false
}
for i := range input {
if input[i] != c[i] {
return false
}
}
return true
}
// FamilyID is a custom type for ColumnFamilyDescriptor IDs.
type FamilyID uint32
// IndexID is a custom type for IndexDescriptor IDs.
type IndexID tree.IndexID
// DescriptorVersion is a custom type for TableDescriptor Versions.
type DescriptorVersion uint32
// FormatVersion is a custom type for TableDescriptor versions of the sql to
// key:value mapping.
//go:generate stringer -type=FormatVersion
type FormatVersion uint32
const (
_ FormatVersion = iota
// BaseFormatVersion corresponds to the encoding described in
// https://www.cockroachlabs.com/blog/sql-in-cockroachdb-mapping-table-data-to-key-value-storage/.
BaseFormatVersion
// FamilyFormatVersion corresponds to the encoding described in
// https://github.com/cockroachdb/cockroach/blob/master/docs/RFCS/20151214_sql_column_families.md
FamilyFormatVersion
// InterleavedFormatVersion corresponds to the encoding described in
// https://github.com/cockroachdb/cockroach/blob/master/docs/RFCS/20160624_sql_interleaved_tables.md
InterleavedFormatVersion
)
// MutationID is a custom type for TableDescriptor mutations.
type MutationID uint32
// MutableTableDescriptor is a custom type for TableDescriptors
// going through schema mutations.
type MutableTableDescriptor struct {
TableDescriptor
// ClusterVersion represents the version of the table descriptor read from the store.
ClusterVersion TableDescriptor
}
// ImmutableTableDescriptor is a custom type for TableDescriptors
// It holds precomputed values and the underlying TableDescriptor
// should be const.
type ImmutableTableDescriptor struct {
TableDescriptor
// publicAndNonPublicCols is a list of public and non-public columns.
// It is partitioned by the state of the column: public, write-only, delete-only
publicAndNonPublicCols []ColumnDescriptor
// publicAndNonPublicCols is a list of public and non-public indexes.
// It is partitioned by the state of the index: public, write-only, delete-only
publicAndNonPublicIndexes []IndexDescriptor
writeOnlyColCount int
writeOnlyIndexCount int
allChecks []TableDescriptor_CheckConstraint
// ReadableColumns is a list of columns (including those undergoing a schema change)
// which can be scanned. Columns in the process of a schema change
// are all set to nullable while column backfilling is still in
// progress, as mutation columns may have NULL values.
ReadableColumns []ColumnDescriptor
// TODO (lucy): populate these and use them
// inboundFKs []*ForeignKeyConstraint
// outboundFKs []*ForeignKeyConstraint
}
// InvalidMutationID is the uninitialised mutation id.
const InvalidMutationID MutationID = 0
const (
// PrimaryKeyIndexName is the name of the index for the primary key.
PrimaryKeyIndexName = "primary"
)
// 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")
func validateName(name, typ string) error {
if len(name) == 0 {
return fmt.Errorf("empty %s name", typ)
}
// TODO(pmattis): Do we want to be more restrictive than this?
return nil
}
// ToEncodingDirection converts a direction from the proto to an encoding.Direction.
func (dir IndexDescriptor_Direction) ToEncodingDirection() (encoding.Direction, error) {
switch dir {
case IndexDescriptor_ASC:
return encoding.Ascending, nil
case IndexDescriptor_DESC:
return encoding.Descending, nil
default:
return encoding.Ascending, errors.Errorf("invalid direction: %s", dir)
}
}
// ErrDescriptorNotFound is returned by GetTableDescFromID to signal that a
// descriptor could not be found with the given id.
var ErrDescriptorNotFound = errors.New("descriptor not found")
// ErrIndexGCMutationsList is returned by FindIndexByID to signal that the
// index with the given ID does not have a descriptor and is in the garbage
// collected mutations list.
var ErrIndexGCMutationsList = errors.New("index in GC mutations list")
// NewMutableCreatedTableDescriptor returns a MutableTableDescriptor from the
// given TableDescriptor with the cluster version being the zero table. This
// is for a table that is created in the transaction.
func NewMutableCreatedTableDescriptor(tbl TableDescriptor) *MutableTableDescriptor {
return &MutableTableDescriptor{TableDescriptor: tbl}
}
// NewMutableExistingTableDescriptor returns a MutableTableDescriptor from the
// given TableDescriptor with the cluster version also set to the descriptor.
// This is for an existing table.
func NewMutableExistingTableDescriptor(tbl TableDescriptor) *MutableTableDescriptor {
return &MutableTableDescriptor{TableDescriptor: tbl, ClusterVersion: tbl}
}
// NewImmutableTableDescriptor returns a ImmutableTableDescriptor from the
// given TableDescriptor.
func NewImmutableTableDescriptor(tbl TableDescriptor) *ImmutableTableDescriptor {
publicAndNonPublicCols := tbl.Columns
publicAndNonPublicIndexes := tbl.Indexes
readableCols := tbl.Columns
desc := &ImmutableTableDescriptor{TableDescriptor: tbl}
if len(tbl.Mutations) > 0 {
publicAndNonPublicCols = make([]ColumnDescriptor, 0, len(tbl.Columns)+len(tbl.Mutations))
publicAndNonPublicIndexes = make([]IndexDescriptor, 0, len(tbl.Indexes)+len(tbl.Mutations))
readableCols = make([]ColumnDescriptor, 0, len(tbl.Columns)+len(tbl.Mutations))
publicAndNonPublicCols = append(publicAndNonPublicCols, tbl.Columns...)
publicAndNonPublicIndexes = append(publicAndNonPublicIndexes, tbl.Indexes...)
readableCols = append(readableCols, tbl.Columns...)
// Fill up mutations into the column/index lists by placing the writable columns/indexes
// before the delete only columns/indexes.
for _, m := range tbl.Mutations {
switch m.State {
case DescriptorMutation_DELETE_AND_WRITE_ONLY:
if idx := m.GetIndex(); idx != nil {
publicAndNonPublicIndexes = append(publicAndNonPublicIndexes, *idx)
desc.writeOnlyIndexCount++
} else if col := m.GetColumn(); col != nil {
publicAndNonPublicCols = append(publicAndNonPublicCols, *col)
desc.writeOnlyColCount++
}
}
}
for _, m := range tbl.Mutations {
switch m.State {
case DescriptorMutation_DELETE_ONLY:
if idx := m.GetIndex(); idx != nil {
publicAndNonPublicIndexes = append(publicAndNonPublicIndexes, *idx)
} else if col := m.GetColumn(); col != nil {
publicAndNonPublicCols = append(publicAndNonPublicCols, *col)
}
}
}
// Iterate through all mutation columns.
for _, c := range publicAndNonPublicCols[len(tbl.Columns):] {
// Mutation column may need to be fetched, but may not be completely backfilled
// and have be null values (even though they may be configured as NOT NULL).
c.Nullable = true
readableCols = append(readableCols, c)
}
}
desc.ReadableColumns = readableCols
desc.publicAndNonPublicCols = publicAndNonPublicCols
desc.publicAndNonPublicIndexes = publicAndNonPublicIndexes
desc.allChecks = make([]TableDescriptor_CheckConstraint, len(tbl.Checks))
for i, c := range tbl.Checks {
desc.allChecks[i] = *c
}
return desc
}
// protoGetter is a sub-interface of client.Txn that can fetch protobufs in a
// transaction.
type protoGetter interface {
// GetProtoTs retrieves a protoutil.Message that's stored at key, storing it
// into the input msg parameter. If the key doesn't exist, the input proto
// will be reset.
GetProtoTs(ctx context.Context, key interface{}, msg protoutil.Message) (hlc.Timestamp, error)
}
// GetDatabaseDescFromID retrieves the database descriptor for the database
// ID passed in using an existing proto getter. Returns an error if the
// descriptor doesn't exist or if it exists and is not a database.
func GetDatabaseDescFromID(
ctx context.Context, protoGetter protoGetter, id ID,
) (*DatabaseDescriptor, error) {
desc := &Descriptor{}
descKey := MakeDescMetadataKey(id)
_, err := protoGetter.GetProtoTs(ctx, descKey, desc)
if err != nil {
return nil, err
}
db := desc.GetDatabase()
if db == nil {
return nil, ErrDescriptorNotFound
}
return db, nil
}
// GetTableDescFromID retrieves the table descriptor for the table
// ID passed in using an existing proto getter. Returns an error if the
// descriptor doesn't exist or if it exists and is not a table.
func GetTableDescFromID(
ctx context.Context, protoGetter protoGetter, id ID,
) (*TableDescriptor, error) {
table, err := getTableDescFromIDRaw(ctx, protoGetter, id)
if err != nil {
return nil, err
}
if err := table.MaybeFillInDescriptor(ctx, protoGetter); err != nil {
return nil, err
}
return table, nil
}
// getTableDescFromIDRaw retrieves the table descriptor for the table
// ID passed in using an existing proto getter. Returns an error if the
// descriptor doesn't exist or if it exists and is not a table. Note that it
// does not "fill in" the descriptor, which performs various upgrade steps for
// migrations and is *required* before ordinary presentation to other code. This
// method is for internal use only and shouldn't get exposed.
func getTableDescFromIDRaw(
ctx context.Context, protoGetter protoGetter, id ID,
) (*TableDescriptor, error) {
desc := &Descriptor{}
descKey := MakeDescMetadataKey(id)
ts, err := protoGetter.GetProtoTs(ctx, descKey, desc)
if err != nil {
return nil, err
}
table := desc.Table(ts)
if table == nil {
return nil, ErrDescriptorNotFound
}
return table, nil
}
// GetMutableTableDescFromID retrieves the table descriptor for the table
// ID passed in using an existing proto getter. Returns an error if the
// descriptor doesn't exist or if it exists and is not a table.
// Otherwise a mutable copy of the table is returned.
func GetMutableTableDescFromID(
ctx context.Context, protoGetter protoGetter, id ID,
) (*MutableTableDescriptor, error) {
table, err := GetTableDescFromID(ctx, protoGetter, id)
if err != nil {
return nil, err
}
return NewMutableExistingTableDescriptor(*table), nil
}
// RunOverAllColumns applies its argument fn to each of the column IDs in desc.
// If there is an error, that error is returned immediately.
func (desc *IndexDescriptor) RunOverAllColumns(fn func(id ColumnID) error) error {
for _, colID := range desc.ColumnIDs {
if err := fn(colID); err != nil {
return err
}
}
for _, colID := range desc.ExtraColumnIDs {
if err := fn(colID); err != nil {
return err
}
}
for _, colID := range desc.StoreColumnIDs {
if err := fn(colID); err != nil {
return err
}
}
return nil
}
// FindPartitionByName searches this partitioning descriptor for a partition
// whose name is the input and returns it, or nil if no match is found.
func (desc *PartitioningDescriptor) FindPartitionByName(name string) *PartitioningDescriptor {
for _, l := range desc.List {
if l.Name == name {
return desc
}
if s := l.Subpartitioning.FindPartitionByName(name); s != nil {
return s
}
}
for _, r := range desc.Range {
if r.Name == name {
return desc
}
}
return nil
}
// FindPartitionByName searches this index descriptor for a partition whose name
// is the input and returns it, or nil if no match is found.
func (desc *IndexDescriptor) FindPartitionByName(name string) *PartitioningDescriptor {
return desc.Partitioning.FindPartitionByName(name)
}
// allocateName sets desc.Name to a value that is not EqualName to any
// of tableDesc's indexes. allocateName roughly follows PostgreSQL's
// convention for automatically-named indexes.
func (desc *IndexDescriptor) allocateName(tableDesc *MutableTableDescriptor) {
segments := make([]string, 0, len(desc.ColumnNames)+2)
segments = append(segments, tableDesc.Name)
segments = append(segments, desc.ColumnNames...)
if desc.Unique {
segments = append(segments, "key")
} else {
segments = append(segments, "idx")
}
baseName := strings.Join(segments, "_")
name := baseName
exists := func(name string) bool {
_, _, err := tableDesc.FindIndexByName(name)
return err == nil
}
for i := 1; exists(name); i++ {
name = fmt.Sprintf("%s%d", baseName, i)
}
desc.Name = name
}
// FillColumns sets the column names and directions in desc.
func (desc *IndexDescriptor) FillColumns(elems tree.IndexElemList) error {
desc.ColumnNames = make([]string, 0, len(elems))
desc.ColumnDirections = make([]IndexDescriptor_Direction, 0, len(elems))
for _, c := range elems {
desc.ColumnNames = append(desc.ColumnNames, string(c.Column))
switch c.Direction {
case tree.Ascending, tree.DefaultDirection:
desc.ColumnDirections = append(desc.ColumnDirections, IndexDescriptor_ASC)
case tree.Descending:
desc.ColumnDirections = append(desc.ColumnDirections, IndexDescriptor_DESC)
default:
return fmt.Errorf("invalid direction %s for column %s", c.Direction, c.Column)
}
}
return nil
}
type returnTrue struct{}
func (returnTrue) Error() string { panic("unimplemented") }
var returnTruePseudoError error = returnTrue{}
// ContainsColumnID returns true if the index descriptor contains the specified
// column ID either in its explicit column IDs, the extra column IDs, or the
// stored column IDs.
func (desc *IndexDescriptor) ContainsColumnID(colID ColumnID) bool {
return desc.RunOverAllColumns(func(id ColumnID) error {
if id == colID {
return returnTruePseudoError
}
return nil
}) != nil
}
// FullColumnIDs returns the index column IDs including any extra (implicit or
// stored (old STORING encoding)) column IDs for non-unique indexes. It also
// returns the direction with which each column was encoded.
func (desc *IndexDescriptor) FullColumnIDs() ([]ColumnID, []IndexDescriptor_Direction) {
if desc.Unique {
return desc.ColumnIDs, desc.ColumnDirections
}
// Non-unique indexes have some of the primary-key columns appended to
// their key.
columnIDs := append([]ColumnID(nil), desc.ColumnIDs...)
columnIDs = append(columnIDs, desc.ExtraColumnIDs...)
dirs := append([]IndexDescriptor_Direction(nil), desc.ColumnDirections...)
for range desc.ExtraColumnIDs {
// Extra columns are encoded in ascending order.
dirs = append(dirs, IndexDescriptor_ASC)
}
return columnIDs, dirs
}
// ColNamesFormat writes a string describing the column names and directions
// in this index to the given buffer.
func (desc *IndexDescriptor) ColNamesFormat(ctx *tree.FmtCtx) {
for i := range desc.ColumnNames {
if i > 0 {
ctx.WriteString(", ")
}
ctx.FormatNameP(&desc.ColumnNames[i])
if desc.Type != IndexDescriptor_INVERTED {
ctx.WriteByte(' ')
ctx.WriteString(desc.ColumnDirections[i].String())
}
}
}
// TODO (tyler): Issue #39771 This method needs more thorough testing, probably
// in structured_test.go. Or possibly replace it with a format method taking
// a format context as argument.
// ColNamesString returns a string describing the column names and directions
// in this index.
func (desc *IndexDescriptor) ColNamesString() string {
f := tree.NewFmtCtx(tree.FmtSimple)
desc.ColNamesFormat(f)
return f.CloseAndGetString()
}
// TODO (tyler): Issue #39771 Same comment as ColNamesString above.
// SQLString returns the SQL string describing this index. If non-empty,
// "ON tableName" is included in the output in the correct place.
func (desc *IndexDescriptor) SQLString(tableName *tree.TableName) string {
f := tree.NewFmtCtx(tree.FmtSimple)
if desc.Unique {
f.WriteString("UNIQUE ")
}
if desc.Type == IndexDescriptor_INVERTED {
f.WriteString("INVERTED ")
}
f.WriteString("INDEX ")
f.FormatNameP(&desc.Name)
if *tableName != AnonymousTable {
f.WriteString(" ON ")
f.FormatNode(tableName)
}
f.WriteString(" (")
desc.ColNamesFormat(f)
f.WriteByte(')')
if len(desc.StoreColumnNames) > 0 {
f.WriteString(" STORING (")
for i := range desc.StoreColumnNames {
if i > 0 {
f.WriteString(", ")
}
f.FormatNameP(&desc.StoreColumnNames[i])
}
f.WriteByte(')')
}
return f.CloseAndGetString()
}
// IsInterleaved returns whether the index is interleaved or not.
func (desc *IndexDescriptor) IsInterleaved() bool {
return len(desc.Interleave.Ancestors) > 0 || len(desc.InterleavedBy) > 0
}
// SetID implements the DescriptorProto interface.
func (desc *TableDescriptor) SetID(id ID) {
desc.ID = id
}
// TypeName returns the plain type of this descriptor.
func (desc *TableDescriptor) TypeName() string {
return "relation"
}
// SetName implements the DescriptorProto interface.
func (desc *TableDescriptor) SetName(name string) {
desc.Name = name
}
// IsTable returns true if the TableDescriptor actually describes a
// Table resource, as opposed to a different resource (like a View).
func (desc *TableDescriptor) IsTable() bool {
return !desc.IsView() && !desc.IsSequence()
}
// IsView returns true if the TableDescriptor actually describes a
// View resource rather than a Table.
func (desc *TableDescriptor) IsView() bool {
return desc.ViewQuery != ""
}
// IsAs returns true if the TableDescriptor actually describes
// a Table resource with an As source.
func (desc *TableDescriptor) IsAs() bool {
return desc.CreateQuery != ""
}
// IsSequence returns true if the TableDescriptor actually describes a
// Sequence resource rather than a Table.
func (desc *TableDescriptor) IsSequence() bool {
return desc.SequenceOpts != nil
}
// IsVirtualTable returns true if the TableDescriptor describes a
// virtual Table (like the information_schema tables) and thus doesn't
// need to be physically stored.
func (desc *TableDescriptor) IsVirtualTable() bool {
return IsVirtualTable(desc.ID)
}
// IsVirtualTable returns true if the TableDescriptor describes a
// virtual Table (like the informationgi_schema tables) and thus doesn't
// need to be physically stored.
func IsVirtualTable(id ID) bool {
return MinVirtualID <= id
}
// IsPhysicalTable returns true if the TableDescriptor actually describes a
// physical Table that needs to be stored in the kv layer, as opposed to a
// different resource like a view or a virtual table. Physical tables have
// primary keys, column families, and indexes (unlike virtual tables).
// Sequences count as physical tables because their values are stored in
// the KV layer.
func (desc *TableDescriptor) IsPhysicalTable() bool {
return desc.IsSequence() || (desc.IsTable() && !desc.IsVirtualTable())
}
// KeysPerRow returns the maximum number of keys used to encode a row for the
// given index. For secondary indexes, we always only use one, but for primary
// indexes, we can encode up to one kv per column family.
func (desc *TableDescriptor) KeysPerRow(indexID IndexID) int {
if desc.PrimaryIndex.ID == indexID {
return len(desc.Families)
}
return 1
}
// AllNonDropColumns returns all the columns, including those being added
// in the mutations.
func (desc *TableDescriptor) AllNonDropColumns() []ColumnDescriptor {
cols := make([]ColumnDescriptor, 0, len(desc.Columns)+len(desc.Mutations))
cols = append(cols, desc.Columns...)
for _, m := range desc.Mutations {
if col := m.GetColumn(); col != nil {
if m.Direction == DescriptorMutation_ADD {
cols = append(cols, *col)
}
}
}
return cols
}
// AllNonDropIndexes returns all the indexes, including those being added
// in the mutations.
func (desc *TableDescriptor) AllNonDropIndexes() []*IndexDescriptor {
indexes := make([]*IndexDescriptor, 0, 1+len(desc.Indexes)+len(desc.Mutations))
if desc.IsPhysicalTable() {
indexes = append(indexes, &desc.PrimaryIndex)
}
for i := range desc.Indexes {
indexes = append(indexes, &desc.Indexes[i])
}
for _, m := range desc.Mutations {
if idx := m.GetIndex(); idx != nil {
if m.Direction == DescriptorMutation_ADD {
indexes = append(indexes, idx)
}
}
}
return indexes
}
// AllActiveAndInactiveChecks returns all check constraints, including both
// "active" ones on the table descriptor which are being enforced for all
// writes, and "inactive" ones queued in the mutations list.
func (desc *TableDescriptor) AllActiveAndInactiveChecks() []*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([]*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 != ConstraintValidity_Validating && c.Validity != ConstraintValidity_Dropping {
checks = append(checks, c)
}
}
for _, m := range desc.Mutations {
if c := m.GetConstraint(); c != nil && c.ConstraintType == ConstraintToUpdate_CHECK {
checks = append(checks, &c.Check)
}
}
return checks
}
// AllActiveAndInactiveForeignKeys returns all foreign keys, including both
// "active" ones on the index descriptor which are being enforced for all
// writes, and "inactive" ones queued in the mutations list. An error is
// returned if multiple foreign keys (including mutations) are found for the
// same index.
func (desc *TableDescriptor) AllActiveAndInactiveForeignKeys() []*ForeignKeyConstraint {
fks := make([]*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 != ConstraintValidity_Validating && fk.Validity != ConstraintValidity_Dropping {
fks = append(fks, fk)
}
}
for i := range desc.Mutations {
if c := desc.Mutations[i].GetConstraint(); c != nil && c.ConstraintType == ConstraintToUpdate_FOREIGN_KEY {
fks = append(fks, &c.ForeignKey)
}
}
return fks
}
// ForeachNonDropIndex runs a function on all indexes, including those being
// added in the mutations.
func (desc *TableDescriptor) ForeachNonDropIndex(f func(*IndexDescriptor) error) error {
if desc.IsPhysicalTable() {
if err := f(&desc.PrimaryIndex); err != nil {
return err
}
}
for i := range desc.Indexes {
if err := f(&desc.Indexes[i]); err != nil {
return err
}
}
for _, m := range desc.Mutations {
if idx := m.GetIndex(); idx != nil && m.Direction == DescriptorMutation_ADD {
if err := f(idx); err != nil {
return err
}
}
}
return nil
}
func generatedFamilyName(familyID 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()
}
// MaybeFillInDescriptor performs any modifications needed to the table descriptor.
// This includes format upgrades and optional changes that can be handled by all version
// (for example: additional default privileges).
// Returns true if any changes were made.
func (desc *TableDescriptor) MaybeFillInDescriptor(
ctx context.Context, protoGetter protoGetter,
) error {
desc.maybeUpgradeFormatVersion()
desc.Privileges.MaybeFixPrivileges(desc.ID)
if protoGetter != nil {
if _, err := desc.MaybeUpgradeForeignKeyRepresentation(ctx, protoGetter, false /* skipFKsWithNoMatchingTable*/); err != nil {
return err
}
}
return nil
}
// MapProtoGetter is a protoGetter that has a hard-coded map of keys to proto
// messages.
type MapProtoGetter struct {
Protos map[interface{}]protoutil.Message
}
// getProto implements the protoGetter interface.
func (m MapProtoGetter) getProto(
ctx context.Context, key interface{}, msg protoutil.Message,
) error {
msg.Reset()
if other, ok := m.Protos[string(key.(roachpb.Key))]; ok {
bytes := make([]byte, other.Size())
if _, err := other.MarshalTo(bytes); err != nil {
return err
}
if err := protoutil.Unmarshal(bytes, msg); err != nil {
return err
}
}
return nil
}
// GetProtoTs implements the protoGetter interface.
func (m MapProtoGetter) GetProtoTs(
ctx context.Context, key interface{}, msg protoutil.Message,
) (hlc.Timestamp, error) {
return hlc.Timestamp{}, m.getProto(ctx, key, msg)
}
// MaybeUpgradeForeignKeyRepresentation destructively modifies the input table
// descriptor by replacing all old-style foreign key references (the ForeignKey
// and ReferencedBy fields on IndexDescriptor) with new-style foreign key
// references (the InboundFKs and OutboundFKs fields on TableDescriptor). It
// uses the supplied proto getter to look up the referenced descriptor on
// outgoing FKs and the origin descriptor on incoming FKs. It returns true in
// the first position if the descriptor was upgraded at all (i.e. had old-style
// references on it) and an error if the descriptor was unable to be upgraded
// for some reason.
// If skipFKsWithNoMatchingTable is set to true, if a *table* that's supposed to
// contain the matching forward/back-reference for an FK is not found, the FK
// is dropped from the table and no error is returned.
// TODO(lucy): Write tests for when skipFKsWithNoMatchingTable is true.
func (desc *TableDescriptor) MaybeUpgradeForeignKeyRepresentation(
ctx context.Context, protoGetter protoGetter, skipFKsWithNoMatchingTable bool,
) (bool, error) {
if desc.Dropped() {
// If the table has been dropped, it's permitted to have corrupted foreign
// keys, so we have no chance to properly upgrade it. Just return as-is.
return false, nil
}
otherUnupgradedTables := make(map[ID]*TableDescriptor)
changed := false
// No need to process mutations, since only descriptors written on a 19.2
// cluster (after finalizing the upgrade) have foreign key mutations.
for i := range desc.Indexes {
newChanged, err := maybeUpgradeForeignKeyRepOnIndex(
ctx, protoGetter, otherUnupgradedTables, desc, &desc.Indexes[i], skipFKsWithNoMatchingTable,
)
if err != nil {
return false, err
}
changed = changed || newChanged
}
newChanged, err := maybeUpgradeForeignKeyRepOnIndex(
ctx, protoGetter, otherUnupgradedTables, desc, &desc.PrimaryIndex, skipFKsWithNoMatchingTable,
)
if err != nil {
return false, err
}
changed = changed || newChanged
return changed, nil
}
// maybeUpgradeForeignKeyRepOnIndex is the meat of the previous function - it
// tries to upgrade a particular index's foreign key representation.
func maybeUpgradeForeignKeyRepOnIndex(
ctx context.Context,
protoGetter protoGetter,
otherUnupgradedTables map[ID]*TableDescriptor,
desc *TableDescriptor,
idx *IndexDescriptor,
skipFKsWithNoMatchingTable bool,
) (bool, error) {
var changed bool
if idx.ForeignKey.IsSet() {
ref := &idx.ForeignKey
if _, ok := otherUnupgradedTables[ref.Table]; !ok {
tbl, err := getTableDescFromIDRaw(ctx, protoGetter, ref.Table)
if err != nil {
if err == ErrDescriptorNotFound && skipFKsWithNoMatchingTable {
// Ignore this FK and keep going.
} else {
return false, err
}
} else {
otherUnupgradedTables[ref.Table] = tbl
}
}
if tbl, ok := otherUnupgradedTables[ref.Table]; ok {
referencedIndex, err := tbl.FindIndexByID(ref.Index)
if err != nil {
return false, err
}
numCols := ref.SharedPrefixLen
outFK := ForeignKeyConstraint{
OriginTableID: desc.ID,
OriginColumnIDs: idx.ColumnIDs[:numCols],
ReferencedTableID: ref.Table,
ReferencedColumnIDs: referencedIndex.ColumnIDs[:numCols],
Name: ref.Name,
Validity: ref.Validity,
OnDelete: ref.OnDelete,
OnUpdate: ref.OnUpdate,
Match: ref.Match,
LegacyOriginIndex: idx.ID,
LegacyReferencedIndex: referencedIndex.ID,
LegacyUpgradedFromOriginReference: idx.ForeignKey,
}
desc.OutboundFKs = append(desc.OutboundFKs, outFK)
}
changed = true
idx.ForeignKey = ForeignKeyReference{}
}
for refIdx := range idx.ReferencedBy {
ref := &(idx.ReferencedBy[refIdx])
if _, ok := otherUnupgradedTables[ref.Table]; !ok {
tbl, err := getTableDescFromIDRaw(ctx, protoGetter, ref.Table)
if err != nil {
if err == ErrDescriptorNotFound && skipFKsWithNoMatchingTable {
// Ignore this FK and keep going.
} else {
return false, err
}
} else {
otherUnupgradedTables[ref.Table] = tbl
}
}
if otherTable, ok := otherUnupgradedTables[ref.Table]; ok {
originIndex, err := otherTable.FindIndexByID(ref.Index)
if err != nil {
return false, err
}
// There are two cases. Either the other table is old (not upgraded yet),
// or it's new (already upgraded).
var inFK ForeignKeyConstraint
if !originIndex.ForeignKey.IsSet() {
// The other table has either no foreign key, indicating a corrupt
// reference, or the other table was upgraded. Assume the second for now.
// If we also find no matching reference in the new-style foreign keys,
// that indicates a corrupt reference.
var forwardFK *ForeignKeyConstraint
for i := range otherTable.OutboundFKs {
otherFK := &otherTable.OutboundFKs[i]
// To find a match, we need to compare the reference's table id and
// index id, which are the only two available fields on backreferences
// in the old representation. Note that we have to compare the index id
// to the matching new forward reference's LegacyOriginIndex field,
// which although marked as Legacy, is populated every time we create
// a new-style fk during the duration of 19.2.
if otherFK.ReferencedTableID == desc.ID &&
otherFK.LegacyOriginIndex == ref.Index {
// Found a match.
forwardFK = otherFK
break
}
}
if forwardFK == nil {
// Corrupted foreign key - there was no forward reference for the back
// reference.
return false, errors.AssertionFailedf(
"error finding foreign key on table %d for backref %+v",
otherTable.ID, ref)
}
inFK = ForeignKeyConstraint{
OriginTableID: ref.Table,
OriginColumnIDs: forwardFK.OriginColumnIDs,
ReferencedTableID: desc.ID,
ReferencedColumnIDs: forwardFK.ReferencedColumnIDs,
Name: forwardFK.Name,
Validity: forwardFK.Validity,
OnDelete: forwardFK.OnDelete,
OnUpdate: forwardFK.OnUpdate,
Match: forwardFK.Match,
LegacyOriginIndex: originIndex.ID,
LegacyReferencedIndex: idx.ID,
LegacyUpgradedFromReferencedReference: *ref,
}
} else {
// We have an old (not upgraded yet) table, with a matching forward
// foreign key.
numCols := originIndex.ForeignKey.SharedPrefixLen
inFK = ForeignKeyConstraint{
OriginTableID: ref.Table,
OriginColumnIDs: originIndex.ColumnIDs[:numCols],
ReferencedTableID: desc.ID,
ReferencedColumnIDs: idx.ColumnIDs[:numCols],
Name: originIndex.ForeignKey.Name,
Validity: originIndex.ForeignKey.Validity,
OnDelete: originIndex.ForeignKey.OnDelete,
OnUpdate: originIndex.ForeignKey.OnUpdate,
Match: originIndex.ForeignKey.Match,
LegacyOriginIndex: originIndex.ID,
LegacyReferencedIndex: idx.ID,
LegacyUpgradedFromReferencedReference: *ref,
}
}
desc.InboundFKs = append(desc.InboundFKs, inFK)
}
changed = true
}
idx.ReferencedBy = nil
return changed, nil
}
// MaybeDowngradeForeignKeyRepresentation non-destructively downgrades the
// receiver into the old foreign key representation (the ForeignKey
// and ReferencedBy fields on IndexDescriptor if and only if the cluster version
// has not yet been upgraded to VersionTopLevelForeignKeys. It returns true in
// the first position if the downgrade occurred, along with a new
// TableDescriptor object that is the downgraded descriptor. The receiver is not
// modified in either case.
func (desc *TableDescriptor) MaybeDowngradeForeignKeyRepresentation(
ctx context.Context, clusterSettings *cluster.Settings,
) (bool, *TableDescriptor, error) {
downgradeUnnecessary := clusterSettings.Version.IsActive(cluster.VersionTopLevelForeignKeys)
if downgradeUnnecessary {
return false, desc, nil