Search in sources :

Example 56 with BatchUpdateException

use of java.sql.BatchUpdateException in project ambry by linkedin.

the class AccountDaoTest method testAddAccountWithException.

@Test
public void testAddAccountWithException() throws Exception {
    when(mockAccountInsertStatement.executeBatch()).thenThrow(new BatchUpdateException());
    TestUtils.assertException(BatchUpdateException.class, () -> accountDao.updateAccounts(Collections.singletonList(testAccountInfo), 50), null);
}
Also used : BatchUpdateException(java.sql.BatchUpdateException) Test(org.junit.Test)

Example 57 with BatchUpdateException

use of java.sql.BatchUpdateException in project hibernate-orm by hibernate.

the class PostgreSQL81DialectTestCase method testExtractConstraintName.

@Test
public void testExtractConstraintName() {
    PostgreSQL81Dialect dialect = new PostgreSQL81Dialect();
    SQLException psqlException = new java.sql.SQLException("ERROR: duplicate key value violates unique constraint \"uk_4bm1x2ultdmq63y3h5r3eg0ej\" Detail: Key (username, server_config)=(user, 1) already exists.", "23505");
    BatchUpdateException batchUpdateException = new BatchUpdateException("Concurrent Error", "23505", null);
    batchUpdateException.setNextException(psqlException);
    String constraintName = dialect.getViolatedConstraintNameExtracter().extractConstraintName(batchUpdateException);
    assertThat(constraintName, is("uk_4bm1x2ultdmq63y3h5r3eg0ej"));
}
Also used : SQLException(java.sql.SQLException) BatchUpdateException(java.sql.BatchUpdateException) Test(org.junit.Test)

Example 58 with BatchUpdateException

use of java.sql.BatchUpdateException in project robovm by robovm.

the class OldStatementTest method testExecuteBatch.

// always returns 1 for no. of updates
public void testExecuteBatch() throws SQLException {
    String[] queries = { "update zoo set name='Masha', family='cat' where id=2;", "drop table if exists hutch", "create table hutch (id integer not null, animal_id integer, address char(20), primary key (id));", "insert into hutch (id, animal_id, address) values (1, 2, 'Birds-house, 1');", "insert into hutch (id, animal_id, address) values (2, 1, 'Horse-house, 5');", "create view address as select address from hutch where animal_id=2", "drop view address;", "drop table hutch;" };
    String[] wrongQueries = { "update zoo set name='Masha', family='cat' where;", "drop table if exists hutch;", "create view address as select address from hutch where animal_id=2;", "drop view address;", "drop table hutch;" };
    int[] result = { 1, 1, 1, 1, 1, 1, 1, 1 };
    Statement st = null;
    //Exception test
    try {
        st = conn.createStatement();
        assertEquals(0, st.executeBatch().length);
        for (int i = 0; i < wrongQueries.length; i++) {
            st.addBatch(wrongQueries[i]);
        }
        st.executeBatch();
        fail("BatchupdateException expected");
    } catch (BatchUpdateException e) {
    //ok
    } finally {
        try {
            st.close();
        } catch (SQLException ee) {
        }
    }
    try {
        st = conn.createStatement();
        assertEquals(0, st.executeBatch().length);
        for (int i = 0; i < queries.length; i++) {
            st.addBatch(queries[i]);
        }
        int[] resArray = st.executeBatch();
        assertTrue(java.util.Arrays.equals(result, resArray));
    } finally {
        try {
            st.close();
        } catch (SQLException ee) {
        }
    }
    try {
        st = conn.createStatement();
        st.addBatch("select * from zoo");
        st.executeBatch();
        fail("Exception expected");
    } catch (BatchUpdateException bue) {
    // ok select returns a resultSet
    } finally {
        try {
            st.close();
        } catch (SQLException ee) {
        }
    }
    //Exception test
    try {
        st.close();
        st.executeBatch();
        fail("SQLException not thrown");
    } catch (SQLException e) {
    //ok
    }
}
Also used : SQLException(java.sql.SQLException) Statement(java.sql.Statement) PreparedStatement(java.sql.PreparedStatement) BatchUpdateException(java.sql.BatchUpdateException)

Example 59 with BatchUpdateException

use of java.sql.BatchUpdateException in project voltdb by VoltDB.

the class JDBCStatement method executeBatch.

/**
     * <!-- start generic documentation -->
     * Submits a batch of commands to the database for execution and
     * if all commands execute successfully, returns an array of update counts.
     * The <code>int</code> elements of the array that is returned are ordered
     * to correspond to the commands in the batch, which are ordered
     * according to the order in which they were added to the batch.
     * The elements in the array returned by the method <code>executeBatch</code>
     * may be one of the following:
     * <OL>
     * <LI>A number greater than or equal to zero -- indicates that the
     * command was processed successfully and is an update count giving the
     * number of rows in the database that were affected by the command's
     * execution
     * <LI>A value of <code>SUCCESS_NO_INFO</code> -- indicates that the command was
     * processed successfully but that the number of rows affected is
     * unknown
     * <P>
     * If one of the commands in a batch update fails to execute properly,
     * this method throws a <code>BatchUpdateException</code>, and a JDBC
     * driver may or may not continue to process the remaining commands in
     * the batch.  However, the driver's behavior must be consistent with a
     * particular DBMS, either always continuing to process commands or never
     * continuing to process commands.  If the driver continues processing
     * after a failure, the array returned by the method
     * <code>BatchUpdateException.getUpdateCounts</code>
     * will contain as many elements as there are commands in the batch, and
     * at least one of the elements will be the following:
     * <P>
     * <LI>A value of <code>EXECUTE_FAILED</code> -- indicates that the command failed
     * to execute successfully and occurs only if a driver continues to
     * process commands after a command fails
     * </OL>
     * <P>
     * (JDBC4 clarification:) <p>
     * <B>NOTE:</B>  Support of an ability to batch updates is optional.
     * <p>
     * The possible implementations and return values have been modified in
     * the Java 2 SDK, Standard Edition, version 1.3 to
     * accommodate the option of continuing to proccess commands in a batch
     * update after a <code>BatchUpdateException</code> obejct has been thrown.
     * <!-- end generic documentation -->
     *
     * <!-- start release-specific documentation -->
     * <div class="ReleaseSpecificDocumentation">
     * <h3>HSQLDB-Specific Information:</h3> <p>
     *
     * Starting with HSQLDB 1.7.2, this feature is supported. <p>
     *
     * HSQLDB stops execution of commands in a batch when one of the commands
     * results in an exception. The size of the returned array equals the
     * number of commands that were executed successfully.<p>
     *
     * When the product is built under the JAVA1 target, an exception
     * is never thrown and it is the responsibility of the client software to
     * check the size of the  returned update count array to determine if any
     * batch items failed.  To build and run under the JAVA2 target, JDK/JRE
     * 1.3 or higher must be used.
     * </div>
     * <!-- end release-specific documentation -->
     *
     * @return an array of update counts containing one element for each
     * command in the batch.  The elements of the array are ordered according
     * to the order in which commands were added to the batch.
     * @exception SQLException if a database access error occurs,
     * this method is called on a closed <code>Statement</code> or the
     * driver does not support batch statements. Throws {@link BatchUpdateException}
     * (a subclass of <code>SQLException</code>) if one of the commands sent to the
     * database fails to execute properly or attempts to return a result set.
     *
     *
     * @see #addBatch
     * @see java.sql.DatabaseMetaData#supportsBatchUpdates
     * @since JDK 1.3 (JDK 1.1.x developers: read the overview for
     * JDBCStatement)
     */
public synchronized int[] executeBatch() throws SQLException {
    checkClosed();
    connection.clearWarningsNoCheck();
    generatedResult = null;
    if (batchResultOut == null) {
        batchResultOut = Result.newBatchedExecuteRequest();
    }
    int batchCount = batchResultOut.getNavigator().getSize();
    try {
        resultIn = connection.sessionProxy.execute(batchResultOut);
        performPostExecute();
    } catch (HsqlException e) {
        batchResultOut.getNavigator().clear();
        throw Util.sqlException(e);
    }
    batchResultOut.getNavigator().clear();
    if (resultIn.isError()) {
        throw Util.sqlException(resultIn);
    }
    RowSetNavigator navigator = resultIn.getNavigator();
    int[] updateCounts = new int[navigator.getSize()];
    for (int i = 0; i < updateCounts.length; i++) {
        Object[] data = (Object[]) navigator.getNext();
        updateCounts[i] = ((Integer) data[0]).intValue();
    }
    if (updateCounts.length != batchCount) {
        if (errorResult == null) {
            throw new BatchUpdateException(updateCounts);
        } else {
            errorResult.getMainString();
            throw new BatchUpdateException(errorResult.getMainString(), errorResult.getSubString(), errorResult.getErrorCode(), updateCounts);
        }
    }
    return updateCounts;
}
Also used : RowSetNavigator(org.hsqldb_voltpatches.navigator.RowSetNavigator) HsqlException(org.hsqldb_voltpatches.HsqlException) BatchUpdateException(java.sql.BatchUpdateException)

Example 60 with BatchUpdateException

use of java.sql.BatchUpdateException in project jdk8u_jdk by JetBrains.

the class BatchUpdateExceptionTests method test4.

/**
     * Create BatchUpdateException with update counts
     */
@Test
public void test4() {
    BatchUpdateException ex = new BatchUpdateException(uc);
    assertTrue(ex.getMessage() == null && ex.getSQLState() == null && ex.getCause() == null && ex.getErrorCode() == 0 && Arrays.equals(ex.getUpdateCounts(), uc) && Arrays.equals(ex.getLargeUpdateCounts(), luc));
}
Also used : BatchUpdateException(java.sql.BatchUpdateException) SerializedBatchUpdateException(util.SerializedBatchUpdateException) Test(org.testng.annotations.Test) BaseTest(util.BaseTest)

Aggregations

BatchUpdateException (java.sql.BatchUpdateException)103 SQLException (java.sql.SQLException)39 PreparedStatement (java.sql.PreparedStatement)33 Statement (java.sql.Statement)22 ArrayList (java.util.ArrayList)19 Test (org.junit.Test)19 Connection (java.sql.Connection)17 Test (org.testng.annotations.Test)17 BaseTest (util.BaseTest)17 SerializedBatchUpdateException (util.SerializedBatchUpdateException)17 ResultSet (java.sql.ResultSet)13 List (java.util.List)12 CallableStatement (java.sql.CallableStatement)8 HashSet (java.util.HashSet)8 IgniteSQLException (org.apache.ignite.internal.processors.query.IgniteSQLException)7 HashMap (java.util.HashMap)6 Map (java.util.Map)5 CustomChangeException (liquibase.exception.CustomChangeException)5 DatabaseException (liquibase.exception.DatabaseException)5 SetupException (liquibase.exception.SetupException)5