-
Notifications
You must be signed in to change notification settings - Fork 3.8k
/
structured.go
3260 lines (2930 loc) · 105 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/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] }
// 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
}
// 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
}
// 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
}
// GetMutableTableDescFromID 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.
// Otherwise a mutable copy of the table is returned.
func GetMutableTableDescFromID(
ctx context.Context, txn *client.Txn, id ID,
) (*MutableTableDescriptor, error) {
table, err := GetTableDescFromID(ctx, txn, 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())
}
}
}
// 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()
}
// 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 ")
if *tableName != AnonymousTable {
f.WriteString("ON ")
f.FormatNode(tableName)
}
f.FormatNameP(&desc.Name)
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
}
// 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() && !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)+len(desc.Mutations))
for _, c := range desc.Checks {
if c.Validity != ConstraintValidity_Validating {
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() (
map[IndexID]*ForeignKeyReference,
error,
) {
fks := make(map[IndexID]*ForeignKeyReference)
// While a foreign key constraint is being validated for existing rows, the
// foreign key reference is present both on the index descriptor and in the
// mutations list in the Validating state, so those FKs are excluded here to
// avoid double-counting.
if desc.PrimaryIndex.ForeignKey.IsSet() && desc.PrimaryIndex.ForeignKey.Validity != ConstraintValidity_Validating {
fks[desc.PrimaryIndex.ID] = &desc.PrimaryIndex.ForeignKey
}
for i := range desc.Indexes {
idx := &desc.Indexes[i]
if idx.ForeignKey.IsSet() && idx.ForeignKey.Validity != ConstraintValidity_Validating {
fks[idx.ID] = &idx.ForeignKey
}
}
for i := range desc.Mutations {
if c := desc.Mutations[i].GetConstraint(); c != nil && c.ConstraintType == ConstraintToUpdate_FOREIGN_KEY {
if _, ok := fks[c.ForeignKeyIndex]; ok {
return nil, errors.AssertionFailedf(
"foreign key mutation found for index that already has a foreign key")
}
fks[c.ForeignKeyIndex] = &c.ForeignKey
}
}
return fks, nil
}
// 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() bool {
changedVersion := desc.maybeUpgradeFormatVersion()
changedPrivileges := desc.Privileges.MaybeFixPrivileges(desc.ID)
return changedVersion || changedPrivileges
}
// maybeUpgradeFormatVersion transforms the TableDescriptor to the latest
// FormatVersion (if it's not already there) and returns true if any changes
// were made.
// This method should be called through MaybeFillInDescriptor, not directly.
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 i := range desc.Columns {
addFamilyForCol(&desc.Columns[i])
}
for i := range desc.Mutations {
m := &desc.Mutations[i]
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 *MutableTableDescriptor) 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.MinUserDescID
}
err := desc.ValidateTable(nil)
desc.ID = savedID
return err
}
func (desc *MutableTableDescriptor) ensurePrimaryKey() error {
if len(desc.PrimaryIndex.ColumnNames) == 0 && desc.IsPhysicalTable() {
// Ensure a Primary Key exists.
s := "unique_rowid()"
col := &ColumnDescriptor{
Name: "rowid",
Type: *types.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.
//
// As an example of a composite encoding, collated string key columns are
// encoded partly as a key and partly as a value. The key part is the collation
// key, so that different strings that collate equal cannot both be used as
// keys. The value part is the usual UTF-8 encoding of the string, stored so
// that it can be recovered later for inspection/display.
func HasCompositeKeyEncoding(semanticType types.Family) bool {
switch semanticType {
case types.CollatedStringFamily,
types.FloatFamily,
types.DecimalFamily:
return true
}
return false
}
// DatumTypeHasCompositeKeyEncoding is a version of HasCompositeKeyEncoding
// which works on datum types.
func DatumTypeHasCompositeKeyEncoding(typ *types.T) bool {
return HasCompositeKeyEncoding(typ.Family())
}
// MustBeValueEncoded returns true if columns of the given kind can only be value
// encoded.
func MustBeValueEncoded(semanticType types.Family) bool {
return semanticType == types.ArrayFamily ||
semanticType == types.JsonFamily ||
semanticType == types.TupleFamily
}
// 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 *MutableTableDescriptor) 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 i := range desc.Columns {
col := &desc.Columns[i]
if HasCompositeKeyEncoding(col.Type.Family()) {
isCompositeColumn[col.ID] = struct{}{}
}
}
// Populate IDs.
for _, index := range indexes {
if index.ID != 0 {
// This index has already been populated. Nothing to do.
continue
}
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(tree.Name(colName))
if err != nil {
return err
}
if desc.PrimaryIndex.ContainsColumnID(col.ID) {
// 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", index.Name, col.Name)
err = errors.WithDetailf(err, "column %q is part of the primary index and therefore implicit in all indexes", col.Name)
return err
}
if index.ContainsColumnID(col.ID) {
return pgerror.Newf(
pgcode.DuplicateColumn,
"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 {