throws IOException, SQLException {
getConnection().setAutoCommit(false);
final int size = 100000;
PreparedStatement ps = prepareStatement(
"INSERT INTO testBlob (a, b) VALUES (?, ?)");
ps.setBinaryStream(1, new LoopingAlphabetStream(size), size);
ps.setInt(2, size);
ps.executeUpdate();
ps.close();
ps = prepareStatement("select a from testBlob where b = ?");
ps.setInt(1, size);
ResultSet rs = ps.executeQuery();
assertTrue("No data found", rs.next());
Blob blob = rs.getBlob(1);
// Try with a one-byte pattern.
byte[] pattern = new byte[] {(byte)'k'}; // k number 11 in the alphabet
assertEquals(11, blob.position(pattern, 1));
// Try with a non-existing pattern.
pattern = new byte[] {(byte)'p', (byte)'o'};
assertEquals(-1, blob.position(pattern, size / 3));
// Loop through all matches
pattern = new byte[] {(byte)'d', (byte)'e'};
long foundAtPos = 1;
int index = 0;
int stepSize = ByteAlphabet.modernLatinLowercase().byteCount();
while ((foundAtPos = blob.position(pattern, foundAtPos +1)) != -1) {
assertEquals((stepSize * index++) + 4, foundAtPos);
byte[] fetchedPattern = blob.getBytes(foundAtPos, pattern.length);
assertTrue(Arrays.equals(pattern, fetchedPattern));
}
// Try a longer pattern.
int pSize = 65*1024; // 65 KB
pattern = new byte[pSize];
assertEquals(pSize, new LoopingAlphabetStream(pSize).read(pattern));
assertEquals(1, blob.position(pattern, 1));
assertEquals(stepSize * 100 +1,
blob.position(pattern, stepSize * 99 + 7));
// Try again after getting the length.
assertEquals(size, blob.length());