-
Notifications
You must be signed in to change notification settings - Fork 3.9k
/
Copy pathschema_changer_test.go
8392 lines (7490 loc) · 260 KB
/
schema_changer_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 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_test
import (
"context"
gosql "database/sql"
"database/sql/driver"
"fmt"
"math/rand"
"strconv"
"strings"
"sync"
"sync/atomic"
"testing"
"time"
"github.com/cockroachdb/cockroach/pkg/base"
"github.com/cockroachdb/cockroach/pkg/clusterversion"
"github.com/cockroachdb/cockroach/pkg/config/zonepb"
"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/kv/kvclient/rangefeed"
"github.com/cockroachdb/cockroach/pkg/roachpb"
"github.com/cockroachdb/cockroach/pkg/security/username"
"github.com/cockroachdb/cockroach/pkg/server"
"github.com/cockroachdb/cockroach/pkg/settings/cluster"
"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/descpb"
"github.com/cockroachdb/cockroach/pkg/sql/catalog/descs"
"github.com/cockroachdb/cockroach/pkg/sql/catalog/desctestutils"
"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/gcjob"
"github.com/cockroachdb/cockroach/pkg/sql/pgwire/pgcode"
"github.com/cockroachdb/cockroach/pkg/sql/schemachanger/scexec"
"github.com/cockroachdb/cockroach/pkg/sql/sqltestutils"
"github.com/cockroachdb/cockroach/pkg/sql/stats"
"github.com/cockroachdb/cockroach/pkg/sql/tests"
"github.com/cockroachdb/cockroach/pkg/startupmigrations"
"github.com/cockroachdb/cockroach/pkg/testutils"
"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/ctxgroup"
"github.com/cockroachdb/cockroach/pkg/util/hlc"
"github.com/cockroachdb/cockroach/pkg/util/json"
"github.com/cockroachdb/cockroach/pkg/util/leaktest"
"github.com/cockroachdb/cockroach/pkg/util/log"
"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/lib/pq"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"golang.org/x/sync/errgroup"
)
// TestSchemaChangeProcess adds mutations manually to a table descriptor and
// ensures that RunStateMachineBeforeBackfill processes the mutation.
// TODO (lucy): This is the only test that creates its own schema changer and
// calls methods on it. Now that every schema changer "belongs" to a single
// instance of a job resumer there's less of a reason to test this way. Should
// this test still even exist?
func TestSchemaChangeProcess(t *testing.T) {
defer leaktest.AfterTest(t)()
defer log.Scope(t).Close(t)
// The descriptor changes made must have an immediate effect
// so disable leases on tables.
defer lease.TestingDisableTableLeases()()
params, _ := tests.CreateTestServerParams()
s, sqlDB, kvDB := serverutils.StartServer(t, params)
defer s.Stopper().Stop(context.Background())
var instance = base.SQLInstanceID(2)
stopper := stop.NewStopper()
execCfg := s.ExecutorConfig().(sql.ExecutorConfig)
rf, err := rangefeed.NewFactory(stopper, kvDB, execCfg.Settings, nil /* knobs */)
require.NoError(t, err)
leaseMgr := lease.NewLeaseManager(
s.AmbientCtx(),
execCfg.NodeInfo.NodeID,
execCfg.DB,
execCfg.Clock,
execCfg.InternalExecutor,
execCfg.Settings,
execCfg.Codec,
lease.ManagerTestingKnobs{},
stopper,
rf,
)
jobRegistry := s.JobRegistry().(*jobs.Registry)
defer stopper.Stop(context.Background())
if _, err := sqlDB.Exec(`
CREATE DATABASE t;
CREATE TABLE t.test (k CHAR PRIMARY KEY, v CHAR, INDEX foo(v));
INSERT INTO t.test VALUES ('a', 'b'), ('c', 'd');
`); err != nil {
t.Fatal(err)
}
tableID := descpb.ID(sqlutils.QueryTableID(t, sqlDB, "t", "public", "test"))
changer := sql.NewSchemaChangerForTesting(
tableID, 0, instance, kvDB, leaseMgr, jobRegistry, &execCfg, cluster.MakeTestingClusterSettings())
// Read table descriptor for version.
tableDesc := desctestutils.TestingGetMutableExistingTableDescriptor(kvDB, keys.SystemSQLCodec, "t", "test")
expectedVersion := tableDesc.Version
ctx := context.Background()
// Check that RunStateMachineBeforeBackfill doesn't do anything
// if there are no mutations queued.
if err := changer.RunStateMachineBeforeBackfill(ctx); err != nil {
t.Fatal(err)
}
tableDesc = desctestutils.TestingGetMutableExistingTableDescriptor(kvDB, keys.SystemSQLCodec, "t", "test")
newVersion := tableDesc.Version
if newVersion != expectedVersion {
t.Fatalf("bad version; e = %d, v = %d", expectedVersion, newVersion)
}
// Check that RunStateMachineBeforeBackfill functions properly.
expectedVersion = tableDesc.Version
// Make a copy of the index for use in a mutation.
index := tableDesc.PublicNonPrimaryIndexes()[0].IndexDescDeepCopy()
index.Name = "bar"
index.ID = tableDesc.NextIndexID
tableDesc.NextIndexID++
changer = sql.NewSchemaChangerForTesting(
tableID, tableDesc.NextMutationID, instance, kvDB, leaseMgr, jobRegistry,
&execCfg, cluster.MakeTestingClusterSettings(),
)
tableDesc.TableDesc().Mutations = append(tableDesc.TableDesc().Mutations, descpb.DescriptorMutation{
Descriptor_: &descpb.DescriptorMutation_Index{Index: &index},
Direction: descpb.DescriptorMutation_ADD,
State: descpb.DescriptorMutation_DELETE_ONLY,
MutationID: tableDesc.NextMutationID,
})
tableDesc.NextMutationID++
// Run state machine in both directions.
for _, direction := range []descpb.DescriptorMutation_Direction{
descpb.DescriptorMutation_ADD, descpb.DescriptorMutation_DROP,
} {
tableDesc.Mutations[0].Direction = direction
expectedVersion++
if err := kvDB.Put(
ctx,
catalogkeys.MakeDescMetadataKey(keys.SystemSQLCodec, tableDesc.GetID()),
tableDesc.DescriptorProto(),
); err != nil {
t.Fatal(err)
}
// The expected end state.
expectedState := descpb.DescriptorMutation_DELETE_AND_WRITE_ONLY
if direction == descpb.DescriptorMutation_DROP {
expectedState = descpb.DescriptorMutation_DELETE_ONLY
}
// Run two times to ensure idempotency of operations.
for i := 0; i < 2; i++ {
if err := changer.RunStateMachineBeforeBackfill(ctx); err != nil {
t.Fatal(err)
}
tableDesc = desctestutils.TestingGetMutableExistingTableDescriptor(
kvDB, keys.SystemSQLCodec, "t", "test")
newVersion = tableDesc.Version
if newVersion != expectedVersion {
t.Fatalf("bad version; e = %d, v = %d", expectedVersion, newVersion)
}
state := tableDesc.Mutations[0].State
if state != expectedState {
t.Fatalf("bad state; e = %d, v = %d", expectedState, state)
}
}
}
// RunStateMachineBeforeBackfill() doesn't complete the schema change.
tableDesc = desctestutils.TestingGetMutableExistingTableDescriptor(
kvDB, keys.SystemSQLCodec, "t", "test")
if len(tableDesc.Mutations) == 0 {
t.Fatalf("table expected to have an outstanding schema change: %v", tableDesc)
}
}
// TODO (lucy): In the current state of the code it doesn't make sense to try to
// test the "async" path separately. This test doesn't have any special
// settings. Should it even still exist?
func TestAsyncSchemaChanger(t *testing.T) {
defer leaktest.AfterTest(t)()
defer log.Scope(t).Close(t)
// The descriptor changes made must have an immediate effect
// so disable leases on tables.
defer lease.TestingDisableTableLeases()()
// Disable synchronous schema change execution so the asynchronous schema
// changer executes all schema changes.
params, _ := tests.CreateTestServerParams()
s, sqlDB, kvDB := serverutils.StartServer(t, params)
defer s.Stopper().Stop(context.Background())
if _, err := sqlDB.Exec(`
CREATE DATABASE t;
CREATE TABLE t.test (k CHAR PRIMARY KEY, v CHAR);
INSERT INTO t.test VALUES ('a', 'b'), ('c', 'd');
`); err != nil {
t.Fatal(err)
}
// Read table descriptor for version.
tableDesc := desctestutils.TestingGetMutableExistingTableDescriptor(
kvDB, keys.SystemSQLCodec, "t", "test")
// A long running schema change operation runs through
// a state machine that increments the version by 6.
expectedVersion := tableDesc.Version + 6
// Run some schema change
if _, err := sqlDB.Exec(`
CREATE INDEX foo ON t.test (v)
`); err != nil {
t.Fatal(err)
}
retryOpts := retry.Options{
InitialBackoff: 20 * time.Millisecond,
MaxBackoff: 200 * time.Millisecond,
Multiplier: 2,
}
// Wait until index is created.
for r := retry.Start(retryOpts); r.Next(); {
tableDesc = desctestutils.TestingGetMutableExistingTableDescriptor(
kvDB, keys.SystemSQLCodec, "t", "test")
if len(tableDesc.PublicNonPrimaryIndexes()) == 1 {
break
}
}
// Ensure that the indexes have been created.
mTest := makeMutationTest(t, kvDB, sqlDB, tableDesc)
indexQuery := `SELECT v FROM t.test@foo`
mTest.CheckQueryResults(t, indexQuery, [][]string{{"b"}, {"d"}})
// Ensure that the version has been incremented.
tableDesc = desctestutils.TestingGetMutableExistingTableDescriptor(
kvDB, keys.SystemSQLCodec, "t", "test")
newVersion := tableDesc.Version
if newVersion != expectedVersion {
t.Fatalf("bad version; e = %d, v = %d", expectedVersion, newVersion)
}
// Apply a schema change that only sets the UpVersion bit.
expectedVersion = newVersion + 1
mTest.Exec(t, `ALTER INDEX t.test@foo RENAME TO ufo`)
for r := retry.Start(retryOpts); r.Next(); {
// Ensure that the version gets incremented.
tableDesc = desctestutils.TestingGetMutableExistingTableDescriptor(
kvDB, keys.SystemSQLCodec, "t", "test")
name := tableDesc.PublicNonPrimaryIndexes()[0].GetName()
if name != "ufo" {
t.Fatalf("bad index name %s", name)
}
newVersion = tableDesc.Version
if newVersion == expectedVersion {
break
}
}
// Run many schema changes simultaneously and check
// that they all get executed.
count := 5
for i := 0; i < count; i++ {
mTest.Exec(t, fmt.Sprintf(`CREATE INDEX foo%d ON t.test (v)`, i))
}
// Wait until indexes are created.
for r := retry.Start(retryOpts); r.Next(); {
tableDesc = desctestutils.TestingGetMutableExistingTableDescriptor(
kvDB, keys.SystemSQLCodec, "t", "test")
if len(tableDesc.PublicNonPrimaryIndexes()) == count+1 {
break
}
}
for i := 0; i < count; i++ {
indexQuery := fmt.Sprintf(`SELECT v FROM t.test@foo%d`, i)
mTest.CheckQueryResults(t, indexQuery, [][]string{{"b"}, {"d"}})
}
if err := sqlutils.RunScrub(sqlDB, "t", "test"); err != nil {
t.Fatal(err)
}
}
// Run a particular schema change and run some OLTP operations in parallel, as
// soon as the schema change starts executing its backfill.
func runSchemaChangeWithOperations(
t *testing.T,
sqlDB *gosql.DB,
kvDB *kv.DB,
schemaChange string,
maxValue int,
keyMultiple int,
backfillNotification chan struct{},
useUpsert bool,
) {
var wg sync.WaitGroup
wg.Add(1)
go func() {
start := timeutil.Now()
// Start schema change that eventually runs a backfill.
if _, err := sqlDB.Exec(schemaChange); err != nil {
t.Error(err)
}
t.Logf("schema change %s took %v", schemaChange, timeutil.Since(start))
wg.Done()
}()
// Wait until the schema change backfill starts.
<-backfillNotification
// Run a variety of operations during the backfill.
ctx := context.Background()
conn, err := sqlDB.Conn(ctx)
require.NoError(t, err)
defer func() { assert.NoError(t, conn.Close()) }()
exec := func(sql string, args ...interface{}) {
t.Helper()
_, err := conn.ExecContext(ctx, sql, args...)
if err != nil {
t.Error(err)
}
}
// Update some rows.
var updatedKeys []int
for i := 0; i < 10; i++ {
k := rand.Intn(maxValue)
v := maxValue + i + 1
exec(`UPDATE t.test SET v = $1 WHERE k = $2`, v, k)
updatedKeys = append(updatedKeys, k)
}
// Reupdate updated values back to what they were before.
for _, k := range updatedKeys {
if rand.Float32() < 0.5 || !useUpsert {
exec(`UPDATE t.test SET v = $1 WHERE k = $2`, maxValue-k, k)
} else {
exec(`UPSERT INTO t.test (k,v) VALUES ($1, $2)`, k, maxValue-k)
}
}
// Delete some rows.
deleteStartKey := rand.Intn(maxValue - 10)
for i := 0; i < 10; i++ {
exec(`DELETE FROM t.test WHERE k = $1`, deleteStartKey+i)
}
// Reinsert deleted rows.
for i := 0; i < 10; i++ {
k := deleteStartKey + i
if rand.Float32() < 0.5 || !useUpsert {
exec(`INSERT INTO t.test VALUES($1, $2)`, k, maxValue-k)
} else {
exec(`UPSERT INTO t.test VALUES($1, $2)`, k, maxValue-k)
}
}
// Insert some new rows.
numInserts := 10
for i := 0; i < numInserts; i++ {
k := maxValue + i + 1
exec(`INSERT INTO t.test VALUES($1, $1)`, k)
}
wg.Wait() // for schema change to complete.
// Verify the number of keys left behind in the table to
// validate schema change operations. We wait for any SCHEMA
// CHANGE GC jobs for temp indexes to show that the temp index
// has been cleared.
if _, err := sqlDB.Exec(`SHOW JOBS WHEN COMPLETE (SELECT job_id FROM [SHOW JOBS] WHERE job_type = 'SCHEMA CHANGE GC')`); err != nil {
t.Fatal(err)
}
testutils.SucceedsSoon(t, func() error {
return sqltestutils.CheckTableKeyCount(ctx, kvDB, keyMultiple, maxValue+numInserts)
})
if err := sqlutils.RunScrub(sqlDB, "t", "test"); err != nil {
t.Fatal(err)
}
// Delete the rows inserted.
for i := 0; i < numInserts; i++ {
if _, err := sqlDB.Exec(`DELETE FROM t.test WHERE k = $1`, maxValue+i+1); err != nil {
t.Error(err)
}
}
}
func TestRollbackOfAddingTable(t *testing.T) {
defer leaktest.AfterTest(t)()
defer log.Scope(t).Close(t)
// Protects shouldError.
var mu syncutil.Mutex
shouldError := true
params, _ := tests.CreateTestServerParams()
params.Knobs = base.TestingKnobs{
SQLSchemaChanger: &sql.SchemaChangerTestingKnobs{
RunBeforeQueryBackfill: func() error {
mu.Lock()
defer mu.Unlock()
if shouldError {
shouldError = false
return jobs.MarkAsPermanentJobError(errors.New("boom"))
}
return nil
},
},
}
ctx := context.Background()
s, sqlDB, _ := serverutils.StartServer(t, params)
defer s.Stopper().Stop(ctx)
_, err := sqlDB.Exec(`CREATE DATABASE d`)
require.NoError(t, err)
// Create a table that the view depends on.
_, err = sqlDB.Exec(`
CREATE TYPE d.animals as ENUM('cat');
CREATE SEQUENCE d.sq1;
CREATE TABLE d.t1 (val INT DEFAULT nextval('d.sq1'), animal d.animals);
`)
require.NoError(t, err)
// This view creation will fail and eventually rollback.
_, err = sqlDB.Exec(
`BEGIN;
CREATE MATERIALIZED VIEW d.v AS SELECT val FROM d.t1;
CREATE VIEW d.v1 AS SELECT A.val AS val2, B.val AS val1, 'cat':::d.animals AS ANIMAL, c.last_value FROM d.v AS A, d.t1 AS B, d.sq1 as C;
COMMIT;`)
require.EqualError(t, err, "pq: transaction committed but schema change aborted with error: (XXUUU): boom")
// Validate existing back references are intact.
_, err = sqlDB.Exec("DROP TYPE d.animals;")
require.Error(t, err, "pq: cannot drop type \"animals\" because other objects ([d.public.t1]) still depend on it")
_, err = sqlDB.Exec("DROP SEQUENCE d.sq1;")
require.Error(t, err, "pq: cannot drop type \"animals\" because other objects ([d.public.t1]) still depend on it")
// Ensure that the dependent objects can still be dropped.
_, err = sqlDB.Exec(`
DROP TABLE d.t1;
DROP TYPE d.animals;
DROP SEQUENCE d.sq1;
`)
require.NoError(t, err)
// Get the view descriptor we just created and verify that it's in the
// dropping state. We're unable to access the descriptor via the usual means
// because catalog.FilterDescriptorState filters out tables in the ADD state,
// and once we move the table to the DROP state we also remove the namespace
// entry. So we just get the most recent descriptor.
var descBytes []byte
rows, err := sqlDB.Query(`SELECT descriptor FROM system.descriptor ORDER BY id DESC LIMIT 2`)
require.NoError(t, err)
require.Equal(t, rows.Next(), true)
require.Equal(t, rows.Next(), true)
require.NoError(t, rows.Scan(&descBytes))
var desc descpb.Descriptor
require.NoError(t, protoutil.Unmarshal(descBytes, &desc))
//nolint:descriptormarshal
viewDesc := desc.GetTable()
require.Equal(t, "v", viewDesc.GetName(), "read a different descriptor than expected")
require.Equal(t, descpb.DescriptorState_DROP, viewDesc.GetState())
// The view should be cleaned up after the failure, so we should be able
// to create a new view with the same name.
_, err = sqlDB.Exec(`CREATE MATERIALIZED VIEW d.v AS SELECT 1`)
require.NoError(t, err)
}
func TestUniqueViolationsAreCaught(t *testing.T) {
defer leaktest.AfterTest(t)()
defer log.Scope(t).Close(t)
readyToMerge := make(chan struct{})
startMerge := make(chan struct{})
params, _ := tests.CreateTestServerParams()
params.Knobs = base.TestingKnobs{
JobsTestingKnobs: jobs.NewTestingKnobsWithShortIntervals(),
SQLSchemaChanger: &sql.SchemaChangerTestingKnobs{
RunBeforeTempIndexMerge: func() {
close(readyToMerge)
<-startMerge
},
},
}
server, sqlDB, _ := serverutils.StartServer(t, params)
defer server.Stopper().Stop(context.Background())
_, err := sqlDB.Exec(`CREATE DATABASE t;
CREATE TABLE t.test (pk INT PRIMARY KEY, v INT);
INSERT INTO t.test VALUES (1,1), (2,2), (3,3)
`)
require.NoError(t, err)
grp := ctxgroup.WithContext(context.Background())
grp.GoCtx(func(ctx context.Context) error {
_, err := sqlDB.Exec(`CREATE UNIQUE INDEX ON t.test (v)`)
return err
})
<-readyToMerge
// This conflicts with the new index but doesn't conflict with
// the online indexes. It should produce a failure on
// validation.
_, err = sqlDB.Exec(`INSERT INTO t.test VALUES (4, 1), (5, 2)`)
require.NoError(t, err)
close(startMerge)
err = grp.Wait()
require.Error(t, err)
}
// Test schema change backfills are not affected by various operations
// that run simultaneously.
func TestRaceWithBackfill(t *testing.T) {
defer leaktest.AfterTest(t)()
defer log.Scope(t).Close(t)
// protects backfillNotification
var mu syncutil.Mutex
var backfillNotification chan struct{}
const numNodes = 5
var chunkSize int64 = 100
var maxValue = 4000
if util.RaceEnabled {
// Race builds are a lot slower, so use a smaller number of rows and a
// correspondingly smaller chunk size.
chunkSize = 5
maxValue = 200
}
params, _ := tests.CreateTestServerParams()
initBackfillNotification := func() chan struct{} {
mu.Lock()
defer mu.Unlock()
backfillNotification = make(chan struct{})
return backfillNotification
}
notifyBackfill := func() {
mu.Lock()
defer mu.Unlock()
if backfillNotification != nil {
// Close channel to notify that the backfill has started.
close(backfillNotification)
backfillNotification = nil
}
}
params.Knobs = base.TestingKnobs{
SQLSchemaChanger: &sql.SchemaChangerTestingKnobs{
BackfillChunkSize: chunkSize,
},
DistSQL: &execinfra.TestingKnobs{
RunBeforeBackfillChunk: func(sp roachpb.Span) error {
notifyBackfill()
return nil
},
},
}
tc := serverutils.StartNewTestCluster(t, numNodes,
base.TestClusterArgs{
ReplicationMode: base.ReplicationManual,
ServerArgs: params,
})
defer tc.Stopper().Stop(context.Background())
kvDB := tc.Server(0).DB()
sqlDB := tc.ServerConn(0)
if _, err := sqlDB.Exec(`
CREATE DATABASE t;
CREATE TABLE t.test (k INT PRIMARY KEY, v INT, pi DECIMAL DEFAULT (DECIMAL '3.14'));
CREATE UNIQUE INDEX vidx ON t.test (v);
`); err != nil {
t.Fatal(err)
}
tableDesc := desctestutils.TestingGetPublicTableDescriptor(kvDB, keys.SystemSQLCodec, "t", "test")
// Add a zone config for the table so that garbage collection happens rapidly.
if _, err := sqltestutils.AddImmediateGCZoneConfig(sqlDB, tableDesc.GetID()); err != nil {
t.Fatal(err)
}
// Bulk insert.
if err := sqltestutils.BulkInsertIntoTable(sqlDB, maxValue); err != nil {
t.Fatal(err)
}
var sps []sql.SplitPoint
for i := 1; i <= numNodes-1; i++ {
sps = append(sps, sql.SplitPoint{TargetNodeIdx: i, Vals: []interface{}{maxValue / numNodes * i}})
}
sql.SplitTable(t, tc, tableDesc, sps)
ctx := context.Background()
// number of keys == 2 * number of rows; 1 column family and 1 index entry
// for each row.
if err := sqltestutils.CheckTableKeyCount(ctx, kvDB, 2, maxValue); err != nil {
t.Fatal(err)
}
if err := sqlutils.RunScrub(sqlDB, "t", "test"); err != nil {
t.Fatal(err)
}
// Run some schema changes with operations.
// Add column with a check constraint.
runSchemaChangeWithOperations(
t,
sqlDB,
kvDB,
"ALTER TABLE t.test ADD COLUMN x DECIMAL DEFAULT (DECIMAL '1.4') CHECK (x >= 0)",
maxValue,
2,
initBackfillNotification(),
true,
)
// Drop column.
runSchemaChangeWithOperations(
t,
sqlDB,
kvDB,
"ALTER TABLE t.test DROP pi",
maxValue,
2,
initBackfillNotification(),
true,
)
// Add index.
runSchemaChangeWithOperations(
t,
sqlDB,
kvDB,
"CREATE UNIQUE INDEX foo ON t.test (v)",
maxValue,
3,
initBackfillNotification(),
true,
)
// Add STORING index (that will have non-nil values).
runSchemaChangeWithOperations(
t,
sqlDB,
kvDB,
"CREATE INDEX bar ON t.test(k) STORING (v)",
maxValue,
4,
initBackfillNotification(),
true,
)
// Verify that the index foo over v is consistent, and that column x has
// been backfilled properly.
rows, err := sqlDB.Query(`SELECT v, x from t.test@foo ORDER BY v`)
if err != nil {
t.Fatal(err)
}
defer rows.Close()
count := 0
for ; rows.Next(); count++ {
var val int
var x float64
if err := rows.Scan(&val, &x); err != nil {
t.Errorf("row %d scan failed: %s", count, err)
continue
}
if count != val {
t.Errorf("e = %d, v = %d", count, val)
}
if x != 1.4 {
t.Errorf("e = %f, v = %f", 1.4, x)
}
}
if err := rows.Err(); err != nil {
t.Fatal(err)
}
eCount := maxValue + 1
if eCount != count {
t.Fatalf("read the wrong number of rows: e = %d, v = %d", eCount, count)
}
}
// Test that a table drop in the middle of a backfill works properly.
// The backfill will terminate in the middle, and the drop will
// successfully complete without deleting the data.
func TestDropWhileBackfill(t *testing.T) {
defer leaktest.AfterTest(t)()
defer log.Scope(t).Close(t)
// protects backfillNotification
var mu syncutil.Mutex
backfillNotification := make(chan struct{})
var partialBackfillDone atomic.Value
partialBackfillDone.Store(false)
const numNodes, chunkSize = 5, 100
maxValue := 4000
if util.RaceEnabled {
// Race builds are a lot slower, so use a smaller number of rows.
// We expect this to also reduce the memory footprint of the test.
maxValue = 200
}
params, _ := tests.CreateTestServerParams()
notifyBackfill := func() {
mu.Lock()
defer mu.Unlock()
if backfillNotification != nil {
// Close channel to notify that the backfill has started.
close(backfillNotification)
backfillNotification = nil
}
}
params.Knobs = base.TestingKnobs{
SQLSchemaChanger: &sql.SchemaChangerTestingKnobs{
BackfillChunkSize: chunkSize,
},
DistSQL: &execinfra.TestingKnobs{
RunBeforeBackfillChunk: func(sp roachpb.Span) error {
if partialBackfillDone.Load().(bool) {
notifyBackfill()
}
partialBackfillDone.Store(true)
// Returning DeadlineExceeded will result in the
// schema change being retried and no data will be written
// to the new index.
return context.DeadlineExceeded
},
},
// Disable backfill migrations, we still need the jobs table migration.
StartupMigrationManager: &startupmigrations.MigrationManagerTestingKnobs{
DisableBackfillMigrations: true,
},
}
tc := serverutils.StartNewTestCluster(t, numNodes,
base.TestClusterArgs{
ReplicationMode: base.ReplicationManual,
ServerArgs: params,
})
defer tc.Stopper().Stop(context.Background())
kvDB := tc.Server(0).DB()
sqlDB := tc.ServerConn(0)
if _, err := sqlDB.Exec(`
SET CLUSTER SETTING sql.defaults.use_declarative_schema_changer = 'off';
`); err != nil {
t.Fatal(err)
}
if _, err := sqlDB.Exec(`
SET use_declarative_schema_changer = 'off';
CREATE DATABASE t;
CREATE TABLE t.test (k INT PRIMARY KEY, v INT, pi DECIMAL DEFAULT (DECIMAL '3.14'));
CREATE UNIQUE INDEX vidx ON t.test (v);
`); err != nil {
t.Fatal(err)
}
// Bulk insert.
if err := sqltestutils.BulkInsertIntoTable(sqlDB, maxValue); err != nil {
t.Fatal(err)
}
// Split the table into multiple ranges.
tableDesc := desctestutils.TestingGetPublicTableDescriptor(kvDB, keys.SystemSQLCodec, "t", "test")
var sps []sql.SplitPoint
for i := 1; i <= numNodes-1; i++ {
sps = append(sps, sql.SplitPoint{TargetNodeIdx: i, Vals: []interface{}{maxValue / numNodes * i}})
}
sql.SplitTable(t, tc, tableDesc, sps)
ctx := context.Background()
// number of keys == 2 * number of rows; 1 column family and 1 index entry
// for each row.
if err := sqltestutils.CheckTableKeyCount(ctx, kvDB, 2, maxValue); err != nil {
t.Fatal(err)
}
if err := sqlutils.RunScrub(sqlDB, "t", "test"); err != nil {
t.Fatal(err)
}
notification := backfillNotification
// Run the schema change in a separate goroutine.
var wg sync.WaitGroup
wg.Add(1)
go func() {
// Start schema change that eventually runs a partial backfill.
if _, err := sqlDB.Exec("CREATE UNIQUE INDEX bar ON t.test (v)"); err != nil && !testutils.IsError(err, "descriptor is being dropped") {
t.Error(err)
}
wg.Done()
}()
// Wait until the schema change backfill is partially complete.
<-notification
if _, err := sqlDB.Exec("DROP TABLE t.test"); err != nil {
t.Fatal(err)
}
// Wait until the schema change is done.
wg.Wait()
// Ensure that the table data hasn't been deleted.
tablePrefix := keys.SystemSQLCodec.TablePrefix(uint32(tableDesc.GetID()))
tableEnd := tablePrefix.PrefixEnd()
if kvs, err := kvDB.Scan(ctx, tablePrefix, tableEnd, 0); err != nil {
t.Fatal(err)
} else if e := 2 * (maxValue + 1); len(kvs) != e {
t.Fatalf("expected %d key value pairs, but got %d", e, len(kvs))
}
// Check that the table descriptor exists so we know the data will
// eventually be deleted.
tbDescKey := catalogkeys.MakeDescMetadataKey(keys.SystemSQLCodec, tableDesc.GetID())
if gr, err := kvDB.Get(ctx, tbDescKey); err != nil {
t.Fatal(err)
} else if !gr.Exists() {
t.Fatalf("table descriptor doesn't exist after table is dropped: %q", tbDescKey)
}
}
// Test that a schema change on encountering a permanent backfill error
// on a remote node terminates properly and returns the database to a
// proper state.
func TestBackfillErrors(t *testing.T) {
defer leaktest.AfterTest(t)()
defer log.Scope(t).Close(t)
const numNodes, chunkSize, maxValue = 5, 100, 4000
params, _ := tests.CreateTestServerParams()
blockGC := make(chan struct{})
params.Knobs = base.TestingKnobs{
SQLSchemaChanger: &sql.SchemaChangerTestingKnobs{
BackfillChunkSize: chunkSize,
},
GCJob: &sql.GCJobTestingKnobs{RunBeforeResume: func(_ jobspb.JobID) error { <-blockGC; return nil }},
}
tc := serverutils.StartNewTestCluster(t, numNodes,
base.TestClusterArgs{
ReplicationMode: base.ReplicationManual,
ServerArgs: params,
})
defer tc.Stopper().Stop(context.Background())
kvDB := tc.Server(0).DB()
sqlDB := tc.ServerConn(0)
if _, err := sqlDB.Exec(`
CREATE DATABASE t;
CREATE TABLE t.test (k INT PRIMARY KEY, v INT);
`); err != nil {
t.Fatal(err)
}
tableDesc := desctestutils.TestingGetPublicTableDescriptor(kvDB, keys.SystemSQLCodec, "t", "test")
// Bulk insert.
if err := sqltestutils.BulkInsertIntoTable(sqlDB, maxValue); err != nil {
t.Fatal(err)
}
// Update v column on some rows to be the same so that the future
// UNIQUE index we create on it fails.
//
// Pick a set of random rows because if we pick a deterministic set
// we can't be sure they will end up on a remote node. We want this
// test to fail if an error is not reported correctly on a local or
// remote node and the randomness allows us to test both.
const numUpdatedRows = 10
for i := 0; i < numUpdatedRows; i++ {
k := rand.Intn(maxValue - numUpdatedRows)
if _, err := sqlDB.Exec(`UPDATE t.test SET v = $1 WHERE k = $2`, 1, k); err != nil {
t.Error(err)
}
}
// Split the table into multiple ranges.
var sps []sql.SplitPoint
for i := 1; i <= numNodes-1; i++ {
sps = append(sps, sql.SplitPoint{TargetNodeIdx: i, Vals: []interface{}{maxValue / numNodes * i}})
}
sql.SplitTable(t, tc, tableDesc, sps)
ctx := context.Background()
if err := sqltestutils.CheckTableKeyCount(ctx, kvDB, 1, maxValue); err != nil {
t.Fatal(err)
}
if _, err := sqlDB.Exec(`
CREATE UNIQUE INDEX vidx ON t.test (v);
`); !testutils.IsError(err, `violates unique constraint "vidx"`) {
t.Fatalf("got err=%s", err)
}
// Index backfill errors at a non-deterministic chunk and the garbage
// keys remain because the async schema changer for the rollback stays
// disabled in order to assert the next errors. Therefore we do not check
// the keycount from this operation and just check that the next failed
// operations do not add more.
keyCount, err := sqltestutils.GetTableKeyCount(ctx, kvDB)
if err != nil {
t.Fatal(err)
}
if _, err := sqlDB.Exec(`
ALTER TABLE t.test ADD COLUMN p DECIMAL NOT NULL DEFAULT (DECIMAL '1-3');
`); !testutils.IsError(err, `could not parse "1-3" as type decimal`) {
t.Fatalf("got err=%s", err)
}
if err := sqltestutils.CheckTableKeyCountExact(ctx, kvDB, keyCount); err != nil {
t.Fatal(err)
}
if _, err := sqlDB.Exec(`
ALTER TABLE t.test ADD COLUMN p DECIMAL NOT NULL;
`); !testutils.IsError(err, `null value in column \"p\" violates not-null constraint`) {
t.Fatalf("got err=%s", err)
}
if err := sqltestutils.CheckTableKeyCountExact(ctx, kvDB, keyCount); err != nil {
t.Fatal(err)
}
close(blockGC)
}
// Test aborting a schema change backfill transaction and check that the
// backfill is completed correctly. The backfill transaction is aborted at a
// time when it thinks it has processed all the rows of the table. Later,
// before the transaction is retried, the table is populated with more rows
// that a backfill chunk, requiring the backfill to forget that it is at the
// end of its processing and needs to continue on to process two more chunks
// of data.
func TestAbortSchemaChangeBackfill(t *testing.T) {
defer leaktest.AfterTest(t)()
defer log.Scope(t).Close(t)
var backfillNotification, commandsDone chan struct{}
var dontAbortBackfill uint32
params, _ := tests.CreateTestServerParams()
const maxValue = 100
backfillCount := int64(0)
retriedBackfill := int64(0)
var retriedSpan roachpb.Span
params.Knobs = base.TestingKnobs{
SQLSchemaChanger: &sql.SchemaChangerTestingKnobs{
// TODO (lucy): Stress this test. This test used to require fast GC, but
// it passes without it.
BackfillChunkSize: maxValue,
},
DistSQL: &execinfra.TestingKnobs{
RunBeforeBackfillChunk: func(sp roachpb.Span) error {
switch atomic.LoadInt64(&backfillCount) {
case 0:
// Keep track of the span provided with the first backfill
// attempt.
retriedSpan = sp
case 1:
// Ensure that the second backfill attempt provides the
// same span as the first.
if sp.EqualValue(retriedSpan) {