-
Notifications
You must be signed in to change notification settings - Fork 3.8k
/
alter_table.go
2357 lines (2185 loc) · 76.1 KB
/
alter_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 2015 The Cockroach Authors.
//
// Use of this software is governed by the CockroachDB Software License
// included in the /LICENSE file.
package sql
import (
"bytes"
"context"
gojson "encoding/json"
"fmt"
"sort"
"time"
"github.com/cockroachdb/cockroach/pkg/build"
"github.com/cockroachdb/cockroach/pkg/jobs"
"github.com/cockroachdb/cockroach/pkg/jobs/jobspb"
"github.com/cockroachdb/cockroach/pkg/server/telemetry"
"github.com/cockroachdb/cockroach/pkg/sql/auditlogging/auditevents"
"github.com/cockroachdb/cockroach/pkg/sql/catalog"
"github.com/cockroachdb/cockroach/pkg/sql/catalog/catalogkeys"
"github.com/cockroachdb/cockroach/pkg/sql/catalog/catpb"
"github.com/cockroachdb/cockroach/pkg/sql/catalog/descpb"
"github.com/cockroachdb/cockroach/pkg/sql/catalog/funcdesc"
"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/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/sem/catconstants"
"github.com/cockroachdb/cockroach/pkg/sql/sem/eval"
"github.com/cockroachdb/cockroach/pkg/sql/sem/semenumpb"
"github.com/cockroachdb/cockroach/pkg/sql/sem/tree"
"github.com/cockroachdb/cockroach/pkg/sql/sem/volatility"
"github.com/cockroachdb/cockroach/pkg/sql/sqlerrors"
"github.com/cockroachdb/cockroach/pkg/sql/sqltelemetry"
"github.com/cockroachdb/cockroach/pkg/sql/stats"
"github.com/cockroachdb/cockroach/pkg/sql/storageparam"
"github.com/cockroachdb/cockroach/pkg/sql/storageparam/tablestorageparam"
"github.com/cockroachdb/cockroach/pkg/sql/types"
"github.com/cockroachdb/cockroach/pkg/util/errorutil/unimplemented"
"github.com/cockroachdb/cockroach/pkg/util/log/eventpb"
"github.com/cockroachdb/cockroach/pkg/util/protoutil"
"github.com/cockroachdb/errors"
)
type alterTableNode struct {
zeroInputPlanNode
n *tree.AlterTable
prefix catalog.ResolvedObjectPrefix
tableDesc *tabledesc.Mutable
// statsData is populated with data for "alter table inject statistics"
// commands - the JSON stats expressions.
// It is parallel with n.Cmds (for the inject stats commands).
statsData map[int]tree.TypedExpr
}
// AlterTable applies a schema change on a table.
// Privileges: CREATE on table.
//
// notes: postgres requires CREATE on the table.
// mysql requires ALTER, CREATE, INSERT on the table.
func (p *planner) AlterTable(ctx context.Context, n *tree.AlterTable) (planNode, error) {
if err := checkSchemaChangeEnabled(
ctx,
p.ExecCfg(),
"ALTER TABLE",
); err != nil {
return nil, err
}
prefix, tableDesc, err := p.ResolveMutableTableDescriptorEx(
ctx, n.Table, !n.IfExists, tree.ResolveRequireTableDesc,
)
if errors.Is(err, resolver.ErrNoPrimaryKey) {
if len(n.Cmds) > 0 && isAlterCmdValidWithoutPrimaryKey(n.Cmds[0]) {
prefix, tableDesc, err = p.ResolveMutableTableDescriptorExAllowNoPrimaryKey(
ctx, n.Table, !n.IfExists, tree.ResolveRequireTableDesc,
)
}
}
if err != nil {
return nil, err
}
if tableDesc == nil {
return newZeroNode(nil /* columns */), nil
}
// This check for CREATE privilege is kept for backwards compatibility.
if err := p.CheckPrivilege(ctx, tableDesc, privilege.CREATE); err != nil {
return nil, pgerror.Wrapf(err, pgcode.InsufficientPrivilege,
"must be owner of table %s or have CREATE privilege on table %s",
tree.Name(tableDesc.GetName()), tree.Name(tableDesc.GetName()))
}
// Disallow schema changes if this table's schema is locked, unless it is to
// set/reset the "schema_locked" storage parameter.
if err = checkSchemaChangeIsAllowed(tableDesc, n); err != nil {
return nil, err
}
n.HoistAddColumnConstraints(func() {
telemetry.Inc(sqltelemetry.SchemaChangeAlterCounterWithExtra("table", "add_column.references"))
})
// See if there's any "inject statistics" in the query and type check the
// expressions.
statsData := make(map[int]tree.TypedExpr)
for i, cmd := range n.Cmds {
injectStats, ok := cmd.(*tree.AlterTableInjectStats)
if !ok {
continue
}
typedExpr, err := p.analyzeExpr(
ctx, injectStats.Stats,
tree.IndexedVarHelper{},
types.Jsonb, true, /* requireType */
"INJECT STATISTICS" /* typingContext */)
if err != nil {
return nil, err
}
statsData[i] = typedExpr
}
return &alterTableNode{
n: n,
prefix: prefix,
tableDesc: tableDesc,
statsData: statsData,
}, nil
}
func isAlterCmdValidWithoutPrimaryKey(cmd tree.AlterTableCmd) bool {
switch t := cmd.(type) {
case *tree.AlterTableAlterPrimaryKey:
return true
case *tree.AlterTableAddConstraint:
cs, ok := t.ConstraintDef.(*tree.UniqueConstraintTableDef)
if ok && cs.PrimaryKey {
return true
}
default:
return false
}
return false
}
// ReadingOwnWrites implements the planNodeReadingOwnWrites interface.
// This is because ALTER TABLE performs multiple KV operations on descriptors
// and expects to see its own writes.
func (n *alterTableNode) ReadingOwnWrites() {}
func (n *alterTableNode) startExec(params runParams) error {
telemetry.Inc(sqltelemetry.SchemaChangeAlterCounter("table"))
// Commands can either change the descriptor directly (for
// alterations that don't require a backfill) or add a mutation to
// the list.
descriptorChanged := false
origNumMutations := len(n.tableDesc.Mutations)
var droppedViews []string
resolved := params.p.ResolvedName(n.n.Table)
tn, ok := resolved.(*tree.TableName)
if !ok {
return errors.AssertionFailedf(
"%q was not resolved as a table but is %T", resolved, resolved)
}
for i, cmd := range n.n.Cmds {
telemetry.Inc(sqltelemetry.SchemaChangeAlterCounterWithExtra("table", cmd.TelemetryName()))
if !n.tableDesc.HasPrimaryKey() && !isAlterCmdValidWithoutPrimaryKey(cmd) {
return errors.Newf("table %q does not have a primary key, cannot perform%s", n.tableDesc.Name, tree.AsString(cmd))
}
switch t := cmd.(type) {
case *tree.AlterTableAddColumn:
if t.ColumnDef.Unique.WithoutIndex {
// TODO(rytaft): add support for this in the future if we want to expose
// UNIQUE WITHOUT INDEX to users.
return errors.WithHint(
pgerror.New(
pgcode.FeatureNotSupported,
"adding a column marked as UNIQUE WITHOUT INDEX is unsupported",
),
"add the column first, then run ALTER TABLE ... ADD CONSTRAINT to add a "+
"UNIQUE WITHOUT INDEX constraint on the column",
)
}
if t.ColumnDef.PrimaryKey.IsPrimaryKey {
return pgerror.Newf(pgcode.InvalidColumnDefinition,
"multiple primary keys for table %q are not allowed", tn.Object())
}
var err error
params.p.runWithOptions(resolveFlags{contextDatabaseID: n.tableDesc.ParentID}, func() {
err = params.p.addColumnImpl(params, n, tn, n.tableDesc, t)
})
if err != nil {
return err
}
case *tree.AlterTableAddConstraint:
if skip, err := validateConstraintNameIsNotUsed(n.tableDesc, t); err != nil {
return err
} else if skip {
continue
}
switch d := t.ConstraintDef.(type) {
case *tree.UniqueConstraintTableDef:
if d.WithoutIndex {
if err := addUniqueWithoutIndexTableDef(
params.ctx,
params.EvalContext(),
params.SessionData(),
d,
n.tableDesc,
*tn,
NonEmptyTable,
t.ValidationBehavior,
params.p.SemaCtx(),
); err != nil {
return err
}
continue
}
if d.PrimaryKey {
if t.ValidationBehavior == tree.ValidationSkip {
return sqlerrors.NewUnsupportedUnvalidatedConstraintError(catconstants.ConstraintTypePK)
}
// Translate this operation into an ALTER PRIMARY KEY command.
alterPK := &tree.AlterTableAlterPrimaryKey{
Columns: d.Columns,
Sharded: d.Sharded,
Name: d.Name,
StorageParams: d.StorageParams,
}
if err := params.p.AlterPrimaryKey(
params.ctx,
n.tableDesc,
*alterPK,
nil, /* localityConfigSwap */
); err != nil {
return err
}
continue
}
if t.ValidationBehavior == tree.ValidationSkip {
return sqlerrors.NewUnsupportedUnvalidatedConstraintError(catconstants.ConstraintTypeUnique)
}
if err := validateColumnsAreAccessible(n.tableDesc, d.Columns); err != nil {
return err
}
tableName, err := params.p.getQualifiedTableName(params.ctx, n.tableDesc)
if err != nil {
return err
}
// We are going to modify the AST to replace any index expressions with
// virtual columns. If the txn ends up retrying, then this change is not
// syntactically valid, since the virtual column is only added in the descriptor
// and not in the AST.
columns := make(tree.IndexElemList, len(d.Columns))
copy(columns, d.Columns)
if err := replaceExpressionElemsWithVirtualCols(
params.ctx,
n.tableDesc,
tableName,
columns,
false, /* isInverted */
false, /* isNewTable */
params.p.SemaCtx(),
params.ExecCfg().Settings.Version.ActiveVersion(params.ctx),
); err != nil {
return err
}
// Check if the columns exist on the table.
for _, column := range columns {
if column.Expr != nil {
return pgerror.New(
pgcode.InvalidTableDefinition,
"cannot create a unique constraint on an expression, use UNIQUE INDEX instead",
)
}
_, err := catalog.MustFindColumnByTreeName(n.tableDesc, column.Column)
if err != nil {
return err
}
}
idx := descpb.IndexDescriptor{
Name: string(d.Name),
Unique: true,
NotVisible: d.Invisibility.Value != 0.0,
Invisibility: d.Invisibility.Value,
StoreColumnNames: d.Storing.ToStrings(),
CreatedAtNanos: params.EvalContext().GetTxnTimestamp(time.Microsecond).UnixNano(),
}
if err := idx.FillColumns(columns); err != nil {
return err
}
if d.Predicate != nil {
expr, err := schemaexpr.ValidatePartialIndexPredicate(
params.ctx, n.tableDesc, d.Predicate, tableName, params.p.SemaCtx(),
params.ExecCfg().Settings.Version.ActiveVersion(params.ctx),
)
if err != nil {
return err
}
idx.Predicate = expr
}
idx, err = params.p.configureIndexDescForNewIndexPartitioning(
params.ctx,
n.tableDesc,
idx,
d.PartitionByIndex,
)
if err != nil {
return err
}
foundIndex := catalog.FindIndexByName(n.tableDesc, string(d.Name))
if foundIndex != nil && foundIndex.Dropped() {
return pgerror.Newf(pgcode.ObjectNotInPrerequisiteState,
"index %q being dropped, try again later", d.Name)
}
if err := n.tableDesc.AddIndexMutationMaybeWithTempIndex(
&idx, descpb.DescriptorMutation_ADD,
); err != nil {
return err
}
// We need to allocate IDs upfront in the event we need to update the zone config
// in the same transaction.
version := params.ExecCfg().Settings.Version.ActiveVersion(params.ctx)
if err := n.tableDesc.AllocateIDs(params.ctx, version); err != nil {
return err
}
if err := params.p.configureZoneConfigForNewIndexPartitioning(
params.ctx,
n.tableDesc,
idx,
); err != nil {
return err
}
if n.tableDesc.IsLocalityRegionalByRow() {
if err := params.p.checkNoRegionChangeUnderway(
params.ctx,
n.tableDesc.GetParentID(),
"create an UNIQUE CONSTRAINT on a REGIONAL BY ROW table",
); err != nil {
return err
}
}
case *tree.CheckConstraintTableDef:
var err error
params.p.runWithOptions(resolveFlags{contextDatabaseID: n.tableDesc.ParentID}, func() {
ckBuilder := schemaexpr.MakeCheckConstraintBuilder(params.ctx, *tn, n.tableDesc, ¶ms.p.semaCtx)
for _, c := range n.tableDesc.AllConstraints() {
ckBuilder.MarkNameInUse(c.GetName())
}
ck, buildErr := ckBuilder.Build(d, params.ExecCfg().Settings.Version.ActiveVersion(params.ctx))
if buildErr != nil {
err = buildErr
return
}
if t.ValidationBehavior == tree.ValidationDefault {
ck.Validity = descpb.ConstraintValidity_Validating
} else {
ck.Validity = descpb.ConstraintValidity_Unvalidated
}
n.tableDesc.AddCheckMutation(ck, descpb.DescriptorMutation_ADD)
})
if err != nil {
return err
}
case *tree.ForeignKeyConstraintTableDef:
// There are two cases that we want to reject FKs related to
// ON UPDATE/DELETE clauses:
// - a FK ON UPDATE action and there is already an ON UPDATE
// expression for the column
// - a FK over a computed column, and we have a ON UPDATE or ON DELETE
// that modifies the FK column value in some manner. We block these
// because the column value cannot change since it is computed. We do
// allow ON DELETE CASCADE though since that removes the entire row.
hasUpdateAction := d.Actions.HasUpdateAction()
if hasUpdateAction || d.Actions.HasDisallowedActionForComputedFKCol() {
for _, fromCol := range d.FromCols {
for _, toCheck := range n.tableDesc.Columns {
if fromCol != toCheck.ColName() {
continue
}
if hasUpdateAction && toCheck.HasOnUpdate() {
return pgerror.Newf(
pgcode.InvalidTableDefinition,
"cannot specify a foreign key update action and an ON UPDATE"+
" expression on the same column",
)
} else if toCheck.IsComputed() {
return sqlerrors.NewInvalidActionOnComputedFKColumnError(hasUpdateAction)
}
}
}
}
affected := make(map[descpb.ID]*tabledesc.Mutable)
// If there are any FKs, we will need to update the table descriptor of the
// depended-on table (to register this table against its DependedOnBy field).
// This descriptor must be looked up uncached, and we'll allow FK dependencies
// on tables that were just added. See the comment at the start of ResolveFK().
// TODO(vivek): check if the cache can be used.
var err error
params.p.runWithOptions(resolveFlags{skipCache: true}, func() {
// Check whether the table is empty, and pass the result to ResolveFK(). If
// the table is empty, then resolveFK will automatically add the necessary
// index for a fk constraint if the index does not exist.
span := n.tableDesc.PrimaryIndexSpan(params.ExecCfg().Codec)
kvs, scanErr := params.p.txn.Scan(params.ctx, span.Key, span.EndKey, 1)
if scanErr != nil {
err = scanErr
return
}
var tableState TableState
if len(kvs) == 0 {
tableState = EmptyTable
} else {
tableState = NonEmptyTable
}
err = ResolveFK(
params.ctx,
params.p.txn,
params.p,
n.prefix.Database,
n.prefix.Schema,
n.tableDesc,
d,
affected,
tableState,
t.ValidationBehavior,
params.p.EvalContext(),
)
})
if err != nil {
return err
}
descriptorChanged = true
for _, updated := range affected {
// Disallow schema change if the FK references a table whose schema is
// locked.
if err := checkSchemaChangeIsAllowed(updated, n.n); err != nil {
return err
}
if err := params.p.writeSchemaChange(
params.ctx, updated, descpb.InvalidMutationID, tree.AsStringWithFQNames(n.n, params.Ann()),
); err != nil {
return err
}
}
// TODO(lucy): Validate() can't be called here because it reads the
// referenced table descs, which may have to be upgraded to the new FK
// representation. That requires reading the original table descriptor
// (which the backreference points to) from KV, but we haven't written
// the updated table desc yet. We can restore the call to Validate()
// after running a migration of all table descriptors, making it
// unnecessary to read the original table desc from KV.
// if err := n.tableDesc.Validate(params.ctx, params.p.txn); err != nil {
// return err
// }
default:
return errors.AssertionFailedf(
"unsupported constraint: %T", t.ConstraintDef)
}
case *tree.AlterTableAlterPrimaryKey:
// For `ALTER PRIMARY KEY`, carry over the primary index name, like how we
// carried over comments associated with the old primary index.
t.Name = tree.Name(n.tableDesc.PrimaryIndex.Name)
if err := params.p.AlterPrimaryKey(
params.ctx,
n.tableDesc,
*t,
nil, /* localityConfigSwap */
); err != nil {
return err
}
// Mark descriptorChanged so that a mutation job is scheduled at the end of startExec.
descriptorChanged = true
case *tree.AlterTableDropColumn:
if params.SessionData().SafeUpdates {
err := pgerror.DangerousStatementf("ALTER TABLE DROP COLUMN will " +
"remove all data in that column and drop any indexes that reference that column")
if !params.extendedEvalCtx.TxnIsSingleStmt {
err = errors.WithIssueLink(err, errors.IssueLink{
IssueURL: build.MakeIssueURL(46541),
Detail: "when used in an explicit transaction combined with other " +
"schema changes to the same table, DROP COLUMN can result in data " +
"loss if one of the other schema change fails or is canceled",
})
}
return err
}
tableDesc := n.tableDesc
if t.Column == catpb.TTLDefaultExpirationColumnName &&
tableDesc.HasRowLevelTTL() &&
tableDesc.GetRowLevelTTL().HasDurationExpr() {
return errors.WithHintf(
pgerror.Newf(
pgcode.InvalidTableDefinition,
`cannot drop column %s while ttl_expire_after is set`,
t.Column,
),
"use ALTER TABLE %[1]s RESET (ttl) or ALTER TABLE %[1]s SET (ttl_expiration_expression = ...) instead",
tree.Name(tableDesc.GetName()),
)
}
colDroppedViews, err := dropColumnImpl(params, tn, tableDesc, tableDesc.GetRowLevelTTL(), t)
if err != nil {
return err
}
droppedViews = append(droppedViews, colDroppedViews...)
case *tree.AlterTableDropConstraint:
name := string(t.Constraint)
c := catalog.FindConstraintByName(n.tableDesc, name)
if c == nil {
if t.IfExists {
continue
}
return sqlerrors.NewUndefinedConstraintError(string(t.Constraint), n.tableDesc.Name)
}
if uwoi := c.AsUniqueWithoutIndex(); uwoi != nil {
if err := params.p.tryRemoveFKBackReferences(
params.ctx, n.tableDesc, uwoi, t.DropBehavior, true,
); err != nil {
return err
}
}
if err := n.tableDesc.DropConstraint(
c,
func(backRef catalog.ForeignKeyConstraint) error {
return params.p.removeFKBackReference(params.ctx, n.tableDesc, backRef.ForeignKeyDesc())
},
func(ck *descpb.TableDescriptor_CheckConstraint) error {
return params.p.removeCheckBackReferenceInFunctions(params.ctx, n.tableDesc, ck)
},
); err != nil {
return err
}
descriptorChanged = true
if err := validateDescriptor(params.ctx, params.p, n.tableDesc); err != nil {
return err
}
case *tree.AlterTableValidateConstraint:
name := string(t.Constraint)
c := catalog.FindConstraintByName(n.tableDesc, name)
if c == nil {
return sqlerrors.NewUndefinedConstraintError(string(t.Constraint), n.tableDesc.Name)
}
switch c.GetConstraintValidity() {
case descpb.ConstraintValidity_Validated:
// Nothing to do.
continue
case descpb.ConstraintValidity_Validating:
return pgerror.Newf(pgcode.ObjectNotInPrerequisiteState,
"constraint %q in the middle of being added, try again later", t.Constraint)
case descpb.ConstraintValidity_Dropping:
return sqlerrors.NewUndefinedConstraintError(string(t.Constraint), n.tableDesc.Name)
}
if ck := c.AsCheck(); ck != nil {
if err := validateCheckInTxn(
params.ctx, params.p.InternalSQLTxn(), params.p.EvalContext(),
¶ms.p.semaCtx, params.p.SessionData(), n.tableDesc, ck,
); err != nil {
return err
}
ck.CheckDesc().Validity = descpb.ConstraintValidity_Validated
} else if fk := c.AsForeignKey(); fk != nil {
if err := validateFkInTxn(
params.ctx, params.p.InternalSQLTxn(), n.tableDesc, name,
); err != nil {
return err
}
fk.ForeignKeyDesc().Validity = descpb.ConstraintValidity_Validated
} else if uwoi := c.AsUniqueWithoutIndex(); uwoi != nil {
if err := validateUniqueWithoutIndexConstraintInTxn(
params.ctx,
params.p.InternalSQLTxn(),
n.tableDesc,
params.p.User(),
name,
); err != nil {
return err
}
uwoi.UniqueWithoutIndexDesc().Validity = descpb.ConstraintValidity_Validated
} else {
return pgerror.Newf(pgcode.WrongObjectType,
"constraint %q of relation %q is not a foreign key, check, or unique without index"+
" constraint", tree.ErrString(&t.Constraint), tree.ErrString(n.n.Table))
}
descriptorChanged = true
case tree.ColumnMutationCmd:
// Column mutations
tableDesc := n.tableDesc
col, err := catalog.MustFindColumnByTreeName(tableDesc, t.GetColumn())
if err != nil {
return err
}
if col.Dropped() {
return pgerror.Newf(pgcode.ObjectNotInPrerequisiteState,
"column %q in the middle of being dropped", t.GetColumn())
}
// Block modification on system columns.
if col.IsSystemColumn() {
return pgerror.Newf(
pgcode.FeatureNotSupported,
"cannot alter system column %q", col.GetName())
}
columnName := col.GetName()
if columnName == catpb.TTLDefaultExpirationColumnName &&
tableDesc.HasRowLevelTTL() &&
tableDesc.GetRowLevelTTL().HasDurationExpr() {
return sqlerrors.NewAlterDependsOnDurationExprError("alter", "column", columnName, tn.Object())
}
// Apply mutations to copy of column descriptor.
if err := applyColumnMutation(params.ctx, tableDesc, col, t, params, n.n.Cmds, tn); err != nil {
return err
}
descriptorChanged = true
case *tree.AlterTablePartitionByTable:
if t.All {
return unimplemented.NewWithIssue(58736, "PARTITION ALL BY not yet implemented")
}
if n.tableDesc.GetLocalityConfig() != nil {
return pgerror.Newf(
pgcode.FeatureNotSupported,
"cannot set PARTITION BY on a table in a multi-region enabled database",
)
}
if n.tableDesc.IsPartitionAllBy() {
return unimplemented.NewWithIssue(58736, "changing partition of table with PARTITION ALL BY not yet implemented")
}
if n.tableDesc.GetPrimaryIndex().IsSharded() {
return pgerror.New(
pgcode.FeatureNotSupported,
"cannot set explicit partitioning with PARTITION BY on hash sharded primary key",
)
}
oldPartitioning := n.tableDesc.GetPrimaryIndex().GetPartitioning().DeepCopy()
if oldPartitioning.NumImplicitColumns() > 0 {
return unimplemented.NewWithIssue(
58731,
"cannot ALTER TABLE PARTITION BY on a table which already has implicit column partitioning",
)
}
newPrimaryIndexDesc := n.tableDesc.GetPrimaryIndex().IndexDescDeepCopy()
newImplicitCols, newPartitioning, err := CreatePartitioning(
params.ctx, params.p.ExecCfg().Settings,
params.EvalContext(),
n.tableDesc,
newPrimaryIndexDesc,
t.PartitionBy,
nil, /* allowedNewColumnNames */
params.p.EvalContext().SessionData().ImplicitColumnPartitioningEnabled ||
n.tableDesc.IsLocalityRegionalByRow(),
)
if err != nil {
return err
}
if newPartitioning.NumImplicitColumns > 0 {
return unimplemented.NewWithIssue(
58731,
"cannot ALTER TABLE and change the partitioning to contain implicit columns",
)
}
isIndexAltered := tabledesc.UpdateIndexPartitioning(&newPrimaryIndexDesc, true /* isIndexPrimary */, newImplicitCols, newPartitioning)
if isIndexAltered {
n.tableDesc.SetPrimaryIndex(newPrimaryIndexDesc)
descriptorChanged = true
if err := deleteRemovedPartitionZoneConfigs(
params.ctx,
params.p.InternalSQLTxn(),
n.tableDesc,
n.tableDesc.GetPrimaryIndexID(),
oldPartitioning,
n.tableDesc.GetPrimaryIndex().GetPartitioning(),
params.extendedEvalCtx.ExecCfg,
params.extendedEvalCtx.Tracing.KVTracingEnabled(),
); err != nil {
return err
}
}
case *tree.AlterTableSetAudit:
changed, err := params.p.setAuditMode(params.ctx, n.tableDesc, t.Mode)
if err != nil {
return err
}
descriptorChanged = descriptorChanged || changed
case *tree.AlterTableInjectStats:
sd, ok := n.statsData[i]
if !ok {
return errors.AssertionFailedf("missing stats data")
}
if !params.extendedEvalCtx.TxnIsSingleStmt {
return errors.New("cannot inject statistics in an explicit transaction")
}
if err := injectTableStats(params, n.tableDesc, sd); err != nil {
return err
}
case *tree.AlterTableSetStorageParams:
setter := tablestorageparam.NewSetter(n.tableDesc)
if err := storageparam.Set(
params.ctx,
params.p.SemaCtx(),
params.EvalContext(),
t.StorageParams,
setter,
); err != nil {
return err
}
var err error
descriptorChanged, err = handleTTLStorageParamChange(
params,
tn,
setter.TableDesc,
setter.UpdatedRowLevelTTL,
)
if err != nil {
return err
}
case *tree.AlterTableResetStorageParams:
setter := tablestorageparam.NewSetter(n.tableDesc)
if err := storageparam.Reset(
params.ctx,
params.EvalContext(),
t.Params,
setter,
); err != nil {
return err
}
var err error
descriptorChanged, err = handleTTLStorageParamChange(
params,
tn,
setter.TableDesc,
setter.UpdatedRowLevelTTL,
)
if err != nil {
return err
}
case *tree.AlterTableRenameColumn:
tableDesc := n.tableDesc
columnName := t.Column
if columnName == catpb.TTLDefaultExpirationColumnName &&
tableDesc.HasRowLevelTTL() &&
tableDesc.GetRowLevelTTL().HasDurationExpr() {
return pgerror.Newf(
pgcode.InvalidTableDefinition,
`cannot rename column %s while ttl_expire_after is set`,
columnName,
)
}
descChanged, err := params.p.renameColumn(params.ctx, tableDesc, columnName, t.NewName)
if err != nil {
return err
}
descriptorChanged = descriptorChanged || descChanged
case *tree.AlterTableRenameConstraint:
constraint := catalog.FindConstraintByName(n.tableDesc, string(t.Constraint))
if constraint == nil {
return sqlerrors.NewUndefinedConstraintError(tree.ErrString(&t.Constraint), n.tableDesc.Name)
}
if t.Constraint == t.NewName {
// Nothing to do.
break
}
switch constraint.GetConstraintValidity() {
case descpb.ConstraintValidity_Validating:
return pgerror.Newf(pgcode.ObjectNotInPrerequisiteState,
"constraint %q in the middle of being added, try again later", t.Constraint)
case descpb.ConstraintValidity_Dropping:
return pgerror.Newf(pgcode.ObjectNotInPrerequisiteState,
"constraint %q in the middle of being dropped", t.Constraint)
}
if other := catalog.FindConstraintByName(n.tableDesc, string(t.NewName)); other != nil {
return pgerror.Newf(pgcode.DuplicateObject,
"duplicate constraint name: %q", tree.ErrString(&t.NewName))
}
// If this is a unique or primary constraint, renames of the constraint
// lead to renames of the underlying index. Ensure that no index with this
// new name exists. This is what postgres does.
if constraint.AsUniqueWithIndex() != nil {
if catalog.FindNonDropIndex(n.tableDesc, func(idx catalog.Index) bool {
return idx.GetName() == string(t.NewName)
}) != nil {
return pgerror.Newf(pgcode.DuplicateRelation,
"relation %v already exists", t.NewName)
}
}
if err := params.p.CheckPrivilege(params.ctx, n.tableDesc, privilege.CREATE); err != nil {
return err
}
depViewRenameError := func(objType string, refTableID descpb.ID) error {
return params.p.dependentError(params.ctx,
objType, tree.ErrString(&t.NewName), n.tableDesc.ParentID, refTableID, "rename",
)
}
if err := n.tableDesc.RenameConstraint(constraint, string(t.NewName), depViewRenameError,
func(desc *tabledesc.Mutable, ref catalog.ForeignKeyConstraint, newName string) error {
return params.p.updateFKBackReferenceName(params.ctx, desc, ref.ForeignKeyDesc(), newName)
}); err != nil {
return err
}
descriptorChanged = true
case *tree.AlterTableSetRLSMode:
return unimplemented.NewWithIssuef(
136700,
"row-level security mode alteration is not supported")
default:
return errors.AssertionFailedf("unsupported alter command: %T", cmd)
}
// Allocate IDs now, so new IDs are available to subsequent commands
version := params.ExecCfg().Settings.Version.ActiveVersion(params.ctx)
if err := n.tableDesc.AllocateIDs(params.ctx, version); err != nil {
return err
}
}
// Were some changes made?
//
// This is only really needed for the unittests that add dummy mutations
// before calling ALTER TABLE commands. We do not want to apply those
// dummy mutations. Most tests trigger errors above
// this line, but tests that run redundant operations like dropping
// a column when it's already dropped will hit this condition and exit.
addedMutations := len(n.tableDesc.Mutations) > origNumMutations
if !addedMutations && !descriptorChanged {
return nil
}
mutationID := descpb.InvalidMutationID
if addedMutations {
mutationID = n.tableDesc.ClusterVersion().NextMutationID
}
if err := params.p.writeSchemaChange(
params.ctx, n.tableDesc, mutationID, tree.AsStringWithFQNames(n.n, params.Ann()),
); err != nil {
return err
}
// Add all newly created type back references.
if err := params.p.addBackRefsFromAllTypesInTable(params.ctx, n.tableDesc); err != nil {
return err
}
// Replace all UDF names with OIDs in check constraints and update back
// references in functions used.
for _, ck := range n.tableDesc.CheckConstraints() {
if err := params.p.updateFunctionReferencesForCheck(params.ctx, n.tableDesc, ck.CheckDesc()); err != nil {
return err
}
}
// Record this table alteration in the event log. This is an auditable log
// event and is recorded in the same transaction as the table descriptor
// update.
return params.p.logEvent(params.ctx,
n.tableDesc.ID,
&eventpb.AlterTable{
TableName: params.p.ResolvedName(n.n.Table).FQString(),
MutationID: uint32(mutationID),
CascadeDroppedViews: droppedViews,
})
}
func (p *planner) setAuditMode(
ctx context.Context, desc *tabledesc.Mutable, auditMode tree.AuditMode,
) (bool, error) {
// An auditing config change is itself auditable!
// We record the event even if the permission check below fails:
// auditing wants to know who tried to change the settings.
event := &auditevents.SensitiveTableAccessEvent{TableDesc: desc, Writing: true}
p.curPlan.auditEventBuilders = append(p.curPlan.auditEventBuilders, event)
// Requires MODIFYCLUSTERSETTING as of 22.2.
// Check for system privilege first, otherwise fall back to role options.
hasModify, err := p.HasGlobalPrivilegeOrRoleOption(ctx, privilege.MODIFYCLUSTERSETTING)
if err != nil {
return false, err
}
if !hasModify {
return false, pgerror.Newf(pgcode.InsufficientPrivilege,
"only users with admin or %s system privilege are allowed to change audit settings on a table ", privilege.MODIFYCLUSTERSETTING)
}
telemetry.Inc(sqltelemetry.SchemaSetAuditModeCounter(auditMode.TelemetryName()))
return desc.SetAuditMode(auditMode)
}
func (n *alterTableNode) Next(runParams) (bool, error) { return false, nil }
func (n *alterTableNode) Values() tree.Datums { return tree.Datums{} }
func (n *alterTableNode) Close(context.Context) {}
// applyColumnMutation applies the mutation specified in `mut` to the given
// columnDescriptor, and saves the containing table descriptor. If the column's
// dependencies on sequences change, it updates them as well.
func applyColumnMutation(
ctx context.Context,
tableDesc *tabledesc.Mutable,
col catalog.Column,
mut tree.ColumnMutationCmd,
params runParams,
cmds tree.AlterTableCmds,
tn *tree.TableName,
) error {
switch t := mut.(type) {
case *tree.AlterTableAlterColumnType:
return AlterColumnType(ctx, tableDesc, col, t, params, cmds, tn)
case *tree.AlterTableSetDefault:
// If our column is computed, block mixing defaults in entirely.
// This check exists here instead of later on during validation because
// adding a null default to a computed column should also be blocked, but
// is undetectable later on since SET DEFAULT NUL means a nil default
// expression.
if col.IsComputed() {
// Block dropping a computed column "default" as well.
if t.Default == nil {
return pgerror.Newf(
pgcode.Syntax,
"column %q of relation %q is a computed column",
col.GetName(),
tn.ObjectName)
}
return pgerror.Newf(
pgcode.Syntax,
"computed column %q cannot also have a DEFAULT expression",
col.GetName())
}
if err := updateNonComputedColExpr(
params,
tableDesc,
col,
t.Default,
&col.ColumnDesc().DefaultExpr,
tree.ColumnDefaultExprInSetDefault,
); err != nil {
return err
}
if col.HasNullDefault() {
// `SET DEFAULT NULL` means a nil default expression.
col.ColumnDesc().DefaultExpr = nil
}
case *tree.AlterTableSetOnUpdate:
// We want to reject uses of ON UPDATE where there is also a foreign key ON
// UPDATE.
for _, fk := range tableDesc.OutboundFKs {
for _, colID := range fk.OriginColumnIDs {
if colID == col.GetID() &&
fk.OnUpdate != semenumpb.ForeignKeyAction_NO_ACTION &&
fk.OnUpdate != semenumpb.ForeignKeyAction_RESTRICT {
return pgerror.Newf(
pgcode.InvalidColumnDefinition,
"column %s(%d) cannot have both an ON UPDATE expression and a foreign"+
" key ON UPDATE action",
col.GetName(),
col.GetID(),
)
}
}