-
Notifications
You must be signed in to change notification settings - Fork 3.8k
/
create_table.go
1664 lines (1507 loc) · 49.6 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 2017 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 sql
import (
"bytes"
"context"
"fmt"
"math"
"sort"
"strings"
"github.com/cockroachdb/cockroach/pkg/internal/client"
"github.com/cockroachdb/cockroach/pkg/keys"
"github.com/cockroachdb/cockroach/pkg/settings/cluster"
"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/privilege"
"github.com/cockroachdb/cockroach/pkg/sql/row"
"github.com/cockroachdb/cockroach/pkg/sql/sem/tree"
"github.com/cockroachdb/cockroach/pkg/sql/sqlbase"
"github.com/cockroachdb/cockroach/pkg/sql/types"
"github.com/cockroachdb/cockroach/pkg/util"
"github.com/cockroachdb/cockroach/pkg/util/errorutil/unimplemented"
"github.com/cockroachdb/cockroach/pkg/util/hlc"
"github.com/cockroachdb/errors"
"github.com/lib/pq/oid"
)
type createTableNode struct {
n *tree.CreateTable
dbDesc *sqlbase.DatabaseDescriptor
sourcePlan planNode
run createTableRun
}
// CreateTable creates a table.
// Privileges: CREATE on database.
// Notes: postgres/mysql require CREATE on database.
func (p *planner) CreateTable(ctx context.Context, n *tree.CreateTable) (planNode, error) {
dbDesc, err := p.ResolveUncachedDatabase(ctx, &n.Table)
if err != nil {
return nil, err
}
if err := p.CheckPrivilege(ctx, dbDesc, privilege.CREATE); err != nil {
return nil, err
}
n.HoistConstraints()
var sourcePlan planNode
var synthRowID bool
if n.As() {
// The sourcePlan is needed to determine the set of columns to use
// to populate the new table descriptor in Start() below.
sourcePlan, err = p.Select(ctx, n.AsSource, []*types.T{})
if err != nil {
return nil, err
}
numColNames := len(n.Defs)
numColumns := len(planColumns(sourcePlan))
if numColNames != 0 && numColNames != numColumns {
sourcePlan.Close(ctx)
return nil, sqlbase.NewSyntaxError(fmt.Sprintf(
"CREATE TABLE specifies %d column name%s, but data source has %d column%s",
numColNames, util.Pluralize(int64(numColNames)),
numColumns, util.Pluralize(int64(numColumns))))
}
// Synthesize an input column that provides the default value for the
// hidden rowid column, if none of the provided columns are specified
// as the PRIMARY KEY.
synthRowID = true
for _, def := range n.Defs {
if d, ok := def.(*tree.ColumnTableDef); !ok {
return nil, errors.Errorf("failed to cast type to ColumnTableDef\n")
} else if d.PrimaryKey {
synthRowID = false
break
}
}
}
ct := &createTableNode{n: n, dbDesc: dbDesc, sourcePlan: sourcePlan}
ct.run.synthRowID = synthRowID
ct.run.fromHeuristicPlanner = true
return ct, nil
}
// createTableRun contains the run-time state of createTableNode
// during local execution.
type createTableRun struct {
autoCommit autoCommitOpt
// synthRowID indicates whether an input column needs to be synthesized to
// provide the default value for the hidden rowid column. The optimizer's plan
// already includes this column (so synthRowID is false), whereas the
// heuristic planner's plan does not, and it is decided based on the existence
// of a user specified PRIMARY KEY constraint.
synthRowID bool
// fromHeuristicPlanner indicates whether the planning was performed by the
// heuristic planner instead of the optimizer.
fromHeuristicPlanner bool
}
func (n *createTableNode) startExec(params runParams) error {
tKey := sqlbase.NewTableKey(n.dbDesc.ID, n.n.Table.Table())
key := tKey.Key()
if exists, err := descExists(params.ctx, params.p.txn, key); err == nil && exists {
if n.n.IfNotExists {
return nil
}
return sqlbase.NewRelationAlreadyExistsError(tKey.Name())
} else if err != nil {
return err
}
id, err := GenerateUniqueDescID(params.ctx, params.extendedEvalCtx.ExecCfg.DB)
if err != nil {
return err
}
// If a new system table is being created (which should only be doable by
// an internal user account), make sure it gets the correct privileges.
privs := n.dbDesc.GetPrivileges()
if n.dbDesc.ID == keys.SystemDatabaseID {
privs = sqlbase.NewDefaultPrivilegeDescriptor()
}
var asCols sqlbase.ResultColumns
var desc sqlbase.MutableTableDescriptor
var affected map[sqlbase.ID]*sqlbase.MutableTableDescriptor
creationTime := params.p.txn.CommitTimestamp()
if n.n.As() {
// TODO(adityamaru): This planning step is only to populate db/schema
// details in the table names in-place, to later store in the table
// descriptor. Figure out a cleaner way to do this.
_, err = params.p.Select(params.ctx, n.n.AsSource, []*types.T{})
if err != nil {
return err
}
asCols = planColumns(n.sourcePlan)
if !n.run.fromHeuristicPlanner && !n.n.AsHasUserSpecifiedPrimaryKey() {
// rowID column is already present in the input as the last column if it
// was planned by the optimizer and the user did not specify a PRIMARY
// KEY. So ignore it for the purpose of creating column metadata (because
// makeTableDescIfAs does it automatically).
asCols = asCols[:len(asCols)-1]
}
desc, err = makeTableDescIfAs(params,
n.n, n.dbDesc.ID, id, creationTime, asCols,
privs, params.p.EvalContext(), nil /* affected */)
if err != nil {
return err
}
// If we have an implicit txn we want to run CTAS async, and consequently
// ensure it gets queued as a SchemaChange.
if params.p.ExtendedEvalContext().TxnImplicit {
desc.State = sqlbase.TableDescriptor_ADD
}
} else {
affected = make(map[sqlbase.ID]*sqlbase.MutableTableDescriptor)
desc, err = makeTableDesc(params, n.n, n.dbDesc.ID, id, creationTime, privs, affected)
if err != nil {
return err
}
if desc.Adding() {
// if this table and all its references are created in the same
// transaction it can be made PUBLIC.
refs, err := desc.FindAllReferences()
if err != nil {
return err
}
var foundExternalReference bool
for id := range refs {
if t := params.p.Tables().getUncommittedTableByID(id).MutableTableDescriptor; t == nil || !t.IsNewTable() {
foundExternalReference = true
break
}
}
if !foundExternalReference {
desc.State = sqlbase.TableDescriptor_PUBLIC
}
}
}
// Descriptor written to store here.
if err := params.p.createDescriptorWithID(
params.ctx, key, id, &desc, params.EvalContext().Settings); err != nil {
return err
}
for _, updated := range affected {
if err := params.p.writeSchemaChange(params.ctx, updated, sqlbase.InvalidMutationID); err != nil {
return err
}
}
for _, index := range desc.AllNonDropIndexes() {
if len(index.Interleave.Ancestors) > 0 {
if err := params.p.finalizeInterleave(params.ctx, &desc, index); err != nil {
return err
}
}
}
if err := desc.Validate(params.ctx, params.p.txn, params.EvalContext().Settings); err != nil {
return err
}
// Log Create Table event. This is an auditable log event and is
// recorded in the same transaction as the table descriptor update.
if err := MakeEventLogger(params.extendedEvalCtx.ExecCfg).InsertEventRecord(
params.ctx,
params.p.txn,
EventLogCreateTable,
int32(desc.ID),
int32(params.extendedEvalCtx.NodeID),
struct {
TableName string
Statement string
User string
}{n.n.Table.FQString(), n.n.String(), params.SessionData().User},
); err != nil {
return err
}
// If we are in an explicit txn or the source has placeholders, we execute the
// CTAS query synchronously.
if n.n.As() && !params.p.ExtendedEvalContext().TxnImplicit {
// This is a very simplified version of the INSERT logic: no CHECK
// expressions, no FK checks, no arbitrary insertion order, no
// RETURNING, etc.
// Instantiate a row inserter and table writer. It has a 1-1
// mapping to the definitions in the descriptor.
ri, err := row.MakeInserter(
params.p.txn,
sqlbase.NewImmutableTableDescriptor(*desc.TableDesc()),
nil,
desc.Columns,
row.SkipFKs,
¶ms.p.alloc)
if err != nil {
return err
}
ti := tableInserterPool.Get().(*tableInserter)
*ti = tableInserter{ri: ri}
tw := tableWriter(ti)
if n.run.autoCommit == autoCommitEnabled {
tw.enableAutoCommit()
}
defer func() {
tw.close(params.ctx)
*ti = tableInserter{}
tableInserterPool.Put(ti)
}()
if err := tw.init(params.p.txn, params.p.EvalContext()); err != nil {
return err
}
// Prepare the buffer for row values. At this point, one more column has
// been added by ensurePrimaryKey() to the list of columns in sourcePlan, if
// a PRIMARY KEY is not specified by the user.
rowBuffer := make(tree.Datums, len(desc.Columns))
pkColIdx := len(desc.Columns) - 1
// The optimizer includes the rowID expression as part of the input
// expression. But the heuristic planner does not do this, so construct
// a rowID expression to be evaluated separately.
var defTypedExpr tree.TypedExpr
if n.run.synthRowID {
// Prepare the rowID expression.
defExprSQL := *desc.Columns[pkColIdx].DefaultExpr
defExpr, err := parser.ParseExpr(defExprSQL)
if err != nil {
return err
}
defTypedExpr, err = params.p.analyzeExpr(
params.ctx,
defExpr,
nil, /*sources*/
tree.IndexedVarHelper{},
types.Any,
false, /*requireType*/
"CREATE TABLE AS")
if err != nil {
return err
}
}
for {
if err := params.p.cancelChecker.Check(); err != nil {
return err
}
if next, err := n.sourcePlan.Next(params); !next {
if err != nil {
return err
}
_, err := tw.finalize(
params.ctx, params.extendedEvalCtx.Tracing.KVTracingEnabled())
if err != nil {
return err
}
break
}
// Populate the buffer and generate the PK value.
copy(rowBuffer, n.sourcePlan.Values())
if n.run.synthRowID {
rowBuffer[pkColIdx], err = defTypedExpr.Eval(params.p.EvalContext())
if err != nil {
return err
}
}
err := tw.row(params.ctx, rowBuffer, params.extendedEvalCtx.Tracing.KVTracingEnabled())
if err != nil {
return err
}
}
}
// The CREATE STATISTICS run for an async CTAS query is initiated by the
// SchemaChanger.
if n.n.As() && params.p.autoCommit {
return nil
}
// Initiate a run of CREATE STATISTICS. We use a large number
// for rowsAffected because we want to make sure that stats always get
// created/refreshed here.
params.ExecCfg().StatsRefresher.NotifyMutation(desc.ID, math.MaxInt32 /* rowsAffected */)
return nil
}
// enableAutoCommit is part of the autoCommitNode interface.
func (n *createTableNode) enableAutoCommit() {
n.run.autoCommit = autoCommitEnabled
}
func (*createTableNode) Next(runParams) (bool, error) { return false, nil }
func (*createTableNode) Values() tree.Datums { return tree.Datums{} }
func (n *createTableNode) Close(ctx context.Context) {
if n.sourcePlan != nil {
n.sourcePlan.Close(ctx)
n.sourcePlan = nil
}
}
type indexMatch bool
const (
matchExact indexMatch = true
matchPrefix indexMatch = false
)
// Referenced cols must be unique, thus referenced indexes must match exactly.
// Referencing cols have no uniqueness requirement and thus may match a strict
// prefix of an index.
func matchesIndex(
cols []sqlbase.ColumnDescriptor, idx sqlbase.IndexDescriptor, exact indexMatch,
) bool {
if len(cols) > len(idx.ColumnIDs) || (exact && len(cols) != len(idx.ColumnIDs)) {
return false
}
for i := range cols {
if cols[i].ID != idx.ColumnIDs[i] {
return false
}
}
return true
}
// resolveFK on the planner calls resolveFK() on the current txn.
//
// The caller must make sure the planner is configured to look up
// descriptors without caching. See the comment on resolveFK().
func (p *planner) resolveFK(
ctx context.Context,
tbl *sqlbase.MutableTableDescriptor,
d *tree.ForeignKeyConstraintTableDef,
backrefs map[sqlbase.ID]*sqlbase.MutableTableDescriptor,
ts FKTableState,
) error {
return ResolveFK(ctx, p.txn, p, tbl, d, backrefs, ts)
}
func qualifyFKColErrorWithDB(
ctx context.Context, txn *client.Txn, tbl *sqlbase.TableDescriptor, col string,
) string {
if txn == nil {
return tree.ErrString(tree.NewUnresolvedName(tbl.Name, col))
}
// TODO(whomever): this ought to use a database cache.
db, err := sqlbase.GetDatabaseDescFromID(ctx, txn, tbl.ParentID)
if err != nil {
return tree.ErrString(tree.NewUnresolvedName(tbl.Name, col))
}
return tree.ErrString(tree.NewUnresolvedName(db.Name, tree.PublicSchema, tbl.Name, col))
}
// FKTableState is the state of the referencing table resolveFK() is called on.
type FKTableState int
const (
// NewTable represents a new table, where the FK constraint is specified in the
// CREATE TABLE
NewTable FKTableState = iota
// EmptyTable represents an existing table that is empty
EmptyTable
// NonEmptyTable represents an existing non-empty table
NonEmptyTable
)
// ResolveFK looks up the tables and columns mentioned in a `REFERENCES`
// constraint and adds metadata representing that constraint to the descriptor.
// It may, in doing so, add to or alter descriptors in the passed in `backrefs`
// map of other tables that need to be updated when this table is created.
// Constraints that are not known to hold for existing data are created
// "unvalidated", but when table is empty (e.g. during creation), no existing
// data imples no existing violations, and thus the constraint can be created
// without the unvalidated flag.
//
// The caller should pass an instance of fkSelfResolver as
// SchemaResolver, so that FK references can find the newly created
// table for self-references.
//
// The caller must also ensure that the SchemaResolver is configured to
// bypass caching and enable visibility of just-added descriptors.
// If there are any FKs, the descriptor of the depended-on table must
// be looked up uncached, and we'll allow FK dependencies on tables
// that were just added.
//
// The passed Txn is used to lookup databases to qualify names in error messages
// but if nil, will result in unqualified names in those errors.
func ResolveFK(
ctx context.Context,
txn *client.Txn,
sc SchemaResolver,
tbl *sqlbase.MutableTableDescriptor,
d *tree.ForeignKeyConstraintTableDef,
backrefs map[sqlbase.ID]*sqlbase.MutableTableDescriptor,
ts FKTableState,
) error {
for _, col := range d.FromCols {
col, _, err := tbl.FindColumnByName(col)
if err != nil {
return err
}
if err := col.CheckCanBeFKRef(); err != nil {
return err
}
}
target, err := ResolveMutableExistingObject(ctx, sc, &d.Table, true /*required*/, ResolveRequireTableDesc)
if err != nil {
return err
}
if target.ID == tbl.ID {
// When adding a self-ref FK to an _existing_ table, we want to make sure
// we edit the same copy.
target = tbl
} else {
// Since this FK is referencing another table, this table must be created in
// a non-public "ADD" state and made public only after all leases on the
// other table are updated to include the backref, if it does not already
// exist.
if ts == NewTable {
tbl.State = sqlbase.TableDescriptor_ADD
}
// If we resolve the same table more than once, we only want to edit a
// single instance of it, so replace target with previously resolved table.
if prev, ok := backrefs[target.ID]; ok {
target = prev
} else {
backrefs[target.ID] = target
}
}
srcCols, err := tbl.FindActiveColumnsByNames(d.FromCols)
if err != nil {
return err
}
targetColNames := d.ToCols
// If no columns are specified, attempt to default to PK.
if len(targetColNames) == 0 {
targetColNames = make(tree.NameList, len(target.PrimaryIndex.ColumnNames))
for i, n := range target.PrimaryIndex.ColumnNames {
targetColNames[i] = tree.Name(n)
}
}
targetCols, err := target.FindActiveColumnsByNames(targetColNames)
if err != nil {
return err
}
if len(targetCols) != len(srcCols) {
return pgerror.Newf(pgcode.Syntax,
"%d columns must reference exactly %d columns in referenced table (found %d)",
len(srcCols), len(srcCols), len(targetCols))
}
for i := range srcCols {
if s, t := srcCols[i], targetCols[i]; !s.Type.Equivalent(&t.Type) {
return pgerror.Newf(pgcode.DatatypeMismatch,
"type of %q (%s) does not match foreign key %q.%q (%s)",
s.Name, s.Type.String(), target.Name, t.Name, t.Type.String())
}
}
constraintName := string(d.Name)
if constraintName == "" {
constraintName = fmt.Sprintf("fk_%s_ref_%s", string(d.FromCols[0]), target.Name)
}
// We can't keep a reference to the index in the slice and at the same time
// add a new index to that slice without losing the reference. Instead, keep
// the index's index into target's list of indexes. If it is a primary index,
// targetIdxIndex is set to -1. Also store the targetIndex's ID so we
// don't have to do the lookup twice.
targetIdxIndex := -1
var targetIdxID sqlbase.IndexID
if matchesIndex(targetCols, target.PrimaryIndex, matchExact) {
targetIdxID = target.PrimaryIndex.ID
} else {
found := false
// Find the index corresponding to the referenced column.
for i, idx := range target.Indexes {
if idx.Unique && matchesIndex(targetCols, idx, matchExact) {
targetIdxIndex = i
targetIdxID = idx.ID
found = true
break
}
}
if !found {
return pgerror.Newf(
pgcode.InvalidForeignKey,
"there is no unique constraint matching given keys for referenced table %s",
target.Name,
)
}
}
// Don't add a SET NULL action on an index that has any column that is NOT
// NULL.
if d.Actions.Delete == tree.SetNull || d.Actions.Update == tree.SetNull {
for _, sourceColumn := range srcCols {
if !sourceColumn.Nullable {
col := qualifyFKColErrorWithDB(ctx, txn, tbl.TableDesc(), sourceColumn.Name)
return pgerror.Newf(pgcode.InvalidForeignKey,
"cannot add a SET NULL cascading action on column %q which has a NOT NULL constraint", col,
)
}
}
}
// Don't add a SET DEFAULT action on an index that has any column that does
// not have a DEFAULT expression.
if d.Actions.Delete == tree.SetDefault || d.Actions.Update == tree.SetDefault {
for _, sourceColumn := range srcCols {
if sourceColumn.DefaultExpr == nil {
col := qualifyFKColErrorWithDB(ctx, txn, tbl.TableDesc(), sourceColumn.Name)
return pgerror.Newf(pgcode.InvalidForeignKey,
"cannot add a SET DEFAULT cascading action on column %q which has no DEFAULT expression", col,
)
}
}
}
ref := sqlbase.ForeignKeyReference{
Table: target.ID,
Index: targetIdxID,
Name: constraintName,
SharedPrefixLen: int32(len(srcCols)),
OnDelete: sqlbase.ForeignKeyReferenceActionValue[d.Actions.Delete],
OnUpdate: sqlbase.ForeignKeyReferenceActionValue[d.Actions.Update],
Match: sqlbase.CompositeKeyMatchMethodValue[d.Match],
}
if ts != NewTable {
ref.Validity = sqlbase.ConstraintValidity_Validating
}
backref := sqlbase.ForeignKeyReference{Table: tbl.ID}
var idx *sqlbase.IndexDescriptor
found := false
if matchesIndex(srcCols, tbl.PrimaryIndex, matchPrefix) {
if tbl.PrimaryIndex.ForeignKey.IsSet() {
return pgerror.Newf(pgcode.InvalidForeignKey,
"columns cannot be used by multiple foreign key constraints")
}
idx = &tbl.PrimaryIndex
found = true
} else {
for i := range tbl.Indexes {
if matchesIndex(srcCols, tbl.Indexes[i], matchPrefix) {
if tbl.Indexes[i].ForeignKey.IsSet() {
return pgerror.Newf(pgcode.InvalidForeignKey,
"columns cannot be used by multiple foreign key constraints")
}
idx = &tbl.Indexes[i]
found = true
break
}
}
}
if found {
if ts == NewTable {
idx.ForeignKey = ref
} else {
tbl.AddForeignKeyValidationMutation(&ref, idx.ID)
}
backref.Index = idx.ID
} else {
// Avoid unexpected index builds from ALTER TABLE ADD CONSTRAINT.
if ts == NonEmptyTable {
return pgerror.Newf(pgcode.InvalidForeignKey,
"foreign key requires an existing index on columns %s", colNames(srcCols))
}
added, err := addIndexForFK(tbl, srcCols, constraintName, ref, ts)
if err != nil {
return err
}
backref.Index = added
}
// TODO (lucy): Should the IsNewTable() case be handled in runSchemaChangesInTxn instead?
if ts == NewTable || tbl.IsNewTable() {
if targetIdxIndex > -1 {
target.Indexes[targetIdxIndex].ReferencedBy = append(target.Indexes[targetIdxIndex].ReferencedBy, backref)
} else {
target.PrimaryIndex.ReferencedBy = append(target.PrimaryIndex.ReferencedBy, backref)
}
}
// Multiple FKs from the same column would potentially result in ambiguous or
// unexpected behavior with conflicting CASCADE/RESTRICT/etc behaviors.
colsInFKs := make(map[sqlbase.ColumnID]struct{})
fks, err := tbl.AllActiveAndInactiveForeignKeys()
if err != nil {
return err
}
for id, fk := range fks {
idx, err := tbl.FindIndexByID(id)
if err != nil {
return err
}
numCols := len(idx.ColumnIDs)
if fk.SharedPrefixLen > 0 {
numCols = int(fk.SharedPrefixLen)
}
for i := 0; i < numCols; i++ {
if _, ok := colsInFKs[idx.ColumnIDs[i]]; ok {
return pgerror.Newf(pgcode.InvalidForeignKey,
"column %q cannot be used by multiple foreign key constraints", idx.ColumnNames[i])
}
colsInFKs[idx.ColumnIDs[i]] = struct{}{}
}
}
return nil
}
// Adds an index to a table descriptor (that is in the process of being created)
// that will support using `srcCols` as the referencing (src) side of an FK.
func addIndexForFK(
tbl *sqlbase.MutableTableDescriptor,
srcCols []sqlbase.ColumnDescriptor,
constraintName string,
ref sqlbase.ForeignKeyReference,
ts FKTableState,
) (sqlbase.IndexID, error) {
// No existing index for the referencing columns found, so we add one.
idx := sqlbase.IndexDescriptor{
Name: fmt.Sprintf("%s_auto_index_%s", tbl.Name, constraintName),
ColumnNames: make([]string, len(srcCols)),
ColumnDirections: make([]sqlbase.IndexDescriptor_Direction, len(srcCols)),
}
for i, c := range srcCols {
idx.ColumnDirections[i] = sqlbase.IndexDescriptor_ASC
idx.ColumnNames[i] = c.Name
}
if ts == NewTable {
idx.ForeignKey = ref
if err := tbl.AddIndex(idx, false); err != nil {
return 0, err
}
if err := tbl.AllocateIDs(); err != nil {
return 0, err
}
added := tbl.Indexes[len(tbl.Indexes)-1]
// Since we just added the index, we can assume it is the last one rather than
// searching all the indexes again. That said, we sanity check that it matches
// in case a refactor ever violates that assumption.
if !matchesIndex(srcCols, added, matchPrefix) {
panic("no matching index and auto-generated index failed to match")
}
return added.ID, nil
}
// TODO (lucy): In the EmptyTable case, we add an index mutation, making this
// the only case where a foreign key is added to an index being added.
// Allowing FKs to be added to other indexes/columns also being added should
// be a generalization of this special case.
if err := tbl.AddIndexMutation(&idx, sqlbase.DescriptorMutation_ADD); err != nil {
return 0, err
}
if err := tbl.AllocateIDs(); err != nil {
return 0, err
}
id := tbl.Mutations[len(tbl.Mutations)-1].GetIndex().ID
tbl.AddForeignKeyValidationMutation(&ref, id)
return id, nil
}
// colNames converts a []colDesc to a human-readable string for use in error messages.
func colNames(cols []sqlbase.ColumnDescriptor) string {
var s bytes.Buffer
s.WriteString(`("`)
for i := range cols {
if i != 0 {
s.WriteString(`", "`)
}
s.WriteString(cols[i].Name)
}
s.WriteString(`")`)
return s.String()
}
func (p *planner) addInterleave(
ctx context.Context,
desc *sqlbase.MutableTableDescriptor,
index *sqlbase.IndexDescriptor,
interleave *tree.InterleaveDef,
) error {
return addInterleave(ctx, p.txn, p, desc, index, interleave)
}
// addInterleave marks an index as one that is interleaved in some parent data
// according to the given definition.
func addInterleave(
ctx context.Context,
txn *client.Txn,
vt SchemaResolver,
desc *sqlbase.MutableTableDescriptor,
index *sqlbase.IndexDescriptor,
interleave *tree.InterleaveDef,
) error {
if interleave.DropBehavior != tree.DropDefault {
return unimplemented.NewWithIssuef(
7854, "unsupported shorthand %s", interleave.DropBehavior)
}
parentTable, err := ResolveExistingObject(
ctx, vt, &interleave.Parent, true /*required*/, ResolveRequireTableDesc,
)
if err != nil {
return err
}
parentIndex := parentTable.PrimaryIndex
// typeOfIndex is used to give more informative error messages.
var typeOfIndex string
if index.ID == desc.PrimaryIndex.ID {
typeOfIndex = "primary key"
} else {
typeOfIndex = "index"
}
if len(interleave.Fields) != len(parentIndex.ColumnIDs) {
return pgerror.Newf(
pgcode.InvalidSchemaDefinition,
"declared interleaved columns (%s) must match the parent's primary index (%s)",
&interleave.Fields,
strings.Join(parentIndex.ColumnNames, ", "),
)
}
if len(interleave.Fields) > len(index.ColumnIDs) {
return pgerror.Newf(
pgcode.InvalidSchemaDefinition,
"declared interleaved columns (%s) must be a prefix of the %s columns being interleaved (%s)",
&interleave.Fields,
typeOfIndex,
strings.Join(index.ColumnNames, ", "),
)
}
for i, targetColID := range parentIndex.ColumnIDs {
targetCol, err := parentTable.FindColumnByID(targetColID)
if err != nil {
return err
}
col, err := desc.FindColumnByID(index.ColumnIDs[i])
if err != nil {
return err
}
if string(interleave.Fields[i]) != col.Name {
return pgerror.Newf(
pgcode.InvalidSchemaDefinition,
"declared interleaved columns (%s) must refer to a prefix of the %s column names being interleaved (%s)",
&interleave.Fields,
typeOfIndex,
strings.Join(index.ColumnNames, ", "),
)
}
if !col.Type.Identical(&targetCol.Type) || index.ColumnDirections[i] != parentIndex.ColumnDirections[i] {
return pgerror.Newf(
pgcode.InvalidSchemaDefinition,
"declared interleaved columns (%s) must match type and sort direction of the parent's primary index (%s)",
&interleave.Fields,
strings.Join(parentIndex.ColumnNames, ", "),
)
}
}
ancestorPrefix := append(
[]sqlbase.InterleaveDescriptor_Ancestor(nil), parentIndex.Interleave.Ancestors...)
intl := sqlbase.InterleaveDescriptor_Ancestor{
TableID: parentTable.ID,
IndexID: parentIndex.ID,
SharedPrefixLen: uint32(len(parentIndex.ColumnIDs)),
}
for _, ancestor := range ancestorPrefix {
intl.SharedPrefixLen -= ancestor.SharedPrefixLen
}
index.Interleave = sqlbase.InterleaveDescriptor{Ancestors: append(ancestorPrefix, intl)}
desc.State = sqlbase.TableDescriptor_ADD
return nil
}
// finalizeInterleave creates backreferences from an interleaving parent to the
// child data being interleaved.
func (p *planner) finalizeInterleave(
ctx context.Context, desc *sqlbase.MutableTableDescriptor, index *sqlbase.IndexDescriptor,
) error {
// TODO(dan): This is similar to finalizeFKs. Consolidate them
if len(index.Interleave.Ancestors) == 0 {
return nil
}
// Only the last ancestor needs the backreference.
ancestor := index.Interleave.Ancestors[len(index.Interleave.Ancestors)-1]
var ancestorTable *sqlbase.MutableTableDescriptor
if ancestor.TableID == desc.ID {
ancestorTable = desc
} else {
var err error
ancestorTable, err = p.Tables().getMutableTableVersionByID(ctx, ancestor.TableID, p.txn)
if err != nil {
return err
}
}
ancestorIndex, err := ancestorTable.FindIndexByID(ancestor.IndexID)
if err != nil {
return err
}
ancestorIndex.InterleavedBy = append(ancestorIndex.InterleavedBy,
sqlbase.ForeignKeyReference{Table: desc.ID, Index: index.ID})
if err := p.writeSchemaChange(ctx, ancestorTable, sqlbase.InvalidMutationID); err != nil {
return err
}
if desc.State == sqlbase.TableDescriptor_ADD {
desc.State = sqlbase.TableDescriptor_PUBLIC
if err := p.writeSchemaChange(ctx, desc, sqlbase.InvalidMutationID); err != nil {
return err
}
}
return nil
}
// CreatePartitioning constructs the partitioning descriptor for an index that
// is partitioned into ranges, each addressable by zone configs.
func CreatePartitioning(
ctx context.Context,
st *cluster.Settings,
evalCtx *tree.EvalContext,
tableDesc *sqlbase.MutableTableDescriptor,
indexDesc *sqlbase.IndexDescriptor,
partBy *tree.PartitionBy,
) (sqlbase.PartitioningDescriptor, error) {
if partBy == nil {
// No CCL necessary if we're looking at PARTITION BY NOTHING.
return sqlbase.PartitioningDescriptor{}, nil
}
return CreatePartitioningCCL(ctx, st, evalCtx, tableDesc, indexDesc, partBy)
}
// CreatePartitioningCCL is the public hook point for the CCL-licensed
// partitioning creation code.
var CreatePartitioningCCL = func(
ctx context.Context,
st *cluster.Settings,
evalCtx *tree.EvalContext,
tableDesc *sqlbase.MutableTableDescriptor,
indexDesc *sqlbase.IndexDescriptor,
partBy *tree.PartitionBy,
) (sqlbase.PartitioningDescriptor, error) {
return sqlbase.PartitioningDescriptor{}, sqlbase.NewCCLRequiredError(errors.New(
"creating or manipulating partitions requires a CCL binary"))
}
// InitTableDescriptor returns a blank TableDescriptor.
func InitTableDescriptor(
id, parentID sqlbase.ID,
name string,
creationTime hlc.Timestamp,
privileges *sqlbase.PrivilegeDescriptor,
) sqlbase.MutableTableDescriptor {
return *sqlbase.NewMutableCreatedTableDescriptor(sqlbase.TableDescriptor{
ID: id,
Name: name,
ParentID: parentID,
FormatVersion: sqlbase.InterleavedFormatVersion,
Version: 1,
ModificationTime: creationTime,
Privileges: privileges,
CreateAsOfTime: creationTime,
})
}
func getFinalSourceQuery(source *tree.Select, evalCtx *tree.EvalContext) string {
// Ensure that all the table names pretty-print as fully qualified, so we
// store that in the table descriptor.
//
// The traversal will update the TableNames in-place, so the changes are
// persisted in n.n.AsSource. We exploit the fact that planning step above
// has populated any missing db/schema details in the table names in-place.
// We use tree.FormatNode merely as a traversal method; its output buffer is
// discarded immediately after the traversal because it is not needed
// further.
f := tree.NewFmtCtx(tree.FmtParsable)
f.SetReformatTableNames(
func(_ *tree.FmtCtx, tn *tree.TableName) {
// Persist the database prefix expansion.
if tn.SchemaName != "" {
// All CTE or table aliases have no schema
// information. Those do not turn into explicit.
tn.ExplicitSchema = true
tn.ExplicitCatalog = true
}
},
)
f.FormatNode(source)
f.Close()
// Substitute placeholders with their values.
ctx := tree.NewFmtCtx(tree.FmtParsable)
ctx.SetPlaceholderFormat(func(ctx *tree.FmtCtx, placeholder *tree.Placeholder) {
d, err := placeholder.Eval(evalCtx)
if err != nil {
panic(fmt.Sprintf("failed to serialize placeholder: %s", err))
}
d.Format(ctx)
})
ctx.FormatNode(source)
return ctx.CloseAndGetString()
}
// makeTableDescIfAs is the MakeTableDesc method for when we have a table
// that is created with the CREATE AS format.
func makeTableDescIfAs(
params runParams,
p *tree.CreateTable,
parentID, id sqlbase.ID,
creationTime hlc.Timestamp,
resultColumns []sqlbase.ResultColumn,