Search in sources :

Example 26 with LoopingAlphabetStream

use of org.apache.derbyTesting.functionTests.util.streams.LoopingAlphabetStream in project derby by apache.

the class TriggerTests method basicSetup.

/**
 * Create the basic tables and data expected by almost all the tests. If a
 * particular test needs anything else, that test will take care of it.
 * @throws SQLException
 */
public void basicSetup() throws SQLException {
    dropTable("TABLE1");
    dropTable("TABLE2");
    dropTable("TABLE3");
    Statement s = createStatement();
    try {
        s.execute("drop trigger trigger1");
    } catch (SQLException sqle) {
    }
    try {
        s.execute("drop trigger trigger2");
    } catch (SQLException sqle) {
    }
    // table1 is the main table on which all the testing is done and it
    // uses table2 at times to do DMLs as part of it's trigger action.
    s.execute("create table table1 (id int, status smallint, bl blob(2G))");
    s.execute("create index i1 on table1(id)");
    // table2 is mostly used as part of the trigger action for table1
    s.execute("create table table2 (id int, updates int default 0)");
    s.execute("create index i2 on table2(id)");
    // table3 does not have lob. It is mostly used to show how things work
    // fine when they may not for table1 since table1 has LOB column.
    s.execute("create table table3 (id int, status smallint, score int)");
    s.execute("create index i3 on table3(id)");
    // load data in table1
    PreparedStatement ps = prepareStatement("insert into table1 values (?, 0, ?)");
    ps.setInt(1, 1);
    ps.setBinaryStream(2, new LoopingAlphabetStream(lobsize), lobsize);
    ps.executeUpdate();
    // load data in table2
    ps = prepareStatement("insert into table2 (id) values (?)");
    ps.setInt(1, 1);
    ps.executeUpdate();
    // load data in table3
    ps = prepareStatement("insert into table3 values (?, 0, ?)");
    ps.setInt(1, 1);
    ps.setInt(2, 2);
    ps.executeUpdate();
    commit();
}
Also used : LoopingAlphabetStream(org.apache.derbyTesting.functionTests.util.streams.LoopingAlphabetStream)

Example 27 with LoopingAlphabetStream

use of org.apache.derbyTesting.functionTests.util.streams.LoopingAlphabetStream in project derby by apache.

the class BlobMemTest method testBlobLength.

/**
 * Insert a blob and test length.
 *
 * @param lengthless  if true use the lengthless setBinaryStream api
 *
 * @throws SQLException
 * @throws IOException
 * @throws InvocationTargetException
 * @throws IllegalAccessException
 * @throws IllegalArgumentException
 */
private void testBlobLength(boolean lengthless, int extraLen) throws SQLException, IOException, IllegalArgumentException, IllegalAccessException, InvocationTargetException {
    setAutoCommit(false);
    Statement s = createStatement();
    s.executeUpdate("CREATE TABLE BLOBTAB (K INT CONSTRAINT PK PRIMARY KEY, B BLOB(" + LONG_BLOB_LENGTH + "))");
    PreparedStatement ps = prepareStatement("INSERT INTO BLOBTAB VALUES(?,?)");
    // We allocate 16MB for the test so use something bigger than that.
    ps.setInt(1, 1);
    int blobLen = LONG_BLOB_LENGTH + extraLen;
    LoopingAlphabetStream stream = new LoopingAlphabetStream(blobLen);
    if (lengthless) {
        Method m = null;
        try {
            Class<?> c = ps.getClass();
            m = c.getMethod("setBinaryStream", new Class[] { Integer.TYPE, InputStream.class });
        } catch (NoSuchMethodException e) {
            // ignore method not found as method may not be present for
            // jdk's lower than 1.6.
            println("Skipping lengthless insert because method is not available");
            return;
        }
        m.invoke(ps, new Object[] { 2, stream });
    } else
        ps.setBinaryStream(2, stream, blobLen);
    if (extraLen == 0) {
        ps.executeUpdate();
    } else {
        try {
            ps.executeUpdate();
            fail("Expected truncation error for blob too large");
        } catch (SQLException sqlE) {
            assertSQLState("Wrong SQL State for truncation", "22001", sqlE);
        }
        // we've forced that error, we're done testing, so return.
        return;
    }
    // insert a zero length blob.
    ps.setInt(1, 2);
    ps.setBytes(2, new byte[] {});
    ps.executeUpdate();
    // insert a null blob.
    ps.setInt(1, 3);
    ps.setBytes(2, null);
    ps.executeUpdate();
    // insert a short blob
    ps.setInt(1, 4);
    ps.setBytes(2, SHORT_BLOB_BYTES);
    ps.executeUpdate();
    // Currently need to use optimizer override to force use of the index.
    // Derby should use sort avoidance and do it automatically, but there
    // appears to be a bug.
    ResultSet rs = s.executeQuery("SELECT K, LENGTH(B), B FROM BLOBTAB" + "-- DERBY-PROPERTIES constraint=pk\n ORDER BY K");
    rs.next();
    assertEquals(LONG_BLOB_LENGTH_STRING, rs.getString(2));
    // make sure we can still access the blob after getting length.
    // It should be ok because we reset the stream
    InputStream rsstream = rs.getBinaryStream(3);
    int len = 0;
    byte[] buf = new byte[32672];
    for (; ; ) {
        int size = rsstream.read(buf);
        if (size == -1)
            break;
        len += size;
        int expectedValue = ((len - 1) % 26) + 'a';
        if (size != 0)
            assertEquals(expectedValue, buf[size - 1]);
    }
    assertEquals(LONG_BLOB_LENGTH, len);
    // empty blob
    rs.next();
    assertEquals("0", rs.getString(2));
    byte[] bytes = rs.getBytes(3);
    assertEquals(0, bytes.length);
    // null blob
    rs.next();
    assertEquals(null, rs.getString(2));
    bytes = rs.getBytes(3);
    assertEquals(null, bytes);
    // short blob
    rs.next();
    assertEquals("3", rs.getString(2));
    bytes = rs.getBytes(3);
    assertTrue(Arrays.equals(SHORT_BLOB_BYTES, bytes));
    rs.close();
    // Select just length without selecting the blob.
    rs = s.executeQuery("SELECT K, LENGTH(B)  FROM BLOBTAB " + "ORDER BY K");
    JDBC.assertFullResultSet(rs, new String[][] { { "1", LONG_BLOB_LENGTH_STRING }, { "2", "0" }, { "3", null }, { "4", "3" } });
}
Also used : SQLException(java.sql.SQLException) PreparedStatement(java.sql.PreparedStatement) Statement(java.sql.Statement) InputStream(java.io.InputStream) ResultSet(java.sql.ResultSet) PreparedStatement(java.sql.PreparedStatement) LoopingAlphabetStream(org.apache.derbyTesting.functionTests.util.streams.LoopingAlphabetStream) Method(java.lang.reflect.Method)

Example 28 with LoopingAlphabetStream

use of org.apache.derbyTesting.functionTests.util.streams.LoopingAlphabetStream in project derby by apache.

the class BlobMemTest method testDerby4477_3645_3646_Repro_lowmem.

/**
 * Tests that a blob can be safely occur multiple times in a SQL select and
 * test that large objects streams are not being materialized when cloned.
 * <p/>
 * See DERBY-4477.
 * @see org.apache.derbyTesting.functionTests.tests.jdbcapi.BLOBTest#testDerby4477_3645_3646_Repro
 * @see ClobMemTest#testDerby4477_3645_3646_Repro_lowmem_clob
 */
public void testDerby4477_3645_3646_Repro_lowmem() throws SQLException, IOException {
    setAutoCommit(false);
    Statement s = createStatement();
    int blobsize = LONG_BLOB_LENGTH;
    s.executeUpdate("CREATE TABLE T_MAIN(" + "ID INT  GENERATED ALWAYS AS IDENTITY PRIMARY KEY, " + "V BLOB(" + blobsize + ") )");
    PreparedStatement ps = prepareStatement("INSERT INTO T_MAIN(V) VALUES (?)");
    int blobLen = blobsize;
    LoopingAlphabetStream stream = new LoopingAlphabetStream(blobLen);
    ps.setBinaryStream(1, stream, blobLen);
    ps.executeUpdate();
    ps.close();
    s.executeUpdate("CREATE TABLE T_COPY ( V1 BLOB(" + blobsize + "), V2 BLOB(" + blobsize + "))");
    // This failed in the repro for DERBY-3645 solved as part of
    // DERBY-4477:
    s.executeUpdate("INSERT INTO T_COPY SELECT  V, V FROM T_MAIN");
    // Check that the two results are identical:
    ResultSet rs = s.executeQuery("SELECT * FROM T_COPY");
    rs.next();
    InputStream is = rs.getBinaryStream(1);
    stream.reset();
    assertEquals(stream, is);
    is = rs.getBinaryStream(2);
    stream.reset();
    assertEquals(stream, is);
    rs.close();
    // This failed in the repro for DERBY-3646 solved as part of
    // DERBY-4477 (repro slightly rewoked here):
    rs = s.executeQuery("SELECT 'I', V, ID, V from T_MAIN");
    rs.next();
    is = rs.getBinaryStream(2);
    stream.reset();
    assertEquals(stream, is);
    is = rs.getBinaryStream(4);
    stream.reset();
    assertEquals(stream, is);
    // clean up
    stream.close();
    is.close();
    s.close();
    rs.close();
    rollback();
}
Also used : PreparedStatement(java.sql.PreparedStatement) Statement(java.sql.Statement) InputStream(java.io.InputStream) ResultSet(java.sql.ResultSet) PreparedStatement(java.sql.PreparedStatement) LoopingAlphabetStream(org.apache.derbyTesting.functionTests.util.streams.LoopingAlphabetStream)

Example 29 with LoopingAlphabetStream

use of org.apache.derbyTesting.functionTests.util.streams.LoopingAlphabetStream in project derby by apache.

the class Datatypes method add_one_row.

public static synchronized void add_one_row(Connection conn, int thread_id) throws Exception {
    try {
        // initialize();
        PreparedStatement ps = conn.prepareStatement(" insert into Datatypes (id,t_char,t_blob," + "t_clob," + " t_date, t_decimal, t_decimal_nn, t_double, " + " t_float, t_int, t_longint, t_numeric_large," + " t_real, t_smallint, t_time, t_timestamp," + " t_varchar) values (" + " ?,?, ?,?, ?, ?,?, ?, ?, ?,?, ?, ?, ?, ?, ?,?)", /* autoincrement feature added, so we need to specify the
					 * column name for prepared statement, otherwise auto increment
					 * column will think it is trying to update/insert a null value
					 * to the column.
					 */
        Statement.RETURN_GENERATED_KEYS);
        InputStream streamIn = null;
        Reader streamReader = null;
        int ind = Rn.nextInt();
        double x;
        Date dt = new Date(1);
        Time tt = new Time(1);
        Timestamp ts = new Timestamp(1);
        String cs = "asdf qwerqwer 12341234 ZXCVZXCVZXCV !@#$!@#$ asdfasdf 1 q a z asdf ASDF qwerasdfzxcvasdfqwer1234asd#";
        ps.setInt(1, ind);
        // scramble the string
        int i1 = Math.abs(ind % 100);
        String cs2 = cs.substring(i1, 99) + cs.substring(0, i1);
        int i2 = i1 < 89 ? i1 + 10 : i1;
        ps.setString(2, cs2.substring(0, i2));
        // "t_blob"
        // to create a stream of random length between 0 and 100K
        int blobLength = Rn.nextInt(102400 - 0 + 1) + 0;
        streamIn = new LoopingAlphabetStream(blobLength);
        ps.setBinaryStream(3, streamIn, blobLength);
        // "t_clob
        // to create a stream of random length between 0 and 100K
        int clobLength = Rn.nextInt(102400 - 0 + 1) + 0;
        streamReader = new LoopingAlphabetReader(clobLength, CharAlphabet.modernLatinLowercase());
        ps.setCharacterStream(4, streamReader, clobLength);
        // "t_ndate"
        dt.setTime(Math.abs(Rn.nextLong() / 150000));
        ps.setDate(5, dt);
        // "t_decimal"
        x = Math.abs(Rn.nextInt() % 18);
        if (x > 5)
            x = 5;
        ps.setDouble(6, Math.abs(Rn.nextDouble() * Math.pow(10, x)));
        // "t_decimal_nn"
        ps.setDouble(7, Rn.nextDouble());
        // "t_double"
        ps.setDouble(8, Rn.nextDouble() * Math.pow(10, Math.abs(Rn.nextInt() % 300)));
        // "t_float"
        ps.setFloat(9, Rn.nextFloat() * (float) Math.pow(10, Math.abs(Rn.nextInt() % 30)));
        // "t_int"
        ps.setInt(10, Rn.nextInt());
        // "t_longint"
        ps.setLong(11, Rn.nextLong());
        // "t_numeric_large"
        x = Math.abs(Rn.nextInt() % 30);
        if (x > 30)
            x = 31;
        ps.setDouble(12, Math.abs(Rn.nextDouble() * Math.pow(10, x)));
        // "t_real"
        ps.setFloat(13, Rn.nextFloat() * (float) Math.pow(10, Math.abs(Rn.nextInt() % 7)));
        // "t_smallint"
        ps.setInt(14, Rn.nextInt() % (256 * 128));
        // "t_time"
        tt.setTime(Math.abs(Rn.nextInt()));
        ps.setTime(15, tt);
        // "t_timestamp"
        ts.setTime(Math.abs(Rn.nextLong() / 50000));
        ps.setTimestamp(16, ts);
        // "t_varchar"
        ps.setString(17, cs.substring(Math.abs(Rn.nextInt() % 100)));
        int rows = ps.executeUpdate();
        if (rows == 1) {
            ResultSet rs = ps.getGeneratedKeys();
            while (rs.next()) {
                ResultSetMetaData rsmd = rs.getMetaData();
                int numCols = rsmd.getColumnCount();
            }
        } else
            System.out.println("t" + thread_id + " insert failed");
        streamReader.close();
        streamIn.close();
    } catch (SQLException se) {
        if (se.getNextException() == null)
            throw se;
        String m = se.getNextException().getSQLState();
        System.out.println(se.getNextException().getMessage() + " SQLSTATE: " + m);
    }
}
Also used : SQLException(java.sql.SQLException) InputStream(java.io.InputStream) LoopingAlphabetReader(org.apache.derbyTesting.functionTests.util.streams.LoopingAlphabetReader) Reader(java.io.Reader) PreparedStatement(java.sql.PreparedStatement) Time(java.sql.Time) Timestamp(java.sql.Timestamp) Date(java.sql.Date) LoopingAlphabetReader(org.apache.derbyTesting.functionTests.util.streams.LoopingAlphabetReader) ResultSetMetaData(java.sql.ResultSetMetaData) ResultSet(java.sql.ResultSet) LoopingAlphabetStream(org.apache.derbyTesting.functionTests.util.streams.LoopingAlphabetStream)

Example 30 with LoopingAlphabetStream

use of org.apache.derbyTesting.functionTests.util.streams.LoopingAlphabetStream in project derby by apache.

the class BlockedByteArrayTest method createBlockedByteArray.

/**
 * Creates a blocked byte array and fills it with data.
 *
 * @param length requested length
 * @return A filled blocked byte array.
 * @throws IOException if reading from the source fails
 */
private BlockedByteArray createBlockedByteArray(long length) throws IOException {
    BlockedByteArray data = new BlockedByteArray();
    InputStream src = new LoopingAlphabetStream(length);
    byte[] buf = new byte[4 * 1024];
    long pos = 0;
    while (pos < length) {
        int readFromSrc = src.read(buf);
        pos += data.writeBytes(pos, buf, 0, readFromSrc);
    }
    return data;
}
Also used : BlockedByteArray(org.apache.derby.impl.io.vfmem.BlockedByteArray) InputStream(java.io.InputStream) LoopingAlphabetStream(org.apache.derbyTesting.functionTests.util.streams.LoopingAlphabetStream)

Aggregations

LoopingAlphabetStream (org.apache.derbyTesting.functionTests.util.streams.LoopingAlphabetStream)61 PreparedStatement (java.sql.PreparedStatement)33 InputStream (java.io.InputStream)31 ResultSet (java.sql.ResultSet)31 Statement (java.sql.Statement)20 Blob (java.sql.Blob)10 SQLException (java.sql.SQLException)9 LoopingAlphabetReader (org.apache.derbyTesting.functionTests.util.streams.LoopingAlphabetReader)9 PositionedStoreStream (org.apache.derby.impl.jdbc.PositionedStoreStream)8 ByteArrayInputStream (java.io.ByteArrayInputStream)7 Connection (java.sql.Connection)7 OutputStream (java.io.OutputStream)5 Reader (java.io.Reader)5 Clob (java.sql.Clob)3 Timestamp (java.sql.Timestamp)3 DataInputStream (java.io.DataInputStream)2 EOFException (java.io.EOFException)2 CallableStatement (java.sql.CallableStatement)2 Date (java.sql.Date)2 Time (java.sql.Time)2