-
Notifications
You must be signed in to change notification settings - Fork 3.8k
/
Copy pathsequence_test.go
826 lines (732 loc) · 27 KB
/
sequence_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
// Copyright 2018 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"
"fmt"
"math"
"math/rand"
"sync"
"testing"
"github.com/cockroachdb/cockroach/pkg/base"
"github.com/cockroachdb/cockroach/pkg/keys"
"github.com/cockroachdb/cockroach/pkg/kv"
"github.com/cockroachdb/cockroach/pkg/sql/catalog"
"github.com/cockroachdb/cockroach/pkg/sql/catalog/catalogkeys"
"github.com/cockroachdb/cockroach/pkg/sql/catalog/catalogkv"
"github.com/cockroachdb/cockroach/pkg/testutils/serverutils"
"github.com/cockroachdb/cockroach/pkg/testutils/sqlutils"
"github.com/cockroachdb/cockroach/pkg/testutils/testcluster"
"github.com/cockroachdb/cockroach/pkg/util/leaktest"
"github.com/stretchr/testify/require"
)
func BenchmarkSequenceIncrement(b *testing.B) {
runSubBenchMark := func(b *testing.B, cacheSize int, parallelism int) {
subBenchMark := func(b *testing.B) {
cluster := serverutils.StartNewTestCluster(b, 3, base.TestClusterArgs{})
defer cluster.Stopper().Stop(context.Background())
sqlDB := cluster.ServerConn(0)
if _, err := sqlDB.Exec(fmt.Sprintf(`
CREATE SEQUENCE seq CACHE %d;
CREATE TABLE tbl (
id INT PRIMARY KEY DEFAULT nextval('seq'),
foo text
);
`, cacheSize)); err != nil {
b.Fatal(err)
}
b.SetParallelism(parallelism)
b.ResetTimer()
b.RunParallel(func(pb *testing.PB) {
session, err := sqlDB.Conn(context.Background())
if err != nil {
b.Fatal(err)
}
conn := sqlutils.MakeSQLRunner(session)
for pb.Next() {
conn.Exec(b, "INSERT INTO tbl (foo) VALUES ('foo')")
}
if err = session.Close(); err != nil {
b.Fatal(err)
}
})
}
b.Run(fmt.Sprintf("Cache-%d-P-%d", cacheSize, parallelism), subBenchMark)
}
cacheSizes := []int{1, 32, 64, 128, 256, 512}
parallelism := []int{1, 2, 4, 8}
for _, cacheSize := range cacheSizes {
for _, p := range parallelism {
runSubBenchMark(b, cacheSize, p)
}
}
}
func BenchmarkUniqueRowID(b *testing.B) {
cluster := serverutils.StartNewTestCluster(b, 3, base.TestClusterArgs{})
defer cluster.Stopper().Stop(context.Background())
sqlDB := cluster.ServerConn(0)
if _, err := sqlDB.Exec(`
CREATE DATABASE test;
USE test;
CREATE TABLE tbl (
id INT PRIMARY KEY DEFAULT unique_rowid(),
foo text
);
`); err != nil {
b.Fatal(err)
}
b.ResetTimer()
for n := 0; n < b.N; n++ {
if _, err := sqlDB.Exec("INSERT INTO tbl (foo) VALUES ('foo')"); err != nil {
b.Fatal(err)
}
}
b.StopTimer()
}
// Regression test for #50711. The root cause of #50711 was the fact that a
// sequenceID popped up in multiple columns' column descriptor. This test
// inspects the table descriptor to ascertain that sequence ownership integrity
// is preserved in various scenarios.
// Scenarios tested:
// - ownership swaps between table columns
// - two sequences being owned simultaneously
// - sequence drops
// - ownership removal
func TestSequenceOwnershipDependencies(t *testing.T) {
defer leaktest.AfterTest(t)()
ctx := context.Background()
params := base.TestServerArgs{}
s, sqlConn, kvDB := serverutils.StartServer(t, params)
defer s.Stopper().Stop(ctx)
if _, err := sqlConn.Exec(`
CREATE DATABASE t;
CREATE TABLE t.test(a INT PRIMARY KEY, b INT)`); err != nil {
t.Fatal(err)
}
// Switch ownership between columns of the same table.
if _, err := sqlConn.Exec("CREATE SEQUENCE t.seq1 OWNED BY t.test.a"); err != nil {
t.Fatal(err)
}
assertColumnOwnsSequences(t, kvDB, "t", "test", 0 /* colIdx */, []string{"seq1"})
assertColumnOwnsSequences(t, kvDB, "t", "test", 1 /* colIdx */, nil /* seqNames */)
if _, err := sqlConn.Exec("ALTER SEQUENCE t.seq1 OWNED BY t.test.b"); err != nil {
t.Fatal(err)
}
assertColumnOwnsSequences(t, kvDB, "t", "test", 0 /* colIdx */, nil /* seqNames */)
assertColumnOwnsSequences(t, kvDB, "t", "test", 1 /* colIdx */, []string{"seq1"})
if _, err := sqlConn.Exec("ALTER SEQUENCE t.seq1 OWNED BY t.test.a"); err != nil {
t.Fatal(err)
}
assertColumnOwnsSequences(t, kvDB, "t", "test", 0 /* colIdx */, []string{"seq1"})
assertColumnOwnsSequences(t, kvDB, "t", "test", 1 /* colIdx */, nil /* seqNames */)
// Add a second sequence in the mix and switch its ownership.
if _, err := sqlConn.Exec("CREATE SEQUENCE t.seq2 OWNED BY t.test.a"); err != nil {
t.Fatal(err)
}
assertColumnOwnsSequences(t, kvDB, "t", "test", 0 /* colIdx */, []string{"seq1", "seq2"})
assertColumnOwnsSequences(t, kvDB, "t", "test", 1 /* colIdx */, nil /* seqNames */)
if _, err := sqlConn.Exec("ALTER SEQUENCE t.seq2 OWNED BY t.test.b"); err != nil {
t.Fatal(err)
}
assertColumnOwnsSequences(t, kvDB, "t", "test", 0 /* colIdx */, []string{"seq1"})
assertColumnOwnsSequences(t, kvDB, "t", "test", 1 /* colIdx */, []string{"seq2"})
if _, err := sqlConn.Exec("ALTER SEQUENCE t.seq2 OWNED BY t.test.a"); err != nil {
t.Fatal(err)
}
assertColumnOwnsSequences(t, kvDB, "t", "test", 0 /* colIdx */, []string{"seq1", "seq2"})
assertColumnOwnsSequences(t, kvDB, "t", "test", 1 /* colIdx */, nil /* seqNames */)
// Ensure dropping sequences removes the ownership dependencies.
if _, err := sqlConn.Exec("DROP SEQUENCE t.seq1"); err != nil {
t.Fatal(err)
}
assertColumnOwnsSequences(t, kvDB, "t", "test", 0 /* colIdx */, []string{"seq2"})
assertColumnOwnsSequences(t, kvDB, "t", "test", 1 /* colIdx */, nil /* seqNames */)
// Ensure removing an owner removes the ownership dependency.
if _, err := sqlConn.Exec("ALTER SEQUENCE t.seq2 OWNED BY NONE"); err != nil {
t.Fatal(err)
}
assertColumnOwnsSequences(t, kvDB, "t", "test", 0 /* colIdx */, nil /* seqNames */)
assertColumnOwnsSequences(t, kvDB, "t", "test", 1 /* colIdx */, nil /* seqNames */)
}
// assertColumnOwnsSequences ensures that the column at (DbName, tbName, colIdx)
// owns all the sequences passed to it (in order) by looking up descriptors in
// kvDB.
func assertColumnOwnsSequences(
t *testing.T, kvDB *kv.DB, dbName string, tbName string, colIdx int, seqNames []string,
) {
tableDesc := catalogkv.TestingGetTableDescriptor(kvDB, keys.SystemSQLCodec, dbName, tbName)
col := tableDesc.PublicColumns()[colIdx]
var seqDescs []catalog.TableDescriptor
for _, seqName := range seqNames {
seqDescs = append(
seqDescs,
catalogkv.TestingGetTableDescriptor(kvDB, keys.SystemSQLCodec, dbName, seqName),
)
}
if col.NumOwnsSequences() != len(seqDescs) {
t.Fatalf(
"unexpected number of sequence ownership dependencies. expected: %d, got:%d",
len(seqDescs), col.NumOwnsSequences(),
)
}
for i := 0; i < col.NumOwnsSequences(); i++ {
seqID := col.GetOwnsSequenceID(i)
if seqID != seqDescs[i].GetID() {
t.Fatalf("unexpected sequence id. expected %d got %d", seqDescs[i].GetID(), seqID)
}
ownerTableID := seqDescs[i].GetSequenceOpts().SequenceOwner.OwnerTableID
ownerColID := seqDescs[i].GetSequenceOpts().SequenceOwner.OwnerColumnID
if ownerTableID != tableDesc.GetID() || ownerColID != col.GetID() {
t.Fatalf(
"unexpected sequence owner. expected table id %d, got: %d; expected column id %d, got :%d",
tableDesc.GetID(), ownerTableID, col.GetID(), ownerColID,
)
}
}
}
// Tests for allowing drops on sequence descriptors in a bad state due to
// ownership bugs. It should be possible to drop tables/sequences that have
// descriptors in an invalid state. See tracking issue #51770 for more details.
// Relevant sub-issues are referenced in test names/inline comments.
func TestInvalidOwnedDescriptorsAreDroppable(t *testing.T) {
defer leaktest.AfterTest(t)()
testCases := []struct {
name string
test func(*testing.T, *kv.DB, *sqlutils.SQLRunner)
}{
// Tests simulating #50711 by breaking the invariant that sequences are owned
// by at most one column at a time.
// Dropping the table should work when the table descriptor is in an invalid
// state. The owned sequence should also be dropped.
{
name: "#50711 drop table",
test: func(t *testing.T, kvDB *kv.DB, sqlDB *sqlutils.SQLRunner) {
addOwnedSequence(t, kvDB, "t", "test", 0, "seq")
addOwnedSequence(t, kvDB, "t", "test", 1, "seq")
sqlDB.Exec(t, "DROP TABLE t.test")
// The sequence should have been dropped as well.
sqlDB.ExpectErr(t, `pq: relation "t.seq" does not exist`, "SELECT * FROM t.seq")
// The valid sequence should have also been dropped.
sqlDB.ExpectErr(t, `pq: relation "t.valid_seq" does not exist`, "SELECT * FROM t.valid_seq")
},
},
{
name: "#50711 drop sequence followed by drop table",
test: func(t *testing.T, kvDB *kv.DB, sqlDB *sqlutils.SQLRunner) {
addOwnedSequence(t, kvDB, "t", "test", 0, "seq")
addOwnedSequence(t, kvDB, "t", "test", 1, "seq")
sqlDB.Exec(t, "DROP SEQUENCE t.seq")
sqlDB.Exec(t, "SELECT * FROM t.valid_seq")
sqlDB.Exec(t, "DROP TABLE t.test")
// The valid sequence should have also been dropped.
sqlDB.ExpectErr(t, `pq: relation "t.valid_seq" does not exist`, "SELECT * FROM t.valid_seq")
},
},
{
// This test invalidates both seq and useq as DROP DATABASE CASCADE operates
// on objects lexicographically -- owned sequences can be dropped both as a
// regular sequence drop and as a side effect of the owner table being dropped.
name: "#50711 drop database cascade",
test: func(t *testing.T, kvDB *kv.DB, sqlDB *sqlutils.SQLRunner) {
addOwnedSequence(t, kvDB, "t", "test", 0, "seq")
addOwnedSequence(t, kvDB, "t", "test", 1, "seq")
addOwnedSequence(t, kvDB, "t", "test", 0, "useq")
addOwnedSequence(t, kvDB, "t", "test", 1, "useq")
sqlDB.Exec(t, "DROP DATABASE t CASCADE")
},
},
// Tests simulating #50781 by modifying the sequence's owner to a table that
// doesn't exist and column's `ownsSequenceIDs` to sequences that don't exist.
{
name: "#50781 drop table followed by drop sequence",
test: func(t *testing.T, kvDB *kv.DB, sqlDB *sqlutils.SQLRunner) {
breakOwnershipMapping(t, kvDB, "t", "test", "seq")
sqlDB.Exec(t, "DROP TABLE t.test")
// The valid sequence should have also been dropped.
sqlDB.ExpectErr(t, `pq: relation "t.valid_seq" does not exist`, "SELECT * FROM t.valid_seq")
sqlDB.Exec(t, "DROP SEQUENCE t.seq")
},
},
{
name: "#50781 drop sequence followed by drop table",
test: func(t *testing.T, kvDB *kv.DB, sqlDB *sqlutils.SQLRunner) {
breakOwnershipMapping(t, kvDB, "t", "test", "seq")
sqlDB.Exec(t, "DROP SEQUENCE t.seq")
sqlDB.Exec(t, "DROP TABLE t.test")
// The valid sequence should have also been dropped.
sqlDB.ExpectErr(t, `pq: relation "t.valid_seq" does not exist`, "SELECT * FROM t.valid_seq")
},
},
// This test invalidates both seq and useq as DROP DATABASE CASCADE operates
// on objects lexicographically -- owned sequences can be dropped both as a
// regular sequence drop and as a side effect of the owner table being dropped.
{
name: "#50781 drop database cascade",
test: func(t *testing.T, kvDB *kv.DB, sqlDB *sqlutils.SQLRunner) {
breakOwnershipMapping(t, kvDB, "t", "test", "seq")
breakOwnershipMapping(t, kvDB, "t", "test", "useq")
sqlDB.Exec(t, "DROP DATABASE t CASCADE")
},
},
{
name: "combined #50711 #50781 drop table followed by sequence",
test: func(t *testing.T, kvDB *kv.DB, sqlDB *sqlutils.SQLRunner) {
addOwnedSequence(t, kvDB, "t", "test", 0, "seq")
addOwnedSequence(t, kvDB, "t", "test", 1, "seq")
breakOwnershipMapping(t, kvDB, "t", "test", "seq")
sqlDB.Exec(t, "DROP TABLE t.test")
// The valid sequence should have also been dropped.
sqlDB.ExpectErr(t, `pq: relation "t.valid_seq" does not exist`, "SELECT * FROM t.valid_seq")
sqlDB.Exec(t, "DROP SEQUENCE t.seq")
},
},
{
name: "combined #50711 #50781 drop sequence followed by table",
test: func(t *testing.T, kvDB *kv.DB, sqlDB *sqlutils.SQLRunner) {
addOwnedSequence(t, kvDB, "t", "test", 0, "seq")
addOwnedSequence(t, kvDB, "t", "test", 1, "seq")
breakOwnershipMapping(t, kvDB, "t", "test", "seq")
sqlDB.Exec(t, "DROP SEQUENCE t.seq")
sqlDB.Exec(t, "DROP TABLE t.test")
// The valid sequence should have also been dropped.
sqlDB.ExpectErr(t, `pq: relation "t.valid_seq" does not exist`, "SELECT * FROM t.valid_seq")
},
},
// This test invalidates both seq and useq as DROP DATABASE CASCADE operates
// on objects lexicographically -- owned sequences can be dropped both as a
// regular sequence drop and as a side effect of the owner table being dropped.
{
name: "combined #50711 #50781 drop database cascade",
test: func(t *testing.T, kvDB *kv.DB, sqlDB *sqlutils.SQLRunner) {
addOwnedSequence(t, kvDB, "t", "test", 0, "seq")
addOwnedSequence(t, kvDB, "t", "test", 1, "seq")
breakOwnershipMapping(t, kvDB, "t", "test", "seq")
addOwnedSequence(t, kvDB, "t", "test", 0, "useq")
addOwnedSequence(t, kvDB, "t", "test", 1, "useq")
breakOwnershipMapping(t, kvDB, "t", "test", "useq")
sqlDB.Exec(t, "DROP DATABASE t CASCADE")
},
},
}
for _, tc := range testCases {
t.Run(tc.name, func(t *testing.T) {
ctx := context.Background()
params := base.TestServerArgs{}
s, sqlConn, kvDB := serverutils.StartServer(t, params)
defer s.Stopper().Stop(ctx)
sqlDB := sqlutils.MakeSQLRunner(sqlConn)
sqlDB.Exec(t, `CREATE DATABASE t;
CREATE TABLE t.test(a INT PRIMARY KEY, b INT);
CREATE SEQUENCE t.seq OWNED BY t.test.a;
CREATE SEQUENCE t.useq OWNED BY t.test.a;
CREATE SEQUENCE t.valid_seq OWNED BY t.test.a`)
tc.test(t, kvDB, sqlDB)
})
}
}
// TestCachedSequences tests the behavior of cached sequences.
func TestCachedSequences(t *testing.T) {
defer leaktest.AfterTest(t)()
// Start test cluster.
ctx := context.Background()
tc := testcluster.StartTestCluster(t, 3, base.TestClusterArgs{})
defer tc.Stopper().Stop(ctx)
sqlSessions := []*sqlutils.SQLRunner{}
for i := 0; i < 3; i++ {
newConn, err := tc.ServerConn(0).Conn(ctx)
if err != nil {
t.Fatal(err)
}
sqlSessions = append(sqlSessions, sqlutils.MakeSQLRunner(newConn))
}
anySession := func() int {
return rand.Intn(3)
}
execStmt := func(t *testing.T, statement string) {
sqlSessions[anySession()].Exec(t, statement)
}
checkIntValue := func(t *testing.T, session int, statement string, value int) {
sqlSessions[session].CheckQueryResults(t, statement, [][]string{
{fmt.Sprintf("%d", value)},
})
}
testCases := []struct {
name string
test func(*testing.T)
}{
// Test a cached sequences in a single session.
{
name: "Single Session Cache Test",
test: func(t *testing.T) {
execStmt(t, `
CREATE SEQUENCE s
CACHE 5
INCREMENT BY 2
START WITH 2
`)
// The cache starts out empty. When the cache is empty, the underlying sequence in the database
// should be incremented by the cache size * increment amount, so it should increase by 10 each time.
// Session 0 caches 5 values (2,4,6,8,10) and uses the first value (2).
//
// caches:
// session 0: 4,6,8,10
// db:
// s: 10
checkIntValue(t, 0, "SELECT nextval('s')", 2)
checkIntValue(t, anySession(), "SELECT last_value FROM s", 10)
// caches:
// session 0: -
// db:
// s: 10
for sequenceNumber := 4; sequenceNumber <= 10; sequenceNumber += 2 {
checkIntValue(t, 0, "SELECT nextval('s')", sequenceNumber)
}
checkIntValue(t, anySession(), "SELECT last_value FROM s", 10)
// Session 0 caches 5 values (12,14,16,18,20) and uses the first value (12).
// caches:
// session 0: 14,16,18,20
// db:
// s: 20
checkIntValue(t, 0, "SELECT nextval('s')", 12)
checkIntValue(t, anySession(), "SELECT last_value FROM s", 20)
// caches:
// node 0: -
// db:
// s: 20
for sequenceNumber := 14; sequenceNumber <= 20; sequenceNumber += 2 {
checkIntValue(t, 0, "SELECT nextval('s')", sequenceNumber)
}
checkIntValue(t, anySession(), "SELECT last_value FROM s", 20)
execStmt(t, "DROP SEQUENCE s")
},
},
// Test multiple cached sequences using multiple sessions.
{
name: "Multi-Session, Multi-Sequence Cache Test",
test: func(t *testing.T) {
execStmt(t, `
CREATE SEQUENCE s1
CACHE 5
INCREMENT BY 2
START WITH 2
`)
execStmt(t, `
CREATE SEQUENCE s2
CACHE 4
INCREMENT BY 3
START WITH 3
`)
// The caches all start out empty. When a cache is empty, the underlying sequence in the database
// should be incremented by the cache size * increment amount.
//
// s1 increases by 10 each time, and s2 increases by 12 each time.
// caches:
// session 0:
// s1: 4,6,8,10
// session 1: -
// session 2: -
// db:
// s1: 10
checkIntValue(t, 0, "SELECT nextval('s1')", 2)
checkIntValue(t, anySession(), "SELECT last_value FROM s1", 10)
// caches:
// session 0:
// s1: 4,6,8,10
// s2: 6,9,12
// session 1: -
// session 2: -
// db:
// s1: 10
// s2: 12
checkIntValue(t, 0, "SELECT nextval('s2')", 3)
checkIntValue(t, anySession(), "SELECT last_value FROM s2", 12)
// caches:
// session 0:
// s1: 4,6,8,10
// s2: 6,9,12
// session 1:
// s1: 14,16,18,20
// session 2: -
// db:
// s1: 20
// s2: 12
checkIntValue(t, 1, "SELECT nextval('s1')", 12)
checkIntValue(t, anySession(), "SELECT last_value FROM s1", 20)
// caches:
// session 0:
// s1: 4,6,8,10
// s2: 6,9,12
// session 1:
// s1: 14,16,18,20
// s2: 18,21,24
// session 2: -
// db:
// s1: 20
// s2: 24
checkIntValue(t, 1, "SELECT nextval('s2')", 15)
checkIntValue(t, anySession(), "SELECT last_value FROM s2", 24)
// caches:
// session 0:
// s1: 4,6,8,10
// s2: 6,9,12
// session 1:
// s1: 14,16,18,20
// s2: 18,21,24
// session 2:
// s1: 24,26,28,30
// db:
// s1: 30
// s2: 24
checkIntValue(t, 2, "SELECT nextval('s1')", 22)
checkIntValue(t, anySession(), "SELECT last_value FROM s1", 30)
// caches:
// session 0:
// s1: 4,6,8,10
// s2: 6,9,12
// session 1:
// s1: 14,16,18,20
// s2: 18,21,24
// session 2:
// s1: 24,26,28,30
// s2: 30,33,36
// db:
// s1: 30
// s2: 36
checkIntValue(t, 2, "SELECT nextval('s2')", 27)
checkIntValue(t, anySession(), "SELECT last_value FROM s2", 36)
// caches:
// session 0:
// s1: 4,6,8,10
// s2: 6,9,12
// session 1:
// s1: 14,16,18,20
// s2: 18,21,24
// session 2:
// s1: 24,26,28,30
// s2: 30,33,36
// db:
// s1: 30
// s2: 36
wg := sync.WaitGroup{}
emptyCache := func(session, start, finish, inc int, seq string) {
for sequenceNumber := start; sequenceNumber <= finish; sequenceNumber += inc {
checkIntValue(t, session, fmt.Sprintf("SELECT nextval('%s')", seq), sequenceNumber)
}
wg.Done()
}
wg.Add(3)
go emptyCache(0, 4, 10, 2, "s1")
go emptyCache(1, 14, 20, 2, "s1")
go emptyCache(2, 24, 30, 2, "s1")
wg.Wait()
wg.Add(3)
go emptyCache(0, 6, 12, 3, "s2")
go emptyCache(1, 18, 24, 3, "s2")
go emptyCache(2, 30, 36, 3, "s2")
wg.Wait()
// caches:
// session 0: -
// session 1: -
// session 2: -
// db:
// s1: 30
// s2: 36
checkIntValue(t, anySession(), "SELECT last_value FROM s1", 30)
checkIntValue(t, anySession(), "SELECT last_value FROM s2", 36)
execStmt(t, "DROP SEQUENCE s1")
execStmt(t, "DROP SEQUENCE s2")
},
},
{
name: "Create Table With GENERATED ALWAYS AS IDENTITY",
test: func(t *testing.T) {
execStmt(t, `
CREATE TABLE demo_t_always (
x INT UNIQUE,
y INT GENERATED ALWAYS AS IDENTITY (START 2 INCREMENT 2 CACHE 5)
)
`)
// The `GENERATED ALWAYS AS IDENTITY` syntax automatically creates
// an underlying sequence named `demo_t_always_y_seq` for the y column of the
// demo_t_always table. Such creation applies the sequence option (
// START 2 INCREMENT 2 CACHE 5) in the statement.
// The cache of demo_t_always_y_seq starts out empty. When the cache is empty,
// the underlying sequence in the database
// should be incremented by the cache size * increment amount,
// so it should increase by 10 each time.
// Session 0 caches 5 values (2,4,6,8,10) and uses the first value (2).
//
// caches:
// session 0: 4,6,8,10
// db:
// s: 10
checkIntValue(t, 0, "SELECT nextval('demo_t_always_y_seq')", 2)
checkIntValue(t, anySession(), "SELECT last_value FROM demo_t_always_y_seq", 10)
// caches:
// session 0: -
// db:
// s: 10
for sequenceNumber := 4; sequenceNumber <= 10; sequenceNumber += 2 {
checkIntValue(t, 0, "SELECT nextval('demo_t_always_y_seq')", sequenceNumber)
}
checkIntValue(t, anySession(), "SELECT last_value FROM demo_t_always_y_seq", 10)
// Session 0 caches 5 values (12,14,16,18,20) and uses the first value (12).
// caches:
// session 0: 14,16,18,20
// db:
// s: 20
checkIntValue(t, 0, "SELECT nextval('demo_t_always_y_seq')", 12)
checkIntValue(t, anySession(), "SELECT last_value FROM demo_t_always_y_seq", 20)
// caches:
// node 0: -
// db:
// s: 20
for sequenceNumber := 14; sequenceNumber <= 20; sequenceNumber += 2 {
checkIntValue(t, 0, "SELECT nextval('demo_t_always_y_seq')", sequenceNumber)
}
checkIntValue(t, anySession(), "SELECT last_value FROM demo_t_always_y_seq", 20)
execStmt(t, "DROP TABLE demo_t_always")
},
},
{
name: "Create Table With GENERATED BY DEFAULT AS IDENTITY",
test: func(t *testing.T) {
execStmt(t, `
CREATE TABLE demo_t_bydefault (
x INT UNIQUE,
y INT GENERATED BY DEFAULT AS IDENTITY (START 2 INCREMENT 2 CACHE 5)
)
`)
// The `GENERATED ALWAYS AS IDENTITY` syntax automatically creates
// an underlying sequence named `demo_t_bydefault_y_seq` for the y column of the
// demo_t_bydefault table. Such creation applies the sequence option (
// START 2 INCREMENT 2 CACHE 5) in the statement.
// The cache of demo_t_bydefault_y_seq starts out empty. When the cache is empty,
// the underlying sequence in the database
// should be incremented by the cache size * increment amount,
// so it should increase by 10 each time.
// Session 0 caches 5 values (2,4,6,8,10) and uses the first value (2).
//
// caches:
// session 0: 4,6,8,10
// db:
// s: 10
checkIntValue(t, 0, "SELECT nextval('demo_t_bydefault_y_seq')", 2)
checkIntValue(t, anySession(), "SELECT last_value FROM demo_t_bydefault_y_seq", 10)
// caches:
// session 0: -
// db:
// s: 10
for sequenceNumber := 4; sequenceNumber <= 10; sequenceNumber += 2 {
checkIntValue(t, 0, "SELECT nextval('demo_t_bydefault_y_seq')", sequenceNumber)
}
checkIntValue(t, anySession(), "SELECT last_value FROM demo_t_bydefault_y_seq", 10)
// Session 0 caches 5 values (12,14,16,18,20) and uses the first value (12).
// caches:
// session 0: 14,16,18,20
// db:
// s: 20
checkIntValue(t, 0, "SELECT nextval('demo_t_bydefault_y_seq')", 12)
checkIntValue(t, anySession(), "SELECT last_value FROM demo_t_bydefault_y_seq", 20)
// caches:
// node 0: -
// db:
// s: 20
for sequenceNumber := 14; sequenceNumber <= 20; sequenceNumber += 2 {
checkIntValue(t, 0, "SELECT nextval('demo_t_bydefault_y_seq')", sequenceNumber)
}
checkIntValue(t, anySession(), "SELECT last_value FROM demo_t_bydefault_y_seq", 20)
execStmt(t, "DROP TABLE demo_t_bydefault")
},
},
}
for _, tc := range testCases {
t.Run(tc.name, func(t *testing.T) {
tc.test(t)
})
}
}
// TestSequencesZeroCacheSize is a regression test for #51259, sequence caching.
// Prior sequences will have cache sizes of 0, and sequences made after will have
// a cache size of at least 1 where 1 means no caching. This test verifies that sequences
// cache sizes of 0 function in the same way as sequences with a cache size of 1.
func TestSequencesZeroCacheSize(t *testing.T) {
defer leaktest.AfterTest(t)()
ctx := context.Background()
params := base.TestServerArgs{}
s, sqlConn, kvDB := serverutils.StartServer(t, params)
defer s.Stopper().Stop(ctx)
sqlDB := sqlutils.MakeSQLRunner(sqlConn)
sqlDB.Exec(t, `
CREATE DATABASE test;
CREATE SEQUENCE test.seq INCREMENT BY 1 START WITH 1;
`)
// Alter the descriptor to have a cache size of 0.
seqDesc := catalogkv.TestingGetMutableExistingTableDescriptor(kvDB, keys.SystemSQLCodec, "test", "seq")
seqDesc.SequenceOpts.CacheSize = 0
err := kvDB.Put(
context.Background(),
catalogkeys.MakeDescMetadataKey(keys.SystemSQLCodec, seqDesc.GetID()),
seqDesc.DescriptorProto(),
)
require.NoError(t, err)
// Verify the sequences increases by 1.
sqlDB.CheckQueryResults(t, `SELECT nextval('test.seq')`, [][]string{{"1"}})
sqlDB.CheckQueryResults(t, `SELECT last_value from test.seq`, [][]string{{"1"}})
sqlDB.CheckQueryResults(t, `SELECT nextval('test.seq')`, [][]string{{"2"}})
sqlDB.CheckQueryResults(t, `SELECT last_value from test.seq`, [][]string{{"2"}})
}
// addOwnedSequence adds the sequence referenced by seqName to the
// ownsSequenceIDs of the column referenced by (dbName, tableName, colIdx).
func addOwnedSequence(
t *testing.T, kvDB *kv.DB, dbName string, tableName string, colIdx int, seqName string,
) {
seqDesc := catalogkv.TestingGetTableDescriptor(kvDB, keys.SystemSQLCodec, dbName, seqName)
tableDesc := catalogkv.TestingGetMutableExistingTableDescriptor(
kvDB, keys.SystemSQLCodec, dbName, tableName)
tableDesc.GetColumns()[colIdx].OwnsSequenceIds = append(
tableDesc.GetColumns()[colIdx].OwnsSequenceIds, seqDesc.GetID())
err := kvDB.Put(
context.Background(),
catalogkeys.MakeDescMetadataKey(keys.SystemSQLCodec, tableDesc.GetID()),
tableDesc.DescriptorProto(),
)
require.NoError(t, err)
}
// breakOwnershipMapping simulates #50781 by setting the sequence's owner table
// to a non-existent tableID and setting the column's `ownsSequenceID` to a
// non-existent sequenceID.
func breakOwnershipMapping(
t *testing.T, kvDB *kv.DB, dbName string, tableName string, seqName string,
) {
seqDesc := catalogkv.TestingGetTableDescriptor(kvDB, keys.SystemSQLCodec, dbName, seqName)
tableDesc := catalogkv.TestingGetMutableExistingTableDescriptor(
kvDB, keys.SystemSQLCodec, dbName, tableName)
for colIdx := range tableDesc.GetColumns() {
for i := range tableDesc.GetColumns()[colIdx].OwnsSequenceIds {
if tableDesc.GetColumns()[colIdx].OwnsSequenceIds[i] == seqDesc.GetID() {
tableDesc.GetColumns()[colIdx].OwnsSequenceIds[i] = math.MaxInt32
}
}
}
seqDesc.GetSequenceOpts().SequenceOwner.OwnerTableID = math.MaxInt32
err := kvDB.Put(
context.Background(),
catalogkeys.MakeDescMetadataKey(keys.SystemSQLCodec, tableDesc.GetID()),
tableDesc.DescriptorProto(),
)
require.NoError(t, err)
err = kvDB.Put(
context.Background(),
catalogkeys.MakeDescMetadataKey(keys.SystemSQLCodec, seqDesc.GetID()),
seqDesc.DescriptorProto(),
)
require.NoError(t, err)
}