-
Notifications
You must be signed in to change notification settings - Fork 0
/
structured.go
2114 lines (1919 loc) · 64.8 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.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
// implied. See the License for the specific language governing
// permissions and limitations under the License.
package sqlbase
import (
"bytes"
"fmt"
"strings"
"unicode/utf8"
"github.com/pkg/errors"
"golang.org/x/net/context"
"github.com/cockroachdb/cockroach/pkg/internal/client"
"github.com/cockroachdb/cockroach/pkg/keys"
"github.com/cockroachdb/cockroach/pkg/roachpb"
"github.com/cockroachdb/cockroach/pkg/sql/parser"
"github.com/cockroachdb/cockroach/pkg/sql/pgwire/pgerror"
"github.com/cockroachdb/cockroach/pkg/util/encoding"
)
// 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 parser.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
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 parser.ColumnID
// FamilyID is a custom type for ColumnFamilyDescriptor IDs.
type FamilyID uint32
// IndexID is a custom type for IndexDescriptor IDs.
type IndexID parser.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/sql_column_families.md
FamilyFormatVersion
// InterleavedFormatVersion corresponds to the encoding described in
// https://github.com/cockroachdb/cockroach/blob/master/docs/RFCS/sql_interleaved_tables.md
InterleavedFormatVersion
)
// MutationID is a custom type for TableDescriptor mutations.
type MutationID uint32
// 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")
// GetDatabaseDescFromID retrieves the database descriptor for the database
// ID passed in using an existing txn. Returns an error if the descriptor
// doesn't exist or if it exists and is not a database.
func GetDatabaseDescFromID(
ctx context.Context, txn *client.Txn, id ID,
) (*DatabaseDescriptor, error) {
desc := &Descriptor{}
descKey := MakeDescMetadataKey(id)
if err := txn.GetProto(ctx, descKey, desc); 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 txn. Returns an error if the
// descriptor doesn't exist or if it exists and is not a table.
func GetTableDescFromID(ctx context.Context, txn *client.Txn, id ID) (*TableDescriptor, error) {
desc := &Descriptor{}
descKey := MakeDescMetadataKey(id)
if err := txn.GetProto(ctx, descKey, desc); err != nil {
return nil, err
}
table := desc.GetTable()
if table == nil {
return nil, ErrDescriptorNotFound
}
return 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
}
// 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 *TableDescriptor) {
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 parser.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 parser.Ascending, parser.DefaultDirection:
desc.ColumnDirections = append(desc.ColumnDirections, IndexDescriptor_ASC)
case parser.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, []encoding.Direction) {
dirs := make([]encoding.Direction, 0, len(desc.ColumnIDs))
for _, dir := range desc.ColumnDirections {
convertedDir, err := dir.ToEncodingDirection()
if err != nil {
panic(err)
}
dirs = append(dirs, convertedDir)
}
if desc.Unique {
return desc.ColumnIDs, dirs
}
// 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...)
for range desc.ExtraColumnIDs {
// Extra columns are encoded ascendingly.
dirs = append(dirs, encoding.Ascending)
}
return columnIDs, dirs
}
// ColNamesString returns a string describing the column names and directions
// in this index.
func (desc *IndexDescriptor) ColNamesString() string {
var buf bytes.Buffer
for i, name := range desc.ColumnNames {
if i > 0 {
buf.WriteString(", ")
}
fmt.Fprintf(&buf, "%s %s", parser.Name(name), desc.ColumnDirections[i])
}
return buf.String()
}
var isUnique = map[bool]string{true: "UNIQUE "}
// 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 string) string {
var storing string
if len(desc.StoreColumnNames) > 0 {
colNames := make(parser.NameList, len(desc.StoreColumnNames))
for i, n := range desc.StoreColumnNames {
colNames[i] = parser.Name(n)
}
storing = fmt.Sprintf(" STORING (%s)", parser.AsString(colNames))
}
var onTable string
if tableName != "" {
onTable = fmt.Sprintf("ON %s ", tableName)
}
return fmt.Sprintf("%sINDEX %s%s (%s)%s",
isUnique[desc.Unique],
onTable,
parser.AsString(parser.Name(desc.Name)),
desc.ColNamesString(),
storing,
)
}
// 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
}
// IsEmpty checks if the descriptor is uninitialized.
func (desc *TableDescriptor) IsEmpty() bool {
// Valid tables cannot have an ID of 0.
return desc.ID == 0
}
// 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()
}
// IsView returns true if the TableDescriptor actually describes a
// View resource rather than a Table.
func (desc *TableDescriptor) IsView() bool {
return desc.ViewQuery != ""
}
// 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 desc.ID == keys.VirtualDescriptorID
}
// 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).
func (desc *TableDescriptor) IsPhysicalTable() bool {
return 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)
}
indexes = append(indexes, desc.Indexes...)
for _, m := range desc.Mutations {
if idx := m.GetIndex(); idx != nil {
if m.Direction == DescriptorMutation_ADD {
indexes = append(indexes, *idx)
}
}
}
return indexes
}
// 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 bytes.Buffer
fmt.Fprintf(&buf, "fam_%d", familyID)
for _, n := range columnNames {
buf.WriteString(`_`)
buf.WriteString(n)
}
return buf.String()
}
// MaybeUpgradeFormatVersion transforms the TableDescriptor to the latest
// FormatVersion (if it's not already there) and returns true if any changes
// were made.
func (desc *TableDescriptor) MaybeUpgradeFormatVersion() bool {
if desc.FormatVersion >= InterleavedFormatVersion {
return false
}
desc.maybeUpgradeToFamilyFormatVersion()
desc.FormatVersion = InterleavedFormatVersion
return true
}
func (desc *TableDescriptor) maybeUpgradeToFamilyFormatVersion() bool {
if desc.FormatVersion >= FamilyFormatVersion {
return false
}
primaryIndexColumnIds := make(map[ColumnID]struct{}, len(desc.PrimaryIndex.ColumnIDs))
for _, colID := range desc.PrimaryIndex.ColumnIDs {
primaryIndexColumnIds[colID] = struct{}{}
}
desc.Families = []ColumnFamilyDescriptor{
{ID: 0, Name: "primary"},
}
desc.NextFamilyID = desc.Families[0].ID + 1
addFamilyForCol := func(col ColumnDescriptor) {
if _, ok := primaryIndexColumnIds[col.ID]; ok {
desc.Families[0].ColumnNames = append(desc.Families[0].ColumnNames, col.Name)
desc.Families[0].ColumnIDs = append(desc.Families[0].ColumnIDs, col.ID)
return
}
colNames := []string{col.Name}
family := ColumnFamilyDescriptor{
ID: FamilyID(col.ID),
Name: generatedFamilyName(FamilyID(col.ID), colNames),
ColumnNames: colNames,
ColumnIDs: []ColumnID{col.ID},
DefaultColumnID: col.ID,
}
desc.Families = append(desc.Families, family)
if family.ID >= desc.NextFamilyID {
desc.NextFamilyID = family.ID + 1
}
}
for _, c := range desc.Columns {
addFamilyForCol(c)
}
for _, m := range desc.Mutations {
if c := m.GetColumn(); c != nil {
addFamilyForCol(*c)
}
}
desc.FormatVersion = FamilyFormatVersion
return true
}
// AllocateIDs allocates column, family, and index ids for any column, family,
// or index which has an ID of 0.
func (desc *TableDescriptor) AllocateIDs() error {
// Only physical tables can have / need a primary key.
if desc.IsPhysicalTable() {
if err := desc.ensurePrimaryKey(); err != nil {
return err
}
}
if desc.NextColumnID == 0 {
desc.NextColumnID = 1
}
if desc.Version == 0 {
desc.Version = 1
}
if desc.NextMutationID == InvalidMutationID {
desc.NextMutationID = 1
}
columnNames := map[string]ColumnID{}
fillColumnID := func(c *ColumnDescriptor) {
columnID := c.ID
if columnID == 0 {
columnID = desc.NextColumnID
desc.NextColumnID++
}
columnNames[c.Name] = columnID
c.ID = columnID
}
for i := range desc.Columns {
fillColumnID(&desc.Columns[i])
}
for _, m := range desc.Mutations {
if c := m.GetColumn(); c != nil {
fillColumnID(c)
}
}
// Only physical tables can have / need indexes and column families.
if desc.IsPhysicalTable() {
if err := desc.allocateIndexIDs(columnNames); err != nil {
return err
}
desc.allocateColumnFamilyIDs(columnNames)
}
// 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.MaxReservedDescID + 1
}
err := desc.ValidateTable()
desc.ID = savedID
return err
}
func (desc *TableDescriptor) ensurePrimaryKey() error {
if len(desc.PrimaryIndex.ColumnNames) == 0 && desc.IsPhysicalTable() {
// Ensure a Primary Key exists.
s := "unique_rowid()"
col := ColumnDescriptor{
Name: "rowid",
Type: ColumnType{
SemanticType: ColumnType_INT,
},
DefaultExpr: &s,
Hidden: true,
Nullable: false,
}
desc.AddColumn(col)
idx := IndexDescriptor{
Unique: true,
ColumnNames: []string{col.Name},
ColumnDirections: []IndexDescriptor_Direction{IndexDescriptor_ASC},
}
if err := desc.AddIndex(idx, true); err != nil {
return err
}
}
return nil
}
// HasCompositeKeyEncoding returns true if key columns of the given kind can
// have a composite encoding. For such types, it can be decided on a
// case-by-base basis whether a given Datum requires the composite encoding.
func HasCompositeKeyEncoding(semanticType ColumnType_SemanticType) bool {
switch semanticType {
case ColumnType_COLLATEDSTRING,
ColumnType_FLOAT,
ColumnType_DECIMAL:
return true
}
return false
}
// MustBeValueEncoded returns true if columns of the given kind can only be value
// encoded.
func MustBeValueEncoded(semanticType ColumnType_SemanticType) bool {
return semanticType == ColumnType_ARRAY
}
// HasOldStoredColumns returns whether the index has stored columns in the old
// format (data encoded the same way as if they were in an implicit column).
func (desc *IndexDescriptor) HasOldStoredColumns() bool {
return len(desc.ExtraColumnIDs) > 0 && len(desc.StoreColumnIDs) < len(desc.StoreColumnNames)
}
func (desc *TableDescriptor) allocateIndexIDs(columnNames map[string]ColumnID) error {
if desc.NextIndexID == 0 {
desc.NextIndexID = 1
}
// Keep track of unnamed indexes.
anonymousIndexes := make([]*IndexDescriptor, 0, len(desc.Indexes)+len(desc.Mutations))
// Create a slice of modifiable index descriptors.
indexes := make([]*IndexDescriptor, 0, 1+len(desc.Indexes)+len(desc.Mutations))
indexes = append(indexes, &desc.PrimaryIndex)
collectIndexes := func(index *IndexDescriptor) {
if len(index.Name) == 0 {
anonymousIndexes = append(anonymousIndexes, index)
}
indexes = append(indexes, index)
}
for i := range desc.Indexes {
collectIndexes(&desc.Indexes[i])
}
for _, m := range desc.Mutations {
if index := m.GetIndex(); index != nil {
collectIndexes(index)
}
}
for _, index := range anonymousIndexes {
index.allocateName(desc)
}
isCompositeColumn := make(map[ColumnID]struct{})
for _, col := range desc.Columns {
if HasCompositeKeyEncoding(col.Type.SemanticType) {
isCompositeColumn[col.ID] = struct{}{}
}
}
// Populate IDs.
for _, index := range indexes {
if index.ID == 0 {
index.ID = desc.NextIndexID
desc.NextIndexID++
}
for j, colName := range index.ColumnNames {
if len(index.ColumnIDs) <= j {
index.ColumnIDs = append(index.ColumnIDs, 0)
}
if index.ColumnIDs[j] == 0 {
index.ColumnIDs[j] = columnNames[colName]
}
}
if index != &desc.PrimaryIndex {
indexHasOldStoredColumns := index.HasOldStoredColumns()
// Need to clear ExtraColumnIDs and StoreColumnIDs because they are used
// by ContainsColumnID.
index.ExtraColumnIDs = nil
index.StoreColumnIDs = nil
var extraColumnIDs []ColumnID
for _, primaryColID := range desc.PrimaryIndex.ColumnIDs {
if !index.ContainsColumnID(primaryColID) {
extraColumnIDs = append(extraColumnIDs, primaryColID)
}
}
index.ExtraColumnIDs = extraColumnIDs
for _, colName := range index.StoreColumnNames {
col, _, err := desc.FindColumnByName(parser.Name(colName))
if err != nil {
return err
}
if desc.PrimaryIndex.ContainsColumnID(col.ID) {
continue
}
if index.ContainsColumnID(col.ID) {
return fmt.Errorf("index %q already contains column %q", index.Name, col.Name)
}
if indexHasOldStoredColumns {
index.ExtraColumnIDs = append(index.ExtraColumnIDs, col.ID)
} else {
index.StoreColumnIDs = append(index.StoreColumnIDs, col.ID)
}
}
}
index.CompositeColumnIDs = nil
for _, colID := range index.ColumnIDs {
if _, ok := isCompositeColumn[colID]; ok {
index.CompositeColumnIDs = append(index.CompositeColumnIDs, colID)
}
}
for _, colID := range index.ExtraColumnIDs {
if _, ok := isCompositeColumn[colID]; ok {
index.CompositeColumnIDs = append(index.CompositeColumnIDs, colID)
}
}
}
return nil
}
func (desc *TableDescriptor) allocateColumnFamilyIDs(columnNames map[string]ColumnID) {
if desc.NextFamilyID == 0 {
if len(desc.Families) == 0 {
desc.Families = []ColumnFamilyDescriptor{
{ID: 0, Name: "primary"},
}
}
desc.NextFamilyID = 1
}
columnsInFamilies := make(map[ColumnID]struct{}, len(desc.Columns))
for i, family := range desc.Families {
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[family.ColumnIDs[j]] = struct{}{}
}
desc.Families[i] = family
}
primaryIndexColIDs := make(map[ColumnID]struct{}, len(desc.PrimaryIndex.ColumnIDs))
for _, colID := range desc.PrimaryIndex.ColumnIDs {
primaryIndexColIDs[colID] = struct{}{}
}
ensureColumnInFamily := func(col *ColumnDescriptor) {
if _, ok := columnsInFamilies[col.ID]; ok {
return
}
if _, ok := primaryIndexColIDs[col.ID]; ok {
// 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 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 = FamilyID(col.ID)
desc.Families = append(desc.Families, ColumnFamilyDescriptor{
ID: familyID,
ColumnNames: []string{col.Name},
ColumnIDs: []ColumnID{col.ID},
})
} else {
idx, ok := fitColumnToFamily(*desc, *col)
if !ok {
idx = len(desc.Families)
desc.Families = append(desc.Families, ColumnFamilyDescriptor{
ID: desc.NextFamilyID,
ColumnNames: []string{},
ColumnIDs: []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, family := range desc.Families {
if len(family.Name) == 0 {
family.Name = generatedFamilyName(family.ID, family.ColumnNames)
}
if family.DefaultColumnID == 0 {
defaultColumnID := ColumnID(0)
for _, colID := range family.ColumnIDs {
if _, ok := primaryIndexColIDs[colID]; !ok {
if defaultColumnID == 0 {
defaultColumnID = colID
} else {
defaultColumnID = ColumnID(0)
break
}
}
}
family.DefaultColumnID = defaultColumnID
}
desc.Families[i] = family
}
}
// Validate validates that the table descriptor is well formed. Checks include
// both single table and cross table invariants.
func (desc *TableDescriptor) Validate(ctx context.Context, txn *client.Txn) error {
err := desc.ValidateTable()
if err != nil {
return err
}
if desc.Dropped() {
return nil
}
return desc.validateCrossReferences(ctx, txn)
}
// validateCrossReferences validates that each reference to another table is
// resolvable and that the necessary back references exist.
func (desc *TableDescriptor) validateCrossReferences(ctx context.Context, txn *client.Txn) error {
// Check that parent DB exists.
{
res, err := txn.Get(ctx, MakeDescMetadataKey(desc.ParentID))
if err != nil {
return err
}
if !res.Exists() {
return errors.Errorf("parentID %d does not exist", desc.ParentID)
}
}
tablesByID := map[ID]*TableDescriptor{desc.ID: desc}
getTable := func(id ID) (*TableDescriptor, error) {
if table, ok := tablesByID[id]; ok {
return table, nil
}
table, err := GetTableDescFromID(ctx, txn, id)
if err != nil {
return nil, err
}
tablesByID[id] = table
return table, nil
}
findTargetIndex := func(tableID ID, indexID IndexID) (*TableDescriptor, *IndexDescriptor, error) {
targetTable, err := getTable(tableID)
if err != nil {
return nil, nil, errors.Wrapf(err, "missing table=%d index=%d", tableID, indexID)
}
targetIndex, err := targetTable.FindIndexByID(indexID)
if err != nil {
return nil, nil, errors.Wrapf(err, "missing table=%s index=%d", targetTable.Name, indexID)
}
return targetTable, targetIndex, nil
}
for _, index := range desc.AllNonDropIndexes() {
// Check foreign keys.
if index.ForeignKey.IsSet() {
targetTable, targetIndex, err := findTargetIndex(
index.ForeignKey.Table, index.ForeignKey.Index)
if err != nil {
return errors.Wrap(err, "invalid foreign key")
}
found := false
for _, backref := range targetIndex.ReferencedBy {
if backref.Table == desc.ID && backref.Index == index.ID {
found = true
break
}
}
if !found {
return errors.Errorf("missing fk back reference to %q@%q from %q@%q",
desc.Name, index.Name, targetTable.Name, targetIndex.Name)
}
}
fkBackrefs := make(map[ForeignKeyReference]struct{})
for _, backref := range index.ReferencedBy {
if _, ok := fkBackrefs[backref]; ok {
return errors.Errorf("duplicated fk backreference %+v", backref)
}
fkBackrefs[backref] = struct{}{}
targetTable, err := getTable(backref.Table)
if err != nil {
return errors.Wrapf(err, "invalid fk backreference table=%d index=%d",
backref.Table, backref.Index)
}
targetIndex, err := targetTable.FindIndexByID(backref.Index)
if err != nil {
return errors.Wrapf(err, "invalid fk backreference table=%s index=%d",
targetTable.Name, backref.Index)
}
if fk := targetIndex.ForeignKey; fk.Table != desc.ID || fk.Index != index.ID {
return errors.Errorf("broken fk backward reference from %q@%q to %q@%q",
desc.Name, index.Name, targetTable.Name, targetIndex.Name)
}
}
// Check interleaves.
if len(index.Interleave.Ancestors) > 0 {
// Only check the most recent ancestor, the rest of them don't point
// back.
ancestor := index.Interleave.Ancestors[len(index.Interleave.Ancestors)-1]
targetTable, targetIndex, err := findTargetIndex(ancestor.TableID, ancestor.IndexID)
if err != nil {
return errors.Wrap(err, "invalid interleave")
}
found := false
for _, backref := range targetIndex.InterleavedBy {
if backref.Table == desc.ID && backref.Index == index.ID {
found = true
break
}
}
if !found {
return errors.Errorf(
"missing interleave back reference to %q@%q from %q@%q",
desc.Name, index.Name, targetTable.Name, targetIndex.Name)
}
}
interleaveBackrefs := make(map[ForeignKeyReference]struct{})
for _, backref := range index.InterleavedBy {
if _, ok := interleaveBackrefs[backref]; ok {
return errors.Errorf("duplicated interleave backreference %+v", backref)
}
interleaveBackrefs[backref] = struct{}{}
targetTable, err := getTable(backref.Table)
if err != nil {
return errors.Wrapf(err, "invalid interleave backreference table=%d index=%d",
backref.Table, backref.Index)
}
targetIndex, err := targetTable.FindIndexByID(backref.Index)
if err != nil {
return errors.Wrapf(err, "invalid interleave backreference table=%s index=%d",
targetTable.Name, backref.Index)
}
if len(targetIndex.Interleave.Ancestors) == 0 {
return errors.Errorf(
"broken interleave backward reference from %q@%q to %q@%q",
desc.Name, index.Name, targetTable.Name, targetIndex.Name)
}
// The last ancestor is required to be a backreference.
ancestor := targetIndex.Interleave.Ancestors[len(targetIndex.Interleave.Ancestors)-1]
if ancestor.TableID != desc.ID || ancestor.IndexID != index.ID {
return errors.Errorf(
"broken interleave backward reference from %q@%q to %q@%q",
desc.Name, index.Name, targetTable.Name, targetIndex.Name)
}
}
}
// TODO(dan): Also validate SharedPrefixLen in the interleaves.
return nil
}
// ValidateTable validates that the table descriptor is well formed. Checks
// include validating the table, column and index names, verifying that column
// names and index names are unique and verifying that column IDs and index IDs
// are consistent. Use Validate to validate that cross-table references are
// correct.
func (desc *TableDescriptor) ValidateTable() error {
if err := validateName(desc.Name, "table"); err != nil {
return err
}
if desc.ID == 0 {
return fmt.Errorf("invalid table ID %d", desc.ID)
}
// TODO(dt, nathan): virtual descs don't validate (missing privs, PK, etc).
if desc.IsVirtualTable() {
return nil
}
// ParentID is the ID of the database holding this table.
// It is often < ID, except when a table gets moved across databases.
if desc.ParentID == 0 {
return fmt.Errorf("invalid parent ID %d", desc.ParentID)
}
// We maintain forward compatibility, so if you see this error message with a
// version older that what this client supports, then there's a
// MaybeUpgradeFormatVersion missing from some codepath.
if v := desc.GetFormatVersion(); v != FamilyFormatVersion && v != InterleavedFormatVersion {
// TODO(dan): We're currently switching from FamilyFormatVersion to
// InterleavedFormatVersion. After a beta is released with this dual version
// support, then:
// - Upgrade the bidirectional reference version to that beta
// - Start constructing all TableDescriptors with InterleavedFormatVersion
// - Change MaybeUpgradeFormatVersion to output InterleavedFormatVersion
// - Change this check to only allow InterleavedFormatVersion