File: PreparedStatementTest.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 (1395 lines) | stat: -rw-r--r-- 50,029 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
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
/*
 
   Derby - Class org.apache.derbyTesting.functionTests.tests.jdbc4.PreparedStatementTest
 
   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.jdbc4;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.Reader;
import java.io.StringReader;
import java.sql.Blob;
import java.sql.CallableStatement;
import java.sql.Clob;
import java.sql.Connection;
import java.sql.NClob;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.RowId;
import java.sql.SQLException;
import java.sql.SQLFeatureNotSupportedException;
import java.sql.SQLXML;
import java.sql.Statement;
import java.sql.Types;
import junit.framework.Test;
import org.apache.derby.iapi.services.io.DerbyIOException;
import org.apache.derby.shared.common.sanity.SanityManager;
import org.apache.derbyTesting.functionTests.util.streams.LoopingAlphabetStream;
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;

/**
 * This class is used to test JDBC4 specific methods in the PreparedStatement(s)
 * object.
 *
 * A number of methods and variables are in place to aid the writing of tests:
 * <ul><li>setBinaryStreamOnBlob
 *     <li>setAsciiStream
 *     <li>key - an id. One is generated each time setUp is run.
 *     <li>reqeustKey() - generate a new unique id.
 *     <li>psInsertX - prepared statements for insert.
 *     <li>psFetchX - prepared statements for fetching values.
 * </ul>
 *
 * For table creation, see the <code>suite</code>-method.
 */
public class PreparedStatementTest extends BaseJDBCTestCase {

    private static final String BLOBTBL = "BlobTestTable";
    private static final String CLOBTBL = "ClobTestTable";
    private static final String LONGVARCHAR = "LongVarcharTestTable";

    /** Key used to id data inserted into the database. */
    private static int globalKey = 1;

    /** Byte array passed in to the database. **/
    private static final byte[] BYTES = {
        0x65, 0x66, 0x67, 0x68, 0x69,
        0x69, 0x68, 0x67, 0x66, 0x65
    };

    // Default connection and prepared statements that are used by the tests.
    /** 
     * Default key to use for insertions.
     * Is unique for each fixture. More keys can be fetched by calling
     * <link>requestKey</link>.
     */
    private int key;
    /** Default connection object. */
    /** PreparedStatement object with no positional arguments. */
    private PreparedStatement ps = null;
    /** PreparedStatement to fetch BLOB with specified id. */
    private PreparedStatement psFetchBlob = null;
    /** PreparedStatement to insert a BLOB with specified id. */
    private PreparedStatement psInsertBlob = null;
    /** PreparedStatement to fetch CLOB with specified id. */
    private PreparedStatement psFetchClob = null;
    /** PreparedStatement to insert a CLOB with specified id. */
    private PreparedStatement psInsertClob = null;
    /** PreparedStatement to insert a LONG VARCHAR with specified id. */
    private PreparedStatement psInsertLongVarchar = null;
    //Statement object
    private Statement s = null;


    
    /**
     * Create a test with the given name.
     * 
     * @param name name of the test.
     */
    public PreparedStatementTest(String name) {
        super(name);
    }
    
    /**
     *
     * Obtain a "regular" connection and PreparedStatement that the tests 
     * can use.
     * 
     * @throws SQLException
     */
    public void setUp() 
        throws SQLException {
        key = requestKey();
        //create the statement object
        s = createStatement();
        //Create the PreparedStatement that will then be used as the basis 
        //throughout this test henceforth
        //This prepared statement will however NOT be used for testing
        //setClob and setBlob
        ps = prepareStatement("select count(*) from sys.systables");
        
        // Prepare misc statements.
        psFetchBlob = prepareStatement("SELECT dBlob FROM " +
                BLOBTBL + " WHERE sno = ?");
        psInsertBlob = prepareStatement("INSERT INTO " + BLOBTBL +
                " VALUES (?, ?)");
        psFetchClob = prepareStatement("SELECT dClob FROM " +
                CLOBTBL + " WHERE sno = ?");
        psInsertClob = prepareStatement("INSERT INTO " + CLOBTBL +
                " VALUES (?, ?)");
        psInsertLongVarchar = prepareStatement("INSERT INTO " + LONGVARCHAR +
                " VALUES (?, ?)");
    }

    /**
     *
     * Release the resources that are used in this test
     *
     * @throws SQLException
     *
     */
    public void tearDown() 
        throws Exception {
        
        s.close();
        ps.close();

        s = null;
        ps = null;

        psFetchBlob.close();
        psFetchClob.close();
        psInsertBlob.close();
        psInsertClob.close();
        psInsertLongVarchar.close();
        
        psFetchBlob = null;
        psFetchClob = null;
        psInsertBlob = null;
        psInsertClob = null;
        psInsertLongVarchar = null;

        super.tearDown();
    }

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

        suite.addTest(baseSuite("PreparedStatementTest:embedded"));
        suite.addTest(
                TestConfiguration.connectionXADecorator(
                        baseSuite("PreparedStatementTest:embedded XADataSource")));
        
        suite.addTest(TestConfiguration.clientServerDecorator(
            baseSuite("PreparedStatementTest:client")));

        suite.addTest(TestConfiguration.clientServerDecorator(
                        TestConfiguration.connectionCPDecorator( baseSuite
                                ("PreparedStatementTest:logical"))));

        // Tests for the client side JDBC statement cache.
        suite.addTest(TestConfiguration.clientServerDecorator(
                statementCachingSuite()));

        suite.addTest(
                TestConfiguration.clientServerDecorator(
                TestConfiguration.connectionXADecorator(
                baseSuite("PreparedStatementTest:client XXXXADataSource"))));

        return suite;
    }

    private static Test baseSuite(String name) {
        BaseTestSuite suite = new BaseTestSuite(name);
        suite.addTestSuite(PreparedStatementTest.class);
        return new CleanDatabaseTestSetup(suite) {

            protected void decorateSQL(Statement stmt) throws SQLException
            {
                    stmt.execute("create table " + BLOBTBL +
                            " (sno int, dBlob BLOB(1M))");
                    stmt.execute("create table " + CLOBTBL +
                            " (sno int, dClob CLOB(1M))");
                    stmt.execute("create table " + LONGVARCHAR  +
                            " (sno int, dLongVarchar LONG VARCHAR)");
                 }
            };
    }
    
    /**
     * Returns a suite for tests that need JDBC statement caching to be enabled.
     */
    private static Test statementCachingSuite() {
        BaseTestSuite suite =
            new BaseTestSuite("JDBC statement caching suite");

        suite.addTest(new PreparedStatementTest("cpTestIsPoolableHintFalse"));
        suite.addTest(new PreparedStatementTest("cpTestIsPoolableHintTrue"));
        return TestConfiguration.connectionCPDecorator(
            new CleanDatabaseTestSetup(suite) {

            protected void decorateSQL(Statement stmt)
                    throws SQLException {
                stmt.execute("create table " + BLOBTBL +
                        " (sno int, dBlob BLOB(1M))");
                stmt.execute("create table " + CLOBTBL +
                        " (sno int, dClob CLOB(1M))");
                stmt.execute("create table " + LONGVARCHAR  +
                        " (sno int, dLongVarchar LONG VARCHAR)");
                 }
            });
    }

    //--------------------------------------------------------------------------
    //BEGIN THE TEST OF THE METHODS THAT THROW AN UNIMPLEMENTED EXCEPTION IN
    //THIS CLASS
    
    /**
     * Tests the setRowId method of the PreparedStatement interface
     *
     * @throws SQLException upon any failure that occurs in the 
     *         call to the method.
     */
    public void testSetRowId() throws SQLException{
        try {
            RowId rowid = null;
            ps.setRowId(0,rowid);
            fail("setRowId should not be implemented");
        }
        catch(SQLFeatureNotSupportedException sqlfne) {
            //Do Nothing, This happens as expected
        }
    }
    
    /**
     * Tests the setNString method of the PreparedStatement interface
     *
     * @throws SQLException upon any failure that occurs in the 
     *         call to the method.
     */
    public void testSetNString() throws SQLException{
        try {
            String str = null;
            ps.setNString(0,str);
            fail("setNString should not be implemented");
        }
        catch(SQLFeatureNotSupportedException sqlfne) {
            //Do Nothing, This happens as expected
        }
    }
    
    /**
     * Tests the setNCharacterStream method of the PreparedStatement interface
     *
     * @throws SQLException upon any failure that occurs in the 
     *         call to the method.
     */
    public void testSetNCharacterStream() throws SQLException{
        try {
            Reader r  = null;
            ps.setNCharacterStream(0,r,0);
            fail("setNCharacterStream should not be implemented");
        }
        catch(SQLFeatureNotSupportedException sqlfne) {
            //Do Nothing, This happens as expected
        }
    }
    
    public void testSetNCharacterStreamLengthlessNotImplemented()
            throws SQLException {
        try {
            ps.setNCharacterStream(1, new StringReader("A string"));
            fail("setNCharacterStream(int,Reader) should not be implemented");
        } catch (SQLFeatureNotSupportedException sfnse) {
            // Do nothing, this is expected behavior.
        }
    }

    public void testSetNClobLengthlessNotImplemented()
            throws SQLException {
        try {
            ps.setNClob(1, new StringReader("A string"));
            fail("setNClob(int,Reader) should not be implemented");
        } catch (SQLFeatureNotSupportedException sfnse) {
            // Do nothing, this is expected behaviour.
        }
    }

    /**
     * Tests the setNClob method of the PreparedStatement interface
     *
     * @throws SQLException upon any failure that occurs in the 
     *         call to the method.
     */
    public void testSetNClob1() throws SQLException{
        try {
            NClob nclob = null;
            ps.setNClob(0,nclob);
            fail("setNClob should not be implemented");
        }
        catch(SQLFeatureNotSupportedException sqlfne) {
            //Do Nothing, This happens as expected
        }
    }
    
    /**
     * Tests the setNClob method of the PreparedStatement interface
     *
     * @throws SQLException upon any failure that occurs in the 
     *         call to the method.
     */
    public void testSetNClob2() throws SQLException{
        try {
            Reader reader = null;
            ps.setNClob(0,reader,0);
            fail("setNClob should not be implemented");
        }
        catch(SQLFeatureNotSupportedException sqlfne) {
            //Do Nothing, This happens as expected
        }
    }
    
    /**
     * Tests the setSQLXML method of the PreparedStatement interface
     *
     * @throws SQLException upon any failure that occurs in the 
     *         call to the method.
     */
    public void testSetSQLXML() throws SQLException{
        try {
            SQLXML sqlxml = null;
            ps.setSQLXML(0,sqlxml);
            fail("setNClob should not be implemented");
        }
        catch(SQLFeatureNotSupportedException sqlfne) {
            //Do Nothing, This happens as expected
        }
    }
    
    //--------------------------------------------------------------------------
    //Now test the methods that are implemented in the PreparedStatement 
    //interface

    public void testIsWrapperForStatement() throws SQLException {
        assertTrue(ps.isWrapperFor(Statement.class));
    }

    public void testIsWrapperForPreparedStatement() throws SQLException {
        assertTrue(ps.isWrapperFor(PreparedStatement.class));
    }

    public void testIsNotWrapperForCallableStatement() throws SQLException {
        assertFalse(ps.isWrapperFor(CallableStatement.class));
    }

    public void testIsNotWrapperForResultSet() throws SQLException {
        assertFalse(ps.isWrapperFor(ResultSet.class));
    }

    public void testIsWrapperForSelf() throws SQLException {
        assertTrue(ps.isWrapperFor(ps.getClass()));
    }

    public void testUnwrapStatement() throws SQLException {
        Statement stmt = ps.unwrap(Statement.class);
        assertSame("Unwrap returned wrong object.", ps, stmt);
    }

    public void testUnwrapPreparedStatement() throws SQLException {
        PreparedStatement ps2 = ps.unwrap(PreparedStatement.class);
        assertSame("Unwrap returned wrong object.", ps, ps2);
    }

    public void testUnwrapAsSelf() throws SQLException {
        PreparedStatement ps2 = ps.unwrap(ps.getClass());
        assertSame("Unwrap returned wrong object.", ps, ps2);
    }

    public void testUnwrapCallableStatement() {
        try {
            CallableStatement cs = ps.unwrap(CallableStatement.class);
            fail("Unwrap didn't fail.");
        } catch (SQLException e) {
            assertSQLState("XJ128", e);
        }
    }

    public void testUnwrapResultSet() {
        try {
            ResultSet rs = ps.unwrap(ResultSet.class);
            fail("Unwrap didn't fail.");
        } catch (SQLException e) {
            assertSQLState("XJ128", e);
        }
    }

    //-----------------------------------------------------------------------
    // Begin test for setClob and setBlob
    
    /*
       we need a table in which a Clob or a Blob can be stored. We basically
       need to write tests for the setClob and the setBlob methods. 
       Proper process would be
       a) Do a createClob or createBlob
       b) Populate data in the LOB
       c) Store in Database

       But the createClob and createBlob implementations are not 
       available on the EmbeddedServer. So instead the workaround adopted
       is 

       a) store a Clob or Blob in Database. 
       b) Retrieve it from the database.
       c) store it back using setClob or setBlob

     */

    /**
     *
     * Test the setClob() method
     *
     * @throws SQLException if a failure occurs during the call to setClob
     *
     */
    public void testSetClob()
            throws IOException, SQLException {
        // Life span of Clob objects are limited by the transaction.  Need
        // autocommit off so Clob objects survive execution of next statement.
        getConnection().setAutoCommit(false);

        //insert default values into the table
        
        String str = "Test data for the Clob object";
        StringReader is = new StringReader("Test data for the Clob object");
        is.reset();
        
        //initially insert the data
        psInsertClob.setInt(1, key);
        psInsertClob.setClob(2, is, str.length());
        psInsertClob.executeUpdate();
        
        //Now query to retrieve the Clob
        psFetchClob.setInt(1, key);
        ResultSet rs = psFetchClob.executeQuery();
        rs.next();
        Clob clobToBeInserted = rs.getClob(1);
        rs.close();
        
        //Now use the setClob method
        int secondKey = requestKey();
        psInsertClob.setInt(1, secondKey);
        psInsertClob.setClob(2, clobToBeInserted);
        psInsertClob.execute();
        
        psInsertClob.close();
        
        //Now test to see that the Clob has been stored correctly
        psFetchClob.setInt(1, secondKey);
        rs = psFetchClob.executeQuery();
        rs.next();
        Clob clobRetrieved = rs.getClob(1);
        
        assertEquals(clobToBeInserted,clobRetrieved);
    }

    /**
     * Insert <code>Clob</code> without specifying length and read it back
     * for verification.
     *
     * @throws IOException If an IOException during the close operation on the
     *                     reader.
     * @throws SQLException If an SQLException occurs.
     */
    public void testSetClobLengthless()
            throws IOException, SQLException {
        // Life span of Clob objects are the transaction.  Need autocommit off
        // to have Clob objects survive execution of next statement.
        getConnection().setAutoCommit(false);

        //Create the Clob and insert data into it.
        Clob insertClob = getConnection().createClob();
        OutputStream os = insertClob.setAsciiStream(1);
        os.write(BYTES);

        //Insert the Clob created above into the
        //database.
        psInsertClob.setInt(1, key);
        psInsertClob.setClob(2, insertClob);
        psInsertClob.execute();

        // Read back test data from database.
        psFetchClob.setInt(1, key);
        ResultSet rs = psFetchClob.executeQuery();
        assertTrue("No results retrieved", rs.next());
        Clob clobRetrieved = rs.getClob(1);

        // Verify test data.
        assertEquals(insertClob, clobRetrieved);
    }

    /**
     *
     * Test the setBlob() method
     *
     * @throws SQLException if a failure occurs during the call to setBlob
     *
     */
    public void testSetBlob()
            throws IOException, SQLException {
        // Life span of Blob objects are limited by the transaction.  Need
        // autocommit off so Blob objects survive execution of next statement.
        getConnection().setAutoCommit(false);
        
        //insert default values into the table
        InputStream is = new java.io.ByteArrayInputStream(BYTES);
        is.reset();
        
        //initially insert the data
        psInsertBlob.setInt(1, key);
        psInsertBlob.setBlob(2, is, BYTES.length);
        psInsertBlob.executeUpdate();
        
        //Now query to retrieve the Blob
        psFetchBlob.setInt(1, key);
        ResultSet rs = psFetchBlob.executeQuery();
        rs.next();
        Blob blobToBeInserted = rs.getBlob(1);
        rs.close();
        
        //Now use the setBlob method
        int secondKey = requestKey();
        psInsertBlob.setInt(1, secondKey);
        psInsertBlob.setBlob(2, blobToBeInserted);
        psInsertBlob.execute();
        
        psInsertBlob.close();
        
        //Now test to see that the Blob has been stored correctly
        psFetchBlob.setInt(1, secondKey);
        rs = psFetchBlob.executeQuery();
        rs.next();
        Blob blobRetrieved = rs.getBlob(1);
        
        assertEquals(blobToBeInserted, blobRetrieved);
    }
    
    /**
     * Insert <code>Blob</code> without specifying length and read it back
     * for verification.
     */
    public void testSetBlobLengthless()
            throws IOException, SQLException {
        // Life span of Blob objects are the transaction.  Need autocommit off
        // to have Blob objects survive execution of next statement.
        getConnection().setAutoCommit(false);
        // Create Blob to be inserted
        Blob insertBlob = getConnection().createBlob();
        OutputStream os = insertBlob.setBinaryStream(1);
        os.write(BYTES);
        int secondKey = requestKey();
        psInsertBlob.setInt(1, secondKey);
        psInsertBlob.setBlob(2, insertBlob);
        psInsertBlob.execute();
        os.close();
        psInsertBlob.close();

        // Read back test data from database.
        psFetchBlob.setInt(1, secondKey);
        ResultSet rs = psFetchBlob.executeQuery();
        assertTrue("No results retrieved", rs.next());
        Blob blobRetrieved = rs.getBlob(1);

        // Verify test data.
        assertEquals(insertBlob, blobRetrieved);
    }

    //-------------------------------------------------
    //Test the methods used to test poolable statements
    
    /**
     *
     * Tests the PreparedStatement interface method setPoolable
     *
     * @throws SQLException
     */
    
    public void testSetPoolable() throws SQLException {
        // Set the poolable statement hint to false
        ps.setPoolable(false);
        assertFalse("Expected a non-poolable statement", ps.isPoolable());
        // Set the poolable statement hint to true
        ps.setPoolable(true);
        assertTrue("Expected a non-poolable statement", ps.isPoolable());
    }

    /**
     *
     * Tests the PreparedStatement interface method setPoolable on a closed
     * PreparedStatement
     *
     * @throws SQLException
     */
    public void testSetPoolableOnClosed() throws SQLException {
        try {
            ps.close();
            // Set the poolable statement hint to false
            ps.setPoolable(false);
            fail("Expected an exception on closed statement");
         } catch(SQLException sqle) {
            // Check which SQLException state we've got and if it is
            // expected, do not print a stackTrace
            // Embedded uses XJ012, client uses XCL31.
            if (sqle.getSQLState().equals("XJ012") ||
                sqle.getSQLState().equals("XCL31")) {
                // All is good and is expected
            } else {
                fail("Unexpected SQLException " + sqle);
            }
        }
    }
    
    /**
     *
     * Tests the PreparedStatement interface method isPoolable
     *
     * @throws SQLException
     *
     */
    public void testIsPoolableDefault() throws SQLException {
        // By default a prepared statement is poolable
        assertTrue("Expected a poolable statement", ps.isPoolable());
    }

    /**
     * Tests that the {@code isPoolable}-hint works by exploiting the fact that
     * the client cannot prepare a statement referring to a deleted table
     * (unless the statement is already in the statement cache).
     *
     * @throws SQLException if something goes wrong...
     */
    public void cpTestIsPoolableHintFalse()
            throws SQLException {
        getConnection().setAutoCommit(false);
        // Create a table, insert a row, then create a statement selecting it.
        Statement stmt = createStatement();
        stmt.executeUpdate("create table testispoolablehint (id int)");
        stmt.executeUpdate("insert into testispoolablehint values 1");
        PreparedStatement ps = prepareStatement(
                "select * from testispoolablehint");
        ps.setPoolable(false);
        JDBC.assertSingleValueResultSet(ps.executeQuery(), "1");
        // Close statement, which should be discarded.
        ps.close();
        // Now delete the table.
        stmt.executeUpdate("drop table testispoolablehint");
        stmt.close();
        // Since there is no cached statement, we'll get exception here.
        try {
            ps = prepareStatement("select * from testispoolablehint");
            fail("Prepared statement not valid, referring non-existing table");
        } catch (SQLException sqle) {
            assertSQLState("42X05", sqle);
        }
    }

    /**
     * Tests that the {@code isPoolable}-hint works by exploiting the fact that
     * the client can prepare a statement referring to a deleted table if JDBC
     * statement caching is enabled and the statement is already in the cache.
     *
     * @throws SQLException if something goes wrong...
     */
    public void cpTestIsPoolableHintTrue()
            throws SQLException {
        getConnection().setAutoCommit(false);
        // Create a table, insert a row, then create a statement selecting it.
        Statement stmt = createStatement();
        stmt.executeUpdate("create table testispoolablehint (id int)");
        stmt.executeUpdate("insert into testispoolablehint values 1");
        PreparedStatement ps = prepareStatement(
                "select * from testispoolablehint");
        ps.setPoolable(true);
        JDBC.assertSingleValueResultSet(ps.executeQuery(), "1");
        // Put the statement into the cache.
        ps.close();
        // Now delete the table and fetch the cached prepared statement.
        stmt.executeUpdate("drop table testispoolablehint");
        stmt.close();
        ps = prepareStatement("select * from testispoolablehint");
        // If we get this far, there is a big change we have fetched an
        // invalid statement from the cache, but we won't get the exception
        // until we try to execute it.
        try {
            ps.executeQuery();
            fail("Prepared statement not valid, referring non-existing table");
        } catch (SQLException sqle) {
            assertSQLState("42X05", sqle);
        }
    }

    /**
     *
     * Tests the PreparedStatement interface method isPoolable on closed
     * PreparedStatement
     *
     * @throws SQLException
     *
     */
    public void testIsPoolableOnClosed() throws SQLException {
        try {
            ps.close();
            boolean p = ps.isPoolable();
            fail("Should throw exception on closed statement");
        } catch(SQLException sqle) {
            // Check which SQLException state we've got and if it is
            // expected, do not print a stackTrace
            // Embedded uses XJ012, client uses XCL31.
            if (sqle.getSQLState().equals("XJ012") ||
                sqle.getSQLState().equals("XCL31")) {
                // All is good and is expected
            } else {
                fail("Unexpected SQLException " + sqle);
            }
        }
    }
    
    /**
     *
     * Tests the PreparedStatement interface method setCharacterStream
     *
     * @throws SQLException
     *
     */
    public void testSetCharacterStream() throws Exception {
        String str = "Test data for the Clob object";
        StringReader is = new StringReader("Test data for the Clob object");
        
        is.reset();
        
        //initially insert the data
        psInsertClob.setInt(1, key);
        psInsertClob.setCharacterStream(2, is, str.length());
        psInsertClob.executeUpdate();
        
        //Now query to retrieve the Clob
        psFetchClob.setInt(1, key);
        ResultSet rs = psFetchClob.executeQuery();
        rs.next();
        Clob clobRetrieved = rs.getClob(1);
        
        String str_out = clobRetrieved.getSubString(1L,(int)clobRetrieved.length());
        
        assertEquals("Error in inserting data into the Clob object",str,str_out);
        psInsertClob.close();

        //Since auto-commit is true in this test
        //this will invalidate the clob object
        //Hence closing the ResultSet after
        //accessing the Clob object.
        //follows the same pattern as testSetBinaryStream().
        rs.close();
    }

    public void testSetCharacterStreamLengthless()
            throws IOException, SQLException {
        // Insert test data.
        String testString = "Test string for setCharacterStream\u1A00";
        Reader reader = new StringReader(testString);
        psInsertClob.setInt(1, key);
        psInsertClob.setCharacterStream(2, reader);
        psInsertClob.execute();
        reader.close();

        // Read back test data from database.
        psFetchClob.setInt(1, key);
        ResultSet rs = psFetchClob.executeQuery();
        assertTrue("No results retrieved", rs.next());
        Clob clobRetrieved = rs.getClob(1);

        // Verify test data.
        assertEquals("Mismatch test data in/out", testString,
                     clobRetrieved.getSubString(1, testString.length()));
    }

     /**
      *
      * Tests the PreparedStatement interface method setAsciiStream
      *
      * @throws SQLException
      *
      */
    
    public void testSetAsciiStream() throws Exception {
        //insert default values into the table
        
        byte [] bytes1 = new byte[10];
        
        InputStream is = new java.io.ByteArrayInputStream(BYTES);
        
        is.reset();
        
        //initially insert the data
        psInsertClob.setInt(1, key);
        psInsertClob.setAsciiStream(2, is, BYTES.length);
        psInsertClob.executeUpdate();
        
        //Now query to retrieve the Clob
        psFetchClob.setInt(1, key);
        ResultSet rs = psFetchClob.executeQuery();
        rs.next();
        Clob ClobRetrieved = rs.getClob(1);
        
        try {
            InputStream is_ret = ClobRetrieved.getAsciiStream();
            is_ret.read(bytes1);
        } catch(IOException ioe) {
            fail("IOException while reading the Clob from the database");
        }
        for(int i=0;i<BYTES.length;i++) {
            assertEquals("Error in inserting data into the Clob",BYTES[i],bytes1[i]);
        }
        psInsertClob.close();

        //Since auto-commit is true in this test
        //this will invalidate the clob object
        //Hence closing the ResultSet after
        //accessing the Clob object.
        //follows the same pattern as testSetBinaryStream().
        rs.close();
    }

    public void testSetAsciiStreamLengthless()
            throws IOException, SQLException {
        // Insert test data.
        InputStream is = new ByteArrayInputStream(BYTES);
        psInsertClob.setInt(1, key);
        psInsertClob.setAsciiStream(2, is);
        psInsertClob.execute();
        is.close();

        // Read back test data from database.
        psFetchClob.setInt(1, key);
        ResultSet rs = psFetchClob.executeQuery();
        assertTrue("No results retrieved", rs.next());
        Clob clobRetrieved = rs.getClob(1);

        // Verify read back data.
        byte[] dbBytes = new byte[10];
        InputStream isRetrieved = clobRetrieved.getAsciiStream();
        assertEquals("Unexpected number of bytes read", BYTES.length,
                isRetrieved.read(dbBytes));
        assertEquals("Stream should be exhausted", -1, isRetrieved.read());
        for (int i=0; i < BYTES.length; i++) {
            assertEquals("Byte mismatch in/out", BYTES[i], dbBytes[i]);
        }

        // Cleanup
        isRetrieved.close();
        psInsertClob.close();
    }

    /**
     *
     * Tests the PreparedStatement interface method setBinaryStream
     *
     * @throws SQLException
     *
     */
    
    public void testSetBinaryStream() throws Exception {
        //insert default values into the table
        
        byte [] bytes1 = new byte[10];
        
        InputStream is = new java.io.ByteArrayInputStream(BYTES);
        
        is.reset();
        
        //initially insert the data
        psInsertBlob.setInt(1, key);
        psInsertBlob.setBinaryStream(2, is, BYTES.length);
        psInsertBlob.executeUpdate();
        
        // Now query to retrieve the Blob
        psFetchBlob.setInt(1, key);
        ResultSet rs = psFetchBlob.executeQuery();
        rs.next();
        Blob blobRetrieved = rs.getBlob(1);
        
        try {
            InputStream is_ret = blobRetrieved.getBinaryStream();
            is_ret.read(bytes1);
        } catch(IOException ioe) {
            fail("IOException while reading the Clob from the database");
        }
        rs.close(); // Because of autocommit, this will invalidate blobRetrieved
        
        for(int i=0;i<BYTES.length;i++) {
            assertEquals("Error in inserting data into the Blob",BYTES[i],bytes1[i]);
        }
        psInsertBlob.close();
    }

    public void testSetBinaryStreamLengthless()
            throws IOException, SQLException {
        // Insert test data.
        InputStream is = new ByteArrayInputStream(BYTES);
        psInsertBlob.setInt(1, key);
        psInsertBlob.setBinaryStream(2, is);
        psInsertBlob.execute();
        is.close();

        // Read back test data from database.
        psFetchBlob.setInt(1, key);
        ResultSet rs = psFetchBlob.executeQuery();
        assertTrue("No results retrieved", rs.next());
        Blob blobRetrieved = rs.getBlob(1);

        // Verify read back data.
        byte[] dbBytes = new byte[10];
        InputStream isRetrieved = blobRetrieved.getBinaryStream();
        assertEquals("Unexpected number of bytes read", BYTES.length,
                isRetrieved.read(dbBytes));
        assertEquals("Stream should be exhausted", -1, isRetrieved.read());
        for (int i=0; i < BYTES.length; i++) {
            assertEquals("Byte mismatch in/out", BYTES[i], dbBytes[i]);
        }

        // Cleanup
        isRetrieved.close();
        psInsertBlob.close();
    }

    public void testSetBinaryStreamLengthLess1KOnBlob()
            throws IOException, SQLException {
        int length = 1*1024;
        setBinaryStreamOnBlob(key, length, -1, 0, true);
        psFetchBlob.setInt(1, key);
        ResultSet rs = psFetchBlob.executeQuery();
        assertTrue("Empty resultset", rs.next());
        assertEquals(new LoopingAlphabetStream(length),
                     rs.getBinaryStream(1));
        assertFalse("Resultset should have been exhausted", rs.next());
        rs.close();
    }

    public void testSetBinaryStreamLengthLess32KOnBlob()
            throws IOException, SQLException {
        int length = 32*1024;
        setBinaryStreamOnBlob(key, length, -1, 0, true);
        psFetchBlob.setInt(1, key);
        ResultSet rs = psFetchBlob.executeQuery();
        assertTrue("Empty resultset", rs.next());
        assertEquals(new LoopingAlphabetStream(length),
                     rs.getBinaryStream(1));
        assertFalse("Resultset should have been exhausted", rs.next());
        rs.close();
    }

    public void testSetBinaryStreamLengthLess65KOnBlob()
            throws IOException, SQLException {
        int length = 65*1024;
        setBinaryStreamOnBlob(key, length, -1, 0, true);
        psFetchBlob.setInt(1, key);
        ResultSet rs = psFetchBlob.executeQuery();
        assertTrue("Empty resultset", rs.next());
        LoopingAlphabetStream s1 = new LoopingAlphabetStream(length);
        assertEquals(new LoopingAlphabetStream(length),
                     rs.getBinaryStream(1));
        assertFalse("Resultset should have been exhausted", rs.next());
        rs.close();
    }

    public void testSetBinaryStreamLengthLessOnBlobTooLong() {
        int length = 1*1024*1024+512;
        try {
            setBinaryStreamOnBlob(key, length, -1, 0, true);
        } catch (SQLException sqle) {
            if (usingEmbedded() || 
                usingDerbyNetClient() ) {
                assertSQLState("XSDA4", sqle);
            } else {
                assertSQLState("22001", sqle);
            }
        }
    }

    public void testExceptionPathOnePage_bs()
            throws SQLException {
        int length = 11;
        try {
            setBinaryStreamOnBlob(key, length -1, length, 0, false);
            fail("Inserted a BLOB with fewer bytes than specified");
        } catch (SQLException sqle) {
            if (usingEmbedded()) {
                assertSQLState("XSDA4", sqle);
            } else {
                assertSQLState("XN017", sqle);
            }
        }
    }

    public void testExceptionPathMultiplePages_bs()
            throws SQLException {
        int length = 1*1024*1024;
        try {
            setBinaryStreamOnBlob(key, length -1, length, 0, false);
            fail("Inserted a BLOB with fewer bytes than specified");
        } catch (SQLException sqle) {
            if (usingEmbedded()) {
                assertSQLState("XSDA4", sqle);
            } else {
                assertSQLState("XN017", sqle);
            }
        }
    }

    public void testBlobExceptionDoesNotRollbackOtherStatements()
            throws IOException, SQLException {
        getConnection().setAutoCommit(false);
        int[] keys = {key, requestKey(), requestKey()};
        for (int i=0; i < keys.length; i++) {
            psInsertBlob.setInt(1, keys[i]);
            psInsertBlob.setNull(2, Types.BLOB);
            assertEquals(1, psInsertBlob.executeUpdate());
        }
        // Now insert a BLOB that fails because the stream is too short.
        int failedKey = requestKey();
        int length = 1*1024*1024;
        try {
            setBinaryStreamOnBlob(failedKey, length -1, length, 0, false);
            fail("Inserted a BLOB with less data than specified");
        } catch (SQLException sqle) {
            if (usingEmbedded()) {
                assertSQLState("XSDA4", sqle);
            } else {
                assertSQLState("XN017", sqle);
            }
        }
        // Now make sure the previous statements are there, and that the last
        // BLOB is not.
        ResultSet rs;
        for (int i=0; i < keys.length; i++) {
            psFetchBlob.setInt(1, keys[i]);
            rs = psFetchBlob.executeQuery();
            assertTrue(rs.next());
            assertFalse(rs.next());
            rs.close();
        }
        psFetchBlob.setInt(1, failedKey);
        rs = psFetchBlob.executeQuery();
        assertFalse(rs.next());
        rs.close();
        rollback();
        // Make sure all data is gone after the rollback.
        for (int i=0; i < keys.length; i++) {
            psFetchBlob.setInt(1, keys[i]);
            rs = psFetchBlob.executeQuery();
            assertFalse(rs.next());
            rs.close();
        }
        // Make sure the failed insert has not "reappeared" somehow...
        psFetchBlob.setInt(1, failedKey);
        rs = psFetchBlob.executeQuery();
        assertFalse(rs.next());

    }

    public void testSetAsciiStreamLengthLess1KOnClob()
            throws IOException, SQLException {
        int length = 1*1024;
        setAsciiStream(psInsertClob, key, length, -1, 0, true);
        psFetchClob.setInt(1, key);
        ResultSet rs = psFetchClob.executeQuery();
        assertTrue("Empty resultset", rs.next());
        assertEquals(new LoopingAlphabetStream(length),
                     rs.getAsciiStream(1));
        assertFalse("Resultset should have been exhausted", rs.next());
        rs.close();
    }

    public void testSetAsciiStreamLengthLess32KOnClob()
            throws IOException, SQLException {
        int length = 32*1024;
        setAsciiStream(psInsertClob, key, length, -1, 0, true);
        psFetchClob.setInt(1, key);
        ResultSet rs = psFetchClob.executeQuery();
        assertTrue("Empty resultset", rs.next());
        assertEquals(new LoopingAlphabetStream(length),
                     rs.getAsciiStream(1));
        assertFalse("Resultset should have been exhausted", rs.next());
        rs.close();
    }

    public void testSetAsciiStreamLengthLess65KOnClob()
            throws IOException, SQLException {
        int length = 65*1024;
        setAsciiStream(psInsertClob, key, length, -1, 0, true);
        psFetchClob.setInt(1, key);
        ResultSet rs = psFetchClob.executeQuery();
        assertTrue("Empty resultset", rs.next());
        assertEquals(new LoopingAlphabetStream(length),
                     rs.getAsciiStream(1));
        assertFalse("Resultset should have been exhausted", rs.next());
        rs.close();
    }

    public void testSetAsciiStreamLengthLessOnClobTooLong() {
        int length = 1*1024*1024+512;
        try {
            setAsciiStream(psInsertClob, key, length, -1, 0, true);
        } catch (SQLException sqle) {
            if (usingEmbedded() || 
                usingDerbyNetClient() ){
                assertSQLState("XSDA4", sqle);
                
            } else {
                assertSQLState("22001", sqle);
                
            }
        }
    }

    public void testSetAsciiStreamLengthLessOnClobTooLongTruncate()
            throws SQLException {
        int trailingBlanks = 512;
        int length = 1*1024*1024 + trailingBlanks;
        setAsciiStream(psInsertClob, key, length, -1, trailingBlanks, true);
    }

    public void testSetAsciiStreamLengthlessOnLongVarCharTooLong() {
        int length = 32700+512;
        try {
            setAsciiStream(psInsertLongVarchar, key, length, -1, 0, true);
            fail("Inserted a LONG VARCHAR that is too long");
        } catch (SQLException sqle) {
            if (usingEmbedded()){
                assertInternalDerbyIOExceptionState("XCL30", "22001", sqle);
                
            } else if ( usingDerbyNetClient() ) {
                assertSQLState("XCL30", sqle);
                
            } else {
                assertSQLState("22001", sqle);
                
            }
        }
    }

    public void testSetAsciiStreamLengthlessOnLongVarCharDontTruncate() {
        int trailingBlanks = 2000;
        int length = 32000 + trailingBlanks;
        try {
            setAsciiStream(psInsertLongVarchar, key, length, -1,
                    trailingBlanks, true);
            fail("Truncation is not allowed for LONG VARCHAR");
        } catch (SQLException sqle) {
            if (usingEmbedded()){
                assertInternalDerbyIOExceptionState("XCL30", "22001", sqle);
                
            } else if( usingDerbyNetClient() ) {
                assertSQLState("XCL30", sqle);
                
            } else {
                assertSQLState("22001", sqle);
                
            }
        }
    }

    /**
     * Test the large update methods added by JDBC 4.2.
     */
    public void testLargeUpdate_jdbc4_2() throws Exception
    {
        Connection  conn = getConnection();

        largeUpdate_jdbc4_2( conn );
    }

    public  static  void    largeUpdate_jdbc4_2( Connection conn )
        throws Exception
    {
        //
        // This test makes use of a debug entry point which is a NOP
        // in an insane production build.
        //
        if (!SanityManager.DEBUG)    { return; }

        println( "Running large update test for JDBC 4.2" );
        
        conn.prepareStatement
            (
             "create procedure setRowCountBase( newBase bigint )\n" +
             "language java parameter style java no sql\n" +
             "external name 'org.apache.derbyTesting.functionTests.tests.jdbc4.StatementTest.setRowCountBase'\n"
             ).execute();
        conn.prepareStatement
            (
             "create table bigintTable( col1 int generated always as identity, col2 bigint )"
             ).execute();

        Statement   stmt = conn.createStatement();
        PreparedStatementWrapper  psw = new PreparedStatementWrapper
            ( conn.prepareStatement( "insert into bigintTable( col2 ) values ( 1 ), ( 2 ), ( 3 ), ( 4 ), ( 5 )" ) );

        largeUpdateTest( stmt, psw, ((long) Integer.MAX_VALUE) + 1L );
        
        StatementTest.setRowCountBase( stmt, false, 0L );
    }
    private static  void    largeUpdateTest
        ( Statement stmt, PreparedStatementWrapper psw, long rowCountBase )
        throws Exception
    {
        StatementTest.setRowCountBase( stmt, false, rowCountBase );

        assertEquals( rowCountBase + 5L, psw.executeLargeUpdate() );
    }

    /************************************************************************
     *                 A U X I L I A R Y  M E T H O D S                     *
     ************************************************************************/

    /**
     * Insert data into a Blob column with setBinaryStream.
     *
     * @param id unique id for inserted row
     * @param actualLength the actual length of the stream
     * @param specifiedLength the specified length of the stream
     * @param trailingBlanks number of characters at the end that is blank
     * @param lengthLess whether to use the length less overloads or not
     */
    private void setBinaryStreamOnBlob(int id,
                                       int actualLength,
                                       int specifiedLength,
                                       int trailingBlanks,
                                       boolean lengthLess)
            throws SQLException {
        psInsertBlob.setInt(1, id);
        if (lengthLess) {
            psInsertBlob.setBinaryStream(2, new LoopingAlphabetStream(
                                                actualLength,
                                                trailingBlanks));
        } else {
            psInsertBlob.setBinaryStream(2,
                               new LoopingAlphabetStream(
                                        actualLength,
                                        trailingBlanks),
                               specifiedLength);
        }
        assertEquals("Insert with setBinaryStream failed",
                1, psInsertBlob.executeUpdate());
    }

    /**
     * Insert data into a column with setAsciiStream.
     * The prepared statement passed must have two positional parameters;
     * one int and one more. Depending on the last parameter, the execute
     * might succeed or it might fail. This is intended behavior, and should
     * be handled by the caller. For instance, calling this method on an
     * INT-column would fail, calling it on a CLOB-column would succeed.
     *
     * @param id unique id for inserted row
     * @param actualLength the actual length of the stream
     * @param specifiedLength the specified length of the stream
     * @param trailingBlanks number of characters at the end that is blank
     * @param lengthLess whether to use the length less overloads or not
     */
    private void setAsciiStream(PreparedStatement ps,
                                int id,
                                int actualLength,
                                int specifiedLength,
                                int trailingBlanks,
                                boolean lengthLess)
            throws SQLException {
        ps.setInt(1, id);
        if (lengthLess) {
            ps.setAsciiStream(2, 
                              new LoopingAlphabetStream(
                                                actualLength,
                                                trailingBlanks));
        } else {
            ps.setAsciiStream(2,
                              new LoopingAlphabetStream(
                                                actualLength,
                                                trailingBlanks),
                              specifiedLength);
        }
        assertEquals("Insert with setAsciiStream failed",
                1, ps.executeUpdate());
    }

    /**
     * Get next key to id inserted data with.
     */
    private static int requestKey() {
        return globalKey++;
    }

    /**
     * This methods is not to be used, but sometimes you have to!
     *
     * @param preSQLState the expected outer SQL state
     * @param expectedInternal the expected internal SQL state
     * @param sqle the outer SQLException
     */
    private void assertInternalDerbyIOExceptionState(
                                        String preSQLState,
                                        String expectedInternal,
                                        SQLException sqle) {
        assertSQLState("Outer/public SQL state incorrect",
                       preSQLState, sqle);
        // We need to dig a little with the current way exceptions are
        // being reported. We can use getCause because we always run with
        // Java SE 6 or later.
        Throwable cause = getLastSQLException(sqle).getCause();
        assertEquals("org.apache.derby.iapi.error.StandardException",
                     cause.getClass().getName());
        cause = cause.getCause();
        assertTrue("Exception not a DerbyIOException",
                   cause instanceof DerbyIOException);
        DerbyIOException dioe = (DerbyIOException)cause;
        assertEquals("Incorrect internal SQL state", expectedInternal,
                     dioe.getSQLState());
    }

    ////////////////////////////////////////////////////////////////////////
    //
    // NESTED JDBC 4.2 WRAPPER AROUND A PreparedStatement
    //
    ////////////////////////////////////////////////////////////////////////

    /**
     * <p>
     * This wrapper is used to expose JDBC 4.2 methods which can run on
     * VM rev levels lower than Java 8.
     * </p>
     */
    public  static  class   PreparedStatementWrapper    extends StatementTest.StatementWrapper
    {
        private PreparedStatement   _wrappedPreparedStatement;

        public  PreparedStatementWrapper( PreparedStatement wrappedPreparedStatement )
        {
            super( wrappedPreparedStatement );
        }

        PreparedStatement   getWrappedPreparedStatement() { return (PreparedStatement) getWrappedStatement(); }

        public  long executeLargeUpdate() throws SQLException
        {
            return ((Long) invoke
                (
                 "executeLargeUpdate",
                 new Class[] {},
                 new Object[] {}
                 )).longValue();
        }
    }
    
}