File: OffsetFetchNextTest.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 (1129 lines) | stat: -rw-r--r-- 36,985 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
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
/*

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

  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.ParameterMetaData;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Types;
import junit.framework.Test;
import org.apache.derbyTesting.junit.BaseJDBCTestCase;
import org.apache.derbyTesting.junit.BaseTestSuite;
import org.apache.derbyTesting.junit.CleanDatabaseTestSetup;
import org.apache.derbyTesting.junit.JDBC;
import org.apache.derbyTesting.junit.TestConfiguration;

/**
 * Test {@code <result offset clause>} and {@code <fetch first clause>}.
 */
public class OffsetFetchNextTest extends BaseJDBCTestCase {

    private final static String LANG_FORMAT_EXCEPTION = "22018";
    private final static String LANG_INTEGER_LITERAL_EXPECTED = "42X20";
    private final static String LANG_INVALID_ROW_COUNT_FIRST = "2201W";
    private final static String LANG_INVALID_ROW_COUNT_OFFSET = "2201X";
    private final static String LANG_MISSING_PARMS = "07000";
    private final static String LANG_SYNTAX_ERROR = "42X01";
	private final static String LANG_ROW_COUNT_OFFSET_FIRST_IS_NULL = "2201Z";

    private final static String PERCENT_TOKEN = "%";
    
    // flavors of SQL Standard syntax
    private final static String FIRST_ROWS_ONLY = "fetch first % rows only";
    private final static String FIRST_ROW_ONLY = "fetch first % row only";
    private final static String NEXT_ROWS_ONLY = "fetch next % rows only";

    // variants
    private final static int SQL_STANDARD_VARIANT = 0;
    private final static int JDBC_VARIANT = SQL_STANDARD_VARIANT + 1;
    private final static int VARIANT_COUNT = JDBC_VARIANT + 1;

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

    public static Test suite() {
        BaseTestSuite suite = new BaseTestSuite("OffsetFetchNextTest");

        suite.addTest(
            baseSuite("OffsetFetchNextTest:embedded"));
        suite.addTest(
            TestConfiguration.clientServerDecorator(
                baseSuite("OffsetFetchNextTest:client")));

        return suite;
    }

    public static Test baseSuite(String suiteName) {
        return new CleanDatabaseTestSetup(
            new BaseTestSuite(OffsetFetchNextTest.class,
                          suiteName)) {
            @Override
            protected void decorateSQL(Statement s)
                    throws SQLException {
                createSchemaObjects(s);
            }
        };
    }


    /**
     * Creates tables used by the tests (never modified, we use rollback after
     * changes).
     */
    private static void createSchemaObjects(Statement st) throws SQLException
    {
        // T1 (no indexes)
        st.executeUpdate("create table t1 (a int, b bigint)");
        st.executeUpdate("insert into t1 (a, b) " +
                         "values (1,1), (1,2), (1,3), (1,4), (1,5)");

        // T2 (primary key)
        st.executeUpdate("create table t2 (a int primary key, b bigint)");
        st.executeUpdate("insert into t2 (a, b) " +
                         "values (1,1), (2,1), (3,1), (4,1), (5,1)");

        // T3 (primary key + secondary key)
        st.executeUpdate("create table t3 (a int primary key, " +
                         "                 b bigint unique)");
        st.executeUpdate("insert into t3 (a, b) " +
                         "values (1,1), (2,2), (3,3), (4,4), (5,5)");
    }

    /**
     * Negative tests. Test various invalid OFFSET and FETCH NEXT clauses.
     *
     * @throws java.sql.SQLException
     */
    public void testErrors() throws SQLException
    {
        Statement st = createStatement();

        String  stub = "select * from t1 %";

        // Wrong range in row count argument
        vetStatement( st, LANG_INVALID_ROW_COUNT_OFFSET, stub, FIRST_ROWS_ONLY, "-1", null, null );

        vetStatement( st, LANG_SYNTAX_ERROR, stub, FIRST_ROWS_ONLY, "-?", null, null );

        assertStatementError(LANG_INVALID_ROW_COUNT_FIRST, st,
                             "select * from t1 fetch first 0 rows only");

        vetStatement( st, LANG_INVALID_ROW_COUNT_FIRST, stub, FIRST_ROWS_ONLY, null, "-1", null );

        // Wrong type in row count argument
        vetStatement( st, LANG_INTEGER_LITERAL_EXPECTED, stub, FIRST_ROWS_ONLY, null, "3.14", null );

        // Wrong order of clauses
        assertStatementError(LANG_SYNTAX_ERROR, st,
                             "select * from t1 " +
                             "fetch first 0 rows only offset 0 rows");
        assertStatementError(LANG_SYNTAX_ERROR, st,
                             "select * from t1 { offset 0 limit 0 }");
    }


    /**
     * Positive tests. Check that the new keyword OFFSET introduced is not
     * reserved so we don't risk breaking existing applications.
     *
     * @throws java.sql.SQLException
     */
    public void testNewKeywordNonReserved() throws SQLException
    {
        setAutoCommit(false);
        prepareStatement("select a,b as offset from t1 offset 0 rows");
        prepareStatement("select a,b as limit from t1 offset 0 rows");

        // Column and table correlation name usage
        prepareStatement("select a,b from t1 as offset");
        prepareStatement("select a,b from t1 as limit");

        prepareStatement("select a,b offset from t1 offset");
        prepareStatement("select a,b limit from t1 limit");

        prepareStatement("select a,b offset from t1 offset +2 rows");

        prepareStatement("select a offset,b from t1 offset ? rows");

        prepareStatement("select offset.a, offset.b offset from t1 as offset offset ? rows");
        prepareStatement("select limit.a, limit.b offset from t1 as limit offset ? rows");

        // DERBY-4562
        Statement s = createStatement();
        s.executeUpdate("create table t4562(i int, offset int)");
        ResultSet rs = s.executeQuery(
            "select * from t4562 where i > 0 and offset + i < 0 offset 2 rows");
        rs.next();

        rs = s.executeQuery(
            "select * from t4562 where i > 0 and offset - i < 0 offset 2 rows");
        rs.next();

        rs = s.executeQuery(
            "select * from t4562 where i > 0 and offset * i < 0 offset 2 rows");
        rs.next();

        rs.close();

        rollback();
    }


    /**
     * Positive tests.
     *
     * @throws java.sql.SQLException
     */
    public void testOffsetFetchFirstReadOnlyForwardOnlyRS() throws SQLException
    {
        Statement stm = createStatement();

        /*
         * offset 0 rows (a no-op)
         */

        vetStatement
            (
             stm, null, "select a, b from t1%", FIRST_ROWS_ONLY, "0", null,
             new String [][] { {"1","1"}, {"1","2"},{"1","3"}, {"1","4"},{"1","5"} }
             );
        vetStatement
            (
             stm, null, "select a,b from t2%", FIRST_ROWS_ONLY, "0", null,
             new String [][] { {"1","1"}, {"2","1"},{"3","1"}, {"4","1"},{"5","1"} }
             );
        vetStatement
            (
             stm, null, "select a,b from t3%", FIRST_ROWS_ONLY, "0", null,
             new String [][] { {"1","1"}, {"2","2"},{"3","3"}, {"4","4"},{"5","5"} }
             );

        /*
         * offset 1 rows
         */

        vetStatement
            (
             stm, null, "select a,b from t1%", FIRST_ROWS_ONLY, "1", null,
             new String [][] { {"1","2"},{"1","3"}, {"1","4"},{"1","5"} }
             );
        vetStatement
            (
             stm, null, "select a,b from t2%", FIRST_ROWS_ONLY, "1", null,
             new String [][] { {"2","1"},{"3","1"}, {"4","1"},{"5","1"} }
             );
        vetStatement
            (
             stm, null, "select a,b from t3%", FIRST_ROWS_ONLY, "1", null,
             new String [][] { {"2","2"},{"3","3"}, {"4","4"},{"5","5"} }
             );

        /*
         * offset 4 rows
         */

        vetStatement
            (
             stm, null, "select a,b from t1%", FIRST_ROWS_ONLY, "4", null,
             new String [][] { {"1","5"} }
             );
        vetStatement
            (
             stm, null, "select a,b from t2%", FIRST_ROWS_ONLY, "4", null,
             new String [][] { {"5","1"} }
             );
        vetStatement
            (
             stm, null, "select a,b from t3%", FIRST_ROWS_ONLY, "4", null,
             new String [][] {  {"5","5"} }
             );

        /*
         * offset 1 rows fetch 1 row. Use "next"/"rows" syntax
         */
        vetStatement
            (
             stm, null, "select a,b from t1%", FIRST_ROWS_ONLY, "1", "1",
             new String [][] { {"1","2"}  }
             );
        vetStatement
            (
             stm, null, "select a,b from t2%", FIRST_ROWS_ONLY, "1", "1",
             new String [][] { {"2","1"}  }
             );
        vetStatement
            (
             stm, null, "select a,b from t3%", FIRST_ROWS_ONLY, "1", "1",
             new String [][] { {"2","2"}  }
             );

        /*
         * offset 1 rows fetch so many rows we drain rs row. Use "first"/"row"
         * syntax
         */
        vetStatement
            (
             stm, null, "select a,b from t1%", FIRST_ROW_ONLY, "1", "10",
             new String [][] { {"1","2"},{"1","3"}, {"1","4"},{"1","5"} }
             );
        vetStatement
            (
             stm, null, "select a,b from t2%", FIRST_ROW_ONLY, "1", "10",
             new String [][] { {"2","1"},{"3","1"}, {"4","1"},{"5","1"} }
             );
        vetStatement
            (
             stm, null, "select a,b from t3%", FIRST_ROW_ONLY, "1", "10",
             new String [][] { {"2","2"},{"3","3"}, {"4","4"},{"5","5"} }
             );

        /*
         * offset so many rows that we see empty rs
         */
        vetStatement
            (
             stm, null, "select a,b from t1%", FIRST_ROW_ONLY, "10", null,
             new String [][] { }
             );
        vetStatement
            (
             stm, null, "select a,b from t2%", FIRST_ROW_ONLY, "10", null,
             new String [][] { }
             );
        vetStatement
            (
             stm, null, "select a,b from t3%", FIRST_ROW_ONLY, "10", null,
             new String [][] { }
             );

        /*
         * fetch first/next row (no row count given)
         */
        queryAndCheck(
            stm,
            "select a,b from t1 fetch first row only",
            new String [][] {{"1","1"}});
        queryAndCheck(
            stm,
            "select a,b from t2 fetch next row only",
            new String [][] {{"1","1"}});
        queryAndCheck(
            stm,
            "select a,b from t3 fetch next row only",
            new String [][] {{"1","1"}});

        /*
         * Combine with order by asc
         */
        queryAndCheck(
            stm,
            "select a,b from t1 order by b asc fetch first row only",
            new String [][] {{"1","1"}});
        queryAndCheck(
            stm,
            "select a,b from t2 order by a asc fetch next row only",
            new String [][] {{"1","1"}});
        queryAndCheck(
            stm,
            "select a,b from t3 order by a asc fetch next row only",
            new String [][] {{"1","1"}});

        /*
         * Combine with order by desc.
         */
        queryAndCheck(
            stm,
            // Note: use column b here since for t1 all column a values are the
            // same and order can change after sorting, want unique row first
            // in rs so we can test it.
            "select a,b from t1 order by b desc fetch first row only",
            new String [][] {{"1","5"}});
        queryAndCheck(
            stm,
            "select a,b from t2 order by a desc fetch next row only",
            new String [][] {{"5","1"}});
        queryAndCheck(
            stm,
            "select a,b from t3 order by a desc fetch next row only",
            new String [][] {{"5","5"}});

        /*
         * Combine with group by, order by.
         */
        queryAndCheck(
            stm,
            "select max(a) from t1 group by b fetch first row only",
            new String [][] {{"1"}});
        vetStatement
            (
             stm, null, "select max(a) from t2 group by b %", FIRST_ROW_ONLY, "0", null,
             new String [][] { {"5"} }
             );
        vetStatement
            (
             stm, null, "select max(a) from t3 group by b order by max(a) %", NEXT_ROWS_ONLY, null, "2",
             new String [][] { {"1"},{"2"} }
             );

        /*
         * Combine with union
         */

        vetStatement
            (
             stm, null, "select * from t1 union all select * from t1 %", FIRST_ROW_ONLY, null, "2",
             new String [][] { {"1","1"}, {"1","2"} }
             );

        /*
         * Combine with join
         */
        vetStatement
            (
             stm, null, "select t2.b, t3.b from t2,t3 where t2.a=t3.a %", FIRST_ROW_ONLY, null, "2",
             new String [][] { {"1","1"}, {"1","2"} }
             );

        stm.close();
    }


    /**
     * Positive tests.
     *
     * @throws java.sql.SQLException
     */
    public void testOffsetFetchFirstUpdatableForwardOnlyRS() throws SQLException
    {
        Statement stm = createStatement(ResultSet.TYPE_FORWARD_ONLY,
                                        ResultSet.CONCUR_UPDATABLE);
        ResultSet   rs;
        String[]    variants;

        setAutoCommit(false);

        /*
         * offset 0 rows (a no-op), update a row and verify result
         */
        variants = makeVariants( "select * from t1 %", FIRST_ROWS_ONLY, "0", null );
        for (String variant : variants)
        {
            rs = stm.executeQuery( variant );
            rs.next();
            rs.next(); // at row 2
            rs.updateInt(1, -rs.getInt(1));
            rs.updateRow();
            rs.close();

            queryAndCheck(
                          stm,
                          "select a,b from t1",
                          new String [][] {
                              {"1","1"}, {"-1","2"},{"1","3"}, {"1","4"},{"1","5"}});

            rollback();
        }

        /*
         * offset 1 rows, update a row and verify result
         */
        variants = makeVariants( "select * from t1 %", FIRST_ROWS_ONLY, "1", null );
        for ( String variant : variants )
        {
            rs = stm.executeQuery( variant );
            rs.next(); // at row 1, but row 2 of underlying rs

            rs.updateInt(1, -rs.getInt(1));
            rs.updateRow();
            rs.close();

            queryAndCheck(
                          stm,
                          "select a,b from t1",
                          new String [][] {
                              {"1","1"}, {"-1","2"},{"1","3"}, {"1","4"},{"1","5"}});

            rollback();
        }
        
        stm.close();
    }


    /**
     * Positive tests with scrollable read-only.
     *
     * @throws java.sql.SQLException
     */
    public void testOffsetFetchFirstReadOnlyScrollableRS() throws SQLException
    {
        Statement stm = createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
                                        ResultSet.CONCUR_READ_ONLY);
        ResultSet   rs;
        String[]    variants;

        /*
         * offset 0 rows (a no-op), update a row and verify result
         */
        variants = makeVariants( "select * from t1 %", FIRST_ROWS_ONLY, "0", null );
        for ( String variant : variants )
        {
            rs = stm.executeQuery( variant );
            rs.next();
            rs.next(); // at row 2
            assertTrue(rs.getInt(2) == 2);
            rs.close();
        }
        
        /*
         * offset 1 rows, fetch 3 row, check that we have the right ones
         */
        variants = makeVariants( "select * from t1 %", FIRST_ROWS_ONLY, "1", "3" );
        for ( String variant : variants )
        {
            rs = stm.executeQuery( variant );
            rs.next();
            rs.next(); // at row 2, but row 3 of underlying rs

            assertTrue(rs.getInt(2) == 3);

            // Go backbards and update
            rs.previous();
            assertTrue(rs.getInt(2) == 2);

            // Try some navigation and border conditions
            rs.previous();
            assertTrue(rs.isBeforeFirst());
            rs.next();
            rs.next();
            rs.next();
            rs.next();
            assertTrue(rs.isAfterLast());
        }
        
        stm.close();
    }


    /**
     * Positive tests with SUR (Scrollable updatable result set).
     *
     * @throws java.sql.SQLException
     */
    public void testOffsetFetchFirstUpdatableScrollableRS() throws SQLException
    {
        Statement stm = createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
                                        ResultSet.CONCUR_UPDATABLE);
        ResultSet   rs;
        String[]    variants;

        setAutoCommit(false);

        /*
         * offset 0 rows (a no-op), update a row and verify result
         * also try the "for update" syntax so we see that it still works
         */
        variants = makeVariants( "select * from t1 % for update", FIRST_ROWS_ONLY, "0", null );
        for (String variant : variants)
        {
            rs = stm.executeQuery( variant );
            rs.next();
            rs.next(); // at row 2
            rs.updateInt(1, -rs.getInt(1));
            rs.updateRow();
            rs.close();

            queryAndCheck(
                          stm,
                          "select a,b from t1",
                          new String [][] {
                              {"1","1"}, {"-1","2"},{"1","3"}, {"1","4"},{"1","5"}});

            rollback();
        }
        
        /*
         * offset 1 rows, fetch 3 row, update some rows and verify result
         */
        variants = makeVariants( "select * from t1 %", NEXT_ROWS_ONLY, "1", "3" );
        for ( String variant : variants )
        {
            rs = stm.executeQuery( variant );
            rs.next();
            rs.next(); // at row 2, but row 3 of underlying rs

            rs.updateInt(1, -rs.getInt(1));
            rs.updateRow();

            // Go backbards and update
            rs.previous();
            rs.updateInt(1, -rs.getInt(1));
            rs.updateRow();

            // Try some navigation and border conditions
            rs.previous();
            assertTrue(rs.isBeforeFirst());
            rs.next();
            rs.next();
            rs.next();
            rs.next();
            assertTrue(rs.isAfterLast());

            // Insert a row
            rs.moveToInsertRow();
            rs.updateInt(1,42);
            rs.updateInt(2,42);
            rs.insertRow();

            // Delete a row
            rs.previous();
            rs.deleteRow();

            // .. and see that a hole is left in its place
            rs.previous();
            rs.next();
            assertTrue(rs.rowDeleted());

            rs.close();

            queryAndCheck(
                          stm,
                          "select a,b from t1",
                          new String [][] {
                              {"1","1"}, {"-1","2"},{"-1","3"},{"1","5"},{"42","42"}});
            rollback();
        }
        
        // Test with projection
        variants = makeVariants( "select * from t1 where a + 1 < b%", NEXT_ROWS_ONLY, "1", null );
        for (String variant : variants)
        {
            rs = stm.executeQuery( variant );
            // should yield 2 rows
            rs.absolute(2);
            assertTrue(rs.getInt(2) == 5);
            rs.updateInt(2, -5);
            rs.updateRow();
            rs.close();

            queryAndCheck(
                          stm,
                          "select a,b from t1",
                          new String [][] {
                              {"1","1"}, {"1","2"},{"1","3"},{"1","4"},{"1","-5"}});
            rollback();
        }
        
        stm.close();
    }


    public void testValues() throws SQLException
    {
        Statement stm = createStatement();

        vetStatement
            (
             stm, null, "values 4%", FIRST_ROW_ONLY, null, "2",
             new String [][] { {"4"} }
             );

        vetStatement
            (
             stm, null, "values 4%", FIRST_ROW_ONLY, "1", null,
             new String [][] { }
             );

        stm.close();
    }

    /**
     * Positive tests, result set metadata
     *
     * @throws java.sql.SQLException
     */
    public void testMetadata() throws SQLException
    {
        Statement stm = createStatement();
        ResultSet   rs;
        String[]    variants;

        variants = makeVariants( "select * from t1%", NEXT_ROWS_ONLY, "1", null );
        for (String variant : variants)
        {
            rs = stm.executeQuery( variant );
            ResultSetMetaData rsmd= rs.getMetaData();
            int cnt = rsmd.getColumnCount();

            String[] cols = new String[]{"A","B"};
            int[] types = {Types.INTEGER, Types.BIGINT};

            for (int i=1; i <= cnt; i++) {
                String name = rsmd.getColumnName(i);
                int type = rsmd.getColumnType(i);

                assertTrue(name.equals(cols[i-1]));
                assertTrue(type == types[i-1]);
            }

            rs.close();
        }
        
        stm.close();
    }


    /**
     * Test that we see correct traces of the filtering in the statistics
     *
     * @throws java.sql.SQLException
     */
    public void testRunTimeStatistics() throws SQLException
    {
        Statement stm = createStatement();
        ResultSet   rs;
        String[]    variants;

        variants = makeVariants( "select a,b from t1%", NEXT_ROWS_ONLY, "2", null );
        for (String variant : variants)
        {
            stm.executeUpdate( "call syscs_util.syscs_set_runtimestatistics(1)" );

            queryAndCheck(
                          stm,
                          variant,
                          new String [][] {
                              {"1","3"}, {"1","4"},{"1","5"}});

            stm.executeUpdate( "call syscs_util.syscs_set_runtimestatistics(0)" );

            rs = stm.executeQuery( "values syscs_util.syscs_get_runtimestatistics()" );
            rs.next();
            String plan = rs.getString(1);

            // Verify that the plan shows the filtering (2 rows of 3 seen):
            assertTrue(plan.indexOf("Row Count (1):\n" +
                                    "Number of opens = 1\n" +
                                    "Rows seen = 3\n" +
                                    "Rows filtered = 2") != -1);

            rs.close();
        }
        
        stm.close();
    }


    /**
     * Test against a bigger table
     *
     * @throws java.sql.SQLException
     */
    public void testBigTable() throws SQLException
    {
        Statement stm = createStatement();

        setAutoCommit(false);

        stm.executeUpdate("declare global temporary table session.t (i int) " +
                          "on commit preserve rows not logged");

        PreparedStatement ps =
            prepareStatement("insert into session.t values ?");

        for (int i=1; i <= 100000; i++) {
            ps.setInt(1, i);
            ps.executeUpdate();

            if (i % 10000 == 0) {
                commit();
            }
        }

        queryAndCheck(
            stm,
            "select count(*) from session.t",
            new String [][] {
                {"100000"}});

        vetStatement
            (
             stm, null, "select i from session.t%", FIRST_ROWS_ONLY, "99999", null,
             new String [][] { {"100000"} }
             );

        stm.executeUpdate("drop table session.t");
        stm.close();
    }

    /**
     * Test that the values of offset and fetch first are not forgotten if
     * a {@code PreparedStatement} is executed multiple times (DERBY-4212).
     *
     * @throws java.sql.SQLException
     */
    public void testRepeatedExecution() throws SQLException
    {
        PreparedStatement ps;
        String[]    variants;

        variants = makeVariants( "select * from t1 order by b%", NEXT_ROWS_ONLY, "2", "2" );
        for (String variant : variants)
        {
            ps = prepareStatement( variant );
            String[][] expected = {{"1", "3"}, {"1", "4"}};
            for (int i = 0; i < 10; i++) {
                JDBC.assertFullResultSet(ps.executeQuery(), expected);
            }
        }
    }

    /**
     * Test dynamic arguments
     *
     * @throws java.sql.SQLException
     */
    public void testDynamicArgs() throws SQLException
    {
        PreparedStatement ps;
        String[]    variants;
        String[][] expected = null;

        // Check look-ahead also for ? in grammar since offset is not reserved
        variants = makeVariants( "select * from t1%", NEXT_ROWS_ONLY, "?", null );
        for (String variant : variants)
        {
            ps = prepareStatement( variant );
        }
        
        
        variants = makeVariants( "select * from t1 order by b%", NEXT_ROWS_ONLY, "?", "?" );
        for ( int j = 0; j < variants.length; j++ )
        {
            // SQL Standard and JDBC limit/offset parameter orders are different
            int offsetParam = ( j == SQL_STANDARD_VARIANT ) ? 1 : 2;
            int fetchParam = ( j == SQL_STANDARD_VARIANT ) ? 2 : 1;
            
            expected = new String[][] {{"1", "3"}, {"1", "4"}};
            ps = prepareStatement( variants[ j ] );

            // Check range errors

            ps.setInt( offsetParam, 0 );
            assertPreparedStatementError(LANG_MISSING_PARMS, ps);

            ps.setInt( offsetParam, -1 );
            ps.setInt( fetchParam, 2 );
            assertPreparedStatementError(LANG_INVALID_ROW_COUNT_OFFSET, ps);

            ps.setInt( offsetParam, 0 );
            ps.setInt( fetchParam, ( j == SQL_STANDARD_VARIANT ) ? 0 : -1 );
            assertPreparedStatementError(LANG_INVALID_ROW_COUNT_FIRST, ps);

            // Check non-integer values
            try {
                ps.setString( offsetParam, "aaa");
            } catch (SQLException e) {
                assertSQLState(LANG_FORMAT_EXCEPTION, e);
            }

            try {
                ps.setString( fetchParam, "aaa");
            } catch (SQLException e) {
                assertSQLState(LANG_FORMAT_EXCEPTION, e);
            }


            // A normal case
            for (int i = 0; i < 2; i++) {
                ps.setInt( offsetParam,2 );
                ps.setInt( fetchParam,2 );
                JDBC.assertFullResultSet(ps.executeQuery(), expected);
            }

            // Now, note that since we now have different values for offset and
            // fetch first, we also exercise reusing the result set for this
            // prepared statement (i.e. the values are computed at execution time,
            // not at result set generation time). Try long value for change.
            ps.setLong( offsetParam, 1L );
            ps.setInt( fetchParam, 3 );
            expected = new String[][]{{"1", "2"}, {"1", "3"}, {"1", "4"}};
            JDBC.assertFullResultSet(ps.executeQuery(), expected);


            //  Try a large number
            ps.setLong( offsetParam, Integer.MAX_VALUE * 2L );
            ps.setInt( fetchParam, 5 );
            JDBC.assertEmpty(ps.executeQuery());
        }
        
        // Mix of prepared and not
        variants = makeVariants( "select * from t1 order by b%", NEXT_ROWS_ONLY, "?", "3" );
        for (String variant : variants)
        {
            ps = prepareStatement( variant );
            ps.setLong(1, 1L);
            JDBC.assertFullResultSet(ps.executeQuery(), expected);
        }

        variants = makeVariants( "select * from t1 order by b%", NEXT_ROWS_ONLY, "4", "?" );
        for (String variant : variants)
        {
            ps = prepareStatement( variant );
            ps.setLong(1, 1L);
            JDBC.assertFullResultSet(ps.executeQuery(), new String[][]{{"1", "5"}});
        }

        // Mix of other dyn args and ours:
        variants = makeVariants( "select * from t1 where a = ? order by b%", NEXT_ROWS_ONLY, "?", "3" );
        for (String variant : variants)
        {
            ps = prepareStatement( variant );
            ps.setInt(1, 1);
            ps.setLong(2, 1L);
            JDBC.assertFullResultSet(ps.executeQuery(), expected);
        }

        variants = makeVariants( "select * from t1 where a = ? order by b%", NEXT_ROWS_ONLY, "1", "?" );
        for (String variant : variants)
        {
            ps = prepareStatement( variant );
            ps.setInt(1, 1);
            ps.setLong(2, 2L);
            expected = new String[][]{{"1", "2"}, {"1", "3"}};
            JDBC.assertFullResultSet(ps.executeQuery(), expected);
        }

        // NULLs not allowed (Note: parameter metadata says "isNullable" for
        // all ? args in Derby...)
        variants = makeVariants( "select * from t1 order by b%", NEXT_ROWS_ONLY, "?", "?" );
        for ( int i = 0; i < variants.length; i++ )
        {
            ps = prepareStatement( variants[ i ] );
            int offsetParam = ( i == SQL_STANDARD_VARIANT ) ? 1 : 2;
            int fetchParam = ( i == SQL_STANDARD_VARIANT ) ? 2 : 1;
            
            ps.setNull( offsetParam, Types.BIGINT );
            ps.setInt( fetchParam, 2 );
            assertPreparedStatementError(LANG_ROW_COUNT_OFFSET_FIRST_IS_NULL, ps);

            ps.setInt( offsetParam,1 );
            ps.setNull( fetchParam, Types.BIGINT );
            assertPreparedStatementError(LANG_ROW_COUNT_OFFSET_FIRST_IS_NULL, ps);
            
            ps.close();
        }
    }

    /**
     * Test dynamic arguments
     *
     * @throws java.sql.SQLException
     */
    public void testDynamicArgsMetaData() throws SQLException
    {

    	//since there is no getParameterMetaData() call available in JSR169 
    	//implementations, do not run this test if we are running JSR169
    	if (JDBC.vmSupportsJSR169()) return;

        PreparedStatement ps;
        String[]    variants;

        variants = makeVariants( "select * from t1 where a = ? order by b%", NEXT_ROWS_ONLY, "?", "?" );
        for (String variant : variants)
        {
            ps = prepareStatement( variant );
            
            ParameterMetaData pmd = ps.getParameterMetaData();
            int[] expectedTypes = { Types.INTEGER, Types.BIGINT, Types.BIGINT };

            for (int i = 0; i < 3; i++) {
                assertEquals("Unexpected parameter type",
                             expectedTypes[i], pmd.getParameterType(i+1));
                assertEquals("Derby ? args are nullable",
                             // Why is that? Cf. logic in ParameterNode.setType
                             ParameterMetaData.parameterNullable,
                             pmd.isNullable(i+1));
            }
            ps.close();
        }
    }

    /**
     * Test some additional corner cases in JDBC limit/offset syntax.
     *
     * @throws java.sql.SQLException
     */
    public void testJDBCLimitOffset() throws SQLException
    {
        // LIMIT 0 is allowed. It means: everything from the OFFSET forward
        PreparedStatement   ps = prepareStatement( "select a from t2 order by a { limit ? }" );
        ps.setInt( 1, 0 );
        JDBC.assertFullResultSet
            (
             ps.executeQuery(),
             new String[][] { { "1" }, { "2" }, { "3" }, { "4" }, { "5" } }
             );
        ps.close();

        ps = prepareStatement( "select a from t2 order by a { limit ? offset 3 }" );
        ps.setInt( 1, 0 );
        JDBC.assertFullResultSet
            (
             ps.executeQuery(),
             new String[][] { { "4" }, { "5" } }
             );
        ps.close();

        // mix JDBC and SQL Standard syntax
        ps = prepareStatement
            (
             "select t.a from\n" +
             "( select * from t2 order by a { limit 3 offset 1 } ) t,\n" +
             "( select * from t3 order by a offset 2 rows fetch next 10 rows only ) s\n" +
             "where t.a = s.a order by t.a"
             );
        JDBC.assertFullResultSet
            (
             ps.executeQuery(),
             new String[][] { { "3" }, { "4" } }
             );
        ps.close();
    }

    /**
     * Run a statement with both SQL Standard and JDBC limit/offset syntax. Verify
     * that we get the expected error or results. The statement has a % literal at the
     * point where the offset/fetchFirst and limit/offset clauses are to be inserted.
     */
    private void    vetStatement
        ( Statement stmt, String sqlState, String stub, String fetchFormat, String offset, String fetchFirst, String[][] expectedResults )
        throws SQLException
    {
        String[]    variants = makeVariants( stub, fetchFormat, offset, fetchFirst );

        for (String text : variants)
        {
            if ( sqlState != null )
            {
                assertStatementError( sqlState, stmt, text );
            }
            else
            {
                queryAndCheck( stmt, text, expectedResults );
            }
        }
    }

    /**
     * Make the SQL Standard and JDBC limit/offset variants of a stub statement,
     * plugging in the given offset and fetch count.
     */
    private String[]    makeVariants
        ( String stub, String fetchFormat, String offset, String fetchFirst )
    {
        String[]    result = new String[ VARIANT_COUNT ];

        result[ SQL_STANDARD_VARIANT ] = makeSQLStandardText( stub, fetchFormat, offset, fetchFirst );
        result[ JDBC_VARIANT ] = makeJDBCText( stub, offset, fetchFirst );

        return result;
    }
    
    /**
     * Substitute the SQL Standard syntax into a stub statement, given an offset and fetch count.
     */
    private String  makeSQLStandardText
        ( String stub, String fetchFormat, String offset, String fetchFirst )
    {
        String  sqlStandardText = "";

        if ( offset != null )
        {
            sqlStandardText = " offset " + offset + " rows ";
        }
        if ( fetchFirst != null )
        {
            sqlStandardText = sqlStandardText + substitute( fetchFormat, PERCENT_TOKEN, fetchFirst );
        }

        sqlStandardText = substitute( stub, PERCENT_TOKEN, sqlStandardText );

        println( sqlStandardText );

        return sqlStandardText;
    }
    /**
     * Substitute JDBC limit/offset syntax into a stub statement, given an offset and fetch count.
     */
    private String  makeJDBCText
        ( String stub, String offset, String fetchFirst )
    {
        String  jdbcText = "";

        if ( offset != null )
        {
            jdbcText = " offset " + offset;
        }
        if ( fetchFirst != null )
        {
            jdbcText = " limit " + fetchFirst + " " + jdbcText;
        }
        else
        {
            jdbcText = "limit 0 " + jdbcText;
        }

        jdbcText = substitute( stub, PERCENT_TOKEN, " { " + jdbcText + " } " );

        println( jdbcText );

        return jdbcText;
    }

    private String  substitute( String stub, String token, String replacement )
    {
        int substitutionIndex = stub.indexOf( token );
        if ( substitutionIndex < 0 ) { fail( "Bad stub: " + stub + ". Can't find token: " + token ); }

        String  prefix = stub.substring( 0, substitutionIndex );
        String  suffix = ( substitutionIndex == stub.length() - 1 ) ?
            "" : stub.substring( substitutionIndex + 1, stub.length() );

        return prefix + replacement + suffix;
    }
    
    private void queryAndCheck(
        Statement stm,
        String queryText,
        String [][] expectedRows) throws SQLException {

        ResultSet rs = stm.executeQuery(queryText);
        JDBC.assertFullResultSet(rs, expectedRows);
    }

}