-
Notifications
You must be signed in to change notification settings - Fork 3.9k
/
Copy pathschema_changer.go
3158 lines (2903 loc) · 109 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/clusterversion"
"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/kv/kvpb"
"github.com/cockroachdb/cockroach/pkg/roachpb"
"github.com/cockroachdb/cockroach/pkg/security/username"
"github.com/cockroachdb/cockroach/pkg/server/telemetry"
"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/catpb"
"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/catalog/typedesc"
"github.com/cockroachdb/cockroach/pkg/sql/clusterunique"
"github.com/cockroachdb/cockroach/pkg/sql/execinfrapb"
"github.com/cockroachdb/cockroach/pkg/sql/faketreeeval"
"github.com/cockroachdb/cockroach/pkg/sql/flowinfra"
"github.com/cockroachdb/cockroach/pkg/sql/gcjob/gcjobnotifier"
"github.com/cockroachdb/cockroach/pkg/sql/isql"
"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/eval"
"github.com/cockroachdb/cockroach/pkg/sql/sem/tree"
"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/storage"
"github.com/cockroachdb/cockroach/pkg/util/admission/admissionpb"
"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/log/logpb"
"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"
)
var schemaChangeJobMaxRetryBackoff = settings.RegisterDurationSetting(
settings.TenantWritable,
"schemachanger.job.max_retry_backoff",
"the exponential back off when retrying jobs for schema changes",
20*time.Second,
settings.PositiveDuration,
)
const (
// RunningStatusWaitingForMVCCGC is used for the GC job when it has cleared
// the data but is waiting for MVCC GC to remove the data.
RunningStatusWaitingForMVCCGC jobs.RunningStatus = "waiting for MVCC GC"
// RunningStatusDeletingData is used for the GC job when it is about
// to clear the data.
RunningStatusDeletingData jobs.RunningStatus = "deleting data"
// 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"
// RunningStatusWriteOnly is for jobs that are currently waiting on
// the cluster to converge to seeing the schema element in the
// WRITE_ONLY state.
RunningStatusWriteOnly jobs.RunningStatus = "waiting in WRITE_ONLY"
// RunningStatusMerging is for jobs that are currently waiting on
// the cluster to converge to seeing the schema element in the
// MERGING state.
RunningStatusMerging jobs.RunningStatus = "waiting in MERGING"
// 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
droppedSchemaIDs catalog.DescriptorIDSet
droppedFnIDs catalog.DescriptorIDSet
sqlInstanceID base.SQLInstanceID
leaseMgr *lease.Manager
db isql.DB
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
}
// NewSchemaChangerForTesting only for tests.
func NewSchemaChangerForTesting(
tableID descpb.ID,
mutationID descpb.MutationID,
sqlInstanceID base.SQLInstanceID,
db isql.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,
metrics: NewSchemaChangerMetrics(),
clock: db.KV().Clock(),
distSQLPlanner: execCfg.DistSQLPlanner,
testingKnobs: &SchemaChangerTestingKnobs{},
}
}
// IsConstraintError returns true if the error is considered as
// an error introduced by the user. For example a constraint
// violation.
func IsConstraintError(err error) bool {
pgCode := pgerror.GetPGCode(err)
return pgCode == pgcode.CheckViolation ||
pgCode == pgcode.UniqueViolation ||
pgCode == pgcode.ForeignKeyViolation ||
pgCode == pgcode.NotNullViolation ||
pgCode == pgcode.IntegrityConstraintViolation
}
// 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, (*kvpb.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,
errSchemaChangeNotFirstInLine,
errTableVersionMismatchSentinel,
) {
return false
}
if flowinfra.IsFlowRetryableError(err) {
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 errSchemaChangeNotFirstInLine = errors.Newf("schema change not first in line")
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 catalog.TableDescriptor, 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.GetViewQuery(), 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 isql.Txn) error {
if err := txn.KV().SetFixedTimestamp(ctx, ts); err != nil {
return err
}
// Create an internal planner as the planner used to serve the user query
// would have committed by this point.
p, cleanup := NewInternalPlanner(
desc,
txn.KV(),
username.RootUserName(),
&MemoryMetrics{},
sc.execCfg,
NewInternalSessionData(ctx, sc.execCfg.Settings, "backfillQueryIntoTable"),
)
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, clusterunique.ID{} /* 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 := kvpb.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 kvpb.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.KV(),
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{},
)
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.Mon().MakeBoundAccount()
defer subqueryResultMemAcc.Close(ctx)
if !sc.distSQLPlanner.PlanAndRunSubqueries(
ctx, localPlanner, localPlanner.ExtendedEvalContextCopy,
localPlanner.curPlan.subqueryPlans, recv, &subqueryResultMemAcc,
false, /* skipDistSQLDiagramGeneration */
false, /* mustUseLeafTxn */
) {
if planAndRunErr = rw.Err(); planAndRunErr != nil {
return
}
}
}
isLocal := !getPlanDistribution(
ctx, localPlanner.Descriptors().HasUncommittedTypes(),
localPlanner.extendedEvalCtx.SessionData().DistSQLMode, localPlanner.curPlan.main,
).WillDistribute()
out := execinfrapb.ProcessorCoreUnion{BulkRowWriter: &execinfrapb.BulkRowWriterSpec{
Table: *table.TableDesc(),
}}
PlanAndRunCTAS(ctx, sc.distSQLPlanner, localPlanner,
txn.KV(), 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")
}
// maybeUpdateScheduledJobsForRowLevelTTL ensures the scheduled jobs related to the
// table's row level TTL are appropriately configured.
func (sc *SchemaChanger) maybeUpdateScheduledJobsForRowLevelTTL(
ctx context.Context, tableDesc catalog.TableDescriptor,
) error {
// Drop the scheduled job if one exists and the table descriptor is being dropped.
if tableDesc.Dropped() && tableDesc.HasRowLevelTTL() {
if err := sc.db.Txn(ctx, func(ctx context.Context, txn isql.Txn) error {
scheduleID := tableDesc.GetRowLevelTTL().ScheduleID
if scheduleID > 0 {
log.Infof(ctx, "dropping TTL schedule %d", scheduleID)
return DeleteSchedule(ctx, sc.execCfg, txn, scheduleID)
}
return nil
}); err != nil {
return err
}
}
return nil
}
func (sc *SchemaChanger) maybeBackfillMaterializedView(
ctx context.Context, table catalog.TableDescriptor,
) error {
if !(table.Adding() && table.MaterializedView()) {
return nil
}
// If materialized view is created with the WITH NO DATA option, skip backfill of the view
// during creation. The RefreshViewRequired field within the table descriptor indicates
// that a materialized view has been created with no data and a REFRESH VIEW operation needs
// to be called on it prior to access.
if table.IsRefreshViewRequired() {
log.Infof(ctx, "skipping backfill for CREATE MATERIALIZED VIEW %s WITH NO DATA", table.GetName())
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")
return sc.txn(ctx, func(ctx context.Context, txn descs.Txn) error {
mut, err := txn.Descriptors().MutableByID(txn.KV()).Table(ctx, table.GetID())
if err != nil {
return err
}
if !mut.Adding() {
return nil
}
mut.State = descpb.DescriptorState_PUBLIC
return txn.Descriptors().WriteDesc(ctx, true /* kvTrace */, mut, txn.KV())
})
}
// ignoreRevertedDropIndex finds all add index mutations that are the
// result of a rollback and changes their direction to DROP.
//
// Prior to 22.1 we would attempt to revert failed DROP INDEX
// mutations. However, not all dependent objects were reverted and it
// required an expensive, full index rebuild.
//
// In 22.1+, we no longer revert failed DROP INDEX mutations, but we
// need to account for mutations created on earlier versions.
//
// In a mixed-version state, if this code runs once, then the mutation
// will have been converted to a DROP and the index will be dropped
// regardless of which node resumes the job after this function
// returns. If the job is resumed only on an older node, then the
// reverted schema change will continue as it would have previously.
//
// TODO(ssd): Once we install a version gate and upgrade that drains
// in-flight schema changes and disallows any old-style index
// backfills, we can remove this extra transaction since we will know
// that any reverted DROP INDEX mutations will either have already
// been processed or will fail (since after the new gate, we will fail
// any ADD INDEX mutations generated on old code).
func (sc *SchemaChanger) ignoreRevertedDropIndex(
ctx context.Context, table catalog.TableDescriptor,
) error {
if !table.IsPhysicalTable() {
return nil
}
return sc.txn(ctx, func(ctx context.Context, txn descs.Txn) error {
mut, err := txn.Descriptors().MutableByID(txn.KV()).Table(ctx, table.GetID())
if err != nil {
return err
}
mutationsModified := false
for _, m := range mut.AllMutations() {
if m.MutationID() != sc.mutationID {
break
}
if !m.IsRollback() || !m.Adding() || m.AsIndex() == nil {
continue
}
log.Warningf(ctx, "ignoring rollback of index drop; index %q will be dropped", m.AsIndex().GetName())
mut.Mutations[m.MutationOrdinal()].Direction = descpb.DescriptorMutation_DROP
mutationsModified = true
}
if mutationsModified {
return txn.Descriptors().WriteDesc(ctx, true /* kvTrace */, mut, txn.KV())
}
return nil
})
}
func startGCJob(
ctx context.Context,
db isql.DB,
jobRegistry *jobs.Registry,
userName username.SQLUsername,
schemaChangeDescription string,
details jobspb.SchemaChangeGCDetails,
useLegacyGCJob bool,
) error {
jobRecord := CreateGCJobRecord(
schemaChangeDescription, userName, details, useLegacyGCJob,
)
jobID := jobRegistry.MakeJobID()
if err := db.Txn(ctx, func(ctx context.Context, txn isql.Txn) error {
_, err := jobRegistry.CreateJobWithTxn(ctx, jobRecord, jobID, txn)
return err
}); err != nil {
return err
}
log.Infof(ctx, "created GC job %d", jobID)
jobRegistry.NotifyToResume(ctx, jobID)
return nil
}
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)
} else if !sc.droppedSchemaIDs.Empty() {
buf = buf.Add("schema", sc.droppedSchemaIDs)
}
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 descs.Txn,
) (err error) {
desc, err = txn.Descriptors().ByID(txn.KV()).Get().Desc(ctx, sc.descID)
return err
}); err != nil {
return nil, err
}
return desc, nil
}
func (sc *SchemaChanger) checkForMVCCCompliantAddIndexMutations(
ctx context.Context, desc catalog.Descriptor,
) error {
tableDesc, ok := desc.(catalog.TableDescriptor)
if !ok {
return nil
}
nonTempAddingIndexes := 0
tempIndexes := 0
for _, m := range tableDesc.AllMutations() {
if m.MutationID() != sc.mutationID {
break
}
idx := m.AsIndex()
if idx == nil {
continue
}
if idx.IsTemporaryIndexForBackfill() {
tempIndexes++
} else if m.Adding() {
nonTempAddingIndexes++
}
}
if tempIndexes != nonTempAddingIndexes {
return errors.Newf("expected %d temporary indexes, but found %d; schema change may have been constructed on a version too old to resume execution",
nonTempAddingIndexes, tempIndexes)
}
return 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 {
// We had a bug where function descriptors are not deleted after DROP
// FUNCTION in legacy schema changer (see #95364). We then add logic to
// handle the deletion in jobs and added upgrades to delete all dropped
// functions. It's possible that such job is resumed after the cluster is
// upgraded (all dropped descriptors are deleted), and we would fail to find
// the descriptor here. In this case, we can simply assume the job is done
// since we only handle descriptor deletes for functions and `droppedFnIDs`
// is not empty only when dropping functions.
if sc.droppedFnIDs.Len() > 0 && errors.Is(err, catalog.ErrDescriptorNotFound) {
return nil
}
return err
}
// Check that we aren't queued behind another schema changer.
if err := sc.notFirstInLine(ctx, desc); err != nil {
return err
}
if err := sc.checkForMVCCCompliantAddIndexMutations(ctx, desc); err != nil {
return err
}
log.Infof(ctx,
"schema change on %q (v%d) starting execution...",
desc.GetName(), desc.GetVersion(),
)
// 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 {
latestDesc, err := WaitToUpdateLeases(ctx, sc.leaseMgr, sc.descID)
if 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(latestDesc)
}
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
}
// Database/Schema descriptors should be deleted if they are in the DROP state.
if !desc.Dropped() {
return nil
}
switch desc.(type) {
case catalog.SchemaDescriptor:
if !sc.droppedSchemaIDs.Contains(desc.GetID()) {
return nil
}
case catalog.DatabaseDescriptor:
if sc.droppedDatabaseID != desc.GetID() {
return nil
}
case catalog.FunctionDescriptor:
if !sc.droppedFnIDs.Contains(desc.GetID()) {
return nil
}
default:
return nil
}
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 && sc.droppedSchemaIDs.Empty() {
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,
!storage.CanUseMVCCRangeTombstones(ctx, sc.settings),
); 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.execCfg, tableDesc); err != nil {
return err
}
}
}
if err := sc.ignoreRevertedDropIndex(ctx, 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 err := sc.maybeUpdateScheduledJobsForRowLevelTTL(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)
if jobs.IsPauseSelfError(err) {
// For testing only
return err
}
}
// 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 {
// Clean up any protected timestamps as a last resort, in case the job
// execution never did itself.
if err := sc.execCfg.ProtectedTimestampManager.Unprotect(ctx, sc.job); err != nil {
log.Warningf(ctx, "unexpected error cleaning up protected timestamp %v", err)
}
// 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 jobs.MarkAsPermanentJobError(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 {
desc, err := WaitToUpdateLeases(ctx, sc.leaseMgr, sc.descID)
if 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(desc)
}
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 descs.Txn) error {
desc, err := txn.Descriptors().ByID(txn.KV()).WithoutNonPublic().Get().Table(ctx, sc.descID)
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 = RunningStatusWriteOnly
}
}
if runStatus != "" && !desc.Dropped() {
if err := sc.job.WithTxn(txn).RunningStatus(
ctx, 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
})
}
// dropViewDeps cleans up any dependencies that are related to a given view,
// including anything that exists because of forward or back references.
func (sc *SchemaChanger) dropViewDeps(
ctx context.Context,
descsCol *descs.Collection,
txn *kv.Txn,
b *kv.Batch,
viewDesc *tabledesc.Mutable,
) error {
// Remove back-references from the tables/views this view depends on.
dependedOn := append([]descpb.ID(nil), viewDesc.DependsOn...)
for _, depID := range dependedOn {
dependencyDesc, err := descsCol.MutableByID(txn).Table(ctx, depID)
if err != nil {
log.Warningf(ctx, "error resolving dependency relation ID %d", depID)
continue
}
// The dependency is also being deleted, so we don't have to remove the
// references.
if dependencyDesc.Dropped() {
continue
}
dependencyDesc.DependedOnBy = removeMatchingReferences(dependencyDesc.DependedOnBy, viewDesc.ID)
if err := descsCol.WriteDescToBatch(ctx, false /* kvTrace*/, dependencyDesc, b); err != nil {
log.Warningf(ctx, "error removing dependency from releation ID %d", depID)
return err
}
}
viewDesc.DependsOn = nil
// If anything depends on this table clean up references from that object as well.
DependedOnBy := append([]descpb.TableDescriptor_Reference(nil), viewDesc.DependedOnBy...)
for _, depRef := range DependedOnBy {
dependencyDesc, err := descsCol.MutableByID(txn).Table(ctx, depRef.ID)
if err != nil {
log.Warningf(ctx, "error resolving dependency relation ID %d", depRef.ID)
continue
}
if dependencyDesc.Dropped() {
continue
}
// Entire dependent view needs to be cleaned up.
if err := sc.dropViewDeps(ctx, descsCol, txn, b, dependencyDesc); err != nil {
return err
}
}
// Clean up sequence and type references from the view.
for _, col := range viewDesc.DeletableColumns() {
typeClosure := typedesc.GetTypeDescriptorClosure(col.GetType())
for _, id := range typeClosure.Ordered() {
typeDesc, err := descsCol.MutableByID(txn).Type(ctx, id)
if err != nil {
log.Warningf(ctx, "error resolving type dependency %d", id)
continue
}
typeDesc.RemoveReferencingDescriptorID(viewDesc.GetID())
if err := descsCol.WriteDescToBatch(ctx, false /* kvTrace*/, typeDesc, b); err != nil {
log.Warningf(ctx, "error removing dependency from type ID %d", id)
return err
}
}
for i := 0; i < col.NumUsesSequences(); i++ {
id := col.GetUsesSequenceID(i)
seqDesc, err := descsCol.MutableByID(txn).Table(ctx, id)
if err != nil {
log.Warningf(ctx, "error resolving sequence dependency %d", id)
continue
}
if seqDesc.Dropped() {