-
Notifications
You must be signed in to change notification settings - Fork 3.8k
/
restore_planning.go
2356 lines (2164 loc) · 75.6 KB
/
restore_planning.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 2016 The Cockroach Authors.
//
// Licensed as a CockroachDB Enterprise file under the Cockroach Community
// License (the "License"); you may not use this file except in compliance with
// the License. You may obtain a copy of the License at
//
// https://github.com/cockroachdb/cockroach/blob/master/licenses/CCL.txt
package backupccl
import (
"context"
"fmt"
"go/constant"
"net/url"
"path"
"sort"
"strconv"
"strings"
"github.com/cockroachdb/cockroach/pkg/ccl/multiregionccl"
"github.com/cockroachdb/cockroach/pkg/ccl/storageccl"
"github.com/cockroachdb/cockroach/pkg/ccl/utilccl"
"github.com/cockroachdb/cockroach/pkg/cloud"
"github.com/cockroachdb/cockroach/pkg/featureflag"
"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/roachpb"
"github.com/cockroachdb/cockroach/pkg/server/telemetry"
"github.com/cockroachdb/cockroach/pkg/settings"
"github.com/cockroachdb/cockroach/pkg/sql"
"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/colinfo"
"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/multiregion"
"github.com/cockroachdb/cockroach/pkg/sql/catalog/schemadesc"
"github.com/cockroachdb/cockroach/pkg/sql/catalog/schemaexpr"
"github.com/cockroachdb/cockroach/pkg/sql/catalog/systemschema"
"github.com/cockroachdb/cockroach/pkg/sql/catalog/tabledesc"
"github.com/cockroachdb/cockroach/pkg/sql/catalog/typedesc"
"github.com/cockroachdb/cockroach/pkg/sql/covering"
"github.com/cockroachdb/cockroach/pkg/sql/parser"
"github.com/cockroachdb/cockroach/pkg/sql/pgwire/pgcode"
"github.com/cockroachdb/cockroach/pkg/sql/pgwire/pgerror"
"github.com/cockroachdb/cockroach/pkg/sql/pgwire/pgnotice"
"github.com/cockroachdb/cockroach/pkg/sql/privilege"
"github.com/cockroachdb/cockroach/pkg/sql/roleoption"
"github.com/cockroachdb/cockroach/pkg/sql/sem/tree"
"github.com/cockroachdb/cockroach/pkg/sql/sqlerrors"
"github.com/cockroachdb/cockroach/pkg/sql/types"
"github.com/cockroachdb/cockroach/pkg/util/hlc"
"github.com/cockroachdb/cockroach/pkg/util/log"
"github.com/cockroachdb/cockroach/pkg/util/tracing"
"github.com/cockroachdb/errors"
"github.com/lib/pq/oid"
)
// DescRewriteMap maps old descriptor IDs to new descriptor and parent IDs.
type DescRewriteMap map[descpb.ID]*jobspb.RestoreDetails_DescriptorRewrite
const (
restoreOptIntoDB = "into_db"
restoreOptSkipMissingFKs = "skip_missing_foreign_keys"
restoreOptSkipMissingSequences = "skip_missing_sequences"
restoreOptSkipMissingSequenceOwners = "skip_missing_sequence_owners"
restoreOptSkipMissingViews = "skip_missing_views"
restoreOptSkipLocalitiesCheck = "skip_localities_check"
restoreOptDebugPauseOn = "debug_pause_on"
// The temporary database system tables will be restored into for full
// cluster backups.
restoreTempSystemDB = "crdb_temp_system"
)
var allowedDebugPauseOnValues = map[string]struct{}{
"error": {},
}
// featureRestoreEnabled is used to enable and disable the RESTORE feature.
var featureRestoreEnabled = settings.RegisterBoolSetting(
"feature.restore.enabled",
"set to true to enable restore, false to disable; default is true",
featureflag.FeatureFlagEnabledDefault,
).WithPublic()
// rewriteViewQueryDBNames rewrites the passed table's ViewQuery replacing all
// non-empty db qualifiers with `newDB`.
//
// TODO: this AST traversal misses tables named in strings (#24556).
func rewriteViewQueryDBNames(table *tabledesc.Mutable, newDB string) error {
stmt, err := parser.ParseOne(table.ViewQuery)
if err != nil {
return pgerror.Wrapf(err, pgcode.Syntax,
"failed to parse underlying query from view %q", table.Name)
}
// Re-format to change all DB names to `newDB`.
f := tree.NewFmtCtx(
tree.FmtParsable,
tree.FmtReformatTableNames(func(ctx *tree.FmtCtx, tn *tree.TableName) {
// empty catalog e.g. ``"".information_schema.tables` should stay empty.
if tn.CatalogName != "" {
tn.CatalogName = tree.Name(newDB)
}
ctx.WithReformatTableNames(nil, func() {
ctx.FormatNode(tn)
})
}),
)
f.FormatNode(stmt.AST)
table.ViewQuery = f.CloseAndGetString()
return nil
}
// rewriteTypesInExpr rewrites all explicit ID type references in the input
// expression string according to rewrites.
func rewriteTypesInExpr(expr string, rewrites DescRewriteMap) (string, error) {
parsed, err := parser.ParseExpr(expr)
if err != nil {
return "", err
}
ctx := tree.NewFmtCtx(
tree.FmtSerializable,
tree.FmtIndexedTypeFormat(func(ctx *tree.FmtCtx, ref *tree.OIDTypeReference) {
newRef := ref
var id descpb.ID
id, err = typedesc.UserDefinedTypeOIDToID(ref.OID)
if err != nil {
return
}
if rw, ok := rewrites[id]; ok {
newRef = &tree.OIDTypeReference{OID: typedesc.TypeIDToOID(rw.ID)}
}
ctx.WriteString(newRef.SQLString())
}),
)
if err != nil {
return "", err
}
ctx.FormatNode(parsed)
return ctx.CloseAndGetString(), nil
}
// rewriteSequencesInExpr rewrites all sequence IDs in the input expression
// string according to rewrites.
func rewriteSequencesInExpr(expr string, rewrites DescRewriteMap) (string, error) {
parsed, err := parser.ParseExpr(expr)
if err != nil {
return "", err
}
rewriteFunc := func(expr tree.Expr) (recurse bool, newExpr tree.Expr, err error) {
id, ok := schemaexpr.GetSeqIDFromExpr(expr)
if !ok {
return true, expr, nil
}
annotateTypeExpr, ok := expr.(*tree.AnnotateTypeExpr)
if !ok {
return true, expr, nil
}
rewrite, ok := rewrites[descpb.ID(id)]
if !ok {
return true, expr, nil
}
annotateTypeExpr.Expr = tree.NewNumVal(
constant.MakeInt64(int64(rewrite.ID)),
strconv.Itoa(int(rewrite.ID)),
false, /* negative */
)
return false, annotateTypeExpr, nil
}
newExpr, err := tree.SimpleVisit(parsed, rewriteFunc)
if err != nil {
return "", err
}
return newExpr.String(), nil
}
// rewriteSequencesInView walks the given viewQuery and
// rewrites all sequence IDs in it according to rewrites.
func rewriteSequencesInView(viewQuery string, rewrites DescRewriteMap) (string, error) {
rewriteFunc := func(expr tree.Expr) (recurse bool, newExpr tree.Expr, err error) {
id, ok := schemaexpr.GetSeqIDFromExpr(expr)
if !ok {
return true, expr, nil
}
annotateTypeExpr, ok := expr.(*tree.AnnotateTypeExpr)
if !ok {
return true, expr, nil
}
rewrite, ok := rewrites[descpb.ID(id)]
if !ok {
return true, expr, nil
}
annotateTypeExpr.Expr = tree.NewNumVal(
constant.MakeInt64(int64(rewrite.ID)),
strconv.Itoa(int(rewrite.ID)),
false, /* negative */
)
return false, annotateTypeExpr, nil
}
stmt, err := parser.ParseOne(viewQuery)
if err != nil {
return "", err
}
newStmt, err := tree.SimpleStmtVisit(stmt.AST, rewriteFunc)
if err != nil {
return "", err
}
return newStmt.String(), nil
}
// maybeFilterMissingViews filters the set of tables to restore to exclude views
// whose dependencies are either missing or are themselves unrestorable due to
// missing dependencies, and returns the resulting set of tables. If the
// skipMissingViews option is not set, an error is returned if any
// unrestorable views are found.
func maybeFilterMissingViews(
tablesByID map[descpb.ID]*tabledesc.Mutable,
typesByID map[descpb.ID]*typedesc.Mutable,
skipMissingViews bool,
) (map[descpb.ID]*tabledesc.Mutable, error) {
// Function that recursively determines whether a given table, if it is a
// view, has valid dependencies. Dependencies are looked up in tablesByID.
var hasValidViewDependencies func(desc *tabledesc.Mutable) bool
hasValidViewDependencies = func(desc *tabledesc.Mutable) bool {
if !desc.IsView() {
return true
}
for _, id := range desc.DependsOn {
if depDesc, ok := tablesByID[id]; !ok || !hasValidViewDependencies(depDesc) {
return false
}
}
for _, id := range desc.DependsOnTypes {
if _, ok := typesByID[id]; !ok {
return false
}
}
return true
}
filteredTablesByID := make(map[descpb.ID]*tabledesc.Mutable)
for id, table := range tablesByID {
if hasValidViewDependencies(table) {
filteredTablesByID[id] = table
} else {
if !skipMissingViews {
return nil, errors.Errorf(
"cannot restore view %q without restoring referenced table (or %q option)",
table.Name, restoreOptSkipMissingViews,
)
}
}
}
return filteredTablesByID, nil
}
func synthesizePGTempSchema(
ctx context.Context, p sql.PlanHookState, schemaName string, dbID descpb.ID,
) (descpb.ID, error) {
var synthesizedSchemaID descpb.ID
err := p.ExecCfg().DB.Txn(ctx, func(ctx context.Context, txn *kv.Txn) error {
var err error
sKey := catalogkeys.NewNameKeyComponents(dbID, keys.RootNamespaceID, schemaName)
schemaID, err := catalogkv.GetDescriptorID(ctx, txn, p.ExecCfg().Codec, sKey)
if err != nil {
return err
}
if schemaID != descpb.InvalidID {
return errors.Newf("attempted to synthesize temp schema during RESTORE but found"+
" another schema already using the same schema key %s", sKey.GetName())
}
synthesizedSchemaID, err = catalogkv.GenerateUniqueDescID(ctx, p.ExecCfg().DB, p.ExecCfg().Codec)
if err != nil {
return err
}
return p.CreateSchemaNamespaceEntry(ctx, catalogkeys.EncodeNameKey(p.ExecCfg().Codec, sKey), synthesizedSchemaID)
})
return synthesizedSchemaID, err
}
// allocateDescriptorRewrites determines the new ID and parentID (a "DescriptorRewrite")
// for each table in sqlDescs and returns a mapping from old ID to said
// DescriptorRewrite. It first validates that the provided sqlDescs can be restored
// into their original database (or the database specified in opts) to avoid
// leaking table IDs if we can be sure the restore would fail.
func allocateDescriptorRewrites(
ctx context.Context,
p sql.PlanHookState,
databasesByID map[descpb.ID]*dbdesc.Mutable,
schemasByID map[descpb.ID]*schemadesc.Mutable,
tablesByID map[descpb.ID]*tabledesc.Mutable,
typesByID map[descpb.ID]*typedesc.Mutable,
restoreDBs []catalog.DatabaseDescriptor,
descriptorCoverage tree.DescriptorCoverage,
opts tree.RestoreOptions,
intoDB string,
newDBName string,
) (DescRewriteMap, error) {
descriptorRewrites := make(DescRewriteMap)
restoreDBNames := make(map[string]catalog.DatabaseDescriptor, len(restoreDBs))
for _, db := range restoreDBs {
restoreDBNames[db.GetName()] = db
}
if len(restoreDBNames) > 0 && intoDB != "" {
return nil, errors.Errorf("cannot use %q option when restoring database(s)", restoreOptIntoDB)
}
// The logic at the end of this function leaks table IDs, so fail fast if
// we can be certain the restore will fail.
// Fail fast if the tables to restore are incompatible with the specified
// options.
maxDescIDInBackup := int64(catalogkeys.MinNonDefaultUserDescriptorID(keys.DeprecatedSystemIDChecker()))
for _, table := range tablesByID {
if int64(table.ID) > maxDescIDInBackup {
maxDescIDInBackup = int64(table.ID)
}
// Check that foreign key targets exist.
for i := range table.OutboundFKs {
fk := &table.OutboundFKs[i]
if _, ok := tablesByID[fk.ReferencedTableID]; !ok {
if !opts.SkipMissingFKs {
return nil, errors.Errorf(
"cannot restore table %q without referenced table %d (or %q option)",
table.Name, fk.ReferencedTableID, restoreOptSkipMissingFKs,
)
}
}
}
// Check that referenced sequences exist.
for i := range table.Columns {
col := &table.Columns[i]
// Ensure that all referenced types are present.
if col.Type.UserDefined() {
// TODO (rohany): This can be turned into an option later.
id, err := typedesc.GetUserDefinedTypeDescID(col.Type)
if err != nil {
return nil, err
}
if _, ok := typesByID[id]; !ok {
return nil, errors.Errorf(
"cannot restore table %q without referenced type %d",
table.Name,
id,
)
}
}
for _, seqID := range col.UsesSequenceIds {
if _, ok := tablesByID[seqID]; !ok {
if !opts.SkipMissingSequences {
return nil, errors.Errorf(
"cannot restore table %q without referenced sequence %d (or %q option)",
table.Name, seqID, restoreOptSkipMissingSequences,
)
}
}
}
for _, seqID := range col.OwnsSequenceIds {
if _, ok := tablesByID[seqID]; !ok {
if !opts.SkipMissingSequenceOwners {
return nil, errors.Errorf(
"cannot restore table %q without referenced sequence %d (or %q option)",
table.Name, seqID, restoreOptSkipMissingSequenceOwners)
}
}
}
}
// Handle sequence ownership dependencies.
if table.IsSequence() && table.SequenceOpts.HasOwner() {
if _, ok := tablesByID[table.SequenceOpts.SequenceOwner.OwnerTableID]; !ok {
if !opts.SkipMissingSequenceOwners {
return nil, errors.Errorf(
"cannot restore sequence %q without referenced owner table %d (or %q option)",
table.Name,
table.SequenceOpts.SequenceOwner.OwnerTableID,
restoreOptSkipMissingSequenceOwners,
)
}
}
}
}
// Include the database descriptors when calculating the max ID.
for _, database := range databasesByID {
if int64(database.ID) > maxDescIDInBackup {
maxDescIDInBackup = int64(database.ID)
}
}
// Include the type descriptors when calculating the max ID.
for _, typ := range typesByID {
if int64(typ.ID) > maxDescIDInBackup {
maxDescIDInBackup = int64(typ.ID)
}
}
// Include the schema descriptors when calculating the max ID.
for _, sc := range schemasByID {
if int64(sc.ID) > maxDescIDInBackup {
maxDescIDInBackup = int64(sc.ID)
}
}
needsNewParentIDs := make(map[string][]descpb.ID)
// Increment the DescIDSequenceKey so that it is higher than the max desc ID
// in the backup. This generator keeps produced the next descriptor ID.
var tempSysDBID descpb.ID
if descriptorCoverage == tree.AllDescriptors {
var err error
// Restore the key which generates descriptor IDs.
if err = p.ExecCfg().DB.Txn(ctx, func(ctx context.Context, txn *kv.Txn) error {
b := txn.NewBatch()
// N.B. This key is usually mutated using the Inc command. That
// command warns that if the key was every Put directly, Inc will
// return an error. This is only to ensure that the type of the key
// doesn't change. Here we just need to be very careful that we only
// write int64 values.
// The generator's value should be set to the value of the next ID
// to generate.
b.Put(p.ExecCfg().Codec.DescIDSequenceKey(), maxDescIDInBackup+1)
return txn.Run(ctx, b)
}); err != nil {
return nil, err
}
tempSysDBID, err = catalogkv.GenerateUniqueDescID(ctx, p.ExecCfg().DB, p.ExecCfg().Codec)
if err != nil {
return nil, err
}
// Remap all of the descriptor belonging to system tables to the temp system
// DB.
descriptorRewrites[tempSysDBID] = &jobspb.RestoreDetails_DescriptorRewrite{ID: tempSysDBID}
for _, table := range tablesByID {
if table.GetParentID() == systemschema.SystemDB.GetID() {
descriptorRewrites[table.GetID()] = &jobspb.RestoreDetails_DescriptorRewrite{
ParentID: tempSysDBID,
ParentSchemaID: keys.PublicSchemaIDForBackup,
}
}
}
for _, sc := range schemasByID {
if sc.GetParentID() == systemschema.SystemDB.GetID() {
descriptorRewrites[sc.GetID()] = &jobspb.RestoreDetails_DescriptorRewrite{ParentID: tempSysDBID}
}
}
for _, typ := range typesByID {
if typ.GetParentID() == systemschema.SystemDB.GetID() {
descriptorRewrites[typ.GetID()] = &jobspb.RestoreDetails_DescriptorRewrite{
ParentID: tempSysDBID,
ParentSchemaID: keys.PublicSchemaIDForBackup,
}
}
}
// When restoring a temporary object, the parent schema which the descriptor
// is originally pointing to is never part of the BACKUP. This is because
// the "pg_temp" schema in which temporary objects are created is not
// represented as a descriptor and thus is not picked up during a full
// cluster BACKUP.
// To overcome this orphaned schema pointer problem, when restoring a
// temporary object we create a "fake" pg_temp schema in temp table's db and
// add it to the namespace table.
// We then remap the temporary object descriptors to point to this schema.
// This allows us to piggy back on the temporary
// reconciliation job which looks for "pg_temp" schemas linked to temporary
// sessions and properly cleans up the temporary objects in it.
haveSynthesizedTempSchema := make(map[descpb.ID]bool)
var synthesizedTempSchemaCount int
for _, table := range tablesByID {
if table.IsTemporary() {
if _, ok := haveSynthesizedTempSchema[table.GetParentSchemaID()]; !ok {
var synthesizedSchemaID descpb.ID
var err error
// NB: TemporarySchemaNameForRestorePrefix is a special value that has
// been chosen to trick the reconciliation job into performing our
// cleanup for us. The reconciliation job strips the "pg_temp" prefix
// and parses the remainder of the string into a session ID. It then
// checks the session ID against its active sessions, and performs
// cleanup on the inactive ones.
// We reserve the high bit to be 0 so as to never collide with an
// actual session ID as normally the high bit is the hlc.Timestamp at
// which the cluster was started.
schemaName := sql.TemporarySchemaNameForRestorePrefix +
strconv.Itoa(synthesizedTempSchemaCount)
synthesizedSchemaID, err = synthesizePGTempSchema(ctx, p, schemaName, table.GetParentID())
if err != nil {
return nil, err
}
// Write a schema descriptor rewrite so that we can remap all
// temporary table descs which were under the original session
// specific pg_temp schema to point to this synthesized schema when we
// are performing the table rewrites.
descriptorRewrites[table.GetParentSchemaID()] = &jobspb.RestoreDetails_DescriptorRewrite{ID: synthesizedSchemaID}
haveSynthesizedTempSchema[table.GetParentSchemaID()] = true
synthesizedTempSchemaCount++
}
}
}
}
// Fail fast if the necessary databases don't exist or are otherwise
// incompatible with this restore.
if err := p.ExecCfg().DB.Txn(ctx, func(ctx context.Context, txn *kv.Txn) error {
// Check that any DBs being restored do _not_ exist.
for name := range restoreDBNames {
found, _, err := catalogkv.LookupDatabaseID(ctx, txn, p.ExecCfg().Codec, name)
if err != nil {
return err
}
if found {
return errors.Errorf("database %q already exists", name)
}
}
// TODO (rohany, pbardea): These checks really need to be refactored.
// Construct rewrites for any user defined schemas.
for _, sc := range schemasByID {
if _, ok := descriptorRewrites[sc.ID]; ok {
continue
}
targetDB, err := resolveTargetDB(ctx, txn, p, databasesByID, intoDB, descriptorCoverage, sc)
if err != nil {
return err
}
if _, ok := restoreDBNames[targetDB]; ok {
needsNewParentIDs[targetDB] = append(needsNewParentIDs[targetDB], sc.ID)
} else {
// Look up the parent database's ID.
parentID, parentDB, err := getDatabaseIDAndDesc(ctx, txn, p.ExecCfg().Codec, targetDB)
if err != nil {
return err
}
if err := p.CheckPrivilege(ctx, parentDB, privilege.CREATE); err != nil {
return err
}
// See if there is an existing schema with the same name.
found, id, err := catalogkv.LookupObjectID(ctx, txn, p.ExecCfg().Codec, parentID, keys.RootNamespaceID, sc.Name)
if err != nil {
return err
}
if !found {
// If we didn't find a matching schema, then we'll restore this schema.
descriptorRewrites[sc.ID] = &jobspb.RestoreDetails_DescriptorRewrite{ParentID: parentID}
} else {
// If we found an existing schema, then we need to remap all references
// to this schema to the existing one.
desc, err := catalogkv.MustGetSchemaDescByID(ctx, txn, p.ExecCfg().Codec, id)
if err != nil {
return err
}
descriptorRewrites[sc.ID] = &jobspb.RestoreDetails_DescriptorRewrite{
ParentID: desc.GetParentID(),
ID: desc.GetID(),
ToExisting: true,
}
}
}
}
for _, table := range tablesByID {
// If a descriptor has already been assigned a rewrite, then move on.
if _, ok := descriptorRewrites[table.ID]; ok {
continue
}
targetDB, err := resolveTargetDB(ctx, txn, p, databasesByID, intoDB, descriptorCoverage,
table)
if err != nil {
return err
}
if _, ok := restoreDBNames[targetDB]; ok {
needsNewParentIDs[targetDB] = append(needsNewParentIDs[targetDB], table.ID)
} else if descriptorCoverage == tree.AllDescriptors {
// Set the remapped ID to the original parent ID, except for system tables which
// should be RESTOREd to the temporary system database.
if targetDB != restoreTempSystemDB {
descriptorRewrites[table.ID] = &jobspb.RestoreDetails_DescriptorRewrite{ParentID: table.ParentID}
}
} else {
var parentID descpb.ID
{
found, newParentID, err := catalogkv.LookupDatabaseID(ctx, txn, p.ExecCfg().Codec, targetDB)
if err != nil {
return err
}
if !found {
return errors.Errorf("a database named %q needs to exist to restore table %q",
targetDB, table.Name)
}
parentID = newParentID
}
// Check that the table name is _not_ in use.
// This would fail the CPut later anyway, but this yields a prettier error.
tableName := tree.NewUnqualifiedTableName(tree.Name(table.GetName()))
err := catalogkv.CheckObjectCollision(ctx, txn, p.ExecCfg().Codec, parentID, table.GetParentSchemaID(), tableName)
if err != nil {
return err
}
// Check privileges.
parentDB, err := catalogkv.MustGetDatabaseDescByID(ctx, txn, p.ExecCfg().Codec, parentID)
if err != nil {
return errors.Wrapf(err,
"failed to lookup parent DB %d", errors.Safe(parentID))
}
if err := p.CheckPrivilege(ctx, parentDB, privilege.CREATE); err != nil {
return err
}
// We're restoring a table and not its parent database. We may block
// restoring multi-region tables to multi-region databases since
// regions may mismatch.
if err := checkMultiRegionCompatible(ctx, txn, p.ExecCfg().Codec, table, parentDB); err != nil {
return pgerror.WithCandidateCode(err, pgcode.FeatureNotSupported)
}
// Create the table rewrite with the new parent ID. We've done all the
// up-front validation that we can.
descriptorRewrites[table.ID] = &jobspb.RestoreDetails_DescriptorRewrite{ParentID: parentID}
// If we're restoring to a public schema of database that already exists
// we can populate the rewrite ParentSchemaID field here since we
// already have the database descriptor.
if table.GetParentSchemaID() == keys.PublicSchemaIDForBackup ||
table.GetParentSchemaID() == descpb.InvalidID {
publicSchemaID := parentDB.GetSchemaID(tree.PublicSchema)
descriptorRewrites[table.ID].ParentSchemaID = publicSchemaID
}
}
}
// Iterate through typesByID to construct a remapping entry for each type.
for _, typ := range typesByID {
// If a descriptor has already been assigned a rewrite, then move on.
if _, ok := descriptorRewrites[typ.ID]; ok {
continue
}
targetDB, err := resolveTargetDB(ctx, txn, p, databasesByID, intoDB, descriptorCoverage, typ)
if err != nil {
return err
}
if _, ok := restoreDBNames[targetDB]; ok {
needsNewParentIDs[targetDB] = append(needsNewParentIDs[targetDB], typ.ID)
} else {
// The remapping logic for a type will perform the remapping for a type's
// array type, so don't perform this logic for the array type itself.
if typ.Kind == descpb.TypeDescriptor_ALIAS {
continue
}
// Look up the parent database's ID.
found, parentID, err := catalogkv.LookupDatabaseID(ctx, txn, p.ExecCfg().Codec, targetDB)
if err != nil {
return err
}
if !found {
return errors.Errorf("a database named %q needs to exist to restore type %q",
targetDB, typ.Name)
}
// Check privileges on the parent DB.
parentDB, err := catalogkv.MustGetDatabaseDescByID(ctx, txn, p.ExecCfg().Codec, parentID)
if err != nil {
return errors.Wrapf(err,
"failed to lookup parent DB %d", errors.Safe(parentID))
}
// See if there is an existing type with the same name.
getParentSchemaID := func(typ *typedesc.Mutable) (parentSchemaID descpb.ID) {
parentSchemaID = typ.GetParentSchemaID()
// If we find UDS with same name defined in the restoring DB, use its ID instead.
if rewrite, ok := descriptorRewrites[parentSchemaID]; ok && rewrite.ID != 0 {
parentSchemaID = rewrite.ID
}
return
}
desc, err := catalogkv.GetDescriptorCollidingWithObject(
ctx,
txn,
p.ExecCfg().Codec,
parentID,
getParentSchemaID(typ),
typ.Name,
)
if err != nil {
return err
}
if desc == nil {
// If we didn't find a type with the same name, then mark that we
// need to create the type.
// Ensure that the user has the correct privilege to create types.
if err := p.CheckPrivilege(ctx, parentDB, privilege.CREATE); err != nil {
return err
}
// Create a rewrite entry for the type.
descriptorRewrites[typ.ID] = &jobspb.RestoreDetails_DescriptorRewrite{ParentID: parentID}
// Ensure that there isn't a collision with the array type name.
arrTyp := typesByID[typ.ArrayTypeID]
typeName := tree.NewUnqualifiedTypeName(arrTyp.GetName())
err = catalogkv.CheckObjectCollision(ctx, txn, p.ExecCfg().Codec, parentID, getParentSchemaID(typ), typeName)
if err != nil {
return errors.Wrapf(err, "name collision for %q's array type", typ.Name)
}
// Create the rewrite entry for the array type as well.
descriptorRewrites[arrTyp.ID] = &jobspb.RestoreDetails_DescriptorRewrite{ParentID: parentID}
} else {
// If there was a name collision, we'll try to see if we can remap
// this type to the type existing in the cluster.
// If the collided object isn't a type, then error out.
existingType, isType := desc.(catalog.TypeDescriptor)
if !isType {
return sqlerrors.MakeObjectAlreadyExistsError(desc.DescriptorProto(), typ.Name)
}
// Check if the collided type is compatible to be remapped to.
if err := typ.IsCompatibleWith(existingType); err != nil {
return errors.Wrapf(
err,
"%q is not compatible with type %q existing in cluster",
existingType.GetName(),
existingType.GetName(),
)
}
// Remap both the type and its array type since they are compatible
// with the type existing in the cluster.
descriptorRewrites[typ.ID] = &jobspb.RestoreDetails_DescriptorRewrite{
ParentID: existingType.GetParentID(),
ID: existingType.GetID(),
ToExisting: true,
}
descriptorRewrites[typ.ArrayTypeID] = &jobspb.RestoreDetails_DescriptorRewrite{
ParentID: existingType.GetParentID(),
ID: existingType.GetArrayTypeID(),
ToExisting: true,
}
}
// If we're restoring to a public schema of database that already exists
// we can populate the rewrite ParentSchemaID field here since we
// already have the database descriptor.
if typ.GetParentSchemaID() == keys.PublicSchemaIDForBackup ||
typ.GetParentSchemaID() == descpb.InvalidID {
publicSchemaID := parentDB.GetSchemaID(tree.PublicSchema)
descriptorRewrites[typ.ID].ParentSchemaID = publicSchemaID
descriptorRewrites[typ.ArrayTypeID].ParentSchemaID = publicSchemaID
}
}
}
return nil
}); err != nil {
return nil, err
}
// Allocate new IDs for each database and table.
//
// NB: we do this in a standalone transaction, not one that covers the
// entire restore since restarts would be terrible (and our bulk import
// primitive are non-transactional), but this does mean if something fails
// during restore we've "leaked" the IDs, in that the generator will have
// been incremented.
//
// NB: The ordering of the new IDs must be the same as the old ones,
// otherwise the keys may sort differently after they're rekeyed. We could
// handle this by chunking the AddSSTable calls more finely in Import, but
// it would be a big performance hit.
for _, db := range restoreDBs {
var newID descpb.ID
var err error
if descriptorCoverage == tree.AllDescriptors {
newID = db.GetID()
} else {
newID, err = catalogkv.GenerateUniqueDescID(ctx, p.ExecCfg().DB, p.ExecCfg().Codec)
if err != nil {
return nil, err
}
}
descriptorRewrites[db.GetID()] = &jobspb.RestoreDetails_DescriptorRewrite{ID: newID}
// If a database restore has specified a new name for the restored database,
// then populate the rewrite with the newDBName, else the restored database name is preserved.
if newDBName != "" {
descriptorRewrites[db.GetID()].NewDBName = newDBName
}
for _, objectID := range needsNewParentIDs[db.GetName()] {
descriptorRewrites[objectID] = &jobspb.RestoreDetails_DescriptorRewrite{ParentID: newID}
}
}
// descriptorsToRemap usually contains all tables that are being restored. In a
// full cluster restore this should only include the system tables that need
// to be remapped to the temporary table. All other tables in a full cluster
// backup should have the same ID as they do in the backup.
descriptorsToRemap := make([]catalog.Descriptor, 0, len(tablesByID))
for _, table := range tablesByID {
if descriptorCoverage == tree.AllDescriptors {
if table.ParentID == systemschema.SystemDB.GetID() {
// This is a system table that should be marked for descriptor creation.
descriptorsToRemap = append(descriptorsToRemap, table)
} else {
// This table does not need to be remapped.
descriptorRewrites[table.ID].ID = table.ID
}
} else {
descriptorsToRemap = append(descriptorsToRemap, table)
}
}
// Update the remapping information for type descriptors.
for _, typ := range typesByID {
if descriptorCoverage == tree.AllDescriptors {
// The type doesn't need to be remapped.
descriptorRewrites[typ.ID].ID = typ.ID
} else {
// If the type is marked to be remapped to an existing type in the
// cluster, then we don't want to generate an ID for it.
if !descriptorRewrites[typ.ID].ToExisting {
descriptorsToRemap = append(descriptorsToRemap, typ)
}
}
}
// Update remapping information for schema descriptors.
for _, sc := range schemasByID {
if descriptorCoverage == tree.AllDescriptors {
// The schema doesn't need to be remapped.
descriptorRewrites[sc.ID].ID = sc.ID
} else {
// If this schema isn't being remapped to an existing schema, then
// request to generate an ID for it.
if !descriptorRewrites[sc.ID].ToExisting {
descriptorsToRemap = append(descriptorsToRemap, sc)
}
}
}
sort.Sort(catalog.Descriptors(descriptorsToRemap))
// Generate new IDs for the schemas, tables, and types that need to be
// remapped.
for _, desc := range descriptorsToRemap {
id, err := catalogkv.GenerateUniqueDescID(ctx, p.ExecCfg().DB, p.ExecCfg().Codec)
if err != nil {
return nil, err
}
descriptorRewrites[desc.GetID()].ID = id
}
// Now that the descriptorRewrites contains a complete rewrite entry for every
// schema that is being restored, we can correctly populate the ParentSchemaID
// of all tables and types.
rewriteObject := func(desc catalog.Descriptor) {
if descriptorRewrites[desc.GetID()].ParentSchemaID != descpb.InvalidID {
// The rewrite is already populated for the Schema ID,
// don't rewrite again.
return
}
curSchemaID := desc.GetParentSchemaID()
newSchemaID := curSchemaID
if rw, ok := descriptorRewrites[curSchemaID]; ok {
newSchemaID = rw.ID
}
descriptorRewrites[desc.GetID()].ParentSchemaID = newSchemaID
}
for _, table := range tablesByID {
rewriteObject(table)
}
for _, typ := range typesByID {
rewriteObject(typ)
}
return descriptorRewrites, nil
}
func getDatabaseIDAndDesc(
ctx context.Context, txn *kv.Txn, codec keys.SQLCodec, targetDB string,
) (dbID descpb.ID, dbDesc catalog.DatabaseDescriptor, err error) {
found := false
found, dbID, err = catalogkv.LookupDatabaseID(ctx, txn, codec, targetDB)
if err != nil {
return 0, nil, err
}
if !found {
return 0, nil, errors.Errorf("a database named %q needs to exist", targetDB)
}
// Check privileges on the parent DB.
dbDesc, err = catalogkv.MustGetDatabaseDescByID(ctx, txn, codec, dbID)
if err != nil {
return 0, nil, errors.Wrapf(err,
"failed to lookup parent DB %d", errors.Safe(dbID))
}
return dbID, dbDesc, nil
}
// If we're doing a full cluster restore - to treat defaultdb and postgres
// as regular databases, we drop them before restoring them again in the
// restore.
func dropDefaultUserDBs(ctx context.Context, execCfg *sql.ExecutorConfig) error {
return sql.DescsTxn(ctx, execCfg, func(ctx context.Context, txn *kv.Txn, col *descs.Collection) error {
ie := execCfg.InternalExecutor
_, err := ie.Exec(ctx, "drop-defaultdb", nil, "DROP DATABASE IF EXISTS defaultdb")
if err != nil {
return err
}
_, err = ie.Exec(ctx, "drop-postgres", nil, "DROP DATABASE IF EXISTS postgres")
if err != nil {
return err
}
return nil
})
}
func resolveTargetDB(
ctx context.Context,
txn *kv.Txn,
p sql.PlanHookState,
databasesByID map[descpb.ID]*dbdesc.Mutable,
intoDB string,
descriptorCoverage tree.DescriptorCoverage,
descriptor catalog.Descriptor,
) (string, error) {
if intoDB != "" {
return intoDB, nil
}
c := keys.DeprecatedSystemIDChecker()
if descriptorCoverage == tree.AllDescriptors && catalog.IsSystemID(c, descriptor.GetParentID()) {
var targetDB string
if descriptor.GetParentID() == systemschema.SystemDB.GetID() {
// For full cluster backups, put the system tables in the temporary
// system table.
targetDB = restoreTempSystemDB
}
return targetDB, nil
}
database, ok := databasesByID[descriptor.GetParentID()]
if !ok {
return "", errors.Errorf("no database with ID %d in backup for object %q (%d)",
descriptor.GetParentID(), descriptor.GetName(), descriptor.GetID())
}
return database.Name, nil
}
// maybeUpgradeDescriptors performs post-deserialization upgrades on the
// descriptors.
//
// This is done, for instance, to use the newer 19.2-style foreign key
// representation, if they are not already upgraded.
//
// if skipFKsWithNoMatchingTable is set, FKs whose "other" table is missing from
// the set provided are omitted during the upgrade, instead of causing an error
// to be returned.
func maybeUpgradeDescriptors(
ctx context.Context, descs []catalog.Descriptor, skipFKsWithNoMatchingTable bool,
) error {
descGetter := catalog.MakeMapDescGetter()
// Populate the catalog.DescGetter with all table descriptors in the backup.
for _, desc := range descs {
descGetter.Descriptors[desc.GetID()] = desc
}
for j, desc := range descs {
var b catalog.DescriptorBuilder
if tableDesc, isTable := desc.(catalog.TableDescriptor); isTable {
b = tabledesc.NewBuilderForFKUpgrade(tableDesc.TableDesc(), skipFKsWithNoMatchingTable)
} else {
b = desc.NewBuilder()
}
err := b.RunPostDeserializationChanges(ctx, descGetter)
if err != nil {
return err