File: Derby2017LayerBTest.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 (515 lines) | stat: -rw-r--r-- 18,596 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
/*

Derby - Class org.apache.derbyTesting.functionTests.tests.jdbcapi.Derby2017LayerBTest

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 junit.framework.Test;

import org.apache.derbyTesting.functionTests.util.streams.LoopingAlphabetReader;

import org.apache.derbyTesting.junit.BaseJDBCTestCase;
import org.apache.derbyTesting.junit.JDBC;
import org.apache.derbyTesting.junit.TestConfiguration;

import java.io.IOException;
import java.io.InputStream;
import java.io.Reader;
import java.io.StringReader;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import static org.apache.derbyTesting.functionTests.tests.jdbcapi.Derby2017LayerATest.*;

/**
 * Tests that inserts with streams that throws an {@code IOException} don't
 * insert data into the database when they shouldn't.
 * <p>
 * The test uses various combinations of auto-commit and rollback.
 */
public class Derby2017LayerBTest
        extends BaseJDBCTestCase {

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

    /**
     * Returns a suite running the test with both the client driver and the
     * embedded driver.
     *
     * @return A suite of tests.
     */
    public static Test suite() {
        return TestConfiguration.defaultSuite(Derby2017LayerBTest.class);
    }

    public void testStreamInsertCharBufferBoundary()
            throws IOException, SQLException {
        // NOTE: Many of these lengths are implementation dependent, and the
        //       code paths in LayerBStreamedEXTDTAReaderInputStream may change
        //       if the implementation of certain points of the DRDA protocol
        //       changes.
        int[] lengths = new int[] {
                1,
                16383,
                0,
                32756,
                36383,
                16384,
                192*1024, // Just a longer stream
            };

        rollback();
        Statement stmt = createStatement();
        try {
            stmt.executeUpdate("create table t2017_len (len int, c clob)");
        } catch (SQLException sqle) {
            assertSQLState("X0Y32", sqle);
            stmt.executeUpdate("delete from t2017_len");
        }
        commit();
        setAutoCommit(false);

        PreparedStatement ps =
                prepareStatement("insert into t2017_len values (?,?)");
        for (int length : lengths) {
            ps.setInt(1, length);
            ps.setCharacterStream(2, new LoopingAlphabetReader(length));
            ps.executeUpdate();
        }

        // Verify the data, basically making sure the status flag isn't
        // included as part of the user data.
        ResultSet rs = stmt.executeQuery("select len, c from t2017_len");
        int rows = 0;
        while (rs.next()) {
            rows++;
            int length = rs.getInt(1);
            assertEquals(new LoopingAlphabetReader(length),
                         rs.getCharacterStream(2));
        }
        assertEquals(lengths.length, rows);
    }

    /**
     * Attempt to insert data with failing streams of various lengths.
     * <p>
     * None of the inserts should be successful, as an {@code IOException} is
     * thrown by all of the streams.
     */
    public void testFailedStreamInsertCharBufferBoundariesImpl()
            throws IOException, SQLException {
        // NOTE: Many of these lengths are implementation dependent, and the
        //       code paths in LayerBStreamedEXTDTAReaderInputStream may change
        //       if the implementation of certain points of the DRDA protocol
        //       changes.
        int[] lengths = new int[] {
                1,
                16383,
                0,
                32756,
                36383,
                16384,
                192*1024, // Just a longer stream
            };

        rollback();
        Statement stmt = createStatement();
        try {
            stmt.executeUpdate("create table t2017_len (len int, c clob)");
        } catch (SQLException sqle) {
            assertSQLState("X0Y32", sqle);
            stmt.executeUpdate("delete from t2017_len");
        }
        commit();
        setAutoCommit(false);

        PreparedStatement ps =
                prepareStatement("insert into t2017_len values (?,?)");
        // Fail at the very beginning of the stream.
        for (int length : lengths) {
            ps.setInt(1, length);
            ps.setCharacterStream(2, new FailingReader(length, -1));
            try {
                ps.executeUpdate();
                fail("Should have failed (length=" + length + ")");
            } catch (SQLException sqle) {
                // TODO: Check when exception handling has been settled.
                //assertSQLState(usingEmbedded() ? "XSDA4" : "XJ001", sqle);
            }
        }

        // Fail around half-way into the stream.
        for (int length : lengths) {
            ps.setInt(1, length);
            ps.setCharacterStream(2,
                    new FailingReader(length, length / 2));
            try {
                ps.executeUpdate();
                fail("Should have failed (length=" + length + ")");
            } catch (SQLException sqle) {
                // TODO: Check when exception handling has been settled.
                //assertSQLState(usingEmbedded() ? "XSDA4" : "XJ001", sqle);
            }
        }

        // Fail at the very end of the stream.
        for (int length : lengths) {
            ps.setInt(1, length);
            ps.setCharacterStream(2,
                    new FailingReader(length, length -1));
            try {
                ps.executeUpdate();
                fail("Should have failed (length=" + length + ")");
            } catch (SQLException sqle) {
                // TODO: Check when exception handling has been settled.
                //assertSQLState(usingEmbedded() ? "XSDA4" : "XJ001", sqle);
            }
        }

        // Verify that there is no data in the table (all failed).
        ResultSet rs = stmt.executeQuery("select count(*) from t2017_len");
        rs.next();
        assertEquals(0, rs.getInt(1));
    }

    public void testFailedStreamInsertChar()
            throws IOException, SQLException {
        String[] INSERT = new String[] {
                "This is row 1",
                "This is row 2",
                "This is row 3",
                "This is row 4, a bit too long",
                "This is row 5, a bit too short",
                "This is row 6",
                "This is row 7",
            };
        String[][] MASTER = new String[][] {
                {"This is row 1"},
                {"This is row 2"},
                {"This is row 3"},
                //{"This is row 4, a bit too long"},
                //{"This is row 5, a bit too short"},
                {"This is row 6"},
                {"This is row 7"},
            };
        doInsertTest(INSERT, MASTER, false, false);
    }

    public void testFailedStreamInsertCharAutoCommit()
            throws IOException, SQLException {
        String[] INSERT = new String[] {
                "This is row 1",
                "This is row 2",
                "This is row 3",
                "This is row 4, a bit too long",
                "This is row 5, a bit too short",
                "This is row 6",
                "This is row 7",
            };
        String[][] MASTER = new String[][] {
                {"This is row 1"},
                {"This is row 2"},
                {"This is row 3"},
                //{"This is row 4, a bit too long"},
                //{"This is row 5, a bit too short"},
                {"This is row 6"},
                {"This is row 7"},
            };
        doInsertTest(INSERT, MASTER, true, false);
    }

    public void testFailedStreamInsertCharRollbackOnError()
            throws IOException, SQLException {
        String[] INSERT = new String[] {
                "This is row 1",
                "This is row 2",
                "This is row 3",
                "This is row 4, a bit too long",
                "This is row 5, a bit too short",
                "This is row 6",
                "This is row 7",
            };
        String[][] MASTER = new String[][] {
                //{"This is row 1"},
                //{"This is row 2"},
                //{"This is row 3"},
                //{"This is row 4, a bit too long"},
                //{"This is row 5, a bit too short"},
                {"This is row 6"},
                {"This is row 7"},
            };
        doInsertTest(INSERT, MASTER, false, true);
    }

    public void testFailedStreamInsertCharAutoCommitRollbackOnError()
            throws IOException, SQLException {
        String[] INSERT = new String[] {
                "This is row 1",
                "This is row 2",
                "This is row 3",
                "This is row 4, a bit too long",
                "This is row 5, a bit too short",
                "This is row 6",
                "This is row 7",
            };
        String[][] MASTER = new String[][] {
                {"This is row 1"},
                {"This is row 2"},
                {"This is row 3"},
                //{"This is row 4, a bit too long"},
                //{"This is row 5, a bit too short"},
                {"This is row 6"},
                {"This is row 7"},
            };
        doInsertTest(INSERT, MASTER, true, true);
    }

    public void testFailedStreamInsertBinary()
            throws IOException, SQLException {
        byte[][] INSERT = generateDefaultInsert();
        String[][] MASTER = generateMaster(INSERT, new int[] {3, 4});
        doInsertTest(INSERT, MASTER, false, false);
    }

    public void testFailedStreamInsertBinaryAutoCommit()
            throws IOException, SQLException {
        byte[][] INSERT = generateDefaultInsert();
        String[][] MASTER = generateMaster(INSERT, new int[] {3, 4});
        doInsertTest(INSERT, MASTER, true, false);
    }

    public void testFailedStreamInsertBinaryRollbackOnError()
            throws IOException, SQLException {
        byte[][] INSERT = generateDefaultInsert();
        String[][] MASTER = generateMaster(INSERT, new int[] {0, 1, 2, 3, 4});
        doInsertTest(INSERT, MASTER, false, true);
    }

    public void testFailedStreamInsertBinaryAutoCommitRollbackOnError()
            throws IOException, SQLException {
        byte[][] INSERT = generateDefaultInsert();
        String[][] MASTER = generateMaster(INSERT, new int[] {3, 4});
        doInsertTest(INSERT, MASTER, true, true);
    }

    /**
     * Performs the base test cycle; insert 3 valid rows, try to insert 2
     * invalid rows, insert 2 valid rows.
     * <p>
     * The outcome depends on whether auto-commit is on, and whether a rollback
     * is issued when an insert fails.
     *
     * @param INSERT the data to insert
     * @param MASTER the expected outcome
     * @param autoCommit the auto-commit state to use
     * @param rollbackOnError whether or not to issue a rollback if an insert
     *      fails
     *
     * @throws IOException if something goes wrong
     * @throws SQLException if something goes wrong
     */
    private void doInsertTest(String[] INSERT, String[][] MASTER,
                              boolean autoCommit, boolean rollbackOnError)
            throws IOException, SQLException {
        // A few sanity checks.
        assertEquals("Expects 7 rows", 7, INSERT.length);
        assertTrue(MASTER.length < INSERT.length);

        rollback();
        Statement stmt = createStatement();
        try {
            stmt.executeUpdate("create table t2017 (c clob)");
        } catch (SQLException sqle) {
            assertSQLState("X0Y32", sqle);
            stmt.executeUpdate("delete from t2017");
        }
        commit();

        setAutoCommit(autoCommit);
        PreparedStatement ps = prepareStatement("insert into t2017 values (?)");
        // Insert the 3 first rows.
        for (int i=0; i < 3; i++) {
            ps.setCharacterStream(1, new StringReader(INSERT[i]));
            assertEquals(1, ps.executeUpdate());
        }

        // Insert the 4th and 5th row with a stream that throws an exception.
        // Partial data read shouldn't be inserted into the database.

        Reader r4 = new FailingReader(10, 3);
        ps.setCharacterStream(1, r4);
        try {
            ps.executeUpdate();
            fail("Insert should have failed");
        } catch (SQLException sqle) {
            // TODO: Check when exception handling has been settled.
            // The states are different between client and embedded.
            //assertSQLState(usingEmbedded() ? "XSDA4" : "XJ001", sqle);
            if (rollbackOnError) {
                rollback();
            }
        }

        Reader r5 = new FailingReader(35002, 35001);
        ps.setCharacterStream(1, r5);
        try {
            ps.executeUpdate();
            fail("Insert should have failed");
        } catch (SQLException sqle) {
            // TODO: Check when exception handling has been settled.
            // The states are different between client and embedded.
            //assertSQLState(usingEmbedded() ? "XSDA4" : "XJ001", sqle);
            if (rollbackOnError) {
                rollback();
            }
        }

        // The errors above should have statement severity. Insert the last
        // two rows and commit.
        for (int i=5; i < INSERT.length; i++) {
            ps.setCharacterStream(1, new StringReader(INSERT[i]));
            assertEquals(1, ps.executeUpdate());
        }

        if (!autoCommit) {
            commit();
        }

        // Select data in the table, compare to MASTER
        ResultSet rs = stmt.executeQuery("select * from t2017");
        JDBC.assertUnorderedResultSet(rs, MASTER);
    }

    /**
     * Performs the base test cycle; insert 3 valid rows, try to insert 2
     * invalid rows, insert 2 valid rows.
     * <p>
     * The outcome depends on whether auto-commit is on, and whether a rollback
     * is issued when an insert fails.
     *
     * @param INSERT the data to insert
     * @param MASTER the expected outcome
     * @param autoCommit the auto-commit state to use
     * @param rollbackOnError whether or not to issue a rollback if an insert
     *      fails
     *
     * @throws IOException if something goes wrong
     * @throws SQLException if something goes wrong
     */
    private void doInsertTest(byte[][] INSERT, String[][] MASTER,
                              boolean autoCommit, boolean rollbackOnError)
            throws IOException, SQLException {
        // A few sanity checks.
        assertEquals("Expects 7 rows", 7, INSERT.length);
        assertTrue(MASTER.length < INSERT.length);

        rollback();
        Statement stmt = createStatement();
        try {
            stmt.executeUpdate("create table t2017_binary (b blob)");
        } catch (SQLException sqle) {
            assertSQLState("X0Y32", sqle);
            stmt.executeUpdate("delete from t2017_binary");
        }
        commit();

        setAutoCommit(autoCommit);
        PreparedStatement ps = prepareStatement(
                "insert into t2017_binary values (?)");
        // Insert the 3 first rows.
        for (int i=0; i < 3; i++) {
            ps.setBinaryStream(1, new ByteArrayInputStream(INSERT[i]));
            assertEquals(1, ps.executeUpdate());
        }

        // Insert the 4th and 5th row with a stream that throws an exception.
        // Partial data read shouldn't be inserted into the database.

        InputStream r4 = new FailingInputStream(new FailingReader(10, 3));
        ps.setBinaryStream(1, r4);
        try {
            ps.executeUpdate();
            fail("Insert should have failed");
        } catch (SQLException sqle) {
            // TODO: Check when exception handling has been settled.
            // The states are different between client and embedded.
            //assertSQLState(usingEmbedded() ? "XSDA4" : "XJ001", sqle);
            if (rollbackOnError) {
                rollback();
            }
        }

        InputStream r5 = new FailingInputStream(
                                    new FailingReader(35002, 35001));
        ps.setBinaryStream(1, r5);
        try {
            ps.executeUpdate();
            fail("Insert should have failed");
        } catch (SQLException sqle) {
            // TODO: Check when exception handling has been settled.
            // The states are different between client and embedded.
            //assertSQLState(usingEmbedded() ? "XSDA4" : "XJ001", sqle);
            if (rollbackOnError) {
                rollback();
            }
        }

        // The errors above should have statement severity. Insert the last
        // two rows and commit.
        for (int i=5; i < INSERT.length; i++) {
            ps.setBinaryStream(1, new ByteArrayInputStream(INSERT[i]));
            assertEquals(1, ps.executeUpdate());
        }

        if (!autoCommit) {
            commit();
        }

        // Select data in the table, compare to MASTER
        ResultSet rs = stmt.executeQuery("select * from t2017_binary");
        JDBC.assertUnorderedResultSet(rs, MASTER);
    }

    /**
     * Simple and <b>non-conforming</b> input stream that will fail after a
     * specified number of bytes read.
     */
    private static class FailingInputStream
            extends InputStream {

        private final FailingReader in;

        public FailingInputStream(FailingReader in) {
            this.in = in;
        }

        public int read()
                throws IOException {
            int c = in.read();
            return (byte)c;
        }
    }
}