forked from cockroachdb/cockroach
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbackup_test.go
11187 lines (9639 loc) · 421 KB
/
backup_test.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.
//
// Use of this software is governed by the CockroachDB Software License
// included in the /LICENSE file.
package backup
import (
"bytes"
"context"
gosql "database/sql"
"encoding/base64"
"encoding/hex"
"fmt"
"hash/crc32"
"io"
"math"
"math/rand"
"net/url"
"os"
"path"
"path/filepath"
"reflect"
"regexp"
"strconv"
"strings"
"sync/atomic"
"syscall"
"testing"
"time"
"github.com/aws/aws-sdk-go-v2/config"
"github.com/cockroachdb/cockroach-go/v2/crdb"
"github.com/cockroachdb/cockroach/pkg/backup/backupbase"
"github.com/cockroachdb/cockroach/pkg/backup/backupdest"
"github.com/cockroachdb/cockroach/pkg/backup/backupencryption"
"github.com/cockroachdb/cockroach/pkg/backup/backupinfo"
"github.com/cockroachdb/cockroach/pkg/backup/backuppb"
"github.com/cockroachdb/cockroach/pkg/backup/backuptestutils"
"github.com/cockroachdb/cockroach/pkg/base"
"github.com/cockroachdb/cockroach/pkg/blobs"
_ "github.com/cockroachdb/cockroach/pkg/ccl/kvccl"
_ "github.com/cockroachdb/cockroach/pkg/ccl/multiregionccl"
_ "github.com/cockroachdb/cockroach/pkg/ccl/multitenantccl"
_ "github.com/cockroachdb/cockroach/pkg/ccl/partitionccl"
"github.com/cockroachdb/cockroach/pkg/ccl/storageccl"
"github.com/cockroachdb/cockroach/pkg/cloud"
"github.com/cockroachdb/cockroach/pkg/cloud/amazon"
"github.com/cockroachdb/cockroach/pkg/cloud/azure"
"github.com/cockroachdb/cockroach/pkg/cloud/cloudpb"
"github.com/cockroachdb/cockroach/pkg/cloud/gcp"
_ "github.com/cockroachdb/cockroach/pkg/cloud/impl" // register cloud storage providers
"github.com/cockroachdb/cockroach/pkg/clusterversion"
"github.com/cockroachdb/cockroach/pkg/jobs"
"github.com/cockroachdb/cockroach/pkg/jobs/jobspb"
"github.com/cockroachdb/cockroach/pkg/jobs/jobstest"
"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/kv/kvpb"
"github.com/cockroachdb/cockroach/pkg/kv/kvserver"
"github.com/cockroachdb/cockroach/pkg/kv/kvserver/protectedts"
"github.com/cockroachdb/cockroach/pkg/kv/kvserver/protectedts/ptutil"
"github.com/cockroachdb/cockroach/pkg/multitenant/mtinfopb"
"github.com/cockroachdb/cockroach/pkg/multitenant/tenantcapabilities"
"github.com/cockroachdb/cockroach/pkg/roachpb"
"github.com/cockroachdb/cockroach/pkg/security/securitytest"
"github.com/cockroachdb/cockroach/pkg/security/username"
"github.com/cockroachdb/cockroach/pkg/settings/cluster"
"github.com/cockroachdb/cockroach/pkg/spanconfig"
"github.com/cockroachdb/cockroach/pkg/sql"
"github.com/cockroachdb/cockroach/pkg/sql/catalog"
"github.com/cockroachdb/cockroach/pkg/sql/catalog/bootstrap"
"github.com/cockroachdb/cockroach/pkg/sql/catalog/descpb"
"github.com/cockroachdb/cockroach/pkg/sql/catalog/descs"
"github.com/cockroachdb/cockroach/pkg/sql/catalog/desctestutils"
"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/isql"
"github.com/cockroachdb/cockroach/pkg/sql/pgwire/pgerror"
"github.com/cockroachdb/cockroach/pkg/sql/randgen"
"github.com/cockroachdb/cockroach/pkg/sql/sem/eval"
"github.com/cockroachdb/cockroach/pkg/sql/sem/tree"
"github.com/cockroachdb/cockroach/pkg/sql/sqltestutils"
"github.com/cockroachdb/cockroach/pkg/sql/stats"
"github.com/cockroachdb/cockroach/pkg/testutils"
"github.com/cockroachdb/cockroach/pkg/testutils/fingerprintutils"
"github.com/cockroachdb/cockroach/pkg/testutils/jobutils"
"github.com/cockroachdb/cockroach/pkg/testutils/serverutils"
"github.com/cockroachdb/cockroach/pkg/testutils/skip"
"github.com/cockroachdb/cockroach/pkg/testutils/sqlutils"
"github.com/cockroachdb/cockroach/pkg/testutils/testcluster"
"github.com/cockroachdb/cockroach/pkg/util"
"github.com/cockroachdb/cockroach/pkg/util/admission"
"github.com/cockroachdb/cockroach/pkg/util/ctxgroup"
"github.com/cockroachdb/cockroach/pkg/util/hlc"
"github.com/cockroachdb/cockroach/pkg/util/ioctx"
"github.com/cockroachdb/cockroach/pkg/util/leaktest"
"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/mon"
"github.com/cockroachdb/cockroach/pkg/util/protoutil"
"github.com/cockroachdb/cockroach/pkg/util/randutil"
"github.com/cockroachdb/cockroach/pkg/util/retry"
"github.com/cockroachdb/cockroach/pkg/util/stop"
"github.com/cockroachdb/cockroach/pkg/util/syncutil"
"github.com/cockroachdb/cockroach/pkg/util/timeutil"
"github.com/cockroachdb/errors"
"github.com/cockroachdb/errors/oserror"
"github.com/cockroachdb/redact"
pgx "github.com/jackc/pgx/v5"
"github.com/kr/pretty"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"golang.org/x/sync/errgroup"
)
func init() {
cloud.RegisterKMSFromURIFactory(MakeTestKMS, "testkms")
}
func makeTableSpan(codec keys.SQLCodec, tableID uint32) roachpb.Span {
k := codec.TablePrefix(tableID)
return roachpb.Span{Key: k, EndKey: k.PrefixEnd()}
}
func TestBackupRestoreStatementResult(t *testing.T) {
defer leaktest.AfterTest(t)()
defer log.Scope(t).Close(t)
const numAccounts = 1
_, sqlDB, dir, cleanupFn := backupRestoreTestSetup(t, singleNode, numAccounts, InitManualReplication)
defer cleanupFn()
if err := backuptestutils.VerifyBackupRestoreStatementResult(
t, sqlDB, "BACKUP DATABASE data INTO $1", localFoo,
); err != nil {
t.Fatal(err)
}
backupPath := getFullBackupPaths(t, sqlDB, localFoo)[0]
// The GZipBackupManifest subtest is to verify that BackupManifest objects
// have been stored in the GZip compressed format.
t.Run("GZipBackupManifest", func(t *testing.T) {
backupDir := fmt.Sprintf("%s/foo", dir)
backupManifestFile := backupDir + backupPath + "/" + backupbase.BackupManifestName
backupManifestBytes, err := os.ReadFile(backupManifestFile)
if err != nil {
t.Fatal(err)
}
require.True(t, backupinfo.IsGZipped(backupManifestBytes))
})
sqlDB.Exec(t, "CREATE DATABASE data2")
if err := backuptestutils.VerifyBackupRestoreStatementResult(
t, sqlDB, "RESTORE TABLE data.* FROM LATEST IN $1 WITH OPTIONS (into_db='data2')", localFoo,
); err != nil {
t.Fatal(err)
}
}
func TestBackupRestoreSingleUserfile(t *testing.T) {
defer leaktest.AfterTest(t)()
defer log.Scope(t).Close(t)
const numAccounts = 1000
ctx := context.Background()
tc, _, _, cleanupFn := backupRestoreTestSetup(t, singleNode, numAccounts, InitManualReplication)
defer cleanupFn()
backupAndRestore(ctx, t, tc, []string{"userfile:///a"}, []string{"userfile:///a"}, numAccounts, nil)
}
func TestBackupRestoreSingleNodeLocal(t *testing.T) {
defer leaktest.AfterTest(t)()
defer log.Scope(t).Close(t)
const numAccounts = 1000
ctx := context.Background()
var chunks int
// Set the testing knob so we count each time we write a checkpoint.
params := base.TestClusterArgs{}
knobs := base.TestingKnobs{
BackupRestore: &sql.BackupRestoreTestingKnobs{
AfterBackupChunk: func() {
chunks++
},
},
}
params.ServerArgs.Knobs = knobs
tc, _, _, cleanupFn := backupRestoreTestSetupWithParams(t, singleNode, numAccounts, InitManualReplication, params)
defer cleanupFn()
backupAndRestore(ctx, t, tc, []string{localFoo}, []string{localFoo}, numAccounts, nil)
// Verify that we sent >0 chunk events to the chunk progress logger.
require.Greater(t, chunks, 0)
}
func TestBackupRestoreMultiNodeLocal(t *testing.T) {
defer leaktest.AfterTest(t)()
defer log.Scope(t).Close(t)
const numAccounts = 1000
ctx := context.Background()
tc, _, _, cleanupFn := backupRestoreTestSetup(t, multiNode, numAccounts, InitManualReplication)
defer cleanupFn()
backupAndRestore(ctx, t, tc, []string{localFoo}, []string{localFoo}, numAccounts, nil)
}
func TestBackupRestoreMultiNodeRemote(t *testing.T) {
defer leaktest.AfterTest(t)()
defer log.Scope(t).Close(t)
const numAccounts = 100
ctx := context.Background()
tc, _, _, cleanupFn := backupRestoreTestSetup(t, multiNode, numAccounts, InitManualReplication)
defer cleanupFn()
// Backing up to node2's local file system
remoteFoo := "nodelocal://2/foo"
backupAndRestore(ctx, t, tc, []string{remoteFoo}, []string{localFoo}, numAccounts, nil)
}
func getLatestFullDir(t *testing.T, sqlDB *sqlutils.SQLRunner, collection string) string {
var fullPath string
sqlDB.QueryRow(t, `SELECT * FROM [SHOW BACKUPS IN $1] LIMIT 1`, collection).Scan(&fullPath)
return fullPath
}
func findSST(t *testing.T, location string) string {
sstMatcher := regexp.MustCompile(`\d+\.sst`)
subDir := filepath.Join(location, "data")
files, err := os.ReadDir(subDir)
if err != nil {
if oserror.IsNotExist(err) {
return ""
}
t.Fatal(err)
}
for _, f := range files {
if sstMatcher.MatchString(f.Name()) {
return f.Name()
}
}
return ""
}
func requireHasSSTs(t *testing.T, locations ...string) {
for _, location := range locations {
require.NotEqual(t, "", findSST(t, location))
}
}
func requireHasNoSSTs(t *testing.T, locations ...string) {
for _, location := range locations {
require.Equal(t, "", findSST(t, location))
}
}
// ensureLeaseholder ensures that each node has at least one leaseholder. These
// are wrapped with SucceedsSoon() because EXPERIMENTAL_RELOCATE can fail if
// there are other replication changes happening.
func ensureLeaseholder(t *testing.T, sqlDB *sqlutils.SQLRunner) {
// Anything that is calling this to ensure *leaseholders* probably cares about
// the work going to the leaseholders as it did before follower reads.
sqlDB.Exec(t, `SET CLUSTER SETTING bulkio.backup.balanced_distribution.enabled = false`)
for _, stmt := range []string{
`ALTER TABLE data.bank SPLIT AT VALUES (0)`,
`ALTER TABLE data.bank SPLIT AT VALUES (100)`,
`ALTER TABLE data.bank SPLIT AT VALUES (200)`,
`ALTER TABLE data.bank EXPERIMENTAL_RELOCATE VALUES (ARRAY[1], 0)`,
`ALTER TABLE data.bank EXPERIMENTAL_RELOCATE VALUES (ARRAY[2], 100)`,
`ALTER TABLE data.bank EXPERIMENTAL_RELOCATE VALUES (ARRAY[3], 200)`,
} {
testutils.SucceedsSoon(t, func() error {
_, err := sqlDB.DB.ExecContext(context.Background(), stmt)
return err
})
}
}
func TestBackupRestorePartitioned(t *testing.T) {
defer leaktest.AfterTest(t)()
defer log.Scope(t).Close(t)
const numAccounts = 1000
// Disabled to run within tenant as certain MR features are not available to tenants.
args := base.TestClusterArgs{
ServerArgs: base.TestServerArgs{
DefaultTestTenant: base.TODOTestTenantDisabled,
},
ServerArgsPerNode: map[int]base.TestServerArgs{
0: {
Locality: roachpb.Locality{Tiers: []roachpb.Tier{
{Key: "region", Value: "west"},
// NB: This has the same value as an az in the east region
// on purpose.
{Key: "az", Value: "az1"},
{Key: "dc", Value: "dc1"},
}},
},
1: {
Locality: roachpb.Locality{Tiers: []roachpb.Tier{
{Key: "region", Value: "east"},
// NB: This has the same value as an az in the west region
// on purpose.
{Key: "az", Value: "az1"},
{Key: "dc", Value: "dc2"},
}},
},
2: {
Locality: roachpb.Locality{Tiers: []roachpb.Tier{
{Key: "region", Value: "east"},
{Key: "az", Value: "az2"},
{Key: "dc", Value: "dc3"},
}},
},
},
}
_, sqlDB, dir, cleanupFn := backupRestoreTestSetupWithParams(t, 3 /* nodes */, numAccounts, InitManualReplication, args)
defer cleanupFn()
// dirOf converts backup URIs based on localFoo to the temporary
// file it represents on disk.
dirOf := func(location string) string {
return strings.Replace(location, localFoo, filepath.Join(dir, "foo"), 1)
}
requireCompressedManifest := func(t *testing.T, locations ...string) {
partitionMatcher := regexp.MustCompile(`^BACKUP_PART_`)
for _, location := range locations {
subDir := dirOf(location)
files, err := os.ReadDir(subDir)
if err != nil {
t.Fatal(err)
}
for _, f := range files {
fName := f.Name()
if partitionMatcher.MatchString(fName) {
backupPartitionFile := subDir + "/" + fName
backupPartitionBytes, err := os.ReadFile(backupPartitionFile)
if err != nil {
t.Fatal(err)
}
require.True(t, backupinfo.IsGZipped(backupPartitionBytes))
}
}
}
}
runBackupRestore := func(t *testing.T, sqlDB *sqlutils.SQLRunner, backupURIs []string) {
locationFmtString, locationURIArgs := uriFmtStringAndArgs(backupURIs, 0)
backupQuery := fmt.Sprintf("BACKUP DATABASE data INTO %s", locationFmtString)
sqlDB.Exec(t, backupQuery, locationURIArgs...)
sqlDB.Exec(t, `DROP DATABASE data;`)
restoreQuery := fmt.Sprintf("RESTORE DATABASE data FROM LATEST IN %s", locationFmtString)
sqlDB.Exec(t, restoreQuery, locationURIArgs...)
}
t.Run("partition-by-unique-key", func(t *testing.T) {
ensureLeaseholder(t, sqlDB)
testSubDir := t.Name()
locations := []string{
localFoo + "/" + testSubDir + "/1",
localFoo + "/" + testSubDir + "/2",
localFoo + "/" + testSubDir + "/3",
}
backupURIs := []string{
// The first location will contain data from node 3 with config
// dc=dc3.
fmt.Sprintf("%s?COCKROACH_LOCALITY=%s", locations[0], url.QueryEscape("default")),
fmt.Sprintf("%s?COCKROACH_LOCALITY=%s", locations[1], url.QueryEscape("dc=dc1")),
fmt.Sprintf("%s?COCKROACH_LOCALITY=%s", locations[2], url.QueryEscape("dc=dc2")),
}
runBackupRestore(t, sqlDB, backupURIs)
backupPath := getFullBackupPaths(t, sqlDB, locations[0])[0]
backupPaths := util.Map(locations, func(uri string) string {
return uri + backupPath
})
// Verify that at least one SST exists in each backup destination.
requireHasSSTs(t, dirOf(backupPaths[0]), dirOf(backupPaths[1]), dirOf(backupPaths[2]))
// Verify that all of the partition manifests are compressed.
requireCompressedManifest(t, backupPaths...)
})
// Test that we're selecting the most specific locality tier for a location.
t.Run("partition-by-different-tiers", func(t *testing.T) {
ensureLeaseholder(t, sqlDB)
testSubDir := t.Name()
locations := []string{
localFoo + "/" + testSubDir + "/1",
localFoo + "/" + testSubDir + "/2",
localFoo + "/" + testSubDir + "/3",
localFoo + "/" + testSubDir + "/4",
}
backupURIs := []string{
fmt.Sprintf("%s?COCKROACH_LOCALITY=%s", locations[0], url.QueryEscape("default")),
fmt.Sprintf("%s?COCKROACH_LOCALITY=%s", locations[1], url.QueryEscape("region=east")),
fmt.Sprintf("%s?COCKROACH_LOCALITY=%s", locations[2], url.QueryEscape("az=az1")),
fmt.Sprintf("%s?COCKROACH_LOCALITY=%s", locations[3], url.QueryEscape("az=az2")),
}
runBackupRestore(t, sqlDB, backupURIs)
backupPath := getFullBackupPaths(t, sqlDB, locations[0])[0]
backupPaths := util.Map(locations, func(uri string) string {
return uri + backupPath
})
// All data should be covered by az=az1 or az=az2, so expect all the
// data on those locations.
requireHasNoSSTs(t, dirOf(backupPaths[0]), dirOf(backupPaths[1]))
requireHasSSTs(t, dirOf(backupPaths[2]), dirOf(backupPaths[3]))
})
t.Run("partition-by-several-keys", func(t *testing.T) {
ensureLeaseholder(t, sqlDB)
testSubDir := t.Name()
locations := []string{
localFoo + "/" + testSubDir + "/1",
localFoo + "/" + testSubDir + "/2",
localFoo + "/" + testSubDir + "/3",
localFoo + "/" + testSubDir + "/4",
}
backupURIs := []string{
fmt.Sprintf("%s?COCKROACH_LOCALITY=%s", locations[0], url.QueryEscape("default")),
fmt.Sprintf("%s?COCKROACH_LOCALITY=%s", locations[1], url.QueryEscape("region=east,az=az1")),
fmt.Sprintf("%s?COCKROACH_LOCALITY=%s", locations[2], url.QueryEscape("region=east,az=az2")),
fmt.Sprintf("%s?COCKROACH_LOCALITY=%s", locations[3], url.QueryEscape("region=west,az=az1")),
}
// Specifying multiple tiers is not supported.
locationFmtString, locationURIArgs := uriFmtStringAndArgs(backupURIs, 0)
backupQuery := fmt.Sprintf("BACKUP DATABASE data INTO %s", locationFmtString)
sqlDB.ExpectErr(t, `tier must be in the form "key=value" not "region=east,az=az1"`, backupQuery, locationURIArgs...)
})
}
func TestBackupRestoreExecLocality(t *testing.T) {
defer leaktest.AfterTest(t)()
defer log.Scope(t).Close(t)
const numAccounts = 1000
// Disabled to run within tenant as certain MR features are not available to tenants.
args := base.TestClusterArgs{
ServerArgs: base.TestServerArgs{
DefaultTestTenant: base.TODOTestTenantDisabled,
},
ServerArgsPerNode: map[int]base.TestServerArgs{
0: {
ExternalIODir: "/west0",
Locality: roachpb.Locality{Tiers: []roachpb.Tier{
{Key: "tier", Value: "0"},
{Key: "region", Value: "west"},
}},
},
1: {
ExternalIODir: "/west1",
Locality: roachpb.Locality{Tiers: []roachpb.Tier{
{Key: "tier", Value: "1"},
{Key: "region", Value: "west"},
}},
},
2: {
ExternalIODir: "/east0",
Locality: roachpb.Locality{Tiers: []roachpb.Tier{
{Key: "tier", Value: "0"},
{Key: "region", Value: "east"},
}},
},
3: {
ExternalIODir: "/east1",
Locality: roachpb.Locality{Tiers: []roachpb.Tier{
{Key: "tier", Value: "1"},
{Key: "region", Value: "east"},
}},
},
},
}
tc, sqlDB, dir, cleanupFn := backupRestoreTestSetupWithParams(t, 4 /* nodes */, numAccounts, InitManualReplication, args)
defer cleanupFn()
// Job exec relocation will return an error while it waits for resumption on a
// matching node, but this makes for a slow test, so just send the job stmt to
// the node which will not need to relocate the coordination, i.e. n3 or n4.
n3, n4 := sqlutils.MakeSQLRunner(tc.Conns[2]), sqlutils.MakeSQLRunner(tc.Conns[3])
t.Run("pin-top", func(t *testing.T) {
ensureLeaseholder(t, sqlDB)
uri := "nodelocal://0/a"
n3.Exec(t, "BACKUP DATABASE data INTO $1 WITH EXECUTION LOCALITY = $2",
uri, "tier=0")
// Check that at least one tier 0 node dir has an SST in it.
subdir := getLatestFullDir(t, n3, uri)
require.True(t, findSST(t, path.Join(dir, "west0", "a", subdir)) != "" || findSST(t, path.Join(dir, "east0", "a", subdir)) != "")
// Check that neither tier 1 node dir has an sst.
requireHasNoSSTs(t, path.Join(dir, "west1", "a", subdir), path.Join(dir, "east1", "a", subdir))
})
t.Run("pin-mid", func(t *testing.T) {
ensureLeaseholder(t, sqlDB)
uri := "nodelocal://0/b"
n4.Exec(t, "BACKUP DATABASE data INTO $1 WITH EXECUTION LOCALITY = $2",
uri, "region=east")
subdir := getLatestFullDir(t, n4, uri)
// Check that at least one east node dir has an SST in it.
require.True(t, findSST(t, path.Join(dir, "east0", "b", subdir)) != "" || findSST(t, path.Join(dir, "east1", "b", subdir)) != "")
// Check that neither west node dir has an sst.
requireHasNoSSTs(t, path.Join(dir, "west0", "b", subdir), path.Join(dir, "west1", "b", subdir))
})
t.Run("pin-single", func(t *testing.T) {
ensureLeaseholder(t, sqlDB)
uri := "nodelocal://0/c"
n4.Exec(t, "BACKUP DATABASE data INTO $1 WITH EXECUTION LOCALITY = $2",
uri, "tier=1,region=east")
subdir := getLatestFullDir(t, n4, uri)
// Check that at least the only node allowed has data in it.
requireHasSSTs(t, path.Join(dir, "east1", "c", subdir))
// Check that no other node has data in it.
requireHasNoSSTs(t, path.Join(dir, "east0", "c", subdir), path.Join(dir, "west0", "c", subdir), path.Join(dir, "west1", "c", subdir))
// TODO(dt): ideally we'd send the RESTORE stmt to a node that cannot reach
// the backup files at all to show that the locality filter means a node
// which _can_ reach the files then runs it and it succeeds, however RESTORE
// _statement_ evaluation, to even create the job, requires reading the from
// the backup to verify it can be restored at all. Thus while specifying an
// execution locality filter is useful for restricting the execution to only
// those nodes with access to the data files, it is still on the operator to
// send the initial statement to a node with access.
var id int64
n4.QueryRow(t, "RESTORE DATABASE data FROM LATEST IN $1 WITH EXECUTION LOCALITY = $2, NEW_DB_NAME = 'restored', DETACHED",
"nodelocal://0/c", "tier=1,region=east").Scan(&id)
n4.CheckQueryResults(t, fmt.Sprintf("SELECT status FROM [SHOW JOB WHEN COMPLETE %d]", id), [][]string{{"succeeded"}})
})
}
// TestBackupManifestFileCount tests that we don't get more than 1 file per node
// in a case where we know that the entire dataset should fit inside the
// file_sst_sink reorder buffer.
func TestBackupManifestFileCount(t *testing.T) {
defer leaktest.AfterTest(t)()
defer log.Scope(t).Close(t)
skip.UnderRace(t, "multinode cluster setup times out under race, likely due to resource starvation.")
const numAccounts = 1000
_, sqlDB, _, cleanupFn := backupRestoreTestSetup(t, multiNode, numAccounts, InitManualReplication)
defer cleanupFn()
sqlDB.Exec(t, "BACKUP INTO 'userfile:///backup'")
rows := sqlDB.QueryRow(t, "SELECT count(distinct(path)) FROM [SHOW BACKUP FILES FROM LATEST IN 'userfile:///backup']")
var count int
rows.Scan(&count)
// We expect no more than (# of backup processors) file per backup processor
require.True(t, multiNode*6 >= count)
}
func TestBackupRestoreAppend(t *testing.T) {
defer leaktest.AfterTest(t)()
defer log.Scope(t).Close(t)
skip.UnderDuress(t, "test is very large")
params := base.TestClusterArgs{
ServerArgs: base.TestServerArgs{
Knobs: base.TestingKnobs{
// NB: Not routing to the leaseholder first
// slows down this test by anywhere from 5x to
// 10x.
KVClient: &kvcoord.ClientTestingKnobs{RouteToLeaseholderFirst: true},
},
},
}
const numAccounts = 400
ctx := context.Background()
tc, sqlDB, tmpDir, cleanupFn := backupRestoreTestSetupWithParams(t, multiNode, numAccounts, InitManualReplication, params)
defer cleanupFn()
if tc.DefaultTenantDeploymentMode().IsExternal() {
tc.GrantTenantCapabilities(
ctx, t, serverutils.TestTenantID(),
map[tenantcapabilities.ID]string{tenantcapabilities.CanAdminRelocateRange: "true"})
}
// Ensure that each node has at least one leaseholder. (These splits were
// made in backupRestoreTestSetup.) These are wrapped with SucceedsSoon()
// because EXPERIMENTAL_RELOCATE can fail if there are other replication
// changes happening.
for _, stmt := range []string{
`ALTER TABLE data.bank EXPERIMENTAL_RELOCATE VALUES (ARRAY[1], 0)`,
`ALTER TABLE data.bank EXPERIMENTAL_RELOCATE VALUES (ARRAY[2], 100)`,
`ALTER TABLE data.bank EXPERIMENTAL_RELOCATE VALUES (ARRAY[3], 200)`,
} {
testutils.SucceedsSoon(t, func() error {
_, err := sqlDB.DB.ExecContext(ctx, stmt)
return err
})
}
// For testing backup *into* collection, pick collection
// shards on each node.
collections := []interface{}{
fmt.Sprintf("nodelocal://1/?COCKROACH_LOCALITY=%s", url.QueryEscape("default")),
fmt.Sprintf("nodelocal://2/?COCKROACH_LOCALITY=%s", url.QueryEscape("dc=dc1")),
fmt.Sprintf("nodelocal://3/?COCKROACH_LOCALITY=%s", url.QueryEscape("dc=dc2")),
}
// Test timeline
//
// tsBefore - Full backup
// ts1 - Incremental backup after UPDATE
// ts1again - Incremental backup (no changes to data.bank)
// ts2 - Full backup after UPDATE
// - Incremental backup after rename
var tsBefore, ts1, ts1again, ts2 string
sqlDB.QueryRow(t, "SELECT cluster_logical_timestamp()").Scan(&tsBefore)
sqlDB.Exec(t, "BACKUP INTO ($1, $2, $3) AS OF SYSTEM TIME "+tsBefore, collections...)
sqlDB.Exec(t, "UPDATE data.bank SET balance = 100")
sqlDB.QueryRow(t, "SELECT cluster_logical_timestamp()").Scan(&ts1)
sqlDB.Exec(t, "BACKUP INTO LATEST IN ($1, $2, $3) AS OF SYSTEM TIME "+ts1, collections...)
// Append to latest again, just to prove we can append to an appended one and
// that appended didn't e.g. mess up LATEST.
sqlDB.QueryRow(t, "SELECT cluster_logical_timestamp()").Scan(&ts1again)
sqlDB.Exec(t, "BACKUP INTO LATEST IN ($1, $2, $3) AS OF SYSTEM TIME "+ts1again, collections...)
sqlDB.Exec(t, "UPDATE data.bank SET balance = 200")
sqlDB.QueryRow(t, "SELECT cluster_logical_timestamp()").Scan(&ts2)
rowsTS2 := sqlDB.QueryStr(t, "SELECT * from data.bank ORDER BY id")
// Start a new full-backup in the collection version.
sqlDB.Exec(t, "BACKUP INTO ($1, $2, $3) AS OF SYSTEM TIME "+ts2, collections...)
sqlDB.Exec(t, "ALTER TABLE data.bank RENAME TO data.renamed")
sqlDB.Exec(t, "BACKUP INTO LATEST IN ($1, $2, $3)", collections...)
// TODO(dt): prevent backing up different targets to same collection?
sqlDB.Exec(t, "DROP DATABASE data CASCADE")
sqlDB.Exec(t, "RESTORE DATABASE data FROM LATEST IN ($1, $2, $3)", collections...)
sqlDB.ExpectErr(t, "relation \"data.bank\" does not exist", "SELECT * FROM data.bank ORDER BY id")
sqlDB.CheckQueryResults(t, "SELECT * from data.renamed ORDER BY id", rowsTS2)
findFullBackupPaths := func(baseDir, glob string) (string, string) {
matches, err := filepath.Glob(glob)
require.NoError(t, err)
require.Equal(t, 2, len(matches))
for i := range matches {
matches[i] = strings.TrimPrefix(filepath.Dir(matches[i]), baseDir)
}
return matches[0], matches[1]
}
// Find the backup times in the collection and try RESTORE'ing to each, and
// within each also check if we can restore to individual times captured with
// incremental backups that were appended to that backup.
fullBackup1, fullBackup2 := findFullBackupPaths(tmpDir, path.Join(tmpDir, "*/*/*/"+backupbase.BackupManifestName))
sqlDB.Exec(t, "DROP DATABASE data CASCADE")
sqlDB.Exec(t, "RESTORE DATABASE data FROM $4 IN ($1, $2, $3) AS OF SYSTEM TIME "+tsBefore,
append(collections, fullBackup1)...)
sqlDB.Exec(t, "DROP DATABASE data CASCADE")
sqlDB.Exec(t, "RESTORE DATABASE data FROM $4 IN ($1, $2, $3) AS OF SYSTEM TIME "+ts1,
append(collections, fullBackup1)...)
sqlDB.Exec(t, "DROP DATABASE data CASCADE")
sqlDB.Exec(t, "RESTORE DATABASE data FROM $4 IN ($1, $2, $3) AS OF SYSTEM TIME "+ts1again,
append(collections, fullBackup1)...)
sqlDB.Exec(t, "DROP DATABASE data CASCADE")
sqlDB.Exec(t, "RESTORE DATABASE data FROM $4 IN ($1, $2, $3) AS OF SYSTEM TIME "+ts2, append(collections, fullBackup2)...)
_, sqlDBRestore, cleanupEmptyCluster := backupRestoreTestSetupEmpty(t, multiNode, tmpDir, InitManualReplication, params)
defer cleanupEmptyCluster()
sqlDBRestore.Exec(t, "RESTORE FROM $4 IN ($1, $2, $3) AS OF SYSTEM TIME "+ts2, append(collections, fullBackup2)...)
// TODO(dt): test restoring to other backups via AOST.
}
func TestBackupAndRestoreJobDescription(t *testing.T) {
defer leaktest.AfterTest(t)()
defer log.Scope(t).Close(t)
skip.UnderRace(t, "this test is heavyweight and is not expected to reveal any direct bugs under stress race")
const numAccounts = 1
_, sqlDB, tmpDir, cleanupFn := backupRestoreTestSetup(t, multiNode, numAccounts, InitManualReplication)
defer cleanupFn()
const c1, c2, c3 = `nodelocal://1/full/`, `nodelocal://2/full/`, `nodelocal://3/full/`
const i1, i2, i3 = `nodelocal://1/inc/`, `nodelocal://3/inc/`, `nodelocal://3/inc/`
collections := []interface{}{
fmt.Sprintf("%s?COCKROACH_LOCALITY=%s", c1, url.QueryEscape("default")),
fmt.Sprintf("%s?COCKROACH_LOCALITY=%s", c2, url.QueryEscape("dc=dc1")),
fmt.Sprintf("%s?COCKROACH_LOCALITY=%s", c3, url.QueryEscape("dc=dc2")),
}
incrementals := []interface{}{
fmt.Sprintf("%s?COCKROACH_LOCALITY=%s", i1, url.QueryEscape("default")),
fmt.Sprintf("%s?COCKROACH_LOCALITY=%s", i2, url.QueryEscape("dc=dc1")),
fmt.Sprintf("%s?COCKROACH_LOCALITY=%s", i3, url.QueryEscape("dc=dc2")),
}
sqlDB.Exec(t, "BACKUP INTO ($1, $2, $3)", collections...)
sqlDB.Exec(t, "BACKUP INTO LATEST IN ($1, $2, $3)", collections...)
sqlDB.Exec(t, "BACKUP INTO LATEST IN ($1, $2, $3) WITH incremental_location=($4, $5, $6)",
append(collections, incrementals...)...)
sqlDB.ExpectErr(t, "the incremental_location option must contain the same number of locality",
"BACKUP INTO LATEST IN $4 WITH incremental_location=($1, $2, $3)",
append(incrementals, collections[0])...)
sqlDB.ExpectErr(t, "No full backup exists in \"/subdir\" to append an incremental backup to. To take a full backup, remove the subdirectory from the backup command",
"BACKUP INTO $4 IN ($1, $2, $3)", append(collections, "subdir")...)
time.Sleep(time.Second + 2)
sqlDB.Exec(t, "BACKUP INTO ($1, $2, $3) AS OF SYSTEM TIME '-1s'", collections...)
// Find the subdirectory created by the full BACKUP INTO statement.
matches, err := filepath.Glob(path.Join(tmpDir, "full/*/*/*/"+backupbase.BackupManifestName))
require.NoError(t, err)
require.Equal(t, 2, len(matches))
for i := range matches {
matches[i] = strings.TrimPrefix(filepath.Dir(matches[i]), tmpDir)
}
full1 := strings.TrimPrefix(matches[0], "/full")
asOf1 := strings.TrimPrefix(matches[1], "/full")
sqlDB.CheckQueryResults(
t, "SELECT description FROM crdb_internal.jobs WHERE job_type = 'BACKUP' AND status != 'failed'",
[][]string{
{fmt.Sprintf("BACKUP INTO '%s' IN ('%s', '%s', '%s')", full1, collections[0],
collections[1], collections[2])},
{fmt.Sprintf("BACKUP INTO '%s' IN ('%s', '%s', '%s')", full1,
collections[0], collections[1], collections[2])},
{fmt.Sprintf("BACKUP INTO '%s' IN ('%s', '%s', '%s') WITH OPTIONS (incremental_location = ('%s', '%s', '%s'))",
full1, collections[0], collections[1], collections[2], incrementals[0],
incrementals[1], incrementals[2])},
{fmt.Sprintf("BACKUP INTO '%s' IN ('%s', '%s', '%s') AS OF SYSTEM TIME '-1s'", asOf1, collections[0],
collections[1], collections[2])},
},
)
sqlDB.CheckQueryResults(t, "SELECT description FROM crdb_internal.jobs WHERE job_type = 'BACKUP' AND status = 'failed'",
[][]string{{fmt.Sprintf("BACKUP INTO '%s' IN ('%s', '%s', '%s')", "/subdir", collections[0],
collections[1], collections[2])}})
sqlDB.Exec(t, "DROP DATABASE data CASCADE")
sqlDB.Exec(t, "RESTORE DATABASE data FROM $4 IN ($1, $2, $3)", append(collections, full1)...)
sqlDB.Exec(t, "DROP DATABASE data CASCADE")
sqlDB.Exec(t, "RESTORE DATABASE data FROM $7 IN ($1, $2, "+
"$3) WITH incremental_location=($4, $5, $6)",
append(collections, incrementals[0], incrementals[1], incrementals[2], full1)...)
// Test restoring from the AOST backup
sqlDB.Exec(t, "DROP DATABASE data CASCADE")
sqlDB.Exec(t, "RESTORE DATABASE data FROM LATEST IN ($1, $2, $3)", collections...)
sqlDB.Exec(t, "DROP DATABASE data CASCADE")
sqlDB.Exec(t, "RESTORE DATABASE data FROM $4 IN ($1, $2, $3)", append(collections, asOf1)...)
sqlDB.CheckQueryResults(
t, "SELECT description FROM crdb_internal.jobs WHERE job_type='RESTORE' ORDER BY created",
[][]string{
{fmt.Sprintf("RESTORE DATABASE data FROM '%s' IN ('%s', '%s', '%s')",
full1, collections[0], collections[1], collections[2])},
{fmt.Sprintf("RESTORE DATABASE data FROM '%s' IN ('%s', '%s', '%s') WITH OPTIONS (incremental_location = ('%s', '%s', '%s'))",
full1, collections[0], collections[1], collections[2],
incrementals[0], incrementals[1], incrementals[2])},
{fmt.Sprintf("RESTORE DATABASE data FROM '%s' IN ('%s', '%s', '%s')",
asOf1, collections[0], collections[1], collections[2])},
// and again from LATEST IN...
{fmt.Sprintf("RESTORE DATABASE data FROM '%s' IN ('%s', '%s', '%s')",
asOf1, collections[0], collections[1], collections[2])},
},
)
}
func TestBackupRestorePartitionedMergeDirectories(t *testing.T) {
defer leaktest.AfterTest(t)()
defer log.Scope(t).Close(t)
const numAccounts = 1000
ctx := context.Background()
tc, _, _, cleanupFn := backupRestoreTestSetup(t, multiNode, numAccounts, InitManualReplication)
defer cleanupFn()
// TODO (lucy): This test writes a partitioned backup where all files are
// written to the same directory, which is similar to the case where a backup
// is created and then all files are consolidated into the same directory, but
// we should still have a separate test where the files are actually moved.
const localFoo1 = localFoo + "/1"
backupURIs := []string{
fmt.Sprintf("%s?COCKROACH_LOCALITY=%s", localFoo1, url.QueryEscape("default")),
fmt.Sprintf("%s?COCKROACH_LOCALITY=%s", localFoo1, url.QueryEscape("dc=dc1")),
fmt.Sprintf("%s?COCKROACH_LOCALITY=%s", localFoo1, url.QueryEscape("dc=dc2")),
}
restoreURIs := []string{
localFoo1,
}
backupAndRestore(ctx, t, tc, backupURIs, restoreURIs, numAccounts, nil)
}
func TestBackupRestoreEmpty(t *testing.T) {
defer leaktest.AfterTest(t)()
defer log.Scope(t).Close(t)
const numAccounts = 0
ctx := context.Background()
tc, _, _, cleanupFn := backupRestoreTestSetup(t, singleNode, numAccounts, InitManualReplication)
defer cleanupFn()
backupAndRestore(ctx, t, tc, []string{localFoo}, []string{localFoo}, numAccounts, nil)
}
// Regression test for #16008. In short, the way RESTORE constructed split keys
// for tables with negative primary key data caused AdminSplit to fail.
func TestBackupRestoreNegativePrimaryKey(t *testing.T) {
defer leaktest.AfterTest(t)()
defer log.Scope(t).Close(t)
skip.UnderRace(t, "test is too slow to run under race, presumably because of the multiple splits")
const numAccounts = 1000
ctx := context.Background()
tc, sqlDB, _, cleanupFn := backupRestoreTestSetup(t, multiNode, numAccounts, InitManualReplication)
defer cleanupFn()
// Give half the accounts negative primary keys.
sqlDB.Exec(t, `UPDATE data.bank SET id = $1 - id WHERE id > $1`, numAccounts/2)
// Resplit that half of the table space.
sqlDB.Exec(t,
`ALTER TABLE data.bank SPLIT AT SELECT generate_series($1, 0, $2)`,
-numAccounts/2, numAccounts/backupRestoreDefaultRanges/2,
)
backupAndRestore(ctx, t, tc, []string{localFoo}, []string{localFoo}, numAccounts, nil)
sqlDB.Exec(t, `CREATE UNIQUE INDEX id2 ON data.bank (id)`)
var unused string
var exportedRows int
sqlDB.QueryRow(t, `BACKUP DATABASE data INTO $1`, localFoo+"/alteredPK").Scan(
&unused, &unused, &unused, &exportedRows,
)
if exportedRows != numAccounts {
t.Fatalf("expected %d rows, got %d", numAccounts, exportedRows)
}
}
func backupAndRestore(
ctx context.Context,
t *testing.T,
tc *testcluster.TestCluster,
backupURIs []string,
restoreURIs []string,
numAccounts int,
kmsURIs []string,
) {
conn := tc.Conns[0]
sqlDB := sqlutils.MakeSQLRunner(conn)
storageConn := tc.SystemLayer(0).SQLConn(t)
storageSQLDB := sqlutils.MakeSQLRunner(storageConn)
storageSQLDB.Exec(t, "SET DATABASE=defaultdb")
{
sqlDB.Exec(t, `CREATE INDEX balance_idx ON data.bank (balance)`)
testutils.SucceedsSoon(t, func() error {
var unused string
var createTable string
sqlDB.QueryRow(t, `SHOW CREATE TABLE data.bank`).Scan(&unused, &createTable)
if !strings.Contains(createTable, "balance_idx") {
return errors.New("expected a balance_idx index")
}
return nil
})
var unused string
var exportedRows int64
backupURIFmtString, backupURIArgs := uriFmtStringAndArgs(backupURIs, 0)
backupQuery := fmt.Sprintf("BACKUP DATABASE data INTO %s", backupURIFmtString)
kmsURIArgs := make([]interface{}, 0)
var kmsURIFmtString string
if len(kmsURIs) > 0 {
kmsURIFmtString, kmsURIArgs = uriFmtStringAndArgs(kmsURIs, len(backupURIs))
backupQuery = fmt.Sprintf("%s WITH kms = %s", backupQuery, kmsURIFmtString)
}
queryArgs := append(backupURIArgs, kmsURIArgs...)
sqlDB.QueryRow(t, backupQuery, queryArgs...).Scan(
&unused, &unused, &unused, &exportedRows,
)
if expected := int64(numAccounts * 1); exportedRows != expected {
t.Fatalf("expected %d rows for %d accounts, got %d", expected, numAccounts, exportedRows)
}
found := false
stmt := `
SELECT payload FROM "".crdb_internal.system_jobs ORDER BY created DESC LIMIT 10
`
rows := sqlDB.Query(t, stmt)
for rows.Next() {
var payloadBytes []byte
if err := rows.Scan(&payloadBytes); err != nil {
t.Fatal(err)
}
payload := &jobspb.Payload{}
if err := protoutil.Unmarshal(payloadBytes, payload); err != nil {
t.Fatal("cannot unmarshal job payload from system.jobs")
}
backupManifest := &backuppb.BackupManifest{}
backupPayload, ok := payload.Details.(*jobspb.Payload_Backup)
if !ok {
continue
}
backupDetails := backupPayload.Backup
found = true
if backupDetails.DeprecatedBackupManifest != nil {
t.Fatal("expected backup_manifest field of backup descriptor payload to be nil")
}
if backupManifest.DeprecatedStatistics != nil {
t.Fatal("expected statistics field of backup descriptor payload to be nil")
}
}
if err := rows.Err(); err != nil {
t.Fatalf("unexpected error querying jobs: %s", err.Error())
}
if !found {
t.Fatal("scanned job rows did not contain a backup!")
}
// Create an incremental backup to exercise incremental destination code that captures a new
// table
sqlDB.Exec(t, `CREATE TABLE data.empty (a INT PRIMARY KEY)`)
incBackupQuery := fmt.Sprintf(`BACKUP DATABASE data INTO LATEST IN %s`, backupURIFmtString)
if len(kmsURIs) > 0 {
incBackupQuery = fmt.Sprintf("%s WITH kms = %s", incBackupQuery, kmsURIFmtString)
}
sqlDB.Exec(t, incBackupQuery, queryArgs...)
}
bankTableID := sqlutils.QueryTableID(t, conn, "data", "public", "bank")
backupTableFingerprint, err := fingerprintutils.FingerprintTable(ctx, conn, bankTableID,
fingerprintutils.Stripped())
require.NoError(t, err)
sqlDB.Exec(t, `DROP DATABASE data CASCADE`)
sqlDB.Exec(t, `CREATE DATABASE foo`)
sqlDB.Exec(t, `USE defaultdb`)
// Create some other descriptors to change up IDs
sqlDB.Exec(t, `CREATE DATABASE other`)
// Force the ID of the restored bank table to be different.
sqlDB.Exec(t, `CREATE TABLE other.empty (a INT PRIMARY KEY)`)
restoreURIFmtString, restoreURIArgs := uriFmtStringAndArgs(restoreURIs, 0)
restoreQuery := fmt.Sprintf("RESTORE DATABASE DATA FROM LATEST IN %s", restoreURIFmtString)
kmsURIArgs := make([]interface{}, 0)
if len(kmsURIs) > 0 {
var kmsURIFmtString string
kmsURIFmtString, kmsURIArgs = uriFmtStringAndArgs(kmsURIs, len(backupURIs))
restoreQuery = fmt.Sprintf("%s WITH kms = %s", restoreQuery, kmsURIFmtString)
}
queryArgs := append(restoreURIArgs, kmsURIArgs...)
verifyRestoreData(ctx, t, conn, sqlDB, storageSQLDB, restoreQuery, queryArgs, numAccounts,
backupTableFingerprint)
}
func verifyRestoreData(
ctx context.Context,
t *testing.T,
conn *gosql.DB,
sqlDB *sqlutils.SQLRunner,
storageSQLDB *sqlutils.SQLRunner,
restoreQuery string,
restoreURIArgs []interface{},
numAccounts int,
bankStrippedFingerprint int64,
) {