File: SequenceGeneratorTest.java

package info (click to toggle)
derby 10.14.2.0-3
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 79,056 kB
  • sloc: java: 691,961; sql: 42,686; xml: 20,512; sh: 3,373; sed: 96; makefile: 60
file content (987 lines) | stat: -rw-r--r-- 34,656 bytes parent folder | download | duplicates (4)
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
/*

   Derby - Class org.apache.derbyTesting.functionTests.tests.lang.SequenceGeneratorTest

   Licensed to the Apache Software Foundation (ASF) under one or more
   contributor license agreements.  See the NOTICE file distributed with
   this work for additional information regarding copyright ownership.
   The ASF licenses this file to you under the Apache License, Version 2.0
   (the "License"); you may not use this file except in compliance with
   the License.  You may obtain a copy of the License at

     http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.

 */

package org.apache.derbyTesting.functionTests.tests.lang;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import junit.framework.Test;
import org.apache.derby.catalog.SequencePreallocator;
import org.apache.derby.iapi.store.access.TransactionController;
import org.apache.derby.iapi.types.SQLLongint;
import org.apache.derby.impl.sql.catalog.SequenceGenerator;
import org.apache.derby.impl.sql.catalog.SequenceRange;
import org.apache.derby.impl.sql.catalog.SequenceUpdater;
import org.apache.derbyTesting.junit.BaseTestSuite;
import org.apache.derbyTesting.junit.CleanDatabaseTestSetup;
import org.apache.derbyTesting.junit.DatabasePropertyTestSetup;
import org.apache.derbyTesting.junit.TestConfiguration;

/**
 * <p>
 * Test sequence generators. See DERBY-712.
 * </p>
 */
public class SequenceGeneratorTest  extends GeneratedColumnsHelper
{
    ///////////////////////////////////////////////////////////////////////////////////
    //
    // CONSTANTS
    //
    ///////////////////////////////////////////////////////////////////////////////////

    // number of pre-allocated values in a sequence generator
    private static final long ALLOCATION_COUNT = 100L;
    private static final int TWEAKED_ALLOCATION_COUNT = 7;

    private static  final   String      TEST_DBO = "TEST_DBO";
    private static  final   String      RUTH = "RUTH";
    private static  final   String      ALICE = "ALICE";
    private static  final   String[]    LEGAL_USERS = { TEST_DBO, ALICE, RUTH  };

    private static  final   String      MISSING_ALLOCATOR = "X0Y85";
    private static  final   String      DUPLICATE_SEQUENCE = "X0Y68";

    ///////////////////////////////////////////////////////////////////////////////////
    //
    // STATE
    //
    ///////////////////////////////////////////////////////////////////////////////////

    private static boolean _fullDebug = false;

    ///////////////////////////////////////////////////////////////////////////////////
    //
    // CONSTRUCTOR
    //
    ///////////////////////////////////////////////////////////////////////////////////


    /**
     * Create a new instance.
     */

    public SequenceGeneratorTest(String name)
    {
        super(name);
    }

    ///////////////////////////////////////////////////////////////////////////////////
    //
    // JUnit BEHAVIOR
    //
    ///////////////////////////////////////////////////////////////////////////////////


    /**
     * Construct top level suite in this JUnit test
     */
    public static Test suite()
    {
        BaseTestSuite suite = (BaseTestSuite)TestConfiguration.embeddedSuite(
            SequenceGeneratorTest.class);

        Test        cleanTest = new CleanDatabaseTestSetup( suite );
        Test        timeoutTest = DatabasePropertyTestSetup.setLockTimeouts( cleanTest, 5, 5 );
        Test        authenticatedTest = DatabasePropertyTestSetup.builtinAuthentication
            ( timeoutTest, LEGAL_USERS, "sequenceGenerator" );
        Test        authorizedTest = TestConfiguration.sqlAuthorizationDecorator( authenticatedTest );

        return authorizedTest;
    }

    ///////////////////////////////////////////////////////////////////////////////////
    //
    // TESTS
    //
    ///////////////////////////////////////////////////////////////////////////////////

    /**
     * <p>
     * Test basic incrementing and pre-allocating of sequence values on disk.
     * </p>
     */
    public void test_01_basic() throws Exception
    {
        Connection  conn = openUserConnection( TEST_DBO );

        int initialValue = Integer.MIN_VALUE;

        goodStatement( conn, "create sequence seq_01\n" );

        assertEquals( (long) initialValue, getCurrentValue( TEST_DBO, "SEQ_01" ) );

        // first run is allocated
        int seq_01_value = initialValue;
        long seq_01_upperBound = seq_01_value + ALLOCATION_COUNT;
        for ( int i = 0; i < ALLOCATION_COUNT; i++ )
        {
            vetBumping( conn, TEST_DBO, "SEQ_01", seq_01_value++, seq_01_upperBound );
        }

        // another run is allocated
        seq_01_upperBound += ALLOCATION_COUNT;
        vetBumping( conn, TEST_DBO, "SEQ_01", seq_01_value++, seq_01_upperBound );

        // DDL flushes the metadata cache
        goodStatement( conn, "create sequence seq_01_a\n" );

        int seq_01_a_value = initialValue;
        long seq_01_a_upperBound = seq_01_a_value + ALLOCATION_COUNT;
        // check the other sequence
        for ( int i = 0; i < 2; i++ )
        {
            vetBumping( conn, TEST_DBO, "SEQ_01_A", seq_01_a_value++, seq_01_a_upperBound );
        }

        //
        // The cache was flushed when seq_01_a was created. This
        // restarts the generator for that sequence and allocates a new range.
        //
        seq_01_upperBound = seq_01_value + ALLOCATION_COUNT;
        vetBumping( conn, TEST_DBO, "SEQ_01", seq_01_value++, seq_01_upperBound );
    }
    private void vetBumping( Connection conn, String schemaName, String sequenceName, int expectedValue, long expectedValueOnDisk )
        throws Exception
    {
        PreparedStatement ps = chattyPrepare( conn, "values( next value for " + schemaName + '.' + sequenceName + " )\n" );

        assertEquals( expectedValue, getScalarInteger( ps ) );
        assertEquals( expectedValueOnDisk, getCurrentValue( schemaName, sequenceName ) );
    }

    /**
     * <p>
     * Test boundary conditions in sequence generators.
     * </p>
     */
    public void test_02_boundary() throws Exception
    {
        T_SequenceUpdater updater;

        updater = new T_SequenceUpdater
          ( (long)Integer.MIN_VALUE, true, 1L, (long) Integer.MAX_VALUE, (long) Integer.MIN_VALUE, (long) Integer.MIN_VALUE );

        assertEquals( -2147483648L, updater.getValueOnDisk().longValue() );

        long        initialValue = (long) Integer.MIN_VALUE;
        long        expectedValueOnDisk = initialValue + ALLOCATION_COUNT;

        for ( long i = 0; i < ALLOCATION_COUNT; i++ )
        {
            vetBumping( updater, initialValue + i, expectedValueOnDisk );
        }
        expectedValueOnDisk += ALLOCATION_COUNT;

        vetBumping( updater, initialValue + ALLOCATION_COUNT, expectedValueOnDisk );

        vetBoundaries( Short.MAX_VALUE, Short.MIN_VALUE );
        vetBoundaries( Integer.MAX_VALUE, Integer.MIN_VALUE );
        vetBoundaries( Long.MAX_VALUE, Long.MIN_VALUE );

        vetBoundaries( Short.MAX_VALUE/2, Short.MIN_VALUE/2 );
        vetBoundaries( Integer.MAX_VALUE/2, Integer.MIN_VALUE/2 );
        vetBoundaries( Long.MAX_VALUE/2, Long.MIN_VALUE/2 );
    }
    private void vetBoundaries
        (
         long maxValue,
         long minValue
         )
        throws Exception
    {
        vetBoundaries( maxValue, minValue, 1L );
        vetBoundaries( maxValue, minValue, ALLOCATION_COUNT );
        vetBoundaries( maxValue, minValue, 2 * ALLOCATION_COUNT );
    }
    private void vetBoundaries
        (
         long maxValue,
         long minValue,
         long stepSize
         )
        throws Exception
    {
        vetUpperBoundary( maxValue, minValue, stepSize );
        vetLowerBoundary( maxValue, minValue, stepSize );
    }
    private void vetUpperBoundary
        (
         long maxValue,
         long minValue,
         long stepSize
         )
        throws Exception
    {
        long restartValue = minValue;
        long firstValue;

        long initValue = maxValue - (ALLOCATION_COUNT * stepSize);
        long finalValue = maxValue;
        long midpoint = (finalValue - initValue) / 2;

        if ( initValue > 0 ) { vetBoundaries( maxValue, minValue, stepSize, initValue, restartValue ); }
        if ( midpoint > 0 ) { vetBoundaries( maxValue, minValue, stepSize, midpoint, restartValue ); }
        if ( finalValue > 0 ) { vetBoundaries( maxValue, minValue, stepSize, finalValue, restartValue ); }
    }
    private void vetLowerBoundary
        (
         long maxValue,
         long minValue,
         long stepSize
         )
        throws Exception
    {
        long restartValue = maxValue;
        long firstValue;

        long initValue = minValue + (ALLOCATION_COUNT * stepSize);
        long finalValue = minValue;
        long midpoint = (finalValue - initValue) / 2;

        if ( initValue < 0 ) { vetBoundaries( maxValue, minValue, -stepSize, initValue, restartValue ); }
        if ( midpoint < 0 ) { vetBoundaries( maxValue, minValue, -stepSize, midpoint, restartValue ); }
        if ( finalValue < 0 ) { vetBoundaries( maxValue, minValue, -stepSize, finalValue, restartValue ); }
    }
    private void vetBoundaries
        (
         long maxValue,
         long minValue,
         long stepSize,
         long firstValue,
         long restartValue
         )
        throws Exception
    {
        long bumps = (2 * ALLOCATION_COUNT) + 1;
        
        vetBumping( firstValue, true, stepSize, maxValue, minValue, restartValue, bumps );
        vetBumping( firstValue, false, stepSize, maxValue, minValue, restartValue, bumps );
    }
    private void vetBumping
        (
         long firstValue,
         boolean canCycle,
         long stepSize,
         long maxValue,
         long minValue,
         long restartValue,
         long bumps
         )
        throws Exception
    {
        if ( _fullDebug) { println( "stepSize = " + stepSize + " and firstValue = " + firstValue + " and canCycle = " + canCycle ); }
        
        SGVetter vetter = new SGVetter
            ( firstValue, canCycle, stepSize, maxValue, minValue, restartValue, ALLOCATION_COUNT );           
        T_SequenceUpdater updater = new T_SequenceUpdater
            ( firstValue, canCycle, stepSize, maxValue, minValue, restartValue );

        if ( _fullDebug) { println( "" ); }
        for ( long i = 0; i < bumps; i++ ) { vetBump( vetter, updater ); }
    }
    private void vetBump( SGVetter vetter, T_SequenceUpdater updater ) throws Exception
    {
        assertLongEquals( vetter.getUpperBound(), updater.getValueOnDisk() );

        Long vetterValue = vetter.getNextValue();

        if ( _fullDebug ) { println( "Expecting value = " + vetterValue + " and expecting ValueOnDisk = " + vetter.getUpperBound() ); }
        
        if ( vetterValue != null )
        {
            long updaterValue = updater.getCurrentValueAndAdvance();

            assertEquals( vetterValue.longValue(), updaterValue );
        }
        else
        {
            try {
                updater.getCurrentValueAndAdvance();
                fail( "Expected to catch cycle exception." );
            }
            catch (Exception e)
            {}
        }

        assertLongEquals( vetter.getUpperBound(), updater.getValueOnDisk() );
    }
    private void assertLongEquals( Long left, Long right )
    {
        if ( left == null ) { assertNull( right ); }
        else
        {
            assertNotNull( right );
            assertEquals( left.longValue(), right.longValue() );
        }
    }
    
    private void vetBumping( T_SequenceUpdater updater, long expectedValue, long expectedValueOnDisk )
        throws Exception
    {
        long actualValue = updater.getCurrentValueAndAdvance();
        long actualValueOnDisk = updater.getValueOnDisk().longValue();
        
        println( "Expected value = " + expectedValue + " vs actual value = " + actualValue );
        println( "    Expected value on disk = " + expectedValueOnDisk + " vs actual value on disk = " + actualValueOnDisk );
        
        assertEquals( expectedValue, actualValue );
        assertEquals( expectedValueOnDisk, actualValueOnDisk );
    }
    
    /**
     * <p>
     * Test non cycling sequence generators.
     * </p>
     */
    public void test_03_nonCycling() throws Exception
    {
        vetNonCycling( Short.MAX_VALUE, Short.MIN_VALUE );
        vetNonCycling( Integer.MAX_VALUE, Integer.MIN_VALUE );
        vetNonCycling( Long.MAX_VALUE, Long.MIN_VALUE );
    }
    private void vetNonCycling
        (
         long maxValue,
         long minValue
         )
        throws Exception
    {
        vetNonCycling( maxValue, minValue, 1L );
        vetNonCycling( maxValue, minValue, -1L );
    }
    private void vetNonCycling
        (
         long maxValue,
         long minValue,
         long stepSize
         )
        throws Exception
    {
        long bumps = 3;
        long firstValue;
        long restartValue;

        if ( stepSize > 0 )
        {
            firstValue = maxValue - bumps;
            restartValue = minValue;
        }
        else
        {
            firstValue = minValue + bumps;
            restartValue = maxValue;
        }

        SGVetter vetter = new SGVetter
            ( firstValue, false, stepSize, maxValue, minValue, restartValue, ALLOCATION_COUNT );           
        T_SequenceUpdater updater = new T_SequenceUpdater
            ( firstValue, false, stepSize, maxValue, minValue, restartValue );

        // make sure we can survive trying to bust the cycle more than once
        long extraBumps = bumps + 2;
        for ( long i = 0; i <= extraBumps; i++ )
        {
            vetBump( vetter, updater );
        }
    }
    
    /**
     * <p>
     * Test that when you reboot the database, you pick up the sequence
     * number on disk, not the last version in memory.
     * </p>
     */
    public void test_04_reboot() throws Exception
    {
        Connection  conn = openUserConnection( TEST_DBO );
        
        int initialValue = Integer.MIN_VALUE;

        goodStatement( conn, "create sequence seq_04\n" );

        int seq_04_value = initialValue;
        long seq_04_upperBound = seq_04_value + ALLOCATION_COUNT;
        vetBumping( conn, TEST_DBO, "SEQ_04", seq_04_value++, seq_04_upperBound );
        vetBumping( conn, TEST_DBO, "SEQ_04", seq_04_value++, seq_04_upperBound );

        getTestConfiguration().shutdownDatabase();
        conn = openUserConnection( TEST_DBO );
        seq_04_upperBound = seq_04_value + ALLOCATION_COUNT;
        vetBumping( conn, TEST_DBO, "SEQ_04", seq_04_value++, seq_04_upperBound );

        getTestConfiguration().shutdownDatabase();
        conn = openUserConnection( TEST_DBO );
        seq_04_upperBound = seq_04_value + ALLOCATION_COUNT;
        vetBumping( conn, TEST_DBO, "SEQ_04", seq_04_value++, seq_04_upperBound );
    }
    
    /**
     * <p>
     * Test that multiple transactions can access the same sequence generator
     * and not block.
     * </p>
     */
    public void test_05_concurrency() throws Exception
    {
        Connection  conn = openUserConnection( TEST_DBO );
        
        int initialValue = Integer.MIN_VALUE;

        goodStatement( conn, "create sequence seq_05\n" );
        goodStatement( conn, "grant usage on sequence seq_05 to public\n" );

        int seq_05_value = initialValue;
        long seq_05_upperBound = seq_05_value;

        Connection  ruthConnection = openUserConnection( "RUTH" );
        Connection  aliceConnection = openUserConnection( "ALICE" );

        ruthConnection.setAutoCommit( false );
        aliceConnection.setAutoCommit( false );

        long loopCount = 2 * ALLOCATION_COUNT;
        for ( long i = 0; i < loopCount; i++ )
        {
            Connection loopConn = ( i % 2 == 0 ) ? ruthConnection : aliceConnection;

            if ( (i % ALLOCATION_COUNT) == 0 ) { seq_05_upperBound += ALLOCATION_COUNT; }

            vetBumping( loopConn, TEST_DBO, "SEQ_05", seq_05_value++, seq_05_upperBound );
        }

        ruthConnection.commit();
        aliceConnection.commit();
    }
    
    /**
     * <p>
     * Test big step sizes.
     * </p>
     */
    public void test_06_bigStepSize() throws Exception
    {
        T_SequenceUpdater updater;
        long stepSize = (Long.MAX_VALUE / ALLOCATION_COUNT) * 3;

        updater = new T_SequenceUpdater
            ( Long.MIN_VALUE, true, stepSize, (long) Long.MAX_VALUE, (long) Long.MIN_VALUE, (long) Long.MIN_VALUE );

        long nextValue = updater.getCurrentValueAndAdvance();
        long currentValueOnDisk = updater.getValueOnDisk().longValue();
        long rangeSize = currentValueOnDisk - nextValue;

        // allocation count truncated to 1 because the step size is so large
        assertEquals( stepSize, rangeSize );

        vetBigStep( Short.MAX_VALUE, Short.MIN_VALUE );
        vetBigStep( Integer.MAX_VALUE, Integer.MIN_VALUE );
        vetBigStep( Long.MAX_VALUE, Long.MIN_VALUE );

        vetBigStep( ALLOCATION_COUNT, 0L );
    }
    private void vetBigStep( long maxValue, long minValue )
        throws Exception
    {
        Long firstValue = minValue;
        long restartValue = minValue;
        long stepSize = maxValue - 1;
        boolean canCycle = true;
        long truncatedAllocationCount = 1L;
        
        SGVetter vetter = new SGVetter
            ( firstValue, canCycle, stepSize, maxValue, minValue, restartValue, truncatedAllocationCount );           
        T_SequenceUpdater updater = new T_SequenceUpdater
            ( firstValue, canCycle, stepSize, maxValue, minValue, restartValue );

        for ( long i = 0; i < ALLOCATION_COUNT; i++ )
        {
            vetBump( vetter, updater );
        }
    }
    
    /**
     * <p>
     * Test that cache flushing doesn't prevent us from dropping
     * a sequence generator.
     * </p>
     */
    public void test_07_dropSequence() throws Exception
    {
        Connection  conn = getConnection();

        goodStatement( conn, "create sequence seq_07\n" );
        
        int initialValue = Integer.MIN_VALUE;
        int seq_07_value = initialValue;
        long seq_07_upperBound = seq_07_value + ALLOCATION_COUNT;
        for ( int i = 0; i < ALLOCATION_COUNT; i++ )
        {
            vetBumping( conn, TEST_DBO, "SEQ_07", seq_07_value++, seq_07_upperBound );
        }

        goodStatement( conn, "values( next value for seq_07 )\n" );
        goodStatement( conn, "drop sequence seq_07 restrict\n" );
        
        expectCompilationError( OBJECT_DOES_NOT_EXIST, "values ( next value for seq_07 )\n" );
    }
    
    /**
     * <p>
     * Test user-written range allocators.
     * </p>
     */
    public void test_08_userWrittenAllocators() throws Exception
    {
        Connection  conn = openUserConnection( TEST_DBO );
        String  className;

        goodStatement( conn, "create sequence seq_08\n" );

        className = getClass().getName() + "$" + "UnknownClass";
        goodStatement
            (
             conn,
             "call syscs_util.syscs_set_database_property( 'derby.language.sequence.preallocator', '" + className + "')"
             );
        expectExecutionError( conn, MISSING_ALLOCATOR, "values ( next value for seq_08 )" );

        className = getClass().getName() + "$" + "BadAllocator";
        goodStatement
            (
             conn,
             "call syscs_util.syscs_set_database_property( 'derby.language.sequence.preallocator', '" + className + "')"
             );
        expectExecutionError( conn, MISSING_ALLOCATOR, "values ( next value for seq_08 )" );

        className = getClass().getName() + "$" + "LegalAllocator";
        goodStatement
            (
             conn,
             "call syscs_util.syscs_set_database_property( 'derby.language.sequence.preallocator', '" + className + "')"
             );
        vetBumping( conn, TEST_DBO, "SEQ_08", Integer.MIN_VALUE, Integer.MIN_VALUE + TWEAKED_ALLOCATION_COUNT );

        goodStatement
            (
             conn,
             "call syscs_util.syscs_set_database_property( 'derby.language.sequence.preallocator', null )"
             );
    }
        
    /**
     * <p>
     * Test overriding the default length of sequence/identity ranges.
     * </p>
     */
    public void test_09_defaultRangeSize() throws Exception
    {
        Connection  conn = openUserConnection( TEST_DBO );
        long    number;

        goodStatement( conn, "create sequence seq_09_01\n" );
        number = 30L;
        goodStatement
            (
             conn,
             "call syscs_util.syscs_set_database_property( 'derby.language.sequence.preallocator', '" + number + "')"
             );
        vetBumping( conn, TEST_DBO, "SEQ_09_01", Integer.MIN_VALUE, Integer.MIN_VALUE + number );

        // 0 results in the usual default
        goodStatement( conn, "create sequence seq_09_02\n" );
        number = 0L;
        goodStatement
            (
             conn,
             "call syscs_util.syscs_set_database_property( 'derby.language.sequence.preallocator', '" + number + "')"
             );
        vetBumping( conn, TEST_DBO, "SEQ_09_02", Integer.MIN_VALUE, Integer.MIN_VALUE + ALLOCATION_COUNT );

        // negative numbers result in Missing Allocator exception
        goodStatement( conn, "create sequence seq_09_03\n" );
        number = -1L;
        goodStatement
            (
             conn,
             "call syscs_util.syscs_set_database_property( 'derby.language.sequence.preallocator', '" + number + "')"
             );
        expectExecutionError( conn, MISSING_ALLOCATOR, "values ( next value for seq_09_03 )" );

        // If the value doesn't fit in an int, we also get a Missing Allocator exception
        goodStatement( conn, "create sequence seq_09_04\n" );
        number = Long.MAX_VALUE - 1L;
        goodStatement
            (
             conn,
             "call syscs_util.syscs_set_database_property( 'derby.language.sequence.preallocator', '" + number + "')"
             );
        expectExecutionError( conn, MISSING_ALLOCATOR, "values ( next value for seq_09_04 )" );
        
        // out of range values will stifle preallocation
        goodStatement( conn, "create sequence seq_09_05 as smallint\n" );
        number = ((long) 3 * Short.MAX_VALUE);
        goodStatement
            (
             conn,
             "call syscs_util.syscs_set_database_property( 'derby.language.sequence.preallocator', '" + number + "')"
             );
        vetBumping( conn, TEST_DBO, "SEQ_09_05", Short.MIN_VALUE, Short.MIN_VALUE + 1 );

        goodStatement
            (
             conn,
             "call syscs_util.syscs_set_database_property( 'derby.language.sequence.preallocator', null )"
             );
    }
    
    /**
     * <p>
     * Test that sequence values are not leaked during an orderly system shutdown.
     * See DERBY-5398.
     * </p>
     */
    public void test_10_5398() throws Exception
    {
        Connection  conn = openUserConnection( TEST_DBO );

        goodStatement( conn, "create sequence seq_10\n" );

        int seq_10_value = Integer.MIN_VALUE;
        long seq_10_upperBound;

        seq_10_upperBound = seq_10_value + ALLOCATION_COUNT;
        vetBumping( conn, TEST_DBO, "SEQ_10", seq_10_value++, seq_10_upperBound );

        // bring down the engine, then reboot the database
        getTestConfiguration().shutdownEngine();
        conn = openUserConnection( TEST_DBO );

        // verify that we did not leak any values
        seq_10_upperBound = seq_10_value + ALLOCATION_COUNT;
        vetBumping( conn, TEST_DBO, "SEQ_10", seq_10_value++, seq_10_upperBound );
    }

    /**
     * <p>
     * Test that sequence values don't repeat via transaction trickery. See DERBY-5493.
     * </p>
     */
    public void test_11_5493_correctness() throws Exception
    {
        Connection  conn = openUserConnection( TEST_DBO );

        goodStatement( conn, "create table t_5493 (x int)\n" );
        goodStatement( conn, "create sequence s_5493\n" );

        boolean oldAutoCommit = conn.getAutoCommit();
        conn.setAutoCommit( false );

        PreparedStatement   ps = chattyPrepare( conn, "select count(*) from sys.syssequences with rs\n" );
        getScalarInteger( ps );
        ps.close();

        int     expectedValue = -2147483648;
        expectExecutionError( conn, TOO_MUCH_CONTENTION, "values next value for s_5493" );

        goodStatement( conn, "drop table t_5493\n" );
        conn.rollback();

        ps = chattyPrepare( conn, "values next value for s_5493" );
        assertEquals( expectedValue++, getScalarInteger( ps ) );
        ps.close();

        goodStatement( conn, "drop sequence s_5493 restrict\n" );
        conn.commit();

        conn.setAutoCommit( oldAutoCommit );
    }

    /**
     * <p>
     * Verify the syscs_peek_at_sequence function introduced by DERBY-5493.
     * </p>
     */
    public void test_12_5493_function() throws Exception
    {
        Connection  dboConn = openUserConnection( TEST_DBO );
        Connection  ruthConn = openUserConnection( "RUTH" );
        PreparedStatement   ps;
        int                 expectedValue;

        goodStatement( dboConn, "create sequence s_5493\n" );
        goodStatement( dboConn, "grant usage on sequence s_5493 to public\n" );

        expectedValue = -2147483648;
        ps = chattyPrepare( dboConn, "values next value for s_5493" );
        assertEquals( expectedValue++, getScalarInteger( ps ) );
        ps.close();

        // test the syscs_peek_at_sequence() function
        ps = chattyPrepare
            (
             dboConn,
             "values syscs_util.syscs_peek_at_sequence( '" + TEST_DBO + "', 'S_5493' )\n"
             );
        assertEquals( expectedValue++, getScalarInteger( ps ) );
        ps.close();

        // error if sequence doesn't exist
        expectExecutionError
            ( dboConn, MISSING_OBJECT, "values syscs_util.syscs_peek_at_sequence( '" + TEST_DBO + "', 'S_5493_1' )\n" );

        // drop the sequence but don't commit

        dboConn.setAutoCommit( false );
        goodStatement( dboConn, "drop sequence s_5493 restrict\n" );
        
        expectExecutionError( dboConn, MISSING_OBJECT, "values syscs_util.syscs_peek_at_sequence( '" + TEST_DBO + "', 'S_5493' )\n" );
        expectCompilationError( dboConn, OBJECT_DOES_NOT_EXIST, "values next value for s_5493" );

        expectExecutionError( ruthConn, LOCK_TIMEOUT, "values syscs_util.syscs_peek_at_sequence( '" + TEST_DBO + "', 'S_5493' )\n" );
        expectCompilationError( ruthConn, LOCK_TIMEOUT, "values next value for " + TEST_DBO + ".s_5493" );

        dboConn.commit();
        dboConn.setAutoCommit( true );
    }

    /**
     * <p>
     * Verify that system crash does not rollback changes to SYSSEQUENCES.CURRENTVALUE.
     * See DERBY-5494.
     * </p>
     */
    public void test_13_5494() throws Exception
    {
        String  dbName = "DB_5494";
        
        // create a sequence and get the first value from it, then crash
        assertLaunchedJUnitTestMethod( getClass().getName() + ".preCrashActions", dbName );

        // now check that the sequence state was correctly recovered
        assertLaunchedJUnitTestMethod( getClass().getName() + ".postCrashActions", dbName );
    }
    // actions to perform just before a crash
    public void    preCrashActions()   throws Exception
    {
        Connection  dboConn = openUserConnection( TEST_DBO );
        Connection  ruthConn = openUserConnection( "RUTH" );
        int initialValue = Integer.MIN_VALUE;

        goodStatement( dboConn, "create sequence s_5494\n" );
        
        assertNextValue( dboConn, TEST_DBO, "S_5494", initialValue );

        assertEquals( (long) (initialValue + ALLOCATION_COUNT), getCurrentValue( ruthConn, TEST_DBO, "S_5494" ) );
    }
    // actions to perform after the crash
    public void    postCrashActions()   throws Exception
    {
        int initialValue = (int) (Integer.MIN_VALUE + ALLOCATION_COUNT);
        
        // now verify that, after the crash, SYSSEQUENCES has still been advanced
        Connection  dboConn = openUserConnection( TEST_DBO );
        assertEquals( (long) initialValue, getCurrentValue( dboConn, TEST_DBO, "S_5494" ) );

        assertNextValue( dboConn, TEST_DBO, "S_5494", initialValue );

        goodStatement( dboConn, "drop sequence s_5494 restrict\n" );
    }
    private void    assertNextValue( Connection conn, String schema, String sequenceName, int expectedValue )
        throws Exception
    {
        PreparedStatement ps = chattyPrepare( conn, "values( next value for " + schema + "." + sequenceName + " )\n" );

        assertEquals( expectedValue, getScalarInteger( ps ) );
    }
    
    /**
     * <p>
     * Verify that we don't get an internal error when creating a sequence-invoking trigger.
     * See DERBY-6553.
     * </p>
     */
    public void test_14_6553() throws Exception
    {
        Connection  dboConn = openUserConnection( TEST_DBO );

        //
        // The original DERBY-6553 test case.
        //
        goodStatement( dboConn, "create table t1_6553_1(x int, y int, z int)" );
        goodStatement( dboConn, "create table t2_6553_1(x int, y int, z int)" );
        goodStatement( dboConn, "create sequence seq_6553_1" );
        goodStatement( dboConn, "values next value for seq_6553_1" );
        goodStatement
            ( dboConn, "create trigger tr1 after insert on t1_6553_1 insert into t2_6553_1(x) values (next value for seq_6553_1)" );

        //
        // The abbreviated test case.
        //
        dboConn.setAutoCommit( false );
        goodStatement( dboConn, "create sequence seq_6553" );
        dboConn.commit();
        goodStatement( dboConn, "values next value for seq_6553" );
        expectExecutionError( dboConn, DUPLICATE_SEQUENCE, "create sequence seq_6553" );
        dboConn.rollback();
        dboConn.setAutoCommit( true );
    }
    
    ///////////////////////////////////////////////////////////////////////////////////
    //
    // MINIONS
    //
    ///////////////////////////////////////////////////////////////////////////////////

    /** Get the current value from a sequence */
    private long getCurrentValue( String schemaName, String sequenceName )
        throws Exception
    {
        return getCurrentValue( openUserConnection( TEST_DBO ), schemaName, sequenceName );
    }
    
    /** Get the current value from a sequence */
    private long getCurrentValue( Connection conn, String schemaName, String sequenceName )
        throws Exception
    {
        PreparedStatement ps = chattyPrepare
            ( conn,
              "select currentvalue from sys.syssequences seq, sys.sysschemas s where s.schemaname = ? and seq.sequencename = ? and s.schemaid = seq.schemaid" );
        ps.setString( 1, schemaName );
        ps.setString( 2, sequenceName );

        long retval = getScalarLong( ps );

        conn.commit();
        
        return retval;
    }

    /** Get a scalar integer result from a query */
    private int getScalarInteger( PreparedStatement ps ) throws Exception
    {
        ResultSet rs = ps.executeQuery();
        rs.next();
        int retval = rs.getInt( 1 );

        rs.close();
        ps.close();

        return retval;
    }

    /** Get a scalar long result from a query */
    private long getScalarLong( PreparedStatement ps ) throws Exception
    {
        ResultSet rs = ps.executeQuery();
        rs.next();
        long retval = rs.getLong( 1 );

        rs.close();
        ps.close();

        return retval;
    }

    ///////////////////////////////////////////////////////////////////////////////////
    //
    // NESTED CLASSES
    //
    ///////////////////////////////////////////////////////////////////////////////////

    /**
     * <p>
     * Machine for testing sequence generators standalone.
     * </p>
     */
    public static final class T_SequenceUpdater extends SequenceUpdater
    {
        private Long _valueOnDisk;
        
        public T_SequenceUpdater
            (
             Long currentValue,
             boolean canCycle,
             long increment,
             long maxValue,
             long minValue,
             long restartValue
             )
        {
            _valueOnDisk = currentValue;
            
            _sequenceGenerator = new SequenceGenerator
                (
                 currentValue,
                 canCycle,
                 increment,
                 maxValue,
                 minValue,
                 restartValue,
                 "DUMMY_SCHEMA",
                 "DUMMY_SEQUENCE",
                 new SequenceRange()
                 );
        }
        
        public Long getValueOnDisk() { return _valueOnDisk; }
        
        public long getCurrentValueAndAdvance() throws Exception
        {
            SQLLongint nextValue = new SQLLongint();
            
            getCurrentValueAndAdvance( nextValue );
            
            return nextValue.getLong();
        }
        
        // SequenceUpdater BEHAVIOR
        protected SequenceGenerator createSequenceGenerator( TransactionController readOnlyTC ) { return _sequenceGenerator; }
        
        protected boolean updateCurrentValueOnDisk( TransactionController tc, Long oldValue, Long newValue, boolean wait )
        {
            _valueOnDisk = newValue;

            return true;
        }
        
        // override so the tests don't get a null pointer exception looking up the lcc
        public boolean updateCurrentValueOnDisk( Long oldValue, Long newValue )
        {
            return updateCurrentValueOnDisk( null, oldValue, newValue, false );
        }
    
    }

    // Illegal preallocator, which does not implement the correct interface
    public  static  final   class   BadAllocator {}

    // Legal preallocator, which preallocates a fixed size range
    public  static final   class   LegalAllocator  implements  SequencePreallocator
    {
        public  LegalAllocator() {}
        
        public  int nextRangeSize( String s, String n ) { return TWEAKED_ALLOCATION_COUNT; }
    }

}