|
| 1 | +package net.snowflake.client.jdbc; |
| 2 | + |
| 3 | +import static net.snowflake.client.TestUtil.randomIntList; |
| 4 | +import static org.junit.jupiter.api.Assertions.assertEquals; |
| 5 | +import static org.junit.jupiter.api.Assertions.assertThrows; |
| 6 | + |
| 7 | +import java.sql.BatchUpdateException; |
| 8 | +import java.sql.Connection; |
| 9 | +import java.sql.SQLException; |
| 10 | +import java.sql.Statement; |
| 11 | +import java.util.Arrays; |
| 12 | +import java.util.List; |
| 13 | +import net.snowflake.client.TestUtil; |
| 14 | +import net.snowflake.client.category.TestTags; |
| 15 | +import org.junit.jupiter.api.Tag; |
| 16 | +import org.junit.jupiter.api.Test; |
| 17 | + |
| 18 | +@Tag(TestTags.STATEMENT) |
| 19 | +public class BatchExecutionIT extends BaseJDBCTest { |
| 20 | + @Test |
| 21 | + public void testClearingBatchAfterStatementExecution() throws SQLException { |
| 22 | + String tableName = TestUtil.randomTableName("SNOW-1853752"); |
| 23 | + int itemsInBatch = 3; |
| 24 | + try (Connection connection = getConnection(); |
| 25 | + Statement statement = connection.createStatement()) { |
| 26 | + statement.execute( |
| 27 | + String.format("CREATE OR REPLACE TABLE %s(id int, s varchar(2))", tableName)); |
| 28 | + List<ThrowingCallable<Integer, SQLException>> executeMethods = |
| 29 | + Arrays.asList( |
| 30 | + () -> statement.executeBatch().length, () -> statement.executeLargeBatch().length); |
| 31 | + for (ThrowingCallable<Integer, SQLException> executeMethod : executeMethods) { |
| 32 | + for (int i : randomIntList(itemsInBatch, 10)) { |
| 33 | + statement.addBatch( |
| 34 | + String.format("INSERT INTO %s(id, s) VALUES (%d, 's%d')", tableName, i, i)); |
| 35 | + } |
| 36 | + assertEquals(itemsInBatch, executeMethod.call()); |
| 37 | + // default behaviour - batch is not cleared |
| 38 | + assertEquals(itemsInBatch, executeMethod.call()); |
| 39 | + statement.clearBatch(); |
| 40 | + for (int i : randomIntList(itemsInBatch, 10)) { |
| 41 | + statement.addBatch( |
| 42 | + String.format( |
| 43 | + "INSERT INTO %s(id, s) VALUES (%d, 'longer string %d')", tableName, i, i)); |
| 44 | + } |
| 45 | + assertThrows(BatchUpdateException.class, executeMethod::call); |
| 46 | + // second call should also fail since batch should not be cleared |
| 47 | + assertThrows(BatchUpdateException.class, executeMethod::call); |
| 48 | + // clear batch for next execution in loop |
| 49 | + statement.clearBatch(); |
| 50 | + } |
| 51 | + } |
| 52 | + } |
| 53 | + |
| 54 | + /** |
| 55 | + * ThrowingCallable is defined here since is not available in OldDriverTests from main package. |
| 56 | + * Can be removed when OldDriver version is set to >=3.15.1 |
| 57 | + */ |
| 58 | + @FunctionalInterface |
| 59 | + interface ThrowingCallable<A, T extends Throwable> { |
| 60 | + A call() throws T; |
| 61 | + } |
| 62 | +} |
0 commit comments