-
Notifications
You must be signed in to change notification settings - Fork 3.8k
/
Copy pathdrop_test.go
1297 lines (1118 loc) · 37.8 KB
/
drop_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"
"fmt"
"math/rand"
"testing"
"time"
"github.com/cockroachdb/cockroach/pkg/base"
"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/roachpb"
"github.com/cockroachdb/cockroach/pkg/security"
"github.com/cockroachdb/cockroach/pkg/server"
"github.com/cockroachdb/cockroach/pkg/sql"
"github.com/cockroachdb/cockroach/pkg/sql/execinfra"
"github.com/cockroachdb/cockroach/pkg/sql/gcjob"
"github.com/cockroachdb/cockroach/pkg/sql/sqlbase"
"github.com/cockroachdb/cockroach/pkg/sql/tests"
"github.com/cockroachdb/cockroach/pkg/sqlmigrations"
"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/sqlutils"
"github.com/cockroachdb/cockroach/pkg/util/leaktest"
"github.com/cockroachdb/cockroach/pkg/util/protoutil"
"github.com/pkg/errors"
"github.com/stretchr/testify/require"
)
// Returns an error if a zone config for the specified table or
// database ID doesn't match the expected parameter. If expected
// is nil, then we verify no zone config exists.
func zoneExists(sqlDB *gosql.DB, expected *zonepb.ZoneConfig, id sqlbase.ID) error {
rows, err := sqlDB.Query(`SELECT * FROM system.zones WHERE id = $1`, id)
if err != nil {
return err
}
defer rows.Close()
if exists := (expected != nil); exists != rows.Next() {
return errors.Errorf("zone config exists = %v", exists)
}
if expected != nil {
// Ensure that the zone config matches.
var storedID sqlbase.ID
var val []byte
if err := rows.Scan(&storedID, &val); err != nil {
return errors.Errorf("row scan failed: %s", err)
}
if storedID != id {
return errors.Errorf("e = %d, v = %d", id, storedID)
}
var cfg zonepb.ZoneConfig
if err := protoutil.Unmarshal(val, &cfg); err != nil {
return err
}
if !expected.Equal(cfg) {
return errors.Errorf("e = %v, v = %v", expected, cfg)
}
}
return nil
}
// Returns an error if a descriptor "exists" for the table id.
func descExists(sqlDB *gosql.DB, exists bool, id sqlbase.ID) error {
rows, err := sqlDB.Query(`SELECT * FROM system.descriptor WHERE id = $1`, id)
if err != nil {
return err
}
defer rows.Close()
if exists != rows.Next() {
return errors.Errorf("descriptor exists = %v", exists)
}
return nil
}
// Set the GC TTL to 0 for the given table ID. One must make sure to disable
// strict GC TTL enforcement when using this.
func addImmediateGCZoneConfig(sqlDB *gosql.DB, id sqlbase.ID) (zonepb.ZoneConfig, error) {
cfg := zonepb.DefaultZoneConfig()
cfg.GC.TTLSeconds = 0
buf, err := protoutil.Marshal(&cfg)
if err != nil {
return cfg, err
}
_, err = sqlDB.Exec(`UPSERT INTO system.zones VALUES ($1, $2)`, id, buf)
return cfg, err
}
func disableGCTTLStrictEnforcement(t *testing.T, db *gosql.DB) (cleanup func()) {
_, err := db.Exec(`SET CLUSTER SETTING kv.gc_ttl.strict_enforcement.enabled = false`)
require.NoError(t, err)
return func() {
_, err := db.Exec(`SET CLUSTER SETTING kv.gc_ttl.strict_enforcement.enabled = DEFAULT`)
require.NoError(t, err)
}
}
func addDefaultZoneConfig(sqlDB *gosql.DB, id sqlbase.ID) (zonepb.ZoneConfig, error) {
cfg := zonepb.DefaultZoneConfig()
buf, err := protoutil.Marshal(&cfg)
if err != nil {
return cfg, err
}
_, err = sqlDB.Exec(`UPSERT INTO system.zones VALUES ($1, $2)`, id, buf)
return cfg, err
}
func TestDropDatabase(t *testing.T) {
defer leaktest.AfterTest(t)()
params, _ := tests.CreateTestServerParams()
s, sqlDB, kvDB := serverutils.StartServer(t, params)
defer s.Stopper().Stop(context.TODO())
ctx := context.TODO()
// Fix the column families so the key counts below don't change if the
// family heuristics are updated.
if _, err := sqlDB.Exec(`
CREATE DATABASE t;
CREATE TABLE t.kv (k CHAR PRIMARY KEY, v CHAR, FAMILY (k), FAMILY (v));
INSERT INTO t.kv VALUES ('c', 'e'), ('a', 'c'), ('b', 'd');
`); err != nil {
t.Fatal(err)
}
dbNameKey := sqlbase.NewDatabaseKey("t").Key()
r, err := kvDB.Get(ctx, dbNameKey)
if err != nil {
t.Fatal(err)
}
if !r.Exists() {
t.Fatalf(`database "t" does not exist`)
}
dbDescKey := sqlbase.MakeDescMetadataKey(sqlbase.ID(r.ValueInt()))
desc := &sqlbase.Descriptor{}
if err := kvDB.GetProto(ctx, dbDescKey, desc); err != nil {
t.Fatal(err)
}
dbDesc := desc.GetDatabase()
tbNameKey := sqlbase.NewPublicTableKey(dbDesc.ID, "kv").Key()
gr, err := kvDB.Get(ctx, tbNameKey)
if err != nil {
t.Fatal(err)
}
if !gr.Exists() {
t.Fatalf(`table "kv" does not exist`)
}
tbDescKey := sqlbase.MakeDescMetadataKey(sqlbase.ID(gr.ValueInt()))
ts, err := kvDB.GetProtoTs(ctx, tbDescKey, desc)
if err != nil {
t.Fatal(err)
}
tbDesc := desc.Table(ts)
// Add a zone config for both the table and database.
cfg := zonepb.DefaultZoneConfig()
buf, err := protoutil.Marshal(&cfg)
if err != nil {
t.Fatal(err)
}
if _, err := sqlDB.Exec(`INSERT INTO system.zones VALUES ($1, $2)`, tbDesc.ID, buf); err != nil {
t.Fatal(err)
}
if _, err := sqlDB.Exec(`INSERT INTO system.zones VALUES ($1, $2)`, dbDesc.ID, buf); err != nil {
t.Fatal(err)
}
if err := zoneExists(sqlDB, &cfg, tbDesc.ID); err != nil {
t.Fatal(err)
}
if err := zoneExists(sqlDB, &cfg, dbDesc.ID); err != nil {
t.Fatal(err)
}
tableSpan := tbDesc.TableSpan()
tests.CheckKeyCount(t, kvDB, tableSpan, 6)
if _, err := sqlDB.Exec(`DROP DATABASE t RESTRICT`); !testutils.IsError(err,
`database "t" is not empty`) {
t.Fatal(err)
}
if _, err := sqlDB.Exec(`DROP DATABASE t CASCADE`); err != nil {
t.Fatal(err)
}
// Data is not deleted.
tests.CheckKeyCount(t, kvDB, tableSpan, 6)
if err := descExists(sqlDB, true, tbDesc.ID); err != nil {
t.Fatal(err)
}
if gr, err := kvDB.Get(ctx, tbNameKey); err != nil {
t.Fatal(err)
} else if gr.Exists() {
t.Fatalf("table descriptor key still exists after database is dropped")
}
if err := descExists(sqlDB, false, dbDesc.ID); err != nil {
t.Fatal(err)
}
// Database zone config is removed once all table data and zone configs are removed.
if err := zoneExists(sqlDB, &cfg, dbDesc.ID); err != nil {
t.Fatal(err)
}
if gr, err := kvDB.Get(ctx, dbNameKey); err != nil {
t.Fatal(err)
} else if gr.Exists() {
t.Fatalf("database descriptor key still exists after database is dropped")
}
if err := zoneExists(sqlDB, &cfg, tbDesc.ID); err != nil {
t.Fatal(err)
}
// Job still running, waiting for GC.
// TODO (lucy): The offset of +4 accounts for unrelated startup migrations.
// Maybe this test API should use an offset starting from the most recent job
// instead.
sqlRun := sqlutils.MakeSQLRunner(sqlDB)
if err := jobutils.VerifySystemJob(t, sqlRun, 4, jobspb.TypeSchemaChange, jobs.StatusSucceeded, jobs.Record{
Username: security.RootUser,
Description: "DROP DATABASE t CASCADE",
DescriptorIDs: sqlbase.IDs{
tbDesc.ID,
},
}); err != nil {
t.Fatal(err)
}
}
// Test that an empty, dropped database's zone config gets deleted immediately.
func TestDropDatabaseEmpty(t *testing.T) {
defer leaktest.AfterTest(t)()
params, _ := tests.CreateTestServerParams()
s, sqlDB, kvDB := serverutils.StartServer(t, params)
defer s.Stopper().Stop(context.TODO())
ctx := context.TODO()
if _, err := sqlDB.Exec(`
CREATE DATABASE t;
`); err != nil {
t.Fatal(err)
}
dKey := sqlbase.NewDatabaseKey("t")
r, err := kvDB.Get(ctx, dKey.Key())
if err != nil {
t.Fatal(err)
}
if !r.Exists() {
t.Fatalf(`database "t" does not exist`)
}
dbID := sqlbase.ID(r.ValueInt())
if cfg, err := addDefaultZoneConfig(sqlDB, dbID); err != nil {
t.Fatal(err)
} else if err := zoneExists(sqlDB, &cfg, dbID); err != nil {
t.Fatal(err)
}
if _, err := sqlDB.Exec(`DROP DATABASE t`); err != nil {
t.Fatal(err)
}
if err := descExists(sqlDB, false, dbID); err != nil {
t.Fatal(err)
}
if err := zoneExists(sqlDB, nil, dbID); err != nil {
t.Fatal(err)
}
}
// Test that a dropped database's data gets deleted properly.
func TestDropDatabaseDeleteData(t *testing.T) {
defer leaktest.AfterTest(t)()
defer func(i time.Duration) { gcjob.MaxSQLGCInterval = i }(gcjob.MaxSQLGCInterval)
gcjob.MaxSQLGCInterval = 500 * time.Millisecond
params, _ := tests.CreateTestServerParams()
s, sqlDB, kvDB := serverutils.StartServer(t, params)
defer s.Stopper().Stop(context.TODO())
ctx := context.TODO()
// Disable strict GC TTL enforcement because we're going to shove a zero-value
// TTL into the system with addImmediateGCZoneConfig.
defer disableGCTTLStrictEnforcement(t, sqlDB)()
// Fix the column families so the key counts below don't change if the
// family heuristics are updated.
if _, err := sqlDB.Exec(`
CREATE DATABASE t;
CREATE TABLE t.kv (k CHAR PRIMARY KEY, v CHAR, FAMILY (k), FAMILY (v));
INSERT INTO t.kv VALUES ('c', 'e'), ('a', 'c'), ('b', 'd');
CREATE TABLE t.kv2 (k CHAR PRIMARY KEY, v CHAR, FAMILY (k), FAMILY (v));
INSERT INTO t.kv2 VALUES ('c', 'd'), ('a', 'b'), ('e', 'a');
`); err != nil {
t.Fatal(err)
}
dKey := sqlbase.NewDatabaseKey("t")
r, err := kvDB.Get(ctx, dKey.Key())
if err != nil {
t.Fatal(err)
}
if !r.Exists() {
t.Fatalf(`database "t" does not exist`)
}
dbDescKey := sqlbase.MakeDescMetadataKey(sqlbase.ID(r.ValueInt()))
desc := &sqlbase.Descriptor{}
if err := kvDB.GetProto(ctx, dbDescKey, desc); err != nil {
t.Fatal(err)
}
dbDesc := desc.GetDatabase()
tKey := sqlbase.NewPublicTableKey(dbDesc.ID, "kv")
gr, err := kvDB.Get(ctx, tKey.Key())
if err != nil {
t.Fatal(err)
}
if !gr.Exists() {
t.Fatalf(`table "kv" does not exist`)
}
tbDescKey := sqlbase.MakeDescMetadataKey(sqlbase.ID(gr.ValueInt()))
ts, err := kvDB.GetProtoTs(ctx, tbDescKey, desc)
if err != nil {
t.Fatal(err)
}
tbDesc := desc.Table(ts)
t2Key := sqlbase.NewPublicTableKey(dbDesc.ID, "kv2")
gr2, err := kvDB.Get(ctx, t2Key.Key())
if err != nil {
t.Fatal(err)
}
if !gr2.Exists() {
t.Fatalf(`table "kv2" does not exist`)
}
tb2DescKey := sqlbase.MakeDescMetadataKey(sqlbase.ID(gr2.ValueInt()))
ts, err = kvDB.GetProtoTs(ctx, tb2DescKey, desc)
if err != nil {
t.Fatal(err)
}
tb2Desc := desc.Table(ts)
tableSpan := tbDesc.TableSpan()
table2Span := tb2Desc.TableSpan()
tests.CheckKeyCount(t, kvDB, tableSpan, 6)
tests.CheckKeyCount(t, kvDB, table2Span, 6)
if _, err := addDefaultZoneConfig(sqlDB, dbDesc.ID); err != nil {
t.Fatal(err)
}
if _, err := sqlDB.Exec(`DROP DATABASE t RESTRICT`); !testutils.IsError(err,
`database "t" is not empty`) {
t.Fatal(err)
}
if _, err := sqlDB.Exec(`DROP DATABASE t CASCADE`); err != nil {
t.Fatal(err)
}
tests.CheckKeyCount(t, kvDB, tableSpan, 6)
tests.CheckKeyCount(t, kvDB, table2Span, 6)
// TODO (lucy): The offset of +4 accounts for unrelated startup migrations.
// Maybe this test API should use an offset starting from the most recent job
// instead.
jobsOffset := 4
sqlRun := sqlutils.MakeSQLRunner(sqlDB)
if err := jobutils.VerifySystemJob(t, sqlRun, jobsOffset, jobspb.TypeSchemaChange, jobs.StatusSucceeded, jobs.Record{
Username: security.RootUser,
Description: "DROP DATABASE t CASCADE",
DescriptorIDs: sqlbase.IDs{
tbDesc.ID, tb2Desc.ID,
},
}); err != nil {
t.Fatal(err)
}
// Push a new zone config for the table with TTL=0 so the data is
// deleted immediately.
if _, err := addImmediateGCZoneConfig(sqlDB, tbDesc.ID); err != nil {
t.Fatal(err)
}
testutils.SucceedsSoon(t, func() error {
if err := descExists(sqlDB, false, tbDesc.ID); err != nil {
return err
}
return zoneExists(sqlDB, nil, tbDesc.ID)
})
// Table 1 data is deleted.
tests.CheckKeyCount(t, kvDB, tableSpan, 0)
tests.CheckKeyCount(t, kvDB, table2Span, 6)
def := zonepb.DefaultZoneConfig()
if err := zoneExists(sqlDB, &def, dbDesc.ID); err != nil {
t.Fatal(err)
}
if err := jobutils.VerifySystemJob(t, sqlRun, 0, jobspb.TypeSchemaChangeGC, jobs.StatusRunning, jobs.Record{
Username: security.RootUser,
Description: "GC for DROP DATABASE t CASCADE",
DescriptorIDs: sqlbase.IDs{
tbDesc.ID, tb2Desc.ID,
},
}); err != nil {
t.Fatal(err)
}
if _, err := addImmediateGCZoneConfig(sqlDB, tb2Desc.ID); err != nil {
t.Fatal(err)
}
if _, err := addImmediateGCZoneConfig(sqlDB, dbDesc.ID); err != nil {
t.Fatal(err)
}
testutils.SucceedsSoon(t, func() error {
if err := descExists(sqlDB, false, tb2Desc.ID); err != nil {
return err
}
return zoneExists(sqlDB, nil, tb2Desc.ID)
})
// Table 2 data is deleted.
tests.CheckKeyCount(t, kvDB, table2Span, 0)
if err := jobutils.VerifySystemJob(t, sqlRun, jobsOffset, jobspb.TypeSchemaChange, jobs.StatusSucceeded, jobs.Record{
Username: security.RootUser,
Description: "DROP DATABASE t CASCADE",
DescriptorIDs: sqlbase.IDs{
tbDesc.ID, tb2Desc.ID,
},
}); err != nil {
t.Fatal(err)
}
// Database zone config is removed once all table data and zone configs are removed.
if err := zoneExists(sqlDB, nil, dbDesc.ID); err != nil {
t.Fatal(err)
}
}
// Tests that SHOW TABLES works correctly when a database is recreated
// during the time the underlying tables are still being deleted.
func TestShowTablesAfterRecreateDatabase(t *testing.T) {
defer leaktest.AfterTest(t)()
params, _ := tests.CreateTestServerParams()
// Turn off the application of schema changes so that tables do not
// get completely dropped.
params.Knobs = base.TestingKnobs{
SQLSchemaChanger: &sql.SchemaChangerTestingKnobs{
SchemaChangeJobNoOp: func() bool {
return true
},
},
}
s, sqlDB, _ := serverutils.StartServer(t, params)
defer s.Stopper().Stop(context.TODO())
if _, err := sqlDB.Exec(`
CREATE DATABASE t;
CREATE TABLE t.kv (k CHAR PRIMARY KEY, v CHAR);
INSERT INTO t.kv VALUES ('c', 'e'), ('a', 'c'), ('b', 'd');
`); err != nil {
t.Fatal(err)
}
if _, err := sqlDB.Exec(`
DROP DATABASE t CASCADE;
CREATE DATABASE t;
`); err != nil {
t.Fatal(err)
}
rows, err := sqlDB.Query(`
SET DATABASE=t;
SHOW TABLES;
`)
if err != nil {
t.Fatal(err)
}
defer rows.Close()
if rows.Next() {
t.Fatal("table should be invisible through SHOW TABLES")
}
}
func TestDropIndex(t *testing.T) {
defer leaktest.AfterTest(t)()
const chunkSize = 200
params, _ := tests.CreateTestServerParams()
emptySpan := true
clearIndexAttempt := false
params.Knobs = base.TestingKnobs{
SQLSchemaChanger: &sql.SchemaChangerTestingKnobs{
BackfillChunkSize: chunkSize,
},
DistSQL: &execinfra.TestingKnobs{
RunBeforeBackfillChunk: func(sp roachpb.Span) error {
if clearIndexAttempt && (sp.Key != nil || sp.EndKey != nil) {
emptySpan = false
}
return nil
},
},
}
s, sqlDB, kvDB := serverutils.StartServer(t, params)
defer s.Stopper().Stop(context.TODO())
// Disable strict GC TTL enforcement because we're going to shove a zero-value
// TTL into the system with addImmediateGCZoneConfig.
defer disableGCTTLStrictEnforcement(t, sqlDB)()
numRows := 2*chunkSize + 1
if err := tests.CreateKVTable(sqlDB, "kv", numRows); err != nil {
t.Fatal(err)
}
tableDesc := sqlbase.GetTableDescriptor(kvDB, "t", "kv")
tests.CheckKeyCount(t, kvDB, tableDesc.TableSpan(), 3*numRows)
idx, _, err := tableDesc.FindIndexByName("foo")
if err != nil {
t.Fatal(err)
}
indexSpan := tableDesc.IndexSpan(idx.ID)
tests.CheckKeyCount(t, kvDB, indexSpan, numRows)
if _, err := sqlDB.Exec(`DROP INDEX t.kv@foo`); err != nil {
t.Fatal(err)
}
tableDesc = sqlbase.GetTableDescriptor(kvDB, "t", "kv")
if _, _, err := tableDesc.FindIndexByName("foo"); err == nil {
t.Fatalf("table descriptor still contains index after index is dropped")
}
// Index data hasn't been deleted.
tests.CheckKeyCount(t, kvDB, indexSpan, numRows)
tests.CheckKeyCount(t, kvDB, tableDesc.TableSpan(), 3*numRows)
// TODO (lucy): The offset of +4 accounts for unrelated startup migrations.
// Maybe this test API should use an offset starting from the most recent job
// instead.
migrationJobOffset := 4
sqlRun := sqlutils.MakeSQLRunner(sqlDB)
if err := jobutils.VerifySystemJob(t, sqlRun, migrationJobOffset+1, jobspb.TypeSchemaChange, jobs.StatusSucceeded, jobs.Record{
Username: security.RootUser,
Description: `DROP INDEX t.public.kv@foo`,
DescriptorIDs: sqlbase.IDs{
tableDesc.ID,
},
}); err != nil {
t.Fatal(err)
}
if _, err := sqlDB.Exec(`CREATE INDEX foo on t.kv (v);`); err != nil {
t.Fatal(err)
}
tableDesc = sqlbase.GetTableDescriptor(kvDB, "t", "kv")
newIdx, _, err := tableDesc.FindIndexByName("foo")
if err != nil {
t.Fatal(err)
}
newIdxSpan := tableDesc.IndexSpan(newIdx.ID)
tests.CheckKeyCount(t, kvDB, newIdxSpan, numRows)
tests.CheckKeyCount(t, kvDB, tableDesc.TableSpan(), 4*numRows)
clearIndexAttempt = true
// Add a zone config for the table.
if _, err := addImmediateGCZoneConfig(sqlDB, tableDesc.ID); err != nil {
t.Fatal(err)
}
testutils.SucceedsSoon(t, func() error {
return jobutils.VerifySystemJob(t, sqlRun, migrationJobOffset+1, jobspb.TypeSchemaChange, jobs.StatusSucceeded, jobs.Record{
Username: security.RootUser,
Description: `DROP INDEX t.public.kv@foo`,
DescriptorIDs: sqlbase.IDs{
tableDesc.ID,
},
})
})
testutils.SucceedsSoon(t, func() error {
return jobutils.VerifySystemJob(t, sqlRun, 0, jobspb.TypeSchemaChangeGC, jobs.StatusSucceeded, jobs.Record{
Username: security.RootUser,
Description: `GC for DROP INDEX t.public.kv@foo`,
DescriptorIDs: sqlbase.IDs{
tableDesc.ID,
},
})
})
if !emptySpan {
t.Fatalf("tried to clear index with non-empty resume span")
}
tests.CheckKeyCount(t, kvDB, newIdxSpan, numRows)
tests.CheckKeyCount(t, kvDB, indexSpan, 0)
tests.CheckKeyCount(t, kvDB, tableDesc.TableSpan(), 3*numRows)
}
func TestDropIndexWithZoneConfigOSS(t *testing.T) {
defer leaktest.AfterTest(t)()
const chunkSize = 200
const numRows = 2*chunkSize + 1
params, _ := tests.CreateTestServerParams()
params.Knobs = base.TestingKnobs{
SQLSchemaChanger: &sql.SchemaChangerTestingKnobs{BackfillChunkSize: chunkSize},
}
s, sqlDBRaw, kvDB := serverutils.StartServer(t, params)
sqlDB := sqlutils.MakeSQLRunner(sqlDBRaw)
defer s.Stopper().Stop(context.Background())
// Create a test table with a secondary index.
if err := tests.CreateKVTable(sqlDBRaw, "kv", numRows); err != nil {
t.Fatal(err)
}
tableDesc := sqlbase.GetTableDescriptor(kvDB, "t", "kv")
indexDesc, _, err := tableDesc.FindIndexByName("foo")
if err != nil {
t.Fatal(err)
}
indexSpan := tableDesc.IndexSpan(indexDesc.ID)
tests.CheckKeyCount(t, kvDB, indexSpan, numRows)
// Hack in zone configs for the primary and secondary indexes. (You need a CCL
// binary to do this properly.) Dropping the index will thus require
// regenerating the zone config's SubzoneSpans, which will fail with a "CCL
// required" error.
zoneConfig := zonepb.ZoneConfig{
Subzones: []zonepb.Subzone{
{IndexID: uint32(tableDesc.PrimaryIndex.ID), Config: s.(*server.TestServer).Cfg.DefaultZoneConfig},
{IndexID: uint32(indexDesc.ID), Config: s.(*server.TestServer).Cfg.DefaultZoneConfig},
},
}
zoneConfigBytes, err := protoutil.Marshal(&zoneConfig)
if err != nil {
t.Fatal(err)
}
sqlDB.Exec(t, `INSERT INTO system.zones VALUES ($1, $2)`, tableDesc.ID, zoneConfigBytes)
if !sqlutils.ZoneConfigExists(t, sqlDB, "INDEX t.public.kv@foo") {
t.Fatal("zone config for index does not exist")
}
// Verify that dropping the index works.
_, err = sqlDBRaw.Exec(`DROP INDEX t.kv@foo`)
require.NoError(t, err)
// Verify that the index and its zone config still exist.
if sqlutils.ZoneConfigExists(t, sqlDB, "INDEX t.public.kv@foo") {
t.Fatal("zone config for index still exists")
}
tests.CheckKeyCount(t, kvDB, indexSpan, numRows)
// TODO(benesch): Run scrub here. It can't currently handle the way t.kv
// declares column families.
tableDesc = sqlbase.GetTableDescriptor(kvDB, "t", "kv")
if _, _, err := tableDesc.FindIndexByName("foo"); err == nil {
t.Fatalf("table descriptor still contains index after index is dropped")
}
}
func TestDropIndexInterleaved(t *testing.T) {
defer leaktest.AfterTest(t)()
const chunkSize = 200
params, _ := tests.CreateTestServerParams()
params.Knobs = base.TestingKnobs{
SQLSchemaChanger: &sql.SchemaChangerTestingKnobs{
BackfillChunkSize: chunkSize,
},
}
s, sqlDB, kvDB := serverutils.StartServer(t, params)
defer s.Stopper().Stop(context.TODO())
numRows := 2*chunkSize + 1
tests.CreateKVInterleavedTable(t, sqlDB, numRows)
tableDesc := sqlbase.GetTableDescriptor(kvDB, "t", "kv")
tableSpan := tableDesc.TableSpan()
tests.CheckKeyCount(t, kvDB, tableSpan, 3*numRows)
if _, err := sqlDB.Exec(`DROP INDEX t.intlv@intlv_idx`); err != nil {
t.Fatal(err)
}
tests.CheckKeyCount(t, kvDB, tableSpan, 2*numRows)
// Ensure that index is not active.
tableDesc = sqlbase.GetTableDescriptor(kvDB, "t", "intlv")
if _, _, err := tableDesc.FindIndexByName("intlv_idx"); err == nil {
t.Fatalf("table descriptor still contains index after index is dropped")
}
}
// Tests DROP TABLE and also checks that the table data is not deleted
// via the synchronous path.
func TestDropTable(t *testing.T) {
defer leaktest.AfterTest(t)()
params, _ := tests.CreateTestServerParams()
s, sqlDB, kvDB := serverutils.StartServer(t, params)
defer s.Stopper().Stop(context.TODO())
ctx := context.TODO()
numRows := 2*sql.TableTruncateChunkSize + 1
if err := tests.CreateKVTable(sqlDB, "kv", numRows); err != nil {
t.Fatal(err)
}
tableDesc := sqlbase.GetTableDescriptor(kvDB, "t", "kv")
nameKey := sqlbase.NewPublicTableKey(keys.MinNonPredefinedUserDescID, "kv").Key()
gr, err := kvDB.Get(ctx, nameKey)
if err != nil {
t.Fatal(err)
}
if !gr.Exists() {
t.Fatalf("Name entry %q does not exist", nameKey)
}
// Add a zone config for the table.
cfg, err := addDefaultZoneConfig(sqlDB, tableDesc.ID)
if err != nil {
t.Fatal(err)
}
if err := zoneExists(sqlDB, &cfg, tableDesc.ID); err != nil {
t.Fatal(err)
}
tableSpan := tableDesc.TableSpan()
tests.CheckKeyCount(t, kvDB, tableSpan, 3*numRows)
if _, err := sqlDB.Exec(`DROP TABLE t.kv`); err != nil {
t.Fatal(err)
}
// Test that deleted table cannot be used. This prevents
// regressions where name -> descriptor ID caches might make
// this statement erronously work.
if _, err := sqlDB.Exec(
`SELECT * FROM t.kv`,
); !testutils.IsError(err, `relation "t.kv" does not exist`) {
t.Fatalf("different error than expected: %+v", err)
}
if gr, err := kvDB.Get(ctx, nameKey); err != nil {
t.Fatal(err)
} else if gr.Exists() {
t.Fatalf("table namekey still exists")
}
// Job still running, waiting for GC.
sqlRun := sqlutils.MakeSQLRunner(sqlDB)
if err := jobutils.VerifySystemJob(t, sqlRun, 5, jobspb.TypeSchemaChange, jobs.StatusSucceeded, jobs.Record{
Username: security.RootUser,
Description: `DROP TABLE t.public.kv`,
DescriptorIDs: sqlbase.IDs{
tableDesc.ID,
},
}); err != nil {
t.Fatal(err)
}
// Can create a table with the same name.
if err := tests.CreateKVTable(sqlDB, "kv", numRows); err != nil {
t.Fatal(err)
}
// A lot of garbage has been left behind to be cleaned up by the
// asynchronous path.
tests.CheckKeyCount(t, kvDB, tableSpan, 3*numRows)
if err := descExists(sqlDB, true, tableDesc.ID); err != nil {
t.Fatal(err)
}
if err := zoneExists(sqlDB, &cfg, tableDesc.ID); err != nil {
t.Fatal(err)
}
}
// Test that after a DROP TABLE the table eventually gets deleted.
func TestDropTableDeleteData(t *testing.T) {
defer leaktest.AfterTest(t)()
params, _ := tests.CreateTestServerParams()
defer func(i time.Duration) { gcjob.MaxSQLGCInterval = i }(gcjob.MaxSQLGCInterval)
gcjob.MaxSQLGCInterval = 500 * time.Millisecond
s, sqlDB, kvDB := serverutils.StartServer(t, params)
defer s.Stopper().Stop(context.TODO())
ctx := context.TODO()
// Disable strict GC TTL enforcement because we're going to shove a zero-value
// TTL into the system with addImmediateGCZoneConfig.
defer disableGCTTLStrictEnforcement(t, sqlDB)()
const numRows = 2*sql.TableTruncateChunkSize + 1
const numKeys = 3 * numRows
const numTables = 5
var descs []*sqlbase.TableDescriptor
for i := 0; i < numTables; i++ {
tableName := fmt.Sprintf("test%d", i)
if err := tests.CreateKVTable(sqlDB, tableName, numRows); err != nil {
t.Fatal(err)
}
descs = append(descs, sqlbase.GetTableDescriptor(kvDB, "t", tableName))
nameKey := sqlbase.NewPublicTableKey(keys.MinNonPredefinedUserDescID, tableName).Key()
gr, err := kvDB.Get(ctx, nameKey)
if err != nil {
t.Fatal(err)
}
if !gr.Exists() {
t.Fatalf("Name entry %q does not exist", nameKey)
}
tableSpan := descs[i].TableSpan()
tests.CheckKeyCount(t, kvDB, tableSpan, numKeys)
if _, err := sqlDB.Exec(fmt.Sprintf(`DROP TABLE t.%s`, tableName)); err != nil {
t.Fatal(err)
}
}
// TODO (lucy): The offset of +4 accounts for unrelated startup migrations.
// Maybe this test API should use an offset starting from the most recent job
// instead.
schemaChangeJobOffset := 4
// Data hasn't been GC-ed.
sqlRun := sqlutils.MakeSQLRunner(sqlDB)
for i := 0; i < numTables; i++ {
if err := descExists(sqlDB, true, descs[i].ID); err != nil {
t.Fatal(err)
}
tableSpan := descs[i].TableSpan()
tests.CheckKeyCount(t, kvDB, tableSpan, numKeys)
if err := jobutils.VerifySystemJob(t, sqlRun, 2*i+1+schemaChangeJobOffset, jobspb.TypeSchemaChange, jobs.StatusSucceeded, jobs.Record{
Username: security.RootUser,
Description: fmt.Sprintf(`DROP TABLE t.public.%s`, descs[i].GetName()),
DescriptorIDs: sqlbase.IDs{
descs[i].ID,
},
}); err != nil {
t.Fatal(err)
}
}
// The closure pushes a zone config reducing the TTL to 0 for descriptor i.
pushZoneCfg := func(i int) {
if _, err := addImmediateGCZoneConfig(sqlDB, descs[i].ID); err != nil {
t.Fatal(err)
}
}
checkTableGCed := func(i int) {
testutils.SucceedsSoon(t, func() error {
if err := descExists(sqlDB, false, descs[i].ID); err != nil {
return err
}
return zoneExists(sqlDB, nil, descs[i].ID)
})
tableSpan := descs[i].TableSpan()
tests.CheckKeyCount(t, kvDB, tableSpan, 0)
// Ensure that the job is marked as succeeded.
if err := jobutils.VerifySystemJob(t, sqlRun, 2*i+1+schemaChangeJobOffset, jobspb.TypeSchemaChange, jobs.StatusSucceeded, jobs.Record{
Username: security.RootUser,
Description: fmt.Sprintf(`DROP TABLE t.public.%s`, descs[i].GetName()),
DescriptorIDs: sqlbase.IDs{
descs[i].ID,
},
}); err != nil {
t.Fatal(err)
}
// Ensure that the job is marked as succeeded.
if err := jobutils.VerifySystemJob(t, sqlRun, i, jobspb.TypeSchemaChangeGC, jobs.StatusSucceeded, jobs.Record{
Username: security.RootUser,
Description: fmt.Sprintf(`GC for DROP TABLE t.public.%s`, descs[i].GetName()),
DescriptorIDs: sqlbase.IDs{
descs[i].ID,
},
}); err != nil {
t.Fatal(err)
}
}
// Push a new zone config for a few tables with TTL=0 so the data
// is deleted immediately.
barrier := rand.Intn(numTables)
for i := 0; i < barrier; i++ {
pushZoneCfg(i)
}
// Check GC worked!
for i := 0; i < numTables; i++ {
if i < barrier {
checkTableGCed(i)
} else {
// Data still present for tables past barrier.
tableSpan := descs[i].TableSpan()
tests.CheckKeyCount(t, kvDB, tableSpan, numKeys)
}
}
// Push the rest of the zone configs and check all the data gets GC-ed.
for i := barrier; i < numTables; i++ {
pushZoneCfg(i)
}
for i := barrier; i < numTables; i++ {
checkTableGCed(i)
}
}
func writeTableDesc(ctx context.Context, db *kv.DB, tableDesc *sqlbase.TableDescriptor) error {
return db.Txn(ctx, func(ctx context.Context, txn *kv.Txn) error {
if err := txn.SetSystemConfigTrigger(); err != nil {
return err
}
tableDesc.ModificationTime = txn.CommitTimestamp()
return txn.Put(ctx, sqlbase.MakeDescMetadataKey(tableDesc.ID), sqlbase.WrapDescriptor(tableDesc))
})
}
// TestDropTableWhileUpgradingFormat ensures that it's safe for a migration to
// upgrade the table descriptor's format while the table is scheduled to be
// dropped.
//
// The new format must be backwards-compatible with the old format, but that's
// true in general.
func TestDropTableWhileUpgradingFormat(t *testing.T) {
defer leaktest.AfterTest(t)()
ctx := context.Background()
defer func(i time.Duration) { gcjob.MaxSQLGCInterval = i }(gcjob.MaxSQLGCInterval)
gcjob.MaxSQLGCInterval = 500 * time.Millisecond
params, _ := tests.CreateTestServerParams()
params.Knobs = base.TestingKnobs{
SQLMigrationManager: &sqlmigrations.MigrationManagerTestingKnobs{
DisableBackfillMigrations: true,
},
}
s, sqlDBRaw, kvDB := serverutils.StartServer(t, params)
defer s.Stopper().Stop(ctx)
sqlDB := sqlutils.MakeSQLRunner(sqlDBRaw)
// Disable strict GC TTL enforcement because we're going to shove a zero-value
// TTL into the system with addImmediateGCZoneConfig.
defer disableGCTTLStrictEnforcement(t, sqlDBRaw)()
const numRows = 100
sqlutils.CreateTable(t, sqlDBRaw, "t", "a INT", numRows, sqlutils.ToRowFn(sqlutils.RowIdxFn))
// Give the table an old format version.
tableDesc := sqlbase.GetTableDescriptor(kvDB, "test", "t")
tableDesc.FormatVersion = sqlbase.FamilyFormatVersion
tableDesc.Version++
if err := writeTableDesc(ctx, kvDB, tableDesc); err != nil {
t.Fatal(err)
}
tableSpan := tableDesc.TableSpan()
tests.CheckKeyCount(t, kvDB, tableSpan, numRows)
sqlDB.Exec(t, `DROP TABLE test.t`)