-
Notifications
You must be signed in to change notification settings - Fork 3.8k
/
backfill.go
2916 lines (2709 loc) · 104 KB
/
backfill.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"
"sort"
"strings"
"time"
"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/kvcoord"
"github.com/cockroachdb/cockroach/pkg/roachpb"
"github.com/cockroachdb/cockroach/pkg/settings"
"github.com/cockroachdb/cockroach/pkg/sql/backfill"
"github.com/cockroachdb/cockroach/pkg/sql/catalog"
"github.com/cockroachdb/cockroach/pkg/sql/catalog/catalogkeys"
"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/execinfra"
"github.com/cockroachdb/cockroach/pkg/sql/execinfrapb"
"github.com/cockroachdb/cockroach/pkg/sql/pgwire/pgcode"
"github.com/cockroachdb/cockroach/pkg/sql/pgwire/pgerror"
"github.com/cockroachdb/cockroach/pkg/sql/row"
"github.com/cockroachdb/cockroach/pkg/sql/rowexec"
"github.com/cockroachdb/cockroach/pkg/sql/rowinfra"
"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/sqlutil"
"github.com/cockroachdb/cockroach/pkg/util/ctxgroup"
"github.com/cockroachdb/cockroach/pkg/util/hlc"
"github.com/cockroachdb/cockroach/pkg/util/log"
"github.com/cockroachdb/cockroach/pkg/util/mon"
"github.com/cockroachdb/cockroach/pkg/util/syncutil"
"github.com/cockroachdb/cockroach/pkg/util/timeutil"
"github.com/cockroachdb/errors"
)
const (
// indexTruncateChunkSize is the maximum number of index entries truncated
// per chunk during an index truncation. This value is larger than the
// other chunk constants because the operation involves only running a
// DeleteRange().
indexTruncateChunkSize = row.TableTruncateChunkSize
// indexTxnBackfillChunkSize is the maximum number index entries backfilled
// per chunk during an index backfill done in a txn. The index backfill
// involves a table scan, and a number of individual ops presented in a batch.
// This value is smaller than ColumnTruncateAndBackfillChunkSize, because it
// involves a number of individual index row updates that can be scattered
// over many ranges.
indexTxnBackfillChunkSize = 100
// checkpointInterval is the interval after which a checkpoint of the
// schema change is posted.
checkpointInterval = 2 * time.Minute
)
// indexBackfillBatchSize is the maximum number of rows we construct index
// entries for before we attempt to fill in a single index batch before queueing
// it up for ingestion and progress reporting in the index backfiller processor.
var indexBackfillBatchSize = settings.RegisterIntSetting(
settings.TenantWritable,
"bulkio.index_backfill.batch_size",
"the number of rows for which we construct index entries in a single batch",
50000,
settings.NonNegativeInt, /* validateFn */
)
// columnBackfillBatchSize is the maximum number of rows we update at once when
// adding or removing columns.
var columnBackfillBatchSize = settings.RegisterIntSetting(
settings.TenantWritable,
"bulkio.column_backfill.batch_size",
"the number of rows updated at a time to add/remove columns",
200,
settings.NonNegativeInt, /* validateFn */
)
// columnBackfillUpdateRunThresholdBytes is the byte size threshold beyond which
// an update batch is run at once when adding or removing columns.
var columnBackfillUpdateRunThresholdBytes = settings.RegisterIntSetting(
settings.TenantWritable,
"bulkio.column_backfill.update_run_threshold_bytes",
"the batch size in bytes above which an update is immediately run when adding/removing columns",
10<<20, /* 10 MiB */
settings.NonNegativeInt, /* validateFn */
)
var _ sort.Interface = columnsByID{}
var _ sort.Interface = indexesByID{}
type columnsByID []descpb.ColumnDescriptor
func (cds columnsByID) Len() int {
return len(cds)
}
func (cds columnsByID) Less(i, j int) bool {
return cds[i].ID < cds[j].ID
}
func (cds columnsByID) Swap(i, j int) {
cds[i], cds[j] = cds[j], cds[i]
}
type indexesByID []descpb.IndexDescriptor
func (ids indexesByID) Len() int {
return len(ids)
}
func (ids indexesByID) Less(i, j int) bool {
return ids[i].ID < ids[j].ID
}
func (ids indexesByID) Swap(i, j int) {
ids[i], ids[j] = ids[j], ids[i]
}
func (sc *SchemaChanger) getChunkSize(chunkSize int64) int64 {
if sc.testingKnobs.BackfillChunkSize > 0 {
return sc.testingKnobs.BackfillChunkSize
}
return chunkSize
}
// scTxnFn is the type of functions that operates using transactions in the backfiller.
type scTxnFn func(ctx context.Context, txn *kv.Txn, evalCtx *extendedEvalContext) error
// historicalTxnRunner is the type of the callback used by the various
// helper functions to run checks at a fixed timestamp (logically, at
// the start of the backfill).
type historicalTxnRunner func(ctx context.Context, fn scTxnFn) error
// makeFixedTimestampRunner creates a historicalTxnRunner suitable for use by the helpers.
func (sc *SchemaChanger) makeFixedTimestampRunner(readAsOf hlc.Timestamp) historicalTxnRunner {
runner := func(ctx context.Context, retryable scTxnFn) error {
return sc.fixedTimestampTxn(ctx, readAsOf, func(
ctx context.Context, txn *kv.Txn, descriptors *descs.Collection,
) error {
// We need to re-create the evalCtx since the txn may retry.
evalCtx := createSchemaChangeEvalCtx(ctx, sc.execCfg, readAsOf, descriptors)
return retryable(ctx, txn, &evalCtx)
})
}
return runner
}
// makeFixedTimestampRunner creates a HistoricalTxnRunner suitable for use by the helpers.
func (sc *SchemaChanger) makeFixedTimestampInternalExecRunner(
readAsOf hlc.Timestamp,
) sqlutil.HistoricalInternalExecTxnRunner {
runner := func(ctx context.Context, retryable sqlutil.InternalExecFn) error {
return sc.fixedTimestampTxn(ctx, readAsOf, func(
ctx context.Context, txn *kv.Txn, descriptors *descs.Collection,
) error {
// We need to re-create the evalCtx since the txn may retry.
ie := sc.ieFactory(ctx, NewFakeSessionData(sc.execCfg.SV()))
return retryable(ctx, txn, ie)
})
}
return runner
}
func (sc *SchemaChanger) fixedTimestampTxn(
ctx context.Context,
readAsOf hlc.Timestamp,
retryable func(ctx context.Context, txn *kv.Txn, descriptors *descs.Collection) error,
) error {
return sc.txn(ctx, func(ctx context.Context, txn *kv.Txn, descriptors *descs.Collection) error {
if err := txn.SetFixedTimestamp(ctx, readAsOf); err != nil {
return err
}
return retryable(ctx, txn, descriptors)
})
}
// runBackfill runs the backfill for the schema changer.
//
// This operates over multiple goroutines concurrently and is thus not
// able to reuse the original kv.Txn safely. The various
// function that it calls make their own txns.
func (sc *SchemaChanger) runBackfill(ctx context.Context) error {
if sc.testingKnobs.RunBeforeBackfill != nil {
if err := sc.testingKnobs.RunBeforeBackfill(); err != nil {
return err
}
}
// Mutations are applied in a FIFO order. Only apply the first set of
// mutations. Collect the elements that are part of the mutation.
var addedIndexSpans []roachpb.Span
var addedIndexes []descpb.IndexID
var temporaryIndexes []descpb.IndexID
var constraintsToDrop []catalog.ConstraintToUpdate
var constraintsToAddBeforeValidation []catalog.ConstraintToUpdate
var constraintsToValidate []catalog.ConstraintToUpdate
var viewToRefresh catalog.MaterializedViewRefresh
// Note that this descriptor is intentionally not leased. If the schema change
// held the lease, certain non-mutation related schema changes would not be
// able to proceed. That might be okay and even desirable. The bigger reason
// to not hold a lease throughout the duration of this schema change stage
// is more practical. The lease manager (and associated descriptor
// infrastructure) does not provide a mechanism to hold a lease over a long
// period of time and update the transaction commit deadline. As such, when
// the schema change job attempts to mutate the descriptor later in this
// method, the descriptor will need to be re-read and the operation should be
// revalidated against the new state of the descriptor. Any work to hold
// leases during mutations will need to consider the user experience when the
// user would like to issue schema changes to be applied asynchronously.
// Perhaps such schema changes could avoid waiting for a single version and
// thus avoid blocked. This will get ironed out in the context of
// transactional schema changes. In all likelihood, not holding a lease here
// is the right thing to do as we would never want this operation to fail
// because a new mutation was enqueued.
tableDesc, err := sc.updateJobRunningStatus(ctx, RunningStatusBackfill)
if err != nil {
return err
}
// Short circuit the backfill if the table has been deleted.
if tableDesc.Dropped() {
return nil
}
version := tableDesc.GetVersion()
log.Infof(ctx, "running backfill for %q, v=%d", tableDesc.GetName(), tableDesc.GetVersion())
needColumnBackfill := false
for _, m := range tableDesc.AllMutations() {
if m.MutationID() != sc.mutationID {
break
}
// If the current mutation is discarded, then
// skip over processing.
if discarded, _ := isCurrentMutationDiscarded(tableDesc, m, m.MutationOrdinal()+1); discarded {
continue
}
if m.Adding() {
if col := m.AsColumn(); col != nil {
// Its possible have a mix of columns that need a backfill and others
// that don't, so preserve the flag if its already been flipped.
needColumnBackfill = needColumnBackfill || catalog.ColumnNeedsBackfill(col)
} else if idx := m.AsIndex(); idx != nil {
if idx.IsTemporaryIndexForBackfill() {
temporaryIndexes = append(temporaryIndexes, idx.GetID())
} else {
addedIndexSpans = append(addedIndexSpans, tableDesc.IndexSpan(sc.execCfg.Codec, idx.GetID()))
addedIndexes = append(addedIndexes, idx.GetID())
}
} else if c := m.AsConstraint(); c != nil {
isValidating := c.IsCheck() && c.Check().Validity == descpb.ConstraintValidity_Validating ||
c.IsForeignKey() && c.ForeignKey().Validity == descpb.ConstraintValidity_Validating ||
c.IsUniqueWithoutIndex() && c.UniqueWithoutIndex().Validity == descpb.ConstraintValidity_Validating ||
c.IsNotNull()
isSkippingValidation, err := shouldSkipConstraintValidation(tableDesc, c)
if err != nil {
return err
}
if isValidating {
constraintsToAddBeforeValidation = append(constraintsToAddBeforeValidation, c)
}
if isValidating && !isSkippingValidation {
constraintsToValidate = append(constraintsToValidate, c)
}
} else if mvRefresh := m.AsMaterializedViewRefresh(); mvRefresh != nil {
viewToRefresh = mvRefresh
} else if m.AsPrimaryKeySwap() != nil || m.AsComputedColumnSwap() != nil || m.AsModifyRowLevelTTL() != nil {
// The backfiller doesn't need to do anything here.
} else {
return errors.AssertionFailedf("unsupported mutation: %+v", m)
}
} else if m.Dropped() {
if col := m.AsColumn(); col != nil {
// Its possible have a mix of columns that need a backfill and others
// that don't, so preserve the flag if its already been flipped.
needColumnBackfill = needColumnBackfill || catalog.ColumnNeedsBackfill(col)
} else if idx := m.AsIndex(); idx != nil {
// no-op. Handled in (*schemaChanger).done by queueing an index gc job.
} else if c := m.AsConstraint(); c != nil {
constraintsToDrop = append(constraintsToDrop, c)
} else if m.AsPrimaryKeySwap() != nil || m.AsComputedColumnSwap() != nil || m.AsMaterializedViewRefresh() != nil || m.AsModifyRowLevelTTL() != nil {
// The backfiller doesn't need to do anything here.
} else {
return errors.AssertionFailedf("unsupported mutation: %+v", m)
}
}
}
// If we were requested to refresh a view, then do so.
if viewToRefresh != nil {
if err := sc.refreshMaterializedView(ctx, tableDesc, viewToRefresh); err != nil {
return err
}
}
// First drop constraints and indexes, then add/drop columns, and only then
// add indexes and constraints.
// Drop constraints.
if len(constraintsToDrop) > 0 {
descs, err := sc.dropConstraints(ctx, constraintsToDrop)
if err != nil {
return err
}
version = descs[tableDesc.GetID()].GetVersion()
}
// Add and drop columns.
if needColumnBackfill {
if err := sc.truncateAndBackfillColumns(ctx, version); err != nil {
return err
}
}
// Add new indexes.
if len(addedIndexSpans) > 0 {
// Check if bulk-adding is enabled and supported by indexes (ie non-unique).
if err := sc.backfillIndexes(ctx, version, addedIndexSpans, addedIndexes, temporaryIndexes); err != nil {
return err
}
}
// Add check and foreign key constraints, publish the new version of the table descriptor,
// and wait until the entire cluster is on the new version. This is basically
// a state transition for the schema change, which must happen after the
// columns are backfilled and before constraint validation begins. This
// ensures that 1) all columns are writable and backfilled when the constraint
// starts being enforced on insert/update (which is relevant in the case where
// a constraint references both public and non-public columns), and 2) the
// validation occurs only when the entire cluster is already enforcing the
// constraint on insert/update.
if len(constraintsToAddBeforeValidation) > 0 {
if err := sc.addConstraints(ctx, constraintsToAddBeforeValidation); err != nil {
return err
}
}
// Validate check and foreign key constraints.
if len(constraintsToValidate) > 0 {
if err := sc.validateConstraints(ctx, constraintsToValidate); err != nil {
return err
}
}
log.Infof(ctx, "completed backfill for %q, v=%d", tableDesc.GetName(), tableDesc.GetVersion())
if sc.testingKnobs.RunAfterBackfill != nil {
if err := sc.testingKnobs.RunAfterBackfill(sc.job.ID()); err != nil {
return err
}
}
return nil
}
// shouldSkipConstraintValidation checks if a validating constraint should skip
// validation and be added directly. A Check Constraint can skip validation if it's
// created for a shard column internally.
func shouldSkipConstraintValidation(
tableDesc catalog.TableDescriptor, c catalog.ConstraintToUpdate,
) (bool, error) {
if !c.IsCheck() {
return false, nil
}
check := c.Check()
// The check constraint on shard column is always on the shard column itself.
if len(check.ColumnIDs) != 1 {
return false, nil
}
checkCol, err := tableDesc.FindColumnWithID(check.ColumnIDs[0])
if err != nil {
return false, err
}
// We only want to skip validation when the shard column is first added and
// the constraint is created internally since the shard column computation is
// well defined. Note that we show the shard column in `SHOW CREATE TABLE`,
// and we don't prevent users from adding other constraints on it. For those
// constraints, we still want to validate.
return tableDesc.IsShardColumn(checkCol) && checkCol.Adding(), nil
}
// dropConstraints publishes a new version of the given table descriptor with
// the given constraint removed from it, and waits until the entire cluster is
// on the new version of the table descriptor. It returns the new table descs.
func (sc *SchemaChanger) dropConstraints(
ctx context.Context, constraints []catalog.ConstraintToUpdate,
) (map[descpb.ID]catalog.TableDescriptor, error) {
log.Infof(ctx, "dropping %d constraints", len(constraints))
fksByBackrefTable := make(map[descpb.ID][]catalog.ConstraintToUpdate)
for _, c := range constraints {
if c.IsForeignKey() {
id := c.ForeignKey().ReferencedTableID
if id != sc.descID {
fksByBackrefTable[id] = append(fksByBackrefTable[id], c)
}
}
}
// Create update closure for the table and all other tables with backreferences.
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
}
b := txn.NewBatch()
for _, constraint := range constraints {
if constraint.IsCheck() || constraint.IsNotNull() {
found := false
for j, c := range scTable.Checks {
if c.Name == constraint.GetName() {
scTable.Checks = append(scTable.Checks[:j], scTable.Checks[j+1:]...)
found = true
break
}
}
if !found {
log.VEventf(
ctx, 2,
"backfiller tried to drop constraint %+v but it was not found, "+
"presumably due to a retry or rollback",
constraint.ConstraintToUpdateDesc(),
)
}
} else if constraint.IsForeignKey() {
var foundExisting bool
for j := range scTable.OutboundFKs {
def := &scTable.OutboundFKs[j]
if def.Name != constraint.GetName() {
continue
}
backrefTable, err := descsCol.GetMutableTableVersionByID(ctx,
constraint.ForeignKey().ReferencedTableID, txn)
if err != nil {
return err
}
if err := removeFKBackReferenceFromTable(
backrefTable, def.Name, scTable,
); err != nil {
return err
}
if err := descsCol.WriteDescToBatch(
ctx, true /* kvTrace */, backrefTable, b,
); err != nil {
return err
}
scTable.OutboundFKs = append(scTable.OutboundFKs[:j], scTable.OutboundFKs[j+1:]...)
foundExisting = true
break
}
if !foundExisting {
log.VEventf(
ctx, 2,
"backfiller tried to drop constraint %+v but it was not found, "+
"presumably due to a retry or rollback",
constraint.ConstraintToUpdateDesc(),
)
}
} else if constraint.IsUniqueWithoutIndex() {
found := false
for j, c := range scTable.UniqueWithoutIndexConstraints {
if c.Name == constraint.GetName() {
scTable.UniqueWithoutIndexConstraints = append(
scTable.UniqueWithoutIndexConstraints[:j],
scTable.UniqueWithoutIndexConstraints[j+1:]...,
)
found = true
break
}
}
if !found {
log.VEventf(
ctx, 2,
"backfiller tried to drop constraint %+v but it was not found, "+
"presumably due to a retry or rollback",
constraint.ConstraintToUpdateDesc(),
)
}
}
}
if err := descsCol.WriteDescToBatch(
ctx, true /* kvTrace */, scTable, b,
); err != nil {
return err
}
return txn.Run(ctx, b)
}); err != nil {
return nil, err
}
log.Info(ctx, "finished dropping constraints")
tableDescs := make(map[descpb.ID]catalog.TableDescriptor, len(fksByBackrefTable)+1)
if err := sc.txn(ctx, func(
ctx context.Context, txn *kv.Txn, descsCol *descs.Collection,
) (err error) {
if tableDescs[sc.descID], err = descsCol.GetImmutableTableByID(
ctx, txn, sc.descID, tree.ObjectLookupFlags{},
); err != nil {
return err
}
for id := range fksByBackrefTable {
desc, err := descsCol.GetImmutableTableByID(
ctx, txn, id, tree.ObjectLookupFlags{
CommonLookupFlags: tree.CommonLookupFlags{
IncludeDropped: true,
},
},
)
if err != nil {
return err
}
// If the backreference table has been dropped, we don't need to do
// anything there.
if !desc.Dropped() {
tableDescs[id] = desc
}
}
return nil
}); err != nil {
return nil, err
}
return tableDescs, nil
}
// addConstraints publishes a new version of the given table descriptor with the
// given constraint added to it, and waits until the entire cluster is on
// the new version of the table descriptor.
func (sc *SchemaChanger) addConstraints(
ctx context.Context, constraints []catalog.ConstraintToUpdate,
) error {
log.Infof(ctx, "adding %d constraints", len(constraints))
fksByBackrefTable := make(map[descpb.ID][]catalog.ConstraintToUpdate)
for _, c := range constraints {
if c.IsForeignKey() {
id := c.ForeignKey().ReferencedTableID
if id != sc.descID {
fksByBackrefTable[id] = append(fksByBackrefTable[id], c)
}
}
}
// Create update closure for the table and all other tables with backreferences
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
}
b := txn.NewBatch()
for _, constraint := range constraints {
if constraint.IsCheck() || constraint.IsNotNull() {
found := false
for _, c := range scTable.Checks {
if c.Name == constraint.GetName() {
log.VEventf(
ctx, 2,
"backfiller tried to add constraint %+v but found existing constraint %+v, "+
"presumably due to a retry or rollback",
constraint, c,
)
// Ensure the constraint on the descriptor is set to Validating, in
// case we're in the middle of rolling back DROP CONSTRAINT
c.Validity = descpb.ConstraintValidity_Validating
found = true
break
}
}
if !found {
scTable.Checks = append(scTable.Checks, &constraint.ConstraintToUpdateDesc().Check)
}
} else if constraint.IsForeignKey() {
var foundExisting bool
for j := range scTable.OutboundFKs {
def := &scTable.OutboundFKs[j]
if def.Name == constraint.GetName() {
if log.V(2) {
log.VEventf(
ctx, 2,
"backfiller tried to add constraint %+v but found existing constraint %+v, "+
"presumably due to a retry or rollback",
constraint.ConstraintToUpdateDesc(), def,
)
}
// Ensure the constraint on the descriptor is set to Validating, in
// case we're in the middle of rolling back DROP CONSTRAINT
def.Validity = descpb.ConstraintValidity_Validating
foundExisting = true
break
}
}
if !foundExisting {
scTable.OutboundFKs = append(scTable.OutboundFKs, constraint.ForeignKey())
backrefTable, err := descsCol.GetMutableTableVersionByID(ctx, constraint.ForeignKey().ReferencedTableID, txn)
if err != nil {
return err
}
// If the backref table is being dropped, then we should treat this as
// the constraint addition failing and rollback.
if backrefTable.Dropped() {
return pgerror.Newf(pgcode.UndefinedTable, "referenced relation %q does not exist", backrefTable.GetName())
}
// Check that a unique constraint for the FK still exists on the
// referenced table. It's possible for the unique index found during
// planning to have been dropped in the meantime, since only the
// presence of the backreference prevents it.
_, err = tabledesc.FindFKReferencedUniqueConstraint(backrefTable, constraint.ForeignKey().ReferencedColumnIDs)
if err != nil {
return err
}
backrefTable.InboundFKs = append(backrefTable.InboundFKs, constraint.ForeignKey())
// Note that this code may add the same descriptor to the batch
// multiple times if it is referenced multiple times. That's fine as
// the last put will win but it's perhaps not ideal. We could add
// code to deduplicate but it doesn't seem worth the hassle.
if backrefTable != scTable {
if err := descsCol.WriteDescToBatch(
ctx, true /* kvTrace */, backrefTable, b,
); err != nil {
return err
}
}
}
} else if constraint.IsUniqueWithoutIndex() {
found := false
for _, c := range scTable.UniqueWithoutIndexConstraints {
if c.Name == constraint.GetName() {
log.VEventf(
ctx, 2,
"backfiller tried to add constraint %+v but found existing constraint %+v, "+
"presumably due to a retry or rollback",
constraint.ConstraintToUpdateDesc(), c,
)
// Ensure the constraint on the descriptor is set to Validating, in
// case we're in the middle of rolling back DROP CONSTRAINT
c.Validity = descpb.ConstraintValidity_Validating
found = true
break
}
}
if !found {
scTable.UniqueWithoutIndexConstraints = append(scTable.UniqueWithoutIndexConstraints,
constraint.UniqueWithoutIndex())
}
}
}
if err := descsCol.WriteDescToBatch(
ctx, true /* kvTrace */, scTable, b,
); err != nil {
return err
}
return txn.Run(ctx, b)
}); err != nil {
return err
}
log.Info(ctx, "finished adding constraints")
return nil
}
// validateConstraints checks that the current table data obeys the
// provided constraints.
//
// This operates over multiple goroutines concurrently and is thus not
// able to reuse the original kv.Txn safely, so it makes its own.
func (sc *SchemaChanger) validateConstraints(
ctx context.Context, constraints []catalog.ConstraintToUpdate,
) error {
if lease.TestingTableLeasesAreDisabled() {
return nil
}
log.Infof(ctx, "validating %d new constraints", len(constraints))
_, err := sc.updateJobRunningStatus(ctx, RunningStatusValidation)
if err != nil {
return err
}
if fn := sc.testingKnobs.RunBeforeConstraintValidation; fn != nil {
if err := fn(constraints); err != nil {
return err
}
}
readAsOf := sc.clock.Now()
var tableDesc catalog.TableDescriptor
if err := sc.fixedTimestampTxn(ctx, readAsOf, func(
ctx context.Context, txn *kv.Txn, descriptors *descs.Collection,
) error {
flags := tree.ObjectLookupFlagsWithRequired()
flags.AvoidLeased = true
tableDesc, err = descriptors.GetImmutableTableByID(ctx, txn, sc.descID, flags)
return err
}); err != nil {
return err
}
grp := ctxgroup.WithContext(ctx)
// The various checks below operate at a fixed timestamp.
runHistoricalTxn := sc.makeFixedTimestampRunner(readAsOf)
for i := range constraints {
c := constraints[i]
grp.GoCtx(func(ctx context.Context) error {
// Make the mutations public in a private copy of the descriptor
// and add it to the Collection, so that we can use SQL below to perform
// the validation. We wouldn't have needed to do this if we could have
// updated the descriptor and run validation in the same transaction. However,
// our current system is incapable of running long running schema changes
// (the validation can take many minutes). So we pretend that the schema
// has been updated and actually update it in a separate transaction that
// follows this one.
descI, err := tableDesc.MakeFirstMutationPublic(catalog.IgnoreConstraints)
if err != nil {
return err
}
desc := descI.(*tabledesc.Mutable)
// Each check operates at the historical timestamp.
return runHistoricalTxn(ctx, func(ctx context.Context, txn *kv.Txn, evalCtx *extendedEvalContext) error {
// If the constraint is a check constraint that fails validation, we
// need a semaContext set up that can resolve types in order to pretty
// print the check expression back to the user.
evalCtx.Txn = txn
// Use the DistSQLTypeResolver because we need to resolve types by ID.
collection := evalCtx.Descs
resolver := descs.NewDistSQLTypeResolver(collection, txn)
semaCtx := tree.MakeSemaContext()
semaCtx.TypeResolver = &resolver
// TODO (rohany): When to release this? As of now this is only going to get released
// after the check is validated.
defer func() { collection.ReleaseAll(ctx) }()
if c.IsCheck() {
if err := validateCheckInTxn(
ctx, &semaCtx, sc.ieFactory, evalCtx.SessionData(), desc, txn, c.Check().Expr,
); err != nil {
return err
}
} else if c.IsForeignKey() {
if err := validateFkInTxn(ctx, sc.ieFactory, evalCtx.SessionData(), desc, txn, collection, c.GetName()); err != nil {
return err
}
} else if c.IsUniqueWithoutIndex() {
if err := validateUniqueWithoutIndexConstraintInTxn(ctx, sc.ieFactory(ctx, evalCtx.SessionData()), desc, txn, c.GetName()); err != nil {
return err
}
} else if c.IsNotNull() {
if err := validateCheckInTxn(
ctx, &semaCtx, sc.ieFactory, evalCtx.SessionData(), desc, txn, c.Check().Expr,
); err != nil {
// TODO (lucy): This should distinguish between constraint
// validation errors and other types of unexpected errors, and
// return a different error code in the former case
return errors.Wrap(err, "validation of NOT NULL constraint failed")
}
} else {
return errors.Errorf("unsupported constraint type: %d", c.ConstraintToUpdateDesc().ConstraintType)
}
return nil
})
})
}
if err := grp.Wait(); err != nil {
return err
}
log.Info(ctx, "finished validating new constraints")
return nil
}
// getTableVersion retrieves the descriptor for the table being
// targeted by the schema changer using the provided txn, and asserts
// that the retrieved descriptor is at the given version. An error is
// returned otherwise.
//
// It operates entirely on the current goroutine and is thus able to
// reuse an existing kv.Txn safely.
func (sc *SchemaChanger) getTableVersion(
ctx context.Context, txn *kv.Txn, tc *descs.Collection, version descpb.DescriptorVersion,
) (catalog.TableDescriptor, error) {
tableDesc, err := tc.GetImmutableTableByID(ctx, txn, sc.descID, tree.ObjectLookupFlags{})
if err != nil {
return nil, err
}
if version != tableDesc.GetVersion() {
return nil, makeErrTableVersionMismatch(tableDesc.GetVersion(), version)
}
return tableDesc, nil
}
// getJobIDForMutationWithDescriptor returns a job id associated with a mutation given
// a table descriptor. Unlike getJobIDForMutation this doesn't need transaction.
// TODO (lucy): This is not a good way to look up all schema change jobs
// associated with a table. We should get rid of MutationJobs and start looking
// up the jobs in the jobs table instead.
func getJobIDForMutationWithDescriptor(
ctx context.Context, tableDesc catalog.TableDescriptor, mutationID descpb.MutationID,
) (jobspb.JobID, error) {
for _, job := range tableDesc.GetMutationJobs() {
if job.MutationID == mutationID {
return job.JobID, nil
}
}
return jobspb.InvalidJobID, errors.AssertionFailedf(
"job not found for table id %d, mutation %d", tableDesc.GetID(), mutationID)
}
// numRangesInSpans returns the number of ranges that cover a set of spans.
//
// It operates entirely on the current goroutine and is thus able to
// reuse an existing kv.Txn safely.
func numRangesInSpans(
ctx context.Context, db *kv.DB, distSQLPlanner *DistSQLPlanner, spans []roachpb.Span,
) (int, error) {
txn := db.NewTxn(ctx, "num-ranges-in-spans")
spanResolver := distSQLPlanner.spanResolver.NewSpanResolverIterator(txn)
rangeIds := make(map[int64]struct{})
for _, span := range spans {
// For each span, iterate the spanResolver until it's exhausted, storing
// the found range ids in the map to de-duplicate them.
spanResolver.Seek(ctx, span, kvcoord.Ascending)
for {
if !spanResolver.Valid() {
return 0, spanResolver.Error()
}
rangeIds[int64(spanResolver.Desc().RangeID)] = struct{}{}
if !spanResolver.NeedAnother() {
break
}
spanResolver.Next(ctx)
}
}
return len(rangeIds), nil
}
// NumRangesInSpanContainedBy returns the number of ranges that covers
// a span and how many of those ranged are wholly contained in containedBy.
//
// It operates entirely on the current goroutine and is thus able to
// reuse an existing kv.Txn safely.
func NumRangesInSpanContainedBy(
ctx context.Context,
db *kv.DB,
distSQLPlanner *DistSQLPlanner,
outerSpan roachpb.Span,
containedBy []roachpb.Span,
) (total, inContainedBy int, _ error) {
txn := db.NewTxn(ctx, "num-ranges-in-spans")
spanResolver := distSQLPlanner.spanResolver.NewSpanResolverIterator(txn)
// For each span, iterate the spanResolver until it's exhausted, storing
// the found range ids in the map to de-duplicate them.
spanResolver.Seek(ctx, outerSpan, kvcoord.Ascending)
var g roachpb.SpanGroup
g.Add(containedBy...)
for {
if !spanResolver.Valid() {
return 0, 0, spanResolver.Error()
}
total++
desc := spanResolver.Desc()
if g.Encloses(desc.RSpan().AsRawSpanWithNoLocals().Intersect(outerSpan)) {
inContainedBy++
}
if !spanResolver.NeedAnother() {
break
}
spanResolver.Next(ctx)
}
return total, inContainedBy, nil
}
// TODO(adityamaru): Consider moving this to sql/backfill. It has a lot of
// schema changer dependencies which will need to be passed around.
func (sc *SchemaChanger) distIndexBackfill(
ctx context.Context,
version descpb.DescriptorVersion,
targetSpans []roachpb.Span,
addedIndexes []descpb.IndexID,
writeAtRequestTimestamp bool,
filter backfill.MutationFilter,
fractionScaler *multiStageFractionScaler,
) error {
// Gather the initial resume spans for the table.
var todoSpans []roachpb.Span
var mutationIdx int
if err := DescsTxn(ctx, sc.execCfg, func(ctx context.Context, txn *kv.Txn, col *descs.Collection) (err error) {
todoSpans, _, mutationIdx, err = rowexec.GetResumeSpans(
ctx, sc.jobRegistry, txn, sc.execCfg.Codec, col, sc.descID, sc.mutationID, filter)
return err
}); err != nil {
return err
}
log.VEventf(ctx, 2, "indexbackfill: initial resume spans %+v", todoSpans)
if todoSpans == nil {
return nil
}
writeAsOf := sc.job.Details().(jobspb.SchemaChangeDetails).WriteTimestamp
if writeAsOf.IsEmpty() {
if err := sc.job.RunningStatus(ctx, nil /* txn */, func(_ context.Context, _ jobspb.Details) (jobs.RunningStatus, error) {
return jobs.RunningStatus("scanning target index for in-progress transactions"), nil
}); err != nil {
return errors.Wrapf(err, "failed to update running status of job %d", errors.Safe(sc.job.ID()))
}
writeAsOf = sc.clock.Now()
log.Infof(ctx, "starting scan of target index as of %v...", writeAsOf)
// Index backfilling ingests SSTs that don't play nicely with running txns
// since they just add their keys blindly. Running a Scan of the target
// spans at the time the SSTs' keys will be written will calcify history up
// to then since the scan will resolve intents and populate tscache to keep
// anything else from sneaking under us. Since these are new indexes, these
// spans should be essentially empty, so this should be a pretty quick and
// cheap scan.
const pageSize = 10000
noop := func(_ []kv.KeyValue) error { return nil }
if err := sc.fixedTimestampTxn(ctx, writeAsOf, func(
ctx context.Context, txn *kv.Txn, _ *descs.Collection,
) error {
for _, span := range targetSpans {
// TODO(dt): a Count() request would be nice here if the target isn't
// empty, since we don't need to drag all the results back just to
// then ignore them -- we just need the iteration on the far end.
if err := txn.Iterate(ctx, span.Key, span.EndKey, pageSize, noop); err != nil {
return err
}
}
return nil
}); err != nil {
return err
}
log.Infof(ctx, "persisting target safe write time %v...", writeAsOf)
if err := sc.db.Txn(ctx, func(ctx context.Context, txn *kv.Txn) error {
details := sc.job.Details().(jobspb.SchemaChangeDetails)
details.WriteTimestamp = writeAsOf
return sc.job.SetDetails(ctx, txn, details)
}); err != nil {
return err
}
if err := sc.job.RunningStatus(ctx, nil /* txn */, func(_ context.Context, _ jobspb.Details) (jobs.RunningStatus, error) {
return RunningStatusBackfill, nil
}); err != nil {
return errors.Wrapf(err, "failed to update running status of job %d", errors.Safe(sc.job.ID()))
}
} else {
log.Infof(ctx, "writing at persisted safe write time %v...", writeAsOf)
}
readAsOf := sc.clock.Now()
var p *PhysicalPlan
var evalCtx extendedEvalContext
var planCtx *PlanningCtx
// The txn is used to fetch a tableDesc, partition the spans and set the
// evalCtx ts all of which is during planning of the DistSQL flow.
if err := sc.txn(ctx, func(
ctx context.Context, txn *kv.Txn, descriptors *descs.Collection,
) error {
// It is okay to release the lease on the descriptor before running the
// index backfill flow because any schema change that would invalidate the
// index being backfilled, would be queued behind the backfill in the
// mutations slice.
// NB: There are tradeoffs to holding the lease throughout the backfill. It
// results in disallowing certain kinds of schema changes to complete eg:
// changing privileges. There might be a more principled solution in
// dropping and acquiring fresh leases at regular checkpoint but it is not
// clear what this buys us in terms of checking the descriptors validity.
// Thus, in favor of simpler code and no correctness concerns we release
// the lease once the flow is planned.
tableDesc, err := sc.getTableVersion(ctx, txn, descriptors, version)
if err != nil {
return err
}
evalCtx = createSchemaChangeEvalCtx(ctx, sc.execCfg, txn.ReadTimestamp(), descriptors)