-
Notifications
You must be signed in to change notification settings - Fork 3.8k
/
create_table.go
1308 lines (1178 loc) · 35.5 KB
/
create_table.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2018 The Cockroach Authors.
//
// Use of this software is governed by the Business Source License
// included in the file licenses/BSL.txt.
//
// As of the Change Date specified in that file, in accordance with
// the Business Source License, use of this software will be governed
// by the Apache License, Version 2.0, included in the file
// licenses/APL.txt.
package testcat
import (
"bytes"
"context"
"fmt"
"reflect"
"sort"
"strconv"
"strings"
"github.com/cockroachdb/cockroach/pkg/geo/geoindex"
"github.com/cockroachdb/cockroach/pkg/settings/cluster"
"github.com/cockroachdb/cockroach/pkg/sql/catalog/colinfo"
"github.com/cockroachdb/cockroach/pkg/sql/catalog/descpb"
"github.com/cockroachdb/cockroach/pkg/sql/catalog/tabledesc"
"github.com/cockroachdb/cockroach/pkg/sql/opt/cat"
"github.com/cockroachdb/cockroach/pkg/sql/sem/eval"
"github.com/cockroachdb/cockroach/pkg/sql/sem/tree"
"github.com/cockroachdb/cockroach/pkg/sql/sessiondatapb"
"github.com/cockroachdb/cockroach/pkg/sql/types"
"github.com/cockroachdb/cockroach/pkg/util"
)
type indexType int
const (
primaryIndex indexType = iota
uniqueIndex
nonUniqueIndex
)
type colType int
const (
// keyCol is part of both lax and strict keys.
keyCol colType = iota
// strictKeyCol is only part of strict key.
strictKeyCol
// nonKeyCol is not part of lax or strict key.
nonKeyCol
)
var uniqueRowIDString = "unique_rowid()"
// creteFKIndexes controls whether we automatically create indexes on the
// referencing side of foreign keys (like it was required before 20.2).
const createFKIndexes = false
// CreateTable creates a test table from a parsed DDL statement and adds it to
// the catalog. This is intended for testing, and is not a complete (and
// probably not fully correct) implementation. It just has to be "good enough".
func (tc *Catalog) CreateTable(stmt *tree.CreateTable) *Table {
stmt.HoistConstraints()
// Update the table name to include catalog and schema if not provided.
tc.qualifyTableName(&stmt.Table)
// Assume that every table in the "system", "information_schema" or
// "pg_catalog" catalog is a virtual table. This is a simplified assumption
// for testing purposes.
if stmt.Table.CatalogName == "system" || stmt.Table.SchemaName == "information_schema" ||
stmt.Table.SchemaName == "pg_catalog" {
return tc.createVirtualTable(stmt)
}
tab := &Table{TabID: tc.nextStableID(), TabName: stmt.Table, Catalog: tc}
// Find the PK columns.
pkCols := make(map[tree.Name]struct{})
for _, def := range stmt.Defs {
switch def := def.(type) {
case *tree.ColumnTableDef:
if def.PrimaryKey.IsPrimaryKey {
pkCols[def.Name] = struct{}{}
}
case *tree.UniqueConstraintTableDef:
if def.PrimaryKey {
for i := range def.Columns {
pkCols[def.Columns[i].Column] = struct{}{}
}
}
}
}
// Add non-mutation columns.
for _, def := range stmt.Defs {
switch def := def.(type) {
case *tree.ColumnTableDef:
if !isMutationColumn(def) {
if _, isPKCol := pkCols[def.Name]; isPKCol {
// Force PK columns to be non-nullable and non-virtual.
def.Nullable.Nullability = tree.NotNull
if def.Computed.Computed {
def.Computed.Virtual = false
}
}
tab.addColumn(def)
}
}
}
// If there is no primary index, add the hidden rowid column.
hasPrimaryIndex := len(pkCols) > 0
if !hasPrimaryIndex {
var rowid cat.Column
ordinal := len(tab.Columns)
rowid.Init(
ordinal,
cat.StableID(1+ordinal),
"rowid",
cat.Ordinary,
types.Int,
false, /* nullable */
cat.Hidden,
&uniqueRowIDString, /* defaultExpr */
nil, /* computedExpr */
nil, /* onUpdateExpr */
cat.NotGeneratedAsIdentity,
nil, /* generatedAsIdentitySequenceOption */
)
tab.Columns = append(tab.Columns, rowid)
}
// Add any mutation columns (after any hidden rowid column).
for _, def := range stmt.Defs {
switch def := def.(type) {
case *tree.ColumnTableDef:
if isMutationColumn(def) {
tab.addColumn(def)
}
}
}
// Add the MVCC timestamp system column.
var mvcc cat.Column
ordinal := len(tab.Columns)
mvcc.Init(
ordinal,
cat.StableID(1+ordinal),
colinfo.MVCCTimestampColumnName,
cat.System,
colinfo.MVCCTimestampColumnType,
true, /* nullable */
cat.Hidden,
nil, /* defaultExpr */
nil, /* computedExpr */
nil, /* onUpdateExpr */
cat.NotGeneratedAsIdentity,
nil, /* generatedAsIdentitySequenceOption */
)
tab.Columns = append(tab.Columns, mvcc)
// Add the tableoid system column.
var tableoid cat.Column
ordinal = len(tab.Columns)
tableoid.Init(
ordinal,
cat.StableID(1+ordinal),
colinfo.TableOIDColumnName,
cat.System,
types.Oid,
true, /* nullable */
cat.Hidden,
nil, /* defaultExpr */
nil, /* computedExpr */
nil, /* onUpdateExpr */
cat.NotGeneratedAsIdentity,
nil, /* generatedAsIdentitySequenceOption */
)
tab.Columns = append(tab.Columns, tableoid)
// Cache the partitioning statement for the primary index.
if stmt.PartitionByTable != nil {
tab.partitionBy = stmt.PartitionByTable.PartitionBy
}
// Add the primary index.
if hasPrimaryIndex {
for _, def := range stmt.Defs {
switch def := def.(type) {
case *tree.ColumnTableDef:
if def.PrimaryKey.IsPrimaryKey {
// Add the primary index over the single column.
tab.addPrimaryColumnIndex(string(def.Name))
}
case *tree.UniqueConstraintTableDef:
if def.PrimaryKey {
tab.addIndex(&def.IndexTableDef, primaryIndex)
}
}
}
} else {
tab.addPrimaryColumnIndex("rowid")
}
// Add check constraints.
for _, def := range stmt.Defs {
switch def := def.(type) {
case *tree.CheckConstraintTableDef:
tab.Checks = append(tab.Checks, cat.CheckConstraint{
Constraint: serializeTableDefExpr(def.Expr),
Validated: validatedCheckConstraint(def),
})
}
}
// Search for index and family definitions.
for _, def := range stmt.Defs {
switch def := def.(type) {
case *tree.UniqueConstraintTableDef:
if def.WithoutIndex {
tab.addUniqueConstraint(def.Name, def.Columns, def.Predicate, def.WithoutIndex)
} else if !def.PrimaryKey {
tab.addIndex(&def.IndexTableDef, uniqueIndex)
}
case *tree.IndexTableDef:
tab.addIndex(def, nonUniqueIndex)
case *tree.FamilyTableDef:
tab.addFamily(def)
case *tree.ColumnTableDef:
if def.Unique.IsUnique {
if def.Unique.WithoutIndex {
tab.addUniqueConstraint(
def.Unique.ConstraintName,
tree.IndexElemList{{Column: def.Name}},
nil, /* predicate */
def.Unique.WithoutIndex,
)
} else {
tab.addIndex(
&tree.IndexTableDef{
Name: tree.Name(fmt.Sprintf("%s_%s_key", stmt.Table.ObjectName, def.Name)),
Columns: tree.IndexElemList{{Column: def.Name}},
},
uniqueIndex,
)
}
}
}
}
// If there are columns missing from explicit family definitions, add them
// to family 0 (ensure that one exists).
if len(tab.Families) == 0 {
tab.Families = []*Family{{FamName: "primary", Ordinal: 0, table: tab}}
}
OuterLoop:
for colOrd := range tab.Columns {
col := &tab.Columns[colOrd]
for _, fam := range tab.Families {
for _, famCol := range fam.Columns {
if col.ColName() == famCol.ColName() {
continue OuterLoop
}
}
}
tab.Families[0].Columns = append(tab.Families[0].Columns,
cat.FamilyColumn{Column: col, Ordinal: colOrd})
}
// Search for foreign key constraints. We want to process them after first
// processing all the indexes (otherwise the foreign keys could add
// unnecessary indexes).
for _, def := range stmt.Defs {
switch def := def.(type) {
case *tree.ForeignKeyConstraintTableDef:
tc.resolveFK(tab, def)
}
}
// Add the new table to the catalog.
tc.AddTable(tab)
return tab
}
func (tc *Catalog) createVirtualTable(stmt *tree.CreateTable) *Table {
tab := &Table{
TabID: tc.nextStableID(),
TabName: stmt.Table,
Catalog: tc,
IsVirtual: true,
IsSystem: true,
}
// Add the dummy PK column.
var pk cat.Column
pk.Init(
0, /* ordinal */
0, /* stableID */
"crdb_internal_vtable_pk",
cat.Ordinary,
types.Int,
false, /* nullable */
cat.Hidden,
nil, /* defaultExpr */
nil, /* computedExpr */
nil, /* onUpdateExpr */
cat.NotGeneratedAsIdentity,
nil, /* generatedAsIdentitySequenceOption */
)
tab.Columns = []cat.Column{pk}
for _, def := range stmt.Defs {
switch def := def.(type) {
case *tree.ColumnTableDef:
tab.addColumn(def)
}
}
tab.Families = []*Family{{FamName: "primary", Ordinal: 0, table: tab}}
for colOrd := range tab.Columns {
tab.Families[0].Columns = append(tab.Families[0].Columns,
cat.FamilyColumn{Column: &tab.Columns[colOrd], Ordinal: colOrd})
}
tab.addPrimaryColumnIndex(string(tab.Columns[0].ColName()))
// Search for index definitions.
for _, def := range stmt.Defs {
switch def := def.(type) {
case *tree.IndexTableDef:
tab.addIndex(def, nonUniqueIndex)
}
}
// Add the new table to the catalog.
tc.AddTable(tab)
return tab
}
// CreateTableAs creates a table in the catalog with the given name and
// columns. It should be used for creating a table from the CREATE TABLE <name>
// AS <query> syntax. In addition to the provided columns, CreateTableAs adds a
// unique rowid column as the primary key. It returns a pointer to the new
// table.
func (tc *Catalog) CreateTableAs(name tree.TableName, columns []cat.Column) *Table {
// Update the table name to include catalog and schema if not provided.
tc.qualifyTableName(&name)
tab := &Table{TabID: tc.nextStableID(), TabName: name, Catalog: tc, Columns: columns}
var rowid cat.Column
ordinal := len(columns)
rowid.Init(
ordinal,
cat.StableID(1+ordinal),
"rowid",
cat.Ordinary,
types.Int,
false, /* nullable */
cat.Hidden,
&uniqueRowIDString, /* defaultExpr */
nil, /* computedExpr */
nil, /* onUpdateExpr */
cat.NotGeneratedAsIdentity,
nil, /* generatedAsIdentitySequenceOption */
)
tab.Columns = append(tab.Columns, rowid)
tab.addPrimaryColumnIndex("rowid")
// Add the new table to the catalog.
tc.AddTable(tab)
return tab
}
// resolveFK processes a foreign key constraint.
func (tc *Catalog) resolveFK(tab *Table, d *tree.ForeignKeyConstraintTableDef) {
fromCols := make([]int, len(d.FromCols))
for i, c := range d.FromCols {
fromCols[i] = tab.FindOrdinal(string(c))
}
var targetTable *Table
if d.Table.ObjectName == tab.Name() {
targetTable = tab
} else {
targetTable = tc.Table(&d.Table)
}
referencedColNames := d.ToCols
if len(referencedColNames) == 0 {
// If no columns are specified, attempt to default to PK, ignoring implicit
// columns.
idx := targetTable.Index(cat.PrimaryIndex)
numImplicitCols := idx.ImplicitColumnCount()
referencedColNames = make(
tree.NameList,
0,
idx.KeyColumnCount()-numImplicitCols,
)
for i := numImplicitCols; i < idx.KeyColumnCount(); i++ {
referencedColNames = append(
referencedColNames,
idx.Column(i).ColName(),
)
}
}
toCols := make([]int, len(referencedColNames))
for i, c := range referencedColNames {
toCols[i] = targetTable.FindOrdinal(string(c))
}
constraintName := string(d.Name)
if constraintName == "" {
constraintName = tabledesc.ForeignKeyConstraintName(
tab.TabName.Table(),
d.FromCols.ToStrings(),
)
}
// Foreign keys require indexes in both tables:
//
// 1. In the target table, we need an index because adding a new row to the
// source table requires looking up whether there is a matching value in
// the target table. This index should already exist because a unique
// constraint is required on the target table (it's a foreign *key*).
//
// 2. In the source table, we need an index because removing a row from the
// target table requires looking up whether there would be orphan values
// left in the source table. This index does not need to be unique; in
// fact, if an existing index has the relevant columns as a prefix, that
// is good enough.
// indexMatches returns true if the key columns in the given index match the
// given columns. If strict is false, it is acceptable if the given columns
// are a prefix of the index key columns.
indexMatches := func(idx *Index, cols []int, strict bool) bool {
if idx.LaxKeyColumnCount() < len(cols) {
return false
}
if strict && idx.LaxKeyColumnCount() > len(cols) {
return false
}
for i := range cols {
if idx.Column(i).Ordinal() != cols[i] {
return false
}
}
if _, isPartialIndex := idx.Predicate(); isPartialIndex {
return false
}
return true
}
// uniqueConstraintMatches returns true if the key columns in the given unique
// constraint match the given columns.
uniqueConstraintMatches := func(uc *UniqueConstraint, cols []int) bool {
if colCount := uc.ColumnCount(); colCount < len(cols) || colCount > len(cols) {
return false
}
for i := range cols {
if uc.columnOrdinals[i] != cols[i] {
return false
}
}
return true
}
// 1. Verify that the target table has a unique index or unique constraint.
var targetIndex *Index
var targetUniqueConstraint *UniqueConstraint
for _, idx := range targetTable.Indexes {
if indexMatches(idx, toCols, true /* strict */) {
targetIndex = idx
break
}
}
if targetIndex == nil {
for i := range targetTable.uniqueConstraints {
uc := &targetTable.uniqueConstraints[i]
if uniqueConstraintMatches(uc, toCols) {
targetUniqueConstraint = uc
break
}
}
}
if targetIndex == nil && targetUniqueConstraint == nil {
panic(fmt.Errorf(
"there is no unique constraint matching given keys for referenced table %s",
targetTable.Name(),
))
}
if createFKIndexes {
// 2. Search for an existing index in the source table; add it if necessary.
found := false
for _, idx := range tab.Indexes {
if indexMatches(idx, fromCols, false /* strict */) {
found = true
break
}
}
if !found {
// Add a non-unique index on fromCols.
idx := tree.IndexTableDef{
Name: tree.Name(fmt.Sprintf("%s_auto_index_%s", tab.TabName.Table(), constraintName)),
Columns: make(tree.IndexElemList, len(fromCols)),
}
for i, c := range fromCols {
idx.Columns[i].Column = tab.Columns[c].ColName()
idx.Columns[i].Direction = tree.Ascending
}
tab.addIndex(&idx, nonUniqueIndex)
}
}
fk := ForeignKeyConstraint{
name: constraintName,
originTableID: tab.ID(),
referencedTableID: targetTable.ID(),
originColumnOrdinals: fromCols,
referencedColumnOrdinals: toCols,
validated: true,
matchMethod: d.Match,
deleteAction: d.Actions.Delete,
updateAction: d.Actions.Update,
}
tab.outboundFKs = append(tab.outboundFKs, fk)
targetTable.inboundFKs = append(targetTable.inboundFKs, fk)
}
func (tt *Table) addUniqueConstraint(
name tree.Name, columns tree.IndexElemList, predicate tree.Expr, withoutIndex bool,
) {
// We don't currently use unique constraints with an index (those are already
// tracked with unique indexes), so don't bother adding them.
// NB: This should stay consistent with opt_catalog.go.
if !withoutIndex {
return
}
cols := make([]int, len(columns))
for i, c := range columns {
cols[i] = tt.FindOrdinal(string(c.Column))
}
sort.Ints(cols)
// Create the constraint.
u := UniqueConstraint{
name: tt.makeUniqueConstraintName(name, columns),
tabID: tt.TabID,
columnOrdinals: cols,
withoutIndex: withoutIndex,
validated: true,
}
// Add partial unique constraint predicate.
if predicate != nil {
u.predicate = tree.Serialize(predicate)
}
// Don't add duplicate constraints.
for _, c := range tt.uniqueConstraints {
if reflect.DeepEqual(c.columnOrdinals, u.columnOrdinals) &&
c.predicate == u.predicate &&
c.withoutIndex == u.withoutIndex {
return
}
}
tt.uniqueConstraints = append(tt.uniqueConstraints, u)
}
func (tt *Table) addColumn(def *tree.ColumnTableDef) {
ordinal := len(tt.Columns)
nullable := !def.PrimaryKey.IsPrimaryKey && def.Nullable.Nullability != tree.NotNull
typ, err := tree.ResolveType(context.Background(), def.Type, tt.Catalog)
if err != nil {
panic(err)
}
name := def.Name
kind := cat.Ordinary
visibility := cat.Visible
if def.IsSerial {
// Here we only take care of the case where
// serial_normalization == SerialUsesRowID.
def.DefaultExpr.Expr = generateDefExprForSerialCol(tt.TabName, name, sessiondatapb.SerialUsesRowID)
}
// Look for name suffixes indicating this is a special column.
if n, ok := extractInaccessibleColumn(def); ok {
name = n
visibility = cat.Inaccessible
} else if n, ok := extractWriteOnlyColumn(def); ok {
name = n
kind = cat.WriteOnly
visibility = cat.Inaccessible
} else if n, ok := extractDeleteOnlyColumn(def); ok {
name = n
kind = cat.DeleteOnly
visibility = cat.Inaccessible
}
var defaultExpr, computedExpr, onUpdateExpr, generatedAsIdentitySequenceOption *string
if def.DefaultExpr.Expr != nil {
s := serializeTableDefExpr(def.DefaultExpr.Expr)
defaultExpr = &s
}
if def.Computed.Expr != nil {
s := serializeTableDefExpr(def.Computed.Expr)
computedExpr = &s
}
if def.OnUpdateExpr.Expr != nil {
s := serializeTableDefExpr(def.OnUpdateExpr.Expr)
onUpdateExpr = &s
}
generatedAsIdentityType := cat.NotGeneratedAsIdentity
if def.GeneratedIdentity.IsGeneratedAsIdentity {
switch def.GeneratedIdentity.GeneratedAsIdentityType {
case tree.GeneratedAlways, tree.GeneratedByDefault:
def.DefaultExpr.Expr = generateDefExprForGeneratedAsIdentityCol(tt.TabName, name)
switch def.GeneratedIdentity.GeneratedAsIdentityType {
case tree.GeneratedAlways:
generatedAsIdentityType = cat.GeneratedAlwaysAsIdentity
case tree.GeneratedByDefault:
generatedAsIdentityType = cat.GeneratedByDefaultAsIdentity
}
default:
panic(fmt.Errorf(
"column %s is of invalid generated as identity type (neither ALWAYS nor BY DEFAULT)",
def.Name,
))
}
}
if def.DefaultExpr.Expr != nil {
s := serializeTableDefExpr(def.DefaultExpr.Expr)
defaultExpr = &s
}
if def.Computed.Expr != nil {
s := serializeTableDefExpr(def.Computed.Expr)
computedExpr = &s
}
if def.GeneratedIdentity.SeqOptions != nil {
s := serializeGeneratedAsIdentitySequenceOption(&def.GeneratedIdentity.SeqOptions)
generatedAsIdentitySequenceOption = &s
}
var col cat.Column
if def.Computed.Virtual {
col.InitVirtualComputed(
ordinal,
cat.StableID(1+ordinal),
name,
typ,
nullable,
visibility,
*computedExpr,
)
} else {
col.Init(
ordinal,
cat.StableID(1+ordinal),
name,
kind,
typ,
nullable,
visibility,
defaultExpr,
computedExpr,
onUpdateExpr,
generatedAsIdentityType,
generatedAsIdentitySequenceOption,
)
}
tt.Columns = append(tt.Columns, col)
}
func (tt *Table) addIndex(def *tree.IndexTableDef, typ indexType) *Index {
return tt.addIndexWithVersion(def, typ, descpb.LatestIndexDescriptorVersion)
}
func (tt *Table) addIndexWithVersion(
def *tree.IndexTableDef, typ indexType, version descpb.IndexDescriptorVersion,
) *Index {
// Add a unique constraint if this is a primary or unique index.
if typ != nonUniqueIndex {
tt.addUniqueConstraint(def.Name, def.Columns, def.Predicate, false /* withoutIndex */)
}
idx := &Index{
IdxName: tt.makeIndexName(def.Name, def.Columns, typ),
Unique: typ != nonUniqueIndex,
Inverted: def.Inverted,
IdxZone: cat.EmptyZone(),
table: tt,
version: version,
}
// Look for name suffixes indicating this is a mutation index.
if name, ok := extractWriteOnlyIndex(def); ok {
idx.IdxName = name
tt.writeOnlyIdxCount++
} else if name, ok := extractDeleteOnlyIndex(def); ok {
idx.IdxName = name
tt.deleteOnlyIdxCount++
}
// Add explicit columns. Primary key columns definitions have already been
// updated to be non-nullable and non-virtual.
// Add the geoConfig if applicable.
idx.ExplicitColCount = len(def.Columns)
notNullIndex := true
for i, colDef := range def.Columns {
isLastIndexCol := i == len(def.Columns)-1
if def.Inverted && isLastIndexCol {
idx.invertedOrd = i
}
col := idx.addColumn(tt, colDef, keyCol, isLastIndexCol)
if col.IsNullable() {
notNullIndex = false
}
if isLastIndexCol && def.Inverted {
switch tt.Columns[col.InvertedSourceColumnOrdinal()].DatumType().Family() {
case types.GeometryFamily:
// Don't use the default config because it creates a huge number of spans.
idx.geoConfig = geoindex.Config{
S2Geometry: &geoindex.S2GeometryConfig{
MinX: -5,
MaxX: 5,
MinY: -5,
MaxY: 5,
S2Config: &geoindex.S2Config{
MinLevel: 0,
MaxLevel: 2,
LevelMod: 1,
MaxCells: 3,
},
},
}
case types.GeographyFamily:
// Don't use the default config because it creates a huge number of spans.
idx.geoConfig = geoindex.Config{
S2Geography: &geoindex.S2GeographyConfig{S2Config: &geoindex.S2Config{
MinLevel: 0,
MaxLevel: 2,
LevelMod: 1,
MaxCells: 3,
}},
}
}
}
}
// Add partitions.
var partitionBy *tree.PartitionBy
if def.PartitionByIndex != nil {
partitionBy = def.PartitionByIndex.PartitionBy
} else if typ == primaryIndex {
partitionBy = tt.partitionBy
}
if partitionBy != nil {
ctx := context.Background()
semaCtx := tree.MakeSemaContext()
evalCtx := eval.MakeTestingEvalContext(cluster.MakeTestingClusterSettings())
if len(partitionBy.List) > 0 {
idx.partitions = make([]Partition, len(partitionBy.List))
for i := range partitionBy.Fields {
if i >= len(idx.Columns) || partitionBy.Fields[i] != idx.Columns[i].ColName() {
panic("partition by columns must be a prefix of the index columns")
}
}
for i := range partitionBy.List {
p := &partitionBy.List[i]
idx.partitions[i] = Partition{
name: string(p.Name),
zone: cat.EmptyZone(),
datums: make([]tree.Datums, 0, len(p.Exprs)),
}
// Get the partition values.
for _, e := range p.Exprs {
d := idx.partitionByListExprToDatums(ctx, &evalCtx, &semaCtx, e)
if d != nil {
idx.partitions[i].datums = append(idx.partitions[i].datums, d)
}
}
}
}
}
if typ == primaryIndex {
var pkOrdinals util.FastIntSet
for _, c := range idx.Columns {
pkOrdinals.Add(c.Ordinal())
}
// Add the rest of the columns in the table.
for i, col := range tt.Columns {
if !pkOrdinals.Contains(i) && col.Kind() != cat.Inverted && !col.IsVirtualComputed() {
idx.addColumnByOrdinal(tt, i, tree.Ascending, nonKeyCol)
}
}
if len(tt.Indexes) != 0 {
panic("primary index should always be 0th index")
}
idx.ordinal = len(tt.Indexes)
tt.Indexes = append(tt.Indexes, idx)
return idx
}
// Add implicit key columns from primary index.
pkCols := tt.Indexes[cat.PrimaryIndex].Columns[:tt.Indexes[cat.PrimaryIndex].KeyCount]
for _, pkCol := range pkCols {
// Only add columns that aren't already part of index.
found := false
for _, colDef := range def.Columns {
if pkCol.ColName() == colDef.Column {
found = true
}
}
if !found {
elem := tree.IndexElem{
Column: pkCol.ColName(),
Direction: tree.Ascending,
}
if typ == uniqueIndex {
// If unique index has no NULL columns, then the implicit columns
// are added as storing columns. Otherwise, they become part of the
// strict key, since they're needed to ensure uniqueness (but they
// are not part of the lax key).
if notNullIndex {
idx.addColumn(tt, elem, nonKeyCol, false /* isLastIndexCol */)
} else {
idx.addColumn(tt, elem, strictKeyCol, false /* isLastIndexCol */)
}
} else {
// Implicit columns are always added to the key for a non-unique
// index. In addition, there is no separate lax key, so the lax
// key column count = key column count.
idx.addColumn(tt, elem, keyCol, false /* isLastIndexCol */)
}
}
}
// Add storing columns.
for _, name := range def.Storing {
if def.Inverted {
panic("inverted indexes don't support stored columns")
}
// Only add storing columns that weren't added as part of adding implicit
// key columns.
found := false
for _, pkCol := range pkCols {
if name == pkCol.ColName() {
found = true
}
}
if !found {
elem := tree.IndexElem{
Column: name,
Direction: tree.Ascending,
}
idx.addColumn(tt, elem, nonKeyCol, false /* isLastIndexCol */)
}
}
if tt.IsVirtual {
// All indexes of virtual tables automatically STORE all other columns in
// the table.
idxCols := idx.Columns
for _, col := range tt.Columns {
found := false
for _, idxCol := range idxCols {
if col.ColName() == idxCol.ColName() {
found = true
break
}
}
if !found {
elem := tree.IndexElem{
Column: col.ColName(),
Direction: tree.Ascending,
}
idx.addColumn(tt, elem, nonKeyCol, false /* isLastIndexCol */)
}
}
}
// Add partial index predicate.
if def.Predicate != nil {
idx.predicate = tree.Serialize(def.Predicate)
}
idx.ordinal = len(tt.Indexes)
tt.Indexes = append(tt.Indexes, idx)
return idx
}
func (tt *Table) makeIndexName(defName tree.Name, cols tree.IndexElemList, typ indexType) string {
name := string(defName)
if name != "" {
return name
}
if typ == primaryIndex {
return tt.TabName.Table() + "_pkey"
}
var sb strings.Builder
sb.WriteString(tt.TabName.Table())
exprCount := 0
for _, col := range cols {
sb.WriteRune('_')
if col.Expr != nil {
sb.WriteString("expr")
if exprCount > 0 {
sb.WriteString(strconv.Itoa(exprCount))
}
exprCount++
} else {
sb.WriteString(col.Column.String())
}
}
if typ == uniqueIndex {
sb.WriteString("_key")
} else {
sb.WriteString("_idx")
}
idxNameExists := func(idxName string) bool {
for _, idx := range tt.Indexes {
if idx.IdxName == idxName {
return true
}
}
return false
}
baseName := sb.String()
name = baseName
for i := 1; ; i++ {
if !idxNameExists(name) {
break
}
name = fmt.Sprintf("%s%d", baseName, i)
}
return name
}
func (tt *Table) makeUniqueConstraintName(defName tree.Name, columns tree.IndexElemList) string {
name := string(defName)
if name == "" {
var buf bytes.Buffer
buf.WriteString("unique")
for i := range columns {
buf.WriteRune('_')
buf.WriteString(string(columns[i].Column))
}
name = buf.String()
}
return name
}
func (tt *Table) addFamily(def *tree.FamilyTableDef) {
// Synthesize name if one was not provided.
name := string(def.Name)
if name == "" {
name = fmt.Sprintf("family%d", len(tt.Families)+1)
}
family := &Family{
FamName: name,
Ordinal: tt.FamilyCount(),
table: tt,
}
// Add columns to family.