-
Notifications
You must be signed in to change notification settings - Fork 3.8k
/
Copy pathcreate_table.go
2139 lines (1963 loc) · 68 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"
"go/constant"
"math"
"sort"
"strconv"
"strings"
"github.com/cockroachdb/cockroach/pkg/clusterversion"
"github.com/cockroachdb/cockroach/pkg/keys"
"github.com/cockroachdb/cockroach/pkg/kv"
"github.com/cockroachdb/cockroach/pkg/server/telemetry"
"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/row"
"github.com/cockroachdb/cockroach/pkg/sql/schema"
"github.com/cockroachdb/cockroach/pkg/sql/sem/tree"
"github.com/cockroachdb/cockroach/pkg/sql/sessiondata"
"github.com/cockroachdb/cockroach/pkg/sql/sqlbase"
"github.com/cockroachdb/cockroach/pkg/sql/sqltelemetry"
"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
}
// 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 if a user specified PK does not exist (so
// synthRowID is false), whereas the heuristic planner's plan does not in this
// case (so synthRowID is true).
synthRowID bool
// fromHeuristicPlanner indicates whether the planning was performed by the
// heuristic planner instead of the optimizer. This is used to determine
// whether or not a row_id was synthesized as part of the planning stage, if a
// user defined PK is not specified.
fromHeuristicPlanner bool
}
// storageParamType indicates the required type of a storage parameter.
type storageParamType int
// storageParamType values
const (
storageParamBool storageParamType = iota
storageParamInt
storageParamFloat
storageParamUnimplemented
)
var storageParamExpectedTypes = map[string]storageParamType{
`fillfactor`: storageParamInt,
`toast_tuple_target`: storageParamUnimplemented,
`parallel_workers`: storageParamUnimplemented,
`autovacuum_enabled`: storageParamUnimplemented,
`toast.autovacuum_enabled`: storageParamUnimplemented,
`autovacuum_vacuum_threshold`: storageParamUnimplemented,
`toast.autovacuum_vacuum_threshold`: storageParamUnimplemented,
`autovacuum_vacuum_scale_factor`: storageParamUnimplemented,
`toast.autovacuum_vacuum_scale_factor`: storageParamUnimplemented,
`autovacuum_analyze_threshold`: storageParamUnimplemented,
`autovacuum_analyze_scale_factor`: storageParamUnimplemented,
`autovacuum_vacuum_cost_delay`: storageParamUnimplemented,
`toast.autovacuum_vacuum_cost_delay`: storageParamUnimplemented,
`autovacuum_vacuum_cost_limit`: storageParamUnimplemented,
`autovacuum_freeze_min_age`: storageParamUnimplemented,
`toast.autovacuum_freeze_min_age`: storageParamUnimplemented,
`autovacuum_freeze_max_age`: storageParamUnimplemented,
`toast.autovacuum_freeze_max_age`: storageParamUnimplemented,
`autovacuum_freeze_table_age`: storageParamUnimplemented,
`toast.autovacuum_freeze_table_age`: storageParamUnimplemented,
`autovacuum_multixact_freeze_min_age`: storageParamUnimplemented,
`toast.autovacuum_multixact_freeze_min_age`: storageParamUnimplemented,
`autovacuum_multixact_freeze_max_age`: storageParamUnimplemented,
`toast.autovacuum_multixact_freeze_max_age`: storageParamUnimplemented,
`autovacuum_multixact_freeze_table_age`: storageParamUnimplemented,
`toast.autovacuum_multixact_freeze_table_age`: storageParamUnimplemented,
`log_autovacuum_min_duration`: storageParamUnimplemented,
`toast.log_autovacuum_min_duration`: storageParamUnimplemented,
`user_catalog_table`: storageParamUnimplemented,
}
// ReadingOwnWrites implements the planNodeReadingOwnWrites interface.
// This is because CREATE TABLE performs multiple KV operations on descriptors
// and expects to see its own writes.
func (n *createTableNode) ReadingOwnWrites() {}
// getTableCreateParams returns the table key needed for the new table,
// as well as the schema id.
func getTableCreateParams(
params runParams, dbID sqlbase.ID, isTemporary bool, tableName string,
) (sqlbase.DescriptorKey, sqlbase.ID, error) {
// By default, all tables are created in the `public` schema.
schemaID := sqlbase.ID(keys.PublicSchemaID)
tKey := sqlbase.MakePublicTableNameKey(params.ctx,
params.ExecCfg().Settings, dbID, tableName)
if isTemporary {
if !params.SessionData().TempTablesEnabled {
return nil, 0, errors.WithTelemetry(
pgerror.WithCandidateCode(
errors.WithHint(
errors.WithIssueLink(
errors.Newf("temporary tables are only supported experimentally"),
errors.IssueLink{IssueURL: unimplemented.MakeURL(46260)},
),
"You can enable temporary tables by running `SET experimental_enable_temp_tables = 'on'`.",
),
pgcode.FeatureNotSupported,
),
"sql.schema.temp_tables_disabled",
)
}
tempSchemaName := params.p.TemporarySchemaName()
sKey := sqlbase.NewSchemaKey(dbID, tempSchemaName)
var err error
schemaID, err = getDescriptorID(params.ctx, params.p.txn, sKey)
if err != nil {
return nil, 0, err
} else if schemaID == sqlbase.InvalidID {
// The temporary schema has not been created yet.
if schemaID, err = createTempSchema(params, sKey); err != nil {
return nil, 0, err
}
}
tKey = sqlbase.NewTableKey(dbID, schemaID, tableName)
}
exists, _, err := sqlbase.LookupObjectID(params.ctx, params.p.txn, dbID, schemaID, tableName)
if err == nil && exists {
return nil, 0, sqlbase.NewRelationAlreadyExistsError(tableName)
} else if err != nil {
return nil, 0, err
}
return tKey, schemaID, nil
}
func (n *createTableNode) startExec(params runParams) error {
telemetry.Inc(sqltelemetry.SchemaChangeCreateCounter("table"))
isTemporary := n.n.Temporary
tKey, schemaID, err := getTableCreateParams(params, n.dbDesc.ID, isTemporary, n.n.Table.Table())
if err != nil {
if sqlbase.IsRelationAlreadyExistsError(err) && n.n.IfNotExists {
return nil
}
return err
}
if n.n.Interleave != nil {
telemetry.Inc(sqltelemetry.CreateInterleavedTableCounter)
}
if isTemporary {
telemetry.Inc(sqltelemetry.CreateTempTableCounter)
// TODO(#46556): support ON COMMIT DROP and DELETE ROWS on TEMPORARY TABLE.
// If we do this, the n.n.OnCommit variable should probably be stored on the
// table descriptor.
// Note UNSET / PRESERVE ROWS behave the same way so we do not need to do that for now.
switch n.n.OnCommit {
case tree.CreateTableOnCommitUnset, tree.CreateTableOnCommitPreserveRows:
default:
return errors.AssertionFailedf("ON COMMIT value %d is unrecognized", n.n.OnCommit)
}
} else if n.n.OnCommit != tree.CreateTableOnCommitUnset {
return pgerror.Newf(
pgcode.InvalidTableDefinition,
"ON COMMIT can only be used on temporary tables",
)
}
// Warn against creating non-partitioned indexes on a partitioned table,
// which is undesirable in most cases.
if n.n.PartitionBy != nil {
for _, def := range n.n.Defs {
if d, ok := def.(*tree.IndexTableDef); ok {
if d.PartitionBy == nil {
params.p.SendClientNotice(
params.ctx,
errors.WithHint(
pgerror.Noticef("creating non-partitioned index on partitioned table may not be performant"),
"Consider modifying the index such that it is also partitioned.",
),
)
}
}
}
}
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.creationTimeForNewTableDescriptor()
if n.n.As() {
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, schemaID, id, creationTime, asCols, privs, params.p.EvalContext(), isTemporary)
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, schemaID, id, creationTime, privs, affected, isTemporary)
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, tKey.Key(), id, &desc, params.EvalContext().Settings,
tree.AsStringWithFQNames(n.n, params.Ann()),
); err != nil {
return err
}
for _, updated := range affected {
// TODO (lucy): Have more consistent/informative names for dependent jobs.
if err := params.p.writeSchemaChange(
params.ctx, updated, sqlbase.InvalidMutationID, "updating referenced table",
); 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); 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 {
err = func() error {
// The data fill portion of CREATE AS must operate on a read snapshot,
// so that it doesn't end up observing its own writes.
prevMode := params.p.Txn().ConfigureStepping(params.ctx, kv.SteppingEnabled)
defer func() { _ = params.p.Txn().ConfigureStepping(params.ctx, prevMode) }()
// 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.ctx,
params.p.txn,
sqlbase.NewImmutableTableDescriptor(*desc.TableDesc()),
desc.Columns,
row.SkipFKs,
nil, /* fkTables */
¶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.ctx, 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
}
}
if err := tw.row(params.ctx, rowBuffer, params.extendedEvalCtx.Tracing.KVTracingEnabled()); err != nil {
return err
}
}
return nil
}()
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
}
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
}
}
// 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,
validationBehavior tree.ValidationBehavior,
) error {
return ResolveFK(ctx, p.txn, p, tbl, d, backrefs, ts, validationBehavior, p.ExecCfg().Settings)
}
func qualifyFKColErrorWithDB(
ctx context.Context, txn *kv.Txn, tbl *sqlbase.TableDescriptor, col string,
) string {
if txn == nil {
return tree.ErrString(tree.NewUnresolvedName(tbl.Name, col))
}
// TODO(solon): 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))
}
schema, err := schema.ResolveNameByID(ctx, txn, db.ID, tbl.GetParentSchemaID())
if err != nil {
return tree.ErrString(tree.NewUnresolvedName(tbl.Name, col))
}
return tree.ErrString(tree.NewUnresolvedName(db.Name, schema, 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
)
// MaybeUpgradeDependentOldForeignKeyVersionTables upgrades the on-disk foreign key descriptor
// version of all table descriptors that have foreign key relationships with desc. This is intended
// to catch upgrade 19.1 version table descriptors that haven't been upgraded yet before an operation
// like drop index which could cause them to lose FK information in the old representation.
func (p *planner) MaybeUpgradeDependentOldForeignKeyVersionTables(
ctx context.Context, desc *sqlbase.MutableTableDescriptor,
) error {
// In order to avoid having old version foreign key descriptors that depend on this
// index lose information when this index is dropped, ensure that they get updated.
maybeUpgradeFKRepresentation := func(id sqlbase.ID) error {
// Read the referenced table and see if the foreign key representation has changed. If it has, write
// the upgraded descriptor back to disk.
tbl, didUpgrade, err := sqlbase.GetTableDescFromIDWithFKsChanged(ctx, p.txn, id)
if err != nil {
return err
}
if didUpgrade {
// TODO (lucy): Have more consistent/informative names for dependent jobs.
err := p.writeSchemaChange(
ctx, sqlbase.NewMutableExistingTableDescriptor(*tbl), sqlbase.InvalidMutationID,
"updating foreign key references on table",
)
if err != nil {
return err
}
}
return nil
}
for i := range desc.OutboundFKs {
if err := maybeUpgradeFKRepresentation(desc.OutboundFKs[i].ReferencedTableID); err != nil {
return err
}
}
for i := range desc.InboundFKs {
if err := maybeUpgradeFKRepresentation(desc.InboundFKs[i].OriginTableID); err != nil {
return err
}
}
return nil
}
// 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 implies 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.
//
// The passed validationBehavior is used to determine whether or not preexisting
// entries in the table need to be validated against the foreign key being added.
// This only applies for existing tables, not new tables.
func ResolveFK(
ctx context.Context,
txn *kv.Txn,
sc SchemaResolver,
tbl *sqlbase.MutableTableDescriptor,
d *tree.ForeignKeyConstraintTableDef,
backrefs map[sqlbase.ID]*sqlbase.MutableTableDescriptor,
ts FKTableState,
validationBehavior tree.ValidationBehavior,
settings *cluster.Settings,
) error {
originColumns := make([]*sqlbase.ColumnDescriptor, len(d.FromCols))
for i, col := range d.FromCols {
col, err := tbl.FindActiveOrNewColumnByName(col)
if err != nil {
return err
}
if err := col.CheckCanBeFKRef(); err != nil {
return err
}
originColumns[i] = col
}
target, err := ResolveMutableExistingObject(ctx, sc, &d.Table, true /*required*/, ResolveRequireTableDesc)
if err != nil {
return err
}
if tbl.Temporary != target.Temporary {
tablePersistenceType := "permanent"
if tbl.Temporary {
tablePersistenceType = "temporary"
}
return pgerror.Newf(
pgcode.InvalidTableDefinition,
"constraints on %s tables may reference only %s tables",
tablePersistenceType,
tablePersistenceType,
)
}
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
}
}
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(originColumns) {
return pgerror.Newf(pgcode.Syntax,
"%d columns must reference exactly %d columns in referenced table (found %d)",
len(originColumns), len(originColumns), len(targetCols))
}
for i := range originColumns {
if s, t := originColumns[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())
}
}
// Verify we are not writing a constraint over the same name.
// This check is done in Verify(), but we must do it earlier
// or else we can hit other checks that break things with
// undesired error codes, e.g. #42858.
// It may be removable after #37255 is complete.
constraintInfo, err := tbl.GetConstraintInfo(ctx, nil)
if err != nil {
return err
}
constraintName := string(d.Name)
if constraintName == "" {
constraintName = sqlbase.GenerateUniqueConstraintName(
fmt.Sprintf("fk_%s_ref_%s", string(d.FromCols[0]), target.Name),
func(p string) bool {
_, ok := constraintInfo[p]
return ok
},
)
} else {
if _, ok := constraintInfo[constraintName]; ok {
return pgerror.Newf(pgcode.DuplicateObject, "duplicate constraint name: %q", constraintName)
}
}
targetColIDs := make(sqlbase.ColumnIDs, len(targetCols))
for i := range targetCols {
targetColIDs[i] = targetCols[i].ID
}
// 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 originColumns {
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 has
// a DEFAULT expression of NULL and a NOT NULL constraint.
if d.Actions.Delete == tree.SetDefault || d.Actions.Update == tree.SetDefault {
for _, sourceColumn := range originColumns {
// Having a default expression of NULL, and a constraint of NOT NULL is a
// contradiction and should never be allowed.
if sourceColumn.DefaultExpr == nil && !sourceColumn.Nullable {
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 a "+
"NOT NULL constraint and a NULL default expression", col,
)
}
}
}
originColumnIDs := make(sqlbase.ColumnIDs, len(originColumns))
for i, col := range originColumns {
originColumnIDs[i] = col.ID
}
var legacyOriginIndexID sqlbase.IndexID
// Search for an index on the origin table that matches. If one doesn't exist,
// we create one automatically if the table to alter is new or empty. We also
// create an index if the foreign key is on a newly added column. This allows
// us to automatically create an index for ADD COLUMN .. REFERENCES.
originIdx, err := sqlbase.FindFKOriginIndexInTxn(tbl, originColumnIDs)
if err == nil {
// If there was no error, we found a suitable index.
legacyOriginIndexID = originIdx.ID
} else {
// No existing suitable index was found.
if ts == NonEmptyTable && !isFKOnNewlyAddedColumn(tbl, originColumns) {
var colNames bytes.Buffer
colNames.WriteString(`("`)
for i, id := range originColumnIDs {
if i != 0 {
colNames.WriteString(`", "`)
}
col, err := tbl.TableDesc().FindColumnByID(id)
if err != nil {
return err
}
colNames.WriteString(col.Name)
}
colNames.WriteString(`")`)
return pgerror.Newf(pgcode.ForeignKeyViolation,
"foreign key requires an existing index on columns %s", colNames.String())
}
id, err := addIndexForFK(tbl, originColumns, constraintName, ts)
if err != nil {
return err
}
legacyOriginIndexID = id
}
referencedIdx, err := sqlbase.FindFKReferencedIndex(target.TableDesc(), targetColIDs)
if err != nil {
return err
}
legacyReferencedIndexID := referencedIdx.ID
var validity sqlbase.ConstraintValidity
if ts != NewTable {
if validationBehavior == tree.ValidationSkip {
validity = sqlbase.ConstraintValidity_Unvalidated
} else {
validity = sqlbase.ConstraintValidity_Validating
}
}
ref := sqlbase.ForeignKeyConstraint{
OriginTableID: tbl.ID,
OriginColumnIDs: originColumnIDs,
ReferencedColumnIDs: targetColIDs,
ReferencedTableID: target.ID,
Name: constraintName,
Validity: validity,
OnDelete: sqlbase.ForeignKeyReferenceActionValue[d.Actions.Delete],
OnUpdate: sqlbase.ForeignKeyReferenceActionValue[d.Actions.Update],
Match: sqlbase.CompositeKeyMatchMethodValue[d.Match],
LegacyOriginIndex: legacyOriginIndexID,
LegacyReferencedIndex: legacyReferencedIndexID,
}
if ts == NewTable {
tbl.OutboundFKs = append(tbl.OutboundFKs, ref)
target.InboundFKs = append(target.InboundFKs, ref)
} else {
tbl.AddForeignKeyMutation(&ref, sqlbase.DescriptorMutation_ADD)
}
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,
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 {
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]
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
return id, nil
}
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 *kv.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, tree.ObjectLookupFlagsWithRequired(), 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})
// TODO (lucy): Have more consistent/informative names for dependent jobs.
if err := p.writeSchemaChange(
ctx, ancestorTable, sqlbase.InvalidMutationID, "updating ancestor table",
); err != nil {
return err
}
if desc.State == sqlbase.TableDescriptor_ADD {
desc.State = sqlbase.TableDescriptor_PUBLIC
// No job description, since this is presumably part of some larger schema change.
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,