-
Notifications
You must be signed in to change notification settings - Fork 3.8k
/
schema_changer.go
2624 lines (2405 loc) · 90.7 KB
/
schema_changer.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 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 (
"context"
"fmt"
"math"
"strings"
"time"
"github.com/cockroachdb/cockroach/pkg/base"
"github.com/cockroachdb/cockroach/pkg/config"
"github.com/cockroachdb/cockroach/pkg/jobs"
"github.com/cockroachdb/cockroach/pkg/jobs/jobspb"
"github.com/cockroachdb/cockroach/pkg/keys"
"github.com/cockroachdb/cockroach/pkg/kv"
"github.com/cockroachdb/cockroach/pkg/kv/kvclient/rangecache"
"github.com/cockroachdb/cockroach/pkg/roachpb"
"github.com/cockroachdb/cockroach/pkg/security"
"github.com/cockroachdb/cockroach/pkg/settings"
"github.com/cockroachdb/cockroach/pkg/settings/cluster"
"github.com/cockroachdb/cockroach/pkg/sql/catalog"
"github.com/cockroachdb/cockroach/pkg/sql/catalog/catalogkeys"
"github.com/cockroachdb/cockroach/pkg/sql/catalog/catalogkv"
"github.com/cockroachdb/cockroach/pkg/sql/catalog/dbdesc"
"github.com/cockroachdb/cockroach/pkg/sql/catalog/descpb"
"github.com/cockroachdb/cockroach/pkg/sql/catalog/descs"
"github.com/cockroachdb/cockroach/pkg/sql/catalog/lease"
"github.com/cockroachdb/cockroach/pkg/sql/catalog/tabledesc"
"github.com/cockroachdb/cockroach/pkg/sql/execinfrapb"
"github.com/cockroachdb/cockroach/pkg/sql/faketreeeval"
"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/sem/tree"
"github.com/cockroachdb/cockroach/pkg/sql/sessiondata"
"github.com/cockroachdb/cockroach/pkg/sql/sessiondatapb"
"github.com/cockroachdb/cockroach/pkg/sql/sqlerrors"
"github.com/cockroachdb/cockroach/pkg/sql/sqltelemetry"
"github.com/cockroachdb/cockroach/pkg/sql/sqlutil"
"github.com/cockroachdb/cockroach/pkg/util/grpcutil"
"github.com/cockroachdb/cockroach/pkg/util/hlc"
"github.com/cockroachdb/cockroach/pkg/util/log"
"github.com/cockroachdb/cockroach/pkg/util/log/eventpb"
"github.com/cockroachdb/cockroach/pkg/util/protoutil"
"github.com/cockroachdb/cockroach/pkg/util/retry"
"github.com/cockroachdb/cockroach/pkg/util/timeutil"
"github.com/cockroachdb/errors"
"github.com/cockroachdb/logtags"
)
const (
// RunningStatusWaitingGC is for jobs that are currently in progress and
// are waiting for the GC interval to expire
RunningStatusWaitingGC jobs.RunningStatus = "waiting for GC TTL"
// RunningStatusDeleteOnly is for jobs that are currently waiting on
// the cluster to converge to seeing the schema element in the DELETE_ONLY
// state.
RunningStatusDeleteOnly jobs.RunningStatus = "waiting in DELETE-ONLY"
// RunningStatusDeleteAndWriteOnly is for jobs that are currently waiting on
// the cluster to converge to seeing the schema element in the
// DELETE_AND_WRITE_ONLY state.
RunningStatusDeleteAndWriteOnly jobs.RunningStatus = "waiting in DELETE-AND-WRITE_ONLY"
// RunningStatusBackfill is for jobs that are currently running a backfill
// for a schema element.
RunningStatusBackfill jobs.RunningStatus = "populating schema"
// RunningStatusValidation is for jobs that are currently validating
// a schema element.
RunningStatusValidation jobs.RunningStatus = "validating schema"
)
// SchemaChanger is used to change the schema on a table.
type SchemaChanger struct {
descID descpb.ID
mutationID descpb.MutationID
droppedDatabaseID descpb.ID
sqlInstanceID base.SQLInstanceID
db *kv.DB
leaseMgr *lease.Manager
metrics *SchemaChangerMetrics
testingKnobs *SchemaChangerTestingKnobs
distSQLPlanner *DistSQLPlanner
jobRegistry *jobs.Registry
// Keep a reference to the job related to this schema change
// so that we don't need to read the job again while updating
// the status of the job.
job *jobs.Job
// Caches updated by DistSQL.
rangeDescriptorCache *rangecache.RangeCache
clock *hlc.Clock
settings *cluster.Settings
execCfg *ExecutorConfig
ieFactory sqlutil.SessionBoundInternalExecutorFactory
}
// NewSchemaChangerForTesting only for tests.
func NewSchemaChangerForTesting(
tableID descpb.ID,
mutationID descpb.MutationID,
sqlInstanceID base.SQLInstanceID,
db *kv.DB,
leaseMgr *lease.Manager,
jobRegistry *jobs.Registry,
execCfg *ExecutorConfig,
settings *cluster.Settings,
) SchemaChanger {
return SchemaChanger{
descID: tableID,
mutationID: mutationID,
sqlInstanceID: sqlInstanceID,
db: db,
leaseMgr: leaseMgr,
jobRegistry: jobRegistry,
settings: settings,
execCfg: execCfg,
// Note that this doesn't end up actually being session-bound but that's
// good enough for testing.
ieFactory: func(
ctx context.Context, sd *sessiondata.SessionData,
) sqlutil.InternalExecutor {
return execCfg.InternalExecutor
},
metrics: NewSchemaChangerMetrics(),
clock: db.Clock(),
distSQLPlanner: execCfg.DistSQLPlanner,
testingKnobs: &SchemaChangerTestingKnobs{},
}
}
// isPermanentSchemaChangeError returns true if the error results in
// a permanent failure of a schema change. This function is a allowlist
// instead of a blocklist: only known safe errors are confirmed to not be
// permanent errors. Anything unknown is assumed to be permanent.
func isPermanentSchemaChangeError(err error) bool {
if err == nil {
return false
}
if grpcutil.IsClosedConnection(err) {
return false
}
// Ignore error thrown because of a read at a very old timestamp.
// The Backfill will grab a new timestamp to read at for the rest
// of the backfill.
if errors.HasType(err, (*roachpb.BatchTimestampBeforeGCError)(nil)) {
return false
}
// Clock sync problems should not lead to permanently failed schema changes.
if hlc.IsUntrustworthyRemoteWallTimeError(err) {
return false
}
if pgerror.IsSQLRetryableError(err) {
return false
}
if errors.IsAny(err,
context.Canceled,
context.DeadlineExceeded,
errExistingSchemaChangeLease,
errExpiredSchemaChangeLease,
errNotHitGCTTLDeadline,
errSchemaChangeDuringDrain,
errSchemaChangeNotFirstInLine,
errTableVersionMismatchSentinel,
) {
return false
}
switch pgerror.GetPGCode(err) {
case pgcode.SerializationFailure, pgcode.InternalConnectionFailure:
return false
case pgcode.Internal, pgcode.RangeUnavailable:
if strings.Contains(err.Error(), context.DeadlineExceeded.Error()) {
return false
}
}
return true
}
var (
errExistingSchemaChangeLease = errors.Newf("an outstanding schema change lease exists")
errExpiredSchemaChangeLease = errors.Newf("the schema change lease has expired")
errSchemaChangeNotFirstInLine = errors.Newf("schema change not first in line")
errNotHitGCTTLDeadline = errors.Newf("not hit gc ttl deadline")
errSchemaChangeDuringDrain = errors.Newf("a schema change ran during the drain phase, re-increment")
)
type errTableVersionMismatch struct {
version descpb.DescriptorVersion
expected descpb.DescriptorVersion
}
var errTableVersionMismatchSentinel = errTableVersionMismatch{}
func makeErrTableVersionMismatch(version, expected descpb.DescriptorVersion) error {
return errors.Mark(errors.WithStack(errTableVersionMismatch{
version: version,
expected: expected,
}), errTableVersionMismatchSentinel)
}
func (e errTableVersionMismatch) Error() string {
return fmt.Sprintf("table version mismatch: %d, expected: %d", e.version, e.expected)
}
// refreshMaterializedView updates the physical data for a materialized view.
func (sc *SchemaChanger) refreshMaterializedView(
ctx context.Context, table *tabledesc.Mutable, refresh catalog.MaterializedViewRefresh,
) error {
// If we aren't requested to backfill any data, then return immediately.
if !refresh.ShouldBackfill() {
return nil
}
// The data for the materialized view is stored under the current set of
// indexes in table. We want to keep all of that data untouched, and write
// out all the data into the new set of indexes denoted by refresh. So, just
// perform some surgery on the input table to denote it as having the desired
// set of indexes. We then backfill into this modified table, which writes
// data only to the new desired indexes. In SchemaChanger.done(), we'll swap
// the indexes from the old versions into the new ones.
tableToRefresh := refresh.TableWithNewIndexes(table)
return sc.backfillQueryIntoTable(ctx, tableToRefresh, table.ViewQuery, refresh.AsOf(), "refreshView")
}
func (sc *SchemaChanger) backfillQueryIntoTable(
ctx context.Context, table catalog.TableDescriptor, query string, ts hlc.Timestamp, desc string,
) error {
if fn := sc.testingKnobs.RunBeforeQueryBackfill; fn != nil {
if err := fn(); err != nil {
return err
}
}
return sc.db.Txn(ctx, func(ctx context.Context, txn *kv.Txn) error {
txn.SetFixedTimestamp(ctx, ts)
// Create an internal planner as the planner used to serve the user query
// would have committed by this point.
p, cleanup := NewInternalPlanner(
desc,
txn,
security.RootUserName(),
&MemoryMetrics{},
sc.execCfg,
sessiondatapb.SessionData{},
)
defer cleanup()
localPlanner := p.(*planner)
stmt, err := parser.ParseOne(query)
if err != nil {
return err
}
// Construct an optimized logical plan of the AS source stmt.
localPlanner.stmt = makeStatement(stmt, ClusterWideID{} /* queryID */)
localPlanner.optPlanningCtx.init(localPlanner)
localPlanner.runWithOptions(resolveFlags{skipCache: true}, func() {
err = localPlanner.makeOptimizerPlan(ctx)
})
if err != nil {
return err
}
defer localPlanner.curPlan.close(ctx)
res := roachpb.BulkOpSummary{}
rw := newCallbackResultWriter(func(ctx context.Context, row tree.Datums) error {
// TODO(adityamaru): Use the BulkOpSummary for either telemetry or to
// return to user.
var counts roachpb.BulkOpSummary
if err := protoutil.Unmarshal([]byte(*row[0].(*tree.DBytes)), &counts); err != nil {
return err
}
res.Add(counts)
return nil
})
recv := MakeDistSQLReceiver(
ctx,
rw,
tree.Rows,
sc.execCfg.RangeDescriptorCache,
txn,
sc.clock,
// Make a session tracing object on-the-fly. This is OK
// because it sets "enabled: false" and thus none of the
// other fields are used.
&SessionTracing{},
sc.execCfg.ContentionRegistry,
nil, /* testingPushCallback */
)
defer recv.Release()
var planAndRunErr error
localPlanner.runWithOptions(resolveFlags{skipCache: true}, func() {
// Resolve subqueries before running the queries' physical plan.
if len(localPlanner.curPlan.subqueryPlans) != 0 {
// Create a separate memory account for the results of the
// subqueries. Note that we intentionally defer the closure of
// the account until we return from this method (after the main
// query is executed).
subqueryResultMemAcc := localPlanner.EvalContext().Mon.MakeBoundAccount()
defer subqueryResultMemAcc.Close(ctx)
if !sc.distSQLPlanner.PlanAndRunSubqueries(
ctx, localPlanner, localPlanner.ExtendedEvalContextCopy,
localPlanner.curPlan.subqueryPlans, recv, &subqueryResultMemAcc,
) {
if planAndRunErr = rw.Err(); planAndRunErr != nil {
return
}
}
}
isLocal := !getPlanDistribution(
ctx, localPlanner, localPlanner.execCfg.NodeID,
localPlanner.extendedEvalCtx.SessionData.DistSQLMode,
localPlanner.curPlan.main,
).WillDistribute()
out := execinfrapb.ProcessorCoreUnion{BulkRowWriter: &execinfrapb.BulkRowWriterSpec{
Table: *table.TableDesc(),
}}
PlanAndRunCTAS(ctx, sc.distSQLPlanner, localPlanner,
txn, isLocal, localPlanner.curPlan.main, out, recv)
if planAndRunErr = rw.Err(); planAndRunErr != nil {
return
}
})
return planAndRunErr
})
}
// maybe backfill a created table by executing the AS query. Return nil if
// successfully backfilled.
//
// Note that this does not connect to the tracing settings of the
// surrounding SQL transaction. This should be OK as (at the time of
// this writing) this code path is only used for standalone CREATE
// TABLE AS statements, which cannot be traced.
func (sc *SchemaChanger) maybeBackfillCreateTableAs(
ctx context.Context, table catalog.TableDescriptor,
) error {
if !(table.Adding() && table.IsAs()) {
return nil
}
log.Infof(ctx, "starting backfill for CREATE TABLE AS with query %q", table.GetCreateQuery())
return sc.backfillQueryIntoTable(ctx, table, table.GetCreateQuery(), table.GetCreateAsOfTime(), "ctasBackfill")
}
func (sc *SchemaChanger) maybeBackfillMaterializedView(
ctx context.Context, table catalog.TableDescriptor,
) error {
if !(table.Adding() && table.MaterializedView()) {
return nil
}
log.Infof(ctx, "starting backfill for CREATE MATERIALIZED VIEW with query %q", table.GetViewQuery())
return sc.backfillQueryIntoTable(ctx, table, table.GetViewQuery(), table.GetCreateAsOfTime(), "materializedViewBackfill")
}
// maybe make a table PUBLIC if it's in the ADD state.
func (sc *SchemaChanger) maybeMakeAddTablePublic(
ctx context.Context, table catalog.TableDescriptor,
) error {
if !table.Adding() {
return nil
}
log.Info(ctx, "making table public")
fks := table.AllActiveAndInactiveForeignKeys()
for _, fk := range fks {
if err := WaitToUpdateLeases(ctx, sc.leaseMgr, fk.ReferencedTableID); err != nil {
return err
}
}
return sc.txn(ctx, func(ctx context.Context, txn *kv.Txn, descsCol *descs.Collection) error {
mut, err := descsCol.GetMutableTableVersionByID(ctx, table.GetID(), txn)
if err != nil {
return err
}
if !mut.Adding() {
return nil
}
mut.State = descpb.DescriptorState_PUBLIC
return descsCol.WriteDesc(ctx, true /* kvTrace */, mut, txn)
})
}
// drainNamesForDescriptor will drain remove the draining names from the
// descriptor with the specified ID. If it is a schema, it will also remove the
// names from the parent database.
//
// If there are no draining names, this call will not update any descriptors.
func drainNamesForDescriptor(
ctx context.Context,
settings *cluster.Settings,
descID descpb.ID,
db *kv.DB,
ie sqlutil.InternalExecutor,
leaseMgr *lease.Manager,
codec keys.SQLCodec,
beforeDrainNames func(),
) error {
log.Info(ctx, "draining previous names")
// Publish a new version with all the names drained after everyone
// has seen the version with the new name. All the draining names
// can be reused henceforth.
run := func(ctx context.Context, txn *kv.Txn, descsCol *descs.Collection) error {
if beforeDrainNames != nil {
beforeDrainNames()
}
// Free up the old name(s) for reuse.
mutDesc, err := descsCol.GetMutableDescriptorByID(ctx, descID, txn)
if err != nil {
return err
}
namesToReclaim := mutDesc.GetDrainingNames()
if len(namesToReclaim) == 0 {
return nil
}
b := txn.NewBatch()
mutDesc.SetDrainingNames(nil)
// Reclaim all old names.
for _, drain := range namesToReclaim {
catalogkv.WriteObjectNamespaceEntryRemovalToBatch(
ctx, b, codec, drain.ParentID, drain.ParentSchemaID, drain.Name, false, /* KVTrace */
)
}
// If the descriptor to drain is a schema, then we need to delete the
// draining names from the parent database's schema mapping.
if _, isSchema := mutDesc.(catalog.SchemaDescriptor); isSchema {
mutDB, err := descsCol.GetMutableDescriptorByID(ctx, mutDesc.GetParentID(), txn)
if err != nil {
return err
}
db := mutDB.(*dbdesc.Mutable)
for _, name := range namesToReclaim {
delete(db.Schemas, name.Name)
}
if err := descsCol.WriteDescToBatch(
ctx, false /* kvTrace */, db, b,
); err != nil {
return err
}
}
if err := descsCol.WriteDescToBatch(
ctx, false /* kvTrace */, mutDesc, b,
); err != nil {
return err
}
return txn.Run(ctx, b)
}
return descs.Txn(ctx, settings, leaseMgr, ie, db, run)
}
func startGCJob(
ctx context.Context,
db *kv.DB,
jobRegistry *jobs.Registry,
username security.SQLUsername,
schemaChangeDescription string,
details jobspb.SchemaChangeGCDetails,
) error {
jobRecord := CreateGCJobRecord(schemaChangeDescription, username, details)
jobID := jobRegistry.MakeJobID()
if err := db.Txn(ctx, func(ctx context.Context, txn *kv.Txn) error {
_, err := jobRegistry.CreateJobWithTxn(ctx, jobRecord, jobID, txn)
return err
}); err != nil {
return err
}
log.Infof(ctx, "starting GC job %d", jobID)
return jobRegistry.NotifyToAdoptJobs(ctx)
}
func (sc *SchemaChanger) execLogTags() *logtags.Buffer {
buf := &logtags.Buffer{}
buf = buf.Add("scExec", nil)
buf = buf.Add("id", sc.descID)
if sc.mutationID != descpb.InvalidMutationID {
buf = buf.Add("mutation", sc.mutationID)
}
if sc.droppedDatabaseID != descpb.InvalidID {
buf = buf.Add("db", sc.droppedDatabaseID)
}
return buf
}
// notFirstInLine checks if that this schema changer is at the front of the line
// to execute if the target descriptor is a table. It returns an error if this
// schema changer needs to wait.
func (sc *SchemaChanger) notFirstInLine(ctx context.Context, desc catalog.Descriptor) error {
if tableDesc, ok := desc.(catalog.TableDescriptor); ok {
// TODO (lucy): Now that marking a schema change job as succeeded doesn't
// happen in the same transaction as removing mutations from a table
// descriptor, it seems possible for a job to be resumed after the mutation
// has already been removed. If there's a mutation provided, we should check
// whether it actually exists on the table descriptor and exit the job if not.
for i, mutation := range tableDesc.AllMutations() {
if mutation.MutationID() == sc.mutationID {
if i != 0 {
log.Infof(ctx,
"schema change on %q (v%d): another change is still in progress",
desc.GetName(), desc.GetVersion(),
)
return errSchemaChangeNotFirstInLine
}
break
}
}
}
return nil
}
func (sc *SchemaChanger) getTargetDescriptor(ctx context.Context) (catalog.Descriptor, error) {
// Retrieve the descriptor that is being changed.
var desc catalog.Descriptor
if err := sc.txn(ctx, func(
ctx context.Context, txn *kv.Txn, descriptors *descs.Collection,
) (err error) {
flags := tree.CommonLookupFlags{
AvoidCached: true,
Required: true,
IncludeOffline: true,
IncludeDropped: true,
}
desc, err = descriptors.GetImmutableDescriptorByID(ctx, txn, sc.descID, flags)
return err
}); err != nil {
return nil, err
}
return desc, nil
}
// Execute the entire schema change in steps.
// inSession is set to false when this is called from the asynchronous
// schema change execution path.
//
// If the txn that queued the schema changer did not commit, this will be a
// no-op, as we'll fail to find the job for our mutation in the jobs registry.
func (sc *SchemaChanger) exec(ctx context.Context) error {
sc.metrics.RunningSchemaChanges.Inc(1)
defer sc.metrics.RunningSchemaChanges.Dec(1)
ctx = logtags.AddTags(ctx, sc.execLogTags())
// Pull out the requested descriptor.
desc, err := sc.getTargetDescriptor(ctx)
if err != nil {
return err
}
// Check that we aren't queued behind another schema changer.
if err := sc.notFirstInLine(ctx, desc); err != nil {
return err
}
log.Infof(ctx,
"schema change on %q (v%d) starting execution...",
desc.GetName(), desc.GetVersion(),
)
// If there are any names to drain, then drain them.
if len(desc.GetDrainingNames()) > 0 {
if err := drainNamesForDescriptor(
ctx, sc.settings, desc.GetID(), sc.db, sc.execCfg.InternalExecutor, sc.leaseMgr,
sc.execCfg.Codec, sc.testingKnobs.OldNamesDrainedNotification,
); err != nil {
return err
}
}
// Wait for the schema change to propagate to all nodes after this function
// returns, so that the new schema is live everywhere. This is not needed for
// correctness but is done to make the UI experience/tests predictable.
waitToUpdateLeases := func(refreshStats bool) error {
if err := WaitToUpdateLeases(ctx, sc.leaseMgr, sc.descID); err != nil {
if errors.Is(err, catalog.ErrDescriptorNotFound) {
return err
}
log.Warningf(ctx, "waiting to update leases: %+v", err)
// As we are dismissing the error, go through the recording motions.
// This ensures that any important error gets reported to Sentry, etc.
sqltelemetry.RecordError(ctx, err, &sc.settings.SV)
}
// We wait to trigger a stats refresh until we know the leases have been
// updated.
if refreshStats {
sc.refreshStats()
}
return nil
}
tableDesc, ok := desc.(catalog.TableDescriptor)
if !ok {
// If our descriptor is not a table, then just drain leases.
if err := waitToUpdateLeases(false /* refreshStats */); err != nil {
return err
}
// Some descriptors should be deleted if they are in the DROP state.
switch desc.(type) {
case catalog.SchemaDescriptor, catalog.DatabaseDescriptor:
if desc.Dropped() {
if err := sc.execCfg.DB.Del(ctx, catalogkeys.MakeDescMetadataKey(sc.execCfg.Codec, desc.GetID())); err != nil {
return err
}
}
}
return nil
}
// Otherwise, continue with the rest of the schema change state machine.
if tableDesc.Dropped() && sc.droppedDatabaseID == descpb.InvalidID {
if tableDesc.IsPhysicalTable() {
// We've dropped this physical table, let's kick off a GC job.
dropTime := timeutil.Now().UnixNano()
if tableDesc.GetDropTime() > 0 {
dropTime = tableDesc.GetDropTime()
}
gcDetails := jobspb.SchemaChangeGCDetails{
Tables: []jobspb.SchemaChangeGCDetails_DroppedID{
{
ID: tableDesc.GetID(),
DropTime: dropTime,
},
},
}
if err := startGCJob(
ctx, sc.db, sc.jobRegistry, sc.job.Payload().UsernameProto.Decode(), sc.job.Payload().Description, gcDetails,
); err != nil {
return err
}
} else {
// We've dropped a non-physical table, no need for a GC job, let's delete
// its descriptor and zone config immediately.
if err := DeleteTableDescAndZoneConfig(ctx, sc.db, sc.execCfg.Codec, tableDesc); err != nil {
return err
}
}
}
if err := sc.maybeBackfillCreateTableAs(ctx, tableDesc); err != nil {
return err
}
if err := sc.maybeBackfillMaterializedView(ctx, tableDesc); err != nil {
return err
}
if err := sc.maybeMakeAddTablePublic(ctx, tableDesc); err != nil {
return err
}
if sc.mutationID == descpb.InvalidMutationID {
// Nothing more to do.
isCreateTableAs := tableDesc.Adding() && tableDesc.IsAs()
return waitToUpdateLeases(isCreateTableAs /* refreshStats */)
}
if err := sc.initJobRunningStatus(ctx); err != nil {
if log.V(2) {
log.Infof(ctx, "failed to update job status: %+v", err)
}
// Go through the recording motions. See comment above.
sqltelemetry.RecordError(ctx, err, &sc.settings.SV)
}
// Run through mutation state machine and backfill.
if err := sc.runStateMachineAndBackfill(ctx); err != nil {
return err
}
defer func() {
if err := waitToUpdateLeases(err == nil /* refreshStats */); err != nil && !errors.Is(err, catalog.ErrDescriptorNotFound) {
// We only expect ErrDescriptorNotFound to be returned. This happens
// when the table descriptor was deleted. We can ignore this error.
log.Warningf(ctx, "unexpected error while waiting for leases to update: %+v", err)
// As we are dismissing the error, go through the recording motions.
// This ensures that any important error gets reported to Sentry, etc.
sqltelemetry.RecordError(ctx, err, &sc.settings.SV)
}
}()
return err
}
// handlePermanentSchemaChangeError cleans up schema changes that cannot
// be completed successfully. For schema changes with mutations, it reverses the
// direction of the mutations so that we can step through the state machine
// backwards. Note that schema changes which don't have mutations are meant to
// run quickly and aren't truly cancellable in the small window they require to
// complete. In that case, cleanup consists of simply resuming the same schema
// change.
// TODO (lucy): This is how "rolling back" has always worked for non-mutation
// schema change jobs, but it's unnatural for the job API and we should rethink
// it.
func (sc *SchemaChanger) handlePermanentSchemaChangeError(
ctx context.Context, err error, evalCtx *extendedEvalContext,
) error {
// Ensure that this is a table descriptor and that the mutation is first in
// line prior to reverting.
{
// Pull out the requested descriptor.
desc, descErr := sc.getTargetDescriptor(ctx)
if descErr != nil {
return descErr
}
// Currently we don't attempt to roll back schema changes for anything other
// than tables. For jobs intended to drop other types of descriptors, we do
// nothing.
if _, ok := desc.(catalog.TableDescriptor); !ok {
return errors.Newf("schema change jobs on databases and schemas cannot be reverted")
}
// Check that we aren't queued behind another schema changer.
if err := sc.notFirstInLine(ctx, desc); err != nil {
return err
}
}
if rollbackErr := sc.rollbackSchemaChange(ctx, err); rollbackErr != nil {
// From now on, the returned error will be a secondary error of the returned
// error, so we'll record the original error now.
secondary := errors.Wrap(err, "original error when rolling back mutations")
sqltelemetry.RecordError(ctx, secondary, &sc.settings.SV)
return errors.WithSecondaryError(rollbackErr, secondary)
}
// TODO (lucy): This is almost the same as in exec(), maybe refactor.
// Wait for the schema change to propagate to all nodes after this function
// returns, so that the new schema is live everywhere. This is not needed for
// correctness but is done to make the UI experience/tests predictable.
waitToUpdateLeases := func(refreshStats bool) error {
if err := WaitToUpdateLeases(ctx, sc.leaseMgr, sc.descID); err != nil {
if errors.Is(err, catalog.ErrDescriptorNotFound) {
return err
}
log.Warningf(ctx, "waiting to update leases: %+v", err)
// As we are dismissing the error, go through the recording motions.
// This ensures that any important error gets reported to Sentry, etc.
sqltelemetry.RecordError(ctx, err, &sc.settings.SV)
}
// We wait to trigger a stats refresh until we know the leases have been
// updated.
if refreshStats {
sc.refreshStats()
}
return nil
}
defer func() {
if err := waitToUpdateLeases(false /* refreshStats */); err != nil && !errors.Is(err, catalog.ErrDescriptorNotFound) {
// We only expect ErrDescriptorNotFound to be returned. This happens
// when the table descriptor was deleted. We can ignore this error.
log.Warningf(ctx, "unexpected error while waiting for leases to update: %+v", err)
// As we are dismissing the error, go through the recording motions.
// This ensures that any important error gets reported to Sentry, etc.
sqltelemetry.RecordError(ctx, err, &sc.settings.SV)
}
}()
return nil
}
// initialize the job running status.
func (sc *SchemaChanger) initJobRunningStatus(ctx context.Context) error {
return sc.txn(ctx, func(ctx context.Context, txn *kv.Txn, descriptors *descs.Collection) error {
flags := tree.ObjectLookupFlagsWithRequired()
flags.AvoidCached = true
desc, err := descriptors.GetImmutableTableByID(ctx, txn, sc.descID, flags)
if err != nil {
return err
}
var runStatus jobs.RunningStatus
for _, mutation := range desc.AllMutations() {
if mutation.MutationID() != sc.mutationID {
// Mutations are applied in a FIFO order. Only apply the first set of
// mutations if they have the mutation ID we're looking for.
break
}
if mutation.Adding() && mutation.DeleteOnly() {
runStatus = RunningStatusDeleteOnly
} else if mutation.Dropped() && mutation.WriteAndDeleteOnly() {
runStatus = RunningStatusDeleteAndWriteOnly
}
}
if runStatus != "" && !desc.Dropped() {
if err := sc.job.RunningStatus(
ctx, txn, func(ctx context.Context, details jobspb.Details) (jobs.RunningStatus, error) {
return runStatus, nil
}); err != nil {
return errors.Wrapf(err, "failed to update job status")
}
}
return nil
})
}
func (sc *SchemaChanger) rollbackSchemaChange(ctx context.Context, err error) error {
log.Warningf(ctx, "reversing schema change %d due to irrecoverable error: %s", sc.job.ID(), err)
if errReverse := sc.maybeReverseMutations(ctx, err); errReverse != nil {
return errReverse
}
if fn := sc.testingKnobs.RunAfterMutationReversal; fn != nil {
if err := fn(sc.job.ID()); err != nil {
return err
}
}
// After this point the schema change has been reversed and any retry
// of the schema change will act upon the reversed schema change.
if err := sc.runStateMachineAndBackfill(ctx); err != nil {
return err
}
// Check if the target table needs to be cleaned up at all. If the target
// table was in the ADD state and the schema change failed, then we need to
// clean up the descriptor.
gcJobID := sc.jobRegistry.MakeJobID()
if err := sc.txn(ctx, func(ctx context.Context, txn *kv.Txn, descsCol *descs.Collection) error {
scTable, err := descsCol.GetMutableTableVersionByID(ctx, sc.descID, txn)
if err != nil {
return err
}
if !scTable.Adding() {
return nil
}
b := txn.NewBatch()
scTable.SetDropped()
if err := descsCol.WriteDescToBatch(ctx, false /* kvTrace */, scTable, b); err != nil {
return err
}
catalogkv.WriteObjectNamespaceEntryRemovalToBatch(
ctx,
b,
sc.execCfg.Codec,
scTable.GetParentID(),
scTable.GetParentSchemaID(),
scTable.GetName(),
false, /* kvTrace */
)
// Queue a GC job.
jobRecord := CreateGCJobRecord(
"ROLLBACK OF "+sc.job.Payload().Description,
sc.job.Payload().UsernameProto.Decode(),
jobspb.SchemaChangeGCDetails{
Tables: []jobspb.SchemaChangeGCDetails_DroppedID{
{
ID: scTable.GetID(),
DropTime: timeutil.Now().UnixNano(),
},
},
},
)
if _, err := sc.jobRegistry.CreateJobWithTxn(ctx, jobRecord, gcJobID, txn); err != nil {
return err
}
return txn.Run(ctx, b)
}); err != nil {
return err
}
log.Infof(ctx, "starting GC job %d", gcJobID)
return sc.jobRegistry.NotifyToAdoptJobs(ctx)
}
// RunStateMachineBeforeBackfill moves the state machine forward
// and wait to ensure that all nodes are seeing the latest version
// of the table.
func (sc *SchemaChanger) RunStateMachineBeforeBackfill(ctx context.Context) error {
log.Info(ctx, "stepping through state machine")
var runStatus jobs.RunningStatus
if err := sc.txn(ctx, func(
ctx context.Context, txn *kv.Txn, descsCol *descs.Collection,
) error {
tbl, err := descsCol.GetMutableTableVersionByID(ctx, sc.descID, txn)
if err != nil {
return err
}
_, dbDesc, err := descsCol.GetImmutableDatabaseByID(
ctx,
txn,
tbl.GetParentID(),
tree.DatabaseLookupFlags{Required: true},
)
if err != nil {
return err
}
runStatus = ""
// Apply mutations belonging to the same version.
for _, m := range tbl.AllMutations() {
if m.MutationID() != sc.mutationID {
// Mutations are applied in a FIFO order. Only apply the first set of
// mutations if they have the mutation ID we're looking for.
break
}
if m.Adding() {
if m.DeleteOnly() {
// TODO(vivek): while moving up the state is appropriate,
// it will be better to run the backfill of a unique index
// twice: once in the DELETE_ONLY state to confirm that
// the index can indeed be created, and subsequently in the
// DELETE_AND_WRITE_ONLY state to fill in the missing elements of the
// index (INSERT and UPDATE that happened in the interim).
tbl.Mutations[m.MutationOrdinal()].State = descpb.DescriptorMutation_DELETE_AND_WRITE_ONLY
runStatus = RunningStatusDeleteAndWriteOnly
}
// else if DELETE_AND_WRITE_ONLY, then the state change has already moved forward.
} else if m.Dropped() {
if m.WriteAndDeleteOnly() {
tbl.Mutations[m.MutationOrdinal()].State = descpb.DescriptorMutation_DELETE_ONLY
runStatus = RunningStatusDeleteOnly
}
// else if DELETE_ONLY, then the state change has already moved forward.
}
// We might have to update some zone configs for indexes that are
// being rewritten. It is important that this is done _before_ the
// index swap occurs. The logic that generates spans for subzone
// configurations removes spans for indexes in the dropping state,
// which we don't want. So, set up the zone configs before we swap.
if err := sc.applyZoneConfigChangeForMutation(
ctx,
txn,
dbDesc,
tbl,
m,
false, // isDone
descsCol,
); err != nil {
return err
}
}
if doNothing := runStatus == "" || tbl.Dropped(); doNothing {
return nil
}
if err := descsCol.WriteDesc(
ctx, true /* kvTrace */, tbl, txn,
); err != nil {
return err
}
if sc.job != nil {
if err := sc.job.RunningStatus(ctx, txn, func(
ctx context.Context, details jobspb.Details,
) (jobs.RunningStatus, error) {
return runStatus, nil
}); err != nil {
return errors.Wrap(err, "failed to update job status")
}
}
return nil
}); err != nil {
return err
}
log.Info(ctx, "finished stepping through state machine")
// wait for the state change to propagate to all leases.
return WaitToUpdateLeases(ctx, sc.leaseMgr, sc.descID)
}
func (sc *SchemaChanger) createIndexGCJob(
ctx context.Context, indexID descpb.IndexID, txn *kv.Txn, jobDesc string,
) error {
dropTime := timeutil.Now().UnixNano()
indexGCDetails := jobspb.SchemaChangeGCDetails{
Indexes: []jobspb.SchemaChangeGCDetails_DroppedIndex{
{
IndexID: indexID,