-
Notifications
You must be signed in to change notification settings - Fork 3.8k
/
create_table.go
2950 lines (2764 loc) · 94.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 CockroachDB Software License
// included in the /LICENSE file.
package sql
import (
"context"
"fmt"
"go/constant"
"strconv"
"strings"
"time"
"github.com/cockroachdb/cockroach/pkg/build"
"github.com/cockroachdb/cockroach/pkg/clusterversion"
"github.com/cockroachdb/cockroach/pkg/docs"
"github.com/cockroachdb/cockroach/pkg/jobs"
"github.com/cockroachdb/cockroach/pkg/jobs/jobspb"
"github.com/cockroachdb/cockroach/pkg/kv"
"github.com/cockroachdb/cockroach/pkg/scheduledjobs"
"github.com/cockroachdb/cockroach/pkg/security/username"
"github.com/cockroachdb/cockroach/pkg/server/telemetry"
"github.com/cockroachdb/cockroach/pkg/settings/cluster"
"github.com/cockroachdb/cockroach/pkg/sql/catalog"
"github.com/cockroachdb/cockroach/pkg/sql/catalog/catenumpb"
"github.com/cockroachdb/cockroach/pkg/sql/catalog/catpb"
"github.com/cockroachdb/cockroach/pkg/sql/catalog/catprivilege"
"github.com/cockroachdb/cockroach/pkg/sql/catalog/colinfo"
"github.com/cockroachdb/cockroach/pkg/sql/catalog/descpb"
"github.com/cockroachdb/cockroach/pkg/sql/catalog/descs"
"github.com/cockroachdb/cockroach/pkg/sql/catalog/multiregion"
"github.com/cockroachdb/cockroach/pkg/sql/catalog/resolver"
"github.com/cockroachdb/cockroach/pkg/sql/catalog/schemaexpr"
"github.com/cockroachdb/cockroach/pkg/sql/catalog/tabledesc"
"github.com/cockroachdb/cockroach/pkg/sql/catalog/typedesc"
"github.com/cockroachdb/cockroach/pkg/sql/paramparse"
"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/pgwire/pgnotice"
"github.com/cockroachdb/cockroach/pkg/sql/privilege"
"github.com/cockroachdb/cockroach/pkg/sql/row"
"github.com/cockroachdb/cockroach/pkg/sql/sem/catconstants"
"github.com/cockroachdb/cockroach/pkg/sql/sem/catid"
"github.com/cockroachdb/cockroach/pkg/sql/sem/eval"
"github.com/cockroachdb/cockroach/pkg/sql/sem/tree"
"github.com/cockroachdb/cockroach/pkg/sql/sem/tree/treebin"
"github.com/cockroachdb/cockroach/pkg/sql/sem/tree/treecmp"
"github.com/cockroachdb/cockroach/pkg/sql/sessiondata"
"github.com/cockroachdb/cockroach/pkg/sql/sqlerrors"
"github.com/cockroachdb/cockroach/pkg/sql/sqltelemetry"
"github.com/cockroachdb/cockroach/pkg/sql/storageparam"
"github.com/cockroachdb/cockroach/pkg/sql/storageparam/indexstorageparam"
"github.com/cockroachdb/cockroach/pkg/sql/storageparam/tablestorageparam"
"github.com/cockroachdb/cockroach/pkg/sql/ttl/ttlbase"
"github.com/cockroachdb/cockroach/pkg/sql/types"
"github.com/cockroachdb/cockroach/pkg/util/errorutil/unimplemented"
"github.com/cockroachdb/cockroach/pkg/util/hlc"
"github.com/cockroachdb/cockroach/pkg/util/log/eventpb"
"github.com/cockroachdb/cockroach/pkg/util/uuid"
"github.com/cockroachdb/errors"
pbtypes "github.com/gogo/protobuf/types"
"github.com/lib/pq/oid"
)
type createTableNode struct {
n *tree.CreateTable
dbDesc catalog.DatabaseDescriptor
sourcePlan planNode
}
// 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() {}
// getNonTemporarySchemaForCreate returns the schema in which to create an object.
// Note that it does not handle the temporary schema -- if the requested schema
// is temporary, the caller needs to use (*planner).getOrCreateTemporarySchema.
func (p *planner) getNonTemporarySchemaForCreate(
ctx context.Context, db catalog.DatabaseDescriptor, scName string,
) (catalog.SchemaDescriptor, error) {
sc, err := p.Descriptors().ByName(p.txn).Get().Schema(ctx, db, scName)
if err != nil {
return nil, err
}
switch sc.SchemaKind() {
case catalog.SchemaPublic:
return sc, nil
case catalog.SchemaUserDefined:
return p.Descriptors().MutableByID(p.txn).Schema(ctx, sc.GetID())
case catalog.SchemaVirtual:
return nil, pgerror.Newf(pgcode.InsufficientPrivilege, "schema cannot be modified: %q", scName)
default:
return nil, errors.AssertionFailedf(
"invalid schema kind for getNonTemporarySchemaForCreate: %d", sc.SchemaKind())
}
}
// getSchemaForCreateTable returns the table key needed for the new table,
// as well as the schema id. It returns valid data in the case that
// the desired object exists.
func getSchemaForCreateTable(
params runParams,
db catalog.DatabaseDescriptor,
persistence tree.Persistence,
tableName *tree.TableName,
kind tree.RequiredTableKind,
ifNotExists bool,
) (schema catalog.SchemaDescriptor, err error) {
// Check we are not creating a table which conflicts with an alias available
// as a built-in type in CockroachDB but an extension type on the public
// schema for PostgreSQL.
if tableName.Schema() == catconstants.PublicSchemaName {
if _, ok := types.PublicSchemaAliases[tableName.Object()]; ok {
return nil, sqlerrors.NewTypeAlreadyExistsError(tableName.Object())
}
}
if persistence.IsTemporary() {
if !params.SessionData().TempTablesEnabled {
return nil, errors.WithTelemetry(
pgerror.WithCandidateCode(
errors.WithHint(
errors.WithIssueLink(
errors.Newf("temporary tables are only supported experimentally"),
errors.IssueLink{IssueURL: build.MakeIssueURL(46260)},
),
"You can enable temporary tables by running `SET experimental_enable_temp_tables = 'on'`.",
),
pgcode.ExperimentalFeature,
),
"sql.schema.temp_tables_disabled",
)
}
// If the table is temporary, get the temporary schema ID.
var err error
schema, err = params.p.getOrCreateTemporarySchema(params.ctx, db)
if err != nil {
return nil, err
}
} else {
// Otherwise, find the ID of the schema to create the table within.
var err error
schema, err = params.p.getNonTemporarySchemaForCreate(params.ctx, db, tableName.Schema())
if err != nil {
return nil, err
}
if schema.SchemaKind() == catalog.SchemaUserDefined {
sqltelemetry.IncrementUserDefinedSchemaCounter(sqltelemetry.UserDefinedSchemaUsedByObject)
}
}
if persistence.IsUnlogged() {
telemetry.Inc(sqltelemetry.CreateUnloggedTableCounter)
params.p.BufferClientNotice(
params.ctx,
pgnotice.Newf("UNLOGGED TABLE will behave as a regular table in CockroachDB"),
)
}
// Check permissions on the schema.
if err := params.p.canCreateOnSchema(
params.ctx, schema.GetID(), db.GetID(), params.p.User(), skipCheckPublicSchema); err != nil {
return nil, err
}
desc, err := descs.GetDescriptorCollidingWithObjectName(
params.ctx,
params.p.Descriptors(),
params.p.txn,
db.GetID(),
schema.GetID(),
tableName.Table(),
)
if err != nil {
return nil, err
}
if desc != nil {
// Ensure that the descriptor that does exist has the appropriate type.
{
mismatchedType := true
if tableDescriptor, ok := desc.(catalog.TableDescriptor); ok {
mismatchedType = false
switch kind {
case tree.ResolveRequireTableDesc:
mismatchedType = !tableDescriptor.IsTable()
case tree.ResolveRequireViewDesc:
mismatchedType = !tableDescriptor.IsView()
case tree.ResolveRequireSequenceDesc:
mismatchedType = !tableDescriptor.IsSequence()
}
// If kind any is passed then there will never be a mismatch
// and we can return an exists error.
}
// Only complain about mismatched types for
// if not exists clauses.
if mismatchedType && ifNotExists {
return nil, pgerror.Newf(pgcode.WrongObjectType,
"%q is not a %s",
tableName.Table(),
kind)
}
}
// Check if the object already exists in a dropped state
if desc.Dropped() {
return nil, pgerror.Newf(pgcode.ObjectNotInPrerequisiteState,
"%s %q is being dropped, try again later",
kind,
tableName.Table())
}
// Still return data in this case.
return schema, sqlerrors.MakeObjectAlreadyExistsError(desc.DescriptorProto(), tableName.FQString())
}
return schema, nil
}
func hasPrimaryKeySerialType(params runParams, colDef *tree.ColumnTableDef) (bool, error) {
if colDef.IsSerial || colDef.GeneratedIdentity.IsGeneratedAsIdentity {
return true, nil
}
if funcExpr, ok := colDef.DefaultExpr.Expr.(*tree.FuncExpr); ok {
searchPath := params.p.CurrentSearchPath()
fd, err := funcExpr.Func.Resolve(params.ctx, &searchPath, params.p.semaCtx.FunctionResolver)
if err != nil {
return false, err
}
if fd.Name == "nextval" {
return true, nil
}
}
return false, nil
}
func (n *createTableNode) startExec(params runParams) error {
// Check if the parent object is a replicated PCR descriptor, which will block
// schema changes.
if n.dbDesc.GetReplicatedPCRVersion() != 0 {
return pgerror.Newf(pgcode.ReadOnlySQLTransaction, "schema changes are not allowed on a reader catalog")
}
telemetry.Inc(sqltelemetry.SchemaChangeCreateCounter("table"))
colsWithPrimaryKeyConstraint := make(map[tree.Name]bool)
// Copy column definition slice, since we will modify it below. This
// ensures, that nothing bad happens on a transaction retry errors, for
// example we implicitly add columns for REGIONAL BY ROW.
// Note: This is only a shallow copy and meant to deal with addition /
// deletion into the slice.
defsCopy := make(tree.TableDefs, 0, len(n.n.Defs))
defsCopy = append(defsCopy, n.n.Defs...)
defer func(originalDefs tree.TableDefs) { n.n.Defs = originalDefs }(n.n.Defs)
n.n.Defs = defsCopy
for _, def := range n.n.Defs {
switch v := def.(type) {
case *tree.UniqueConstraintTableDef:
if v.PrimaryKey {
for _, indexEle := range v.IndexTableDef.Columns {
colsWithPrimaryKeyConstraint[indexEle.Column] = true
}
}
case *tree.ColumnTableDef:
if v.PrimaryKey.IsPrimaryKey {
colsWithPrimaryKeyConstraint[v.Name] = true
}
}
}
for _, def := range n.n.Defs {
switch v := def.(type) {
case *tree.ColumnTableDef:
if _, ok := colsWithPrimaryKeyConstraint[v.Name]; ok {
primaryKeySerial, err := hasPrimaryKeySerialType(params, v)
if err != nil {
return err
}
if primaryKeySerial {
params.p.BufferClientNotice(
params.ctx,
pgnotice.Newf("using sequential values in a primary key does not perform as well as using random UUIDs. See %s", docs.URL("serial.html")),
)
break
}
}
}
}
schema, err := getSchemaForCreateTable(params, n.dbDesc, n.n.Persistence, &n.n.Table,
tree.ResolveRequireTableDesc, n.n.IfNotExists)
if err != nil {
if sqlerrors.IsRelationAlreadyExistsError(err) && n.n.IfNotExists {
params.p.BufferClientNotice(
params.ctx,
pgnotice.Newf("relation %q already exists, skipping", n.n.Table.Table()),
)
return nil
}
return err
}
if n.n.Persistence.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.
// Avoid the warning if we have PARTITION ALL BY as all indexes will implicitly
// have relevant partitioning columns prepended at the front.
if n.n.PartitionByTable.ContainsPartitions() {
for _, def := range n.n.Defs {
if d, ok := def.(*tree.IndexTableDef); ok {
if d.PartitionByIndex == nil && !n.n.PartitionByTable.All {
params.p.BufferClientNotice(
params.ctx,
errors.WithHint(
pgnotice.Newf("creating non-partitioned index on partitioned table may not be performant"),
"Consider modifying the index such that it is also partitioned.",
),
)
}
}
}
}
id, err := params.extendedEvalCtx.DescIDGenerator.
GenerateUniqueDescID(params.ctx)
if err != nil {
return err
}
var desc *tabledesc.Mutable
var affected map[descpb.ID]*tabledesc.Mutable
// creationTime is initialized to a zero value and populated at read time.
// See the comment in desc.MaybeIncrementVersion.
//
// TODO(ajwerner): remove the timestamp from newTableDesc and its friends,
// it's currently relied on in import and restore code and tests.
var creationTime hlc.Timestamp
privs, err := catprivilege.CreatePrivilegesFromDefaultPrivileges(
n.dbDesc.GetDefaultPrivilegeDescriptor(),
schema.GetDefaultPrivilegeDescriptor(),
n.dbDesc.GetID(),
params.SessionData().User(),
privilege.Tables,
)
if err != nil {
return err
}
if n.n.As() {
asCols := planColumns(n.sourcePlan)
if !n.n.AsHasUserSpecifiedPrimaryKey() {
// rowID column is already present in the input as the last column
// if the user did not specify a PRIMARY KEY. So ignore it for the
// purpose of creating column metadata (because newTableDescIfAs
// does it automatically).
asCols = asCols[:len(asCols)-1]
}
desc, err = newTableDescIfAs(
params, n.n, n.dbDesc, schema, id, creationTime, asCols, privs, params.p.EvalContext(),
)
if err != nil {
return err
}
// If we have a single statement txn we want to run CTAS async, and
// consequently ensure it gets queued as a SchemaChange.
if params.extendedEvalCtx.TxnIsSingleStmt {
desc.State = descpb.DescriptorState_ADD
}
} else {
affected = make(map[descpb.ID]*tabledesc.Mutable)
desc, err = newTableDesc(params, n.n, n.dbDesc, schema, 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.
// TODO(chengxiong): do we need to do something here? Like. add logic to find all references.
refs, err := desc.FindAllReferences()
if err != nil {
return err
}
var foundExternalReference bool
for id := range refs {
if _, t, err := params.p.Descriptors().GetUncommittedMutableTableByID(id); err != nil {
return err
} else if t == nil || !t.IsNew() {
foundExternalReference = true
break
}
}
if !foundExternalReference {
desc.State = descpb.DescriptorState_PUBLIC
}
}
}
// Replace all UDF names with OIDs in check constraints and update back
// references in functions used.
for _, ck := range desc.CheckConstraints() {
if err := params.p.updateFunctionReferencesForCheck(params.ctx, desc, ck.CheckDesc()); err != nil {
return err
}
}
// Update cross-references between functions and columns.
for i := range desc.Columns {
if err := params.p.maybeUpdateFunctionReferencesForColumn(params.ctx, desc, &desc.Columns[i]); err != nil {
return err
}
}
// Descriptor written to store here.
if err := params.p.createDescriptor(
params.ctx,
desc,
tree.AsStringWithFQNames(n.n, params.Ann()),
); err != nil {
return err
}
for _, updated := range affected {
if err := params.p.writeSchemaChange(
params.ctx, updated, descpb.InvalidMutationID,
fmt.Sprintf("updating referenced FK table %s(%d) for table %s(%d)",
updated.Name, updated.ID, desc.Name, desc.ID,
),
); err != nil {
return err
}
}
// Install back references to types used by this table.
if err := params.p.addBackRefsFromAllTypesInTable(params.ctx, desc); err != nil {
return err
}
if err := validateDescriptor(params.ctx, params.p, desc); err != nil {
return err
}
if desc.LocalityConfig != nil {
dbDesc, err := params.p.Descriptors().ByIDWithoutLeased(params.p.txn).WithoutNonPublic().Get().Database(params.ctx, desc.ParentID)
if err != nil {
return errors.Wrap(err, "error resolving database for multi-region")
}
regionConfig, err := SynthesizeRegionConfig(params.ctx, params.p.txn, dbDesc.GetID(), params.p.Descriptors())
if err != nil {
return err
}
if err := ApplyZoneConfigForMultiRegionTable(
params.ctx,
params.p.InternalSQLTxn(),
params.p.ExecCfg(),
params.p.extendedEvalCtx.Tracing.KVTracingEnabled(),
regionConfig,
desc,
ApplyZoneConfigForMultiRegionTableOptionTableAndIndexes,
); err != nil {
return err
}
// Save the reference on the multi-region enum if there is a dependency with
// the descriptor.
if desc.GetMultiRegionEnumDependencyIfExists() {
regionEnumID, err := dbDesc.MultiRegionEnumID()
if err != nil {
return err
}
typeDesc, err := params.p.Descriptors().MutableByID(params.p.txn).Type(params.ctx, regionEnumID)
if err != nil {
return errors.Wrap(err, "error resolving multi-region enum")
}
typeDesc.AddReferencingDescriptorID(desc.ID)
err = params.p.writeTypeSchemaChange(
params.ctx, typeDesc, "add REGIONAL BY TABLE back reference")
if err != nil {
return errors.Wrap(err, "error adding backreference to multi-region enum")
}
}
}
// Log Create Table event. This is an auditable log event and is
// recorded in the same transaction as the table descriptor update.
if err := params.p.logEvent(params.ctx,
desc.ID,
&eventpb.CreateTable{
TableName: n.n.Table.FQString(),
}); err != nil {
return err
}
// If we are in a multi-statement txn or the source has placeholders, we
// execute the CTAS query synchronously.
if n.n.As() && !params.extendedEvalCtx.TxnIsSingleStmt {
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.
internal := params.p.SessionData().Internal
ri, err := row.MakeInserter(
params.ctx,
params.p.txn,
params.ExecCfg().Codec,
desc.ImmutableCopy().(catalog.TableDescriptor),
nil, /* uniqueWithTombstoneIndexes */
desc.PublicColumns(),
&tree.DatumAlloc{},
¶ms.ExecCfg().Settings.SV,
internal,
params.ExecCfg().GetRowMetrics(internal),
)
if err != nil {
return err
}
ti := tableInserterPool.Get().(*tableInserter)
*ti = tableInserter{ri: ri}
defer func() {
ti.close(params.ctx)
*ti = tableInserter{}
tableInserterPool.Put(ti)
}()
if err := ti.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))
for {
if err := params.p.cancelChecker.Check(); err != nil {
return err
}
if next, err := n.sourcePlan.Next(params); !next {
if err != nil {
return err
}
if err := ti.finalize(params.ctx); err != nil {
return err
}
break
}
// Periodically flush out the batches, so that we don't issue gigantic
// raft commands.
if ti.currentBatchSize >= ti.maxBatchSize ||
ti.b.ApproximateMutationBytes() >= ti.maxBatchByteSize {
if err := ti.flushAndStartNewBatch(params.ctx); err != nil {
return err
}
}
// Populate the buffer.
copy(rowBuffer, n.sourcePlan.Values())
// CREATE TABLE AS does not copy indexes from the input table.
// An empty row.PartialIndexUpdateHelper is used here because
// there are no indexes, partial or otherwise, to update.
var pm row.PartialIndexUpdateHelper
if err := ti.row(params.ctx, rowBuffer, pm, params.extendedEvalCtx.Tracing.KVTracingEnabled()); err != nil {
return err
}
}
return nil
}()
if err != nil {
return err
}
}
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
}
}
func qualifyFKColErrorWithDB(
ctx context.Context,
db catalog.DatabaseDescriptor,
sc catalog.SchemaDescriptor,
tbl catalog.TableDescriptor,
col string,
) string {
return tree.ErrString(tree.NewUnresolvedName(
db.GetName(),
sc.GetName(),
tbl.GetName(),
col,
))
}
// TableState is the state of the referencing table ResolveFK() or
// ResolveUniqueWithoutIndexConstraint() is called on.
type TableState int
const (
// NewTable represents a new table, where the constraint is specified in the
// CREATE TABLE
NewTable TableState = iota
// EmptyTable represents an existing table that is empty
EmptyTable
// NonEmptyTable represents an existing non-empty table
NonEmptyTable
)
// addUniqueWithoutIndexColumnTableDef runs various checks on the given
// ColumnTableDef before adding it as a UNIQUE WITHOUT INDEX constraint to the
// given table descriptor.
func addUniqueWithoutIndexColumnTableDef(
ctx context.Context,
evalCtx *eval.Context,
sessionData *sessiondata.SessionData,
d *tree.ColumnTableDef,
desc *tabledesc.Mutable,
ts TableState,
validationBehavior tree.ValidationBehavior,
) error {
if !sessionData.EnableUniqueWithoutIndexConstraints {
return pgerror.New(pgcode.FeatureNotSupported,
"unique constraints without an index are not yet supported",
)
}
// Add a unique constraint.
if err := ResolveUniqueWithoutIndexConstraint(
ctx,
desc,
string(d.Unique.ConstraintName),
[]string{string(d.Name)},
"", /* predicate */
ts,
validationBehavior,
); err != nil {
return err
}
return nil
}
// addUniqueWithoutIndexTableDef runs various checks on the given
// UniqueConstraintTableDef before adding it as a UNIQUE WITHOUT INDEX
// constraint to the given table descriptor.
func addUniqueWithoutIndexTableDef(
ctx context.Context,
evalCtx *eval.Context,
sessionData *sessiondata.SessionData,
d *tree.UniqueConstraintTableDef,
desc *tabledesc.Mutable,
tn tree.TableName,
ts TableState,
validationBehavior tree.ValidationBehavior,
semaCtx *tree.SemaContext,
) error {
if !sessionData.EnableUniqueWithoutIndexConstraints {
return pgerror.New(pgcode.FeatureNotSupported,
"unique constraints without an index are not yet supported",
)
}
if len(d.Storing) > 0 {
return pgerror.New(pgcode.FeatureNotSupported,
"unique constraints without an index cannot store columns",
)
}
if d.PartitionByIndex.ContainsPartitions() {
return pgerror.New(pgcode.FeatureNotSupported,
"partitioned unique constraints without an index are not supported",
)
}
if d.Invisibility.Value != 0.0 {
// Theoretically, this should never happen because this is not supported by
// the parser. This is just a safe check.
return pgerror.Newf(pgcode.FeatureNotSupported,
"creating a unique constraint using UNIQUE WITH NOT VISIBLE INDEX is not supported",
)
}
// If there is a predicate, validate it.
var predicate string
if d.Predicate != nil {
var err error
predicate, err = schemaexpr.ValidateUniqueWithoutIndexPredicate(
ctx, tn, desc, d.Predicate, semaCtx, evalCtx.Settings.Version.ActiveVersionOrEmpty(ctx),
)
if err != nil {
return err
}
}
// Add a unique constraint.
colNames := make([]string, len(d.Columns))
for i := range colNames {
colNames[i] = string(d.Columns[i].Column)
}
if err := ResolveUniqueWithoutIndexConstraint(
ctx, desc, string(d.Name), colNames, predicate, ts, validationBehavior,
); err != nil {
return err
}
return nil
}
// ResolveUniqueWithoutIndexConstraint looks up the columns mentioned in a
// UNIQUE WITHOUT INDEX constraint and adds metadata representing that
// constraint to the descriptor.
//
// The passed validationBehavior is used to determine whether or not preexisting
// entries in the table need to be validated against the unique constraint being
// added. This only applies for existing tables, not new tables.
func ResolveUniqueWithoutIndexConstraint(
ctx context.Context,
tbl *tabledesc.Mutable,
constraintName string,
colNames []string,
predicate string,
ts TableState,
validationBehavior tree.ValidationBehavior,
) error {
var colSet catalog.TableColSet
cols := make([]catalog.Column, len(colNames))
for i, name := range colNames {
col, err := tbl.FindActiveOrNewColumnByName(tree.Name(name))
if err != nil {
return err
}
// Ensure that the columns don't have duplicates.
if colSet.Contains(col.GetID()) {
return pgerror.Newf(pgcode.DuplicateColumn,
"column %q appears twice in unique constraint", col.GetName())
}
colSet.Add(col.GetID())
cols[i] = col
}
// Verify we are not writing a constraint over the same name.
if constraintName == "" {
constraintName = tabledesc.GenerateUniqueName(
fmt.Sprintf("unique_%s", strings.Join(colNames, "_")),
func(p string) bool {
return catalog.FindConstraintByName(tbl, p) != nil
},
)
} else {
if c := catalog.FindConstraintByName(tbl, constraintName); c != nil {
return pgerror.Newf(pgcode.DuplicateObject, "duplicate constraint name: %q", constraintName)
}
}
columnIDs := make(descpb.ColumnIDs, len(cols))
for i, col := range cols {
columnIDs[i] = col.GetID()
}
validity := descpb.ConstraintValidity_Validated
if ts != NewTable {
if validationBehavior == tree.ValidationSkip {
validity = descpb.ConstraintValidity_Unvalidated
} else {
validity = descpb.ConstraintValidity_Validating
}
}
uc := descpb.UniqueWithoutIndexConstraint{
Name: constraintName,
TableID: tbl.ID,
ColumnIDs: columnIDs,
Predicate: predicate,
Validity: validity,
ConstraintID: tbl.NextConstraintID,
}
tbl.NextConstraintID++
if ts == NewTable {
tbl.UniqueWithoutIndexConstraints = append(tbl.UniqueWithoutIndexConstraints, uc)
} else {
tbl.AddUniqueWithoutIndexMutation(&uc, descpb.DescriptorMutation_ADD)
}
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 resolver.SchemaResolver,
parentDB catalog.DatabaseDescriptor,
parentSchema catalog.SchemaDescriptor,
tbl *tabledesc.Mutable,
d *tree.ForeignKeyConstraintTableDef,
backrefs map[descpb.ID]*tabledesc.Mutable,
ts TableState,
validationBehavior tree.ValidationBehavior,
evalCtx *eval.Context,
) error {
var originColSet catalog.TableColSet
originCols := make([]catalog.Column, len(d.FromCols))
for i, fromCol := range d.FromCols {
col, err := tbl.FindActiveOrNewColumnByName(fromCol)
if err != nil {
return err
}
if err := col.CheckCanBeOutboundFKRef(); err != nil {
return err
}
// Ensure that the origin columns don't have duplicates.
if originColSet.Contains(col.GetID()) {
return pgerror.Newf(pgcode.InvalidForeignKey,
"foreign key contains duplicate column %q", col.GetName())
}
originColSet.Add(col.GetID())
originCols[i] = col
}
_, target, err := resolver.ResolveMutableExistingTableObject(ctx, sc, &d.Table, true /*required*/, tree.ResolveRequireTableDesc)
if err != nil {
return err
}
if target.ParentID != tbl.ParentID {
if !allowCrossDatabaseFKs.Get(&evalCtx.Settings.SV) {
return errors.WithHint(
pgerror.Newf(pgcode.InvalidForeignKey,
"foreign references between databases are not allowed (see the '%s' cluster setting)",
allowCrossDatabaseFKsSetting),
crossDBReferenceDeprecationHint(),
)
}
}
if tbl.Temporary != target.Temporary {
persistenceType := "permanent"
if tbl.Temporary {
persistenceType = "temporary"
}
return pgerror.Newf(
pgcode.InvalidTableDefinition,
"constraints on %s tables may reference only %s tables",
persistenceType,
persistenceType,
)
}
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 = descpb.DescriptorState_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
}
}
referencedColNames := d.ToCols
// If no columns are specified, attempt to default to PK, ignoring implicit columns.
if len(referencedColNames) == 0 {
numImplicitCols := target.GetPrimaryIndex().ImplicitPartitioningColumnCount()
referencedColNames = make(
tree.NameList,
0,
target.GetPrimaryIndex().NumKeyColumns()-numImplicitCols,
)
for i := numImplicitCols; i < target.GetPrimaryIndex().NumKeyColumns(); i++ {
referencedColNames = append(
referencedColNames,
tree.Name(target.GetPrimaryIndex().GetKeyColumnName(i)),
)
}
}
referencedCols, err := catalog.MustFindPublicColumnsByNameList(target, referencedColNames)
if err != nil {
return err
}
for i := range referencedCols {
if err := referencedCols[i].CheckCanBeInboundFKRef(); err != nil {
return err
}
}
if len(referencedCols) != len(originCols) {
return pgerror.Newf(pgcode.Syntax,
"%d columns must reference exactly %d columns in referenced table (found %d)",
len(originCols), len(originCols), len(referencedCols))
}
for i := range originCols {
if s, t := originCols[i], referencedCols[i]; !s.GetType().Equivalent(t.GetType()) {
return pgerror.Newf(pgcode.DatatypeMismatch,
"type of %q (%s) does not match foreign key %q.%q (%s)",
s.GetName(), s.GetType().String(), target.Name, t.GetName(), t.GetType().String())
}
// Send a notice to client if origin col type is not identical to the
// referenced col.
if s, t := originCols[i], referencedCols[i]; !s.GetType().Identical(t.GetType()) {
notice := pgnotice.Newf(
"type of foreign key column %q (%s) is not identical to referenced column %q.%q (%s)",
s.ColName(), s.GetType().SQLString(), target.Name, t.GetName(), t.GetType().SQLString())
evalCtx.ClientNoticeSender.BufferClientNotice(ctx, notice)
}
}
// 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.
constraintName := string(d.Name)
if constraintName == "" {
constraintName = tabledesc.GenerateUniqueName(
tabledesc.ForeignKeyConstraintName(tbl.GetName(), d.FromCols.ToStrings()),
func(p string) bool {
return catalog.FindConstraintByName(tbl, p) != nil
},
)
} else {
if c := catalog.FindConstraintByName(tbl, constraintName); c != nil {
return pgerror.Newf(pgcode.DuplicateObject, "duplicate constraint name: %q", constraintName)
}
}
originColumnIDs := make(descpb.ColumnIDs, len(originCols))
for i, col := range originCols {
originColumnIDs[i] = col.GetID()