Search in sources :

Example 41 with BatchUpdateException

use of java.sql.BatchUpdateException in project derby by apache.

the class BatchUpdateTest method testUnderlyingExceptionIsVisible.

/**
 * Test that the underlying exception is included in the output when we
 * call printStackTrace() on a BatchUpdateException. Earlier, with the
 * client driver, the underlying cause of a BatchUpdateException could not
 * be seen without calling getNextException().
 */
public void testUnderlyingExceptionIsVisible() throws SQLException {
    setAutoCommit(false);
    Statement s = createStatement();
    s.addBatch("create table t(x int unique not null)");
    for (int i = 0; i < 3; i++) {
        s.addBatch("insert into t values 1");
    }
    BatchUpdateException bue = null;
    try {
        s.executeBatch();
    } catch (BatchUpdateException e) {
        bue = e;
    }
    assertNotNull("Did not get duplicate key exception", bue);
    StringWriter w = new StringWriter();
    bue.printStackTrace(new PrintWriter(w, true));
    String stackTrace = w.toString();
    if (stackTrace.indexOf("duplicate key") == -1) {
        fail("Could not see 'duplicate key' in printStackTrace()", bue);
    }
}
Also used : StringWriter(java.io.StringWriter) PreparedStatement(java.sql.PreparedStatement) Statement(java.sql.Statement) CallableStatement(java.sql.CallableStatement) BatchUpdateException(java.sql.BatchUpdateException) PrintWriter(java.io.PrintWriter)

Example 42 with BatchUpdateException

use of java.sql.BatchUpdateException in project derby by apache.

the class CallableTest method xtestBatchUpdate.

/**
 * Batches up calls to a SQL procedure that updates a value in a table.
 * Uses DriverManager and Batch calls, so requires JDBC 2 support.
 * @throws SQLException
 */
public void xtestBatchUpdate() throws SQLException {
    // Setup table data
    Statement stmt = createStatement();
    stmt.executeUpdate("INSERT INTO BATCH_TABLE VALUES(1, 'STRING_1',10)");
    stmt.executeUpdate("INSERT INTO BATCH_TABLE VALUES(2, 'STRING_2',0)");
    stmt.executeUpdate("INSERT INTO BATCH_TABLE VALUES(3, 'STRING_3',0)");
    stmt.executeUpdate("INSERT INTO BATCH_TABLE VALUES(4, 'STRING_4a',0)");
    stmt.executeUpdate("INSERT INTO BATCH_TABLE VALUES(4, 'STRING_4b',0)");
    // Setup batch to modify value to 10 * the id (makes verification easy).
    CallableStatement cstmt = prepareCall("CALL BATCH_UPDATE_PROC(?,?)");
    // Id 2's value will be updated to 20.
    cstmt.setInt(1, 2);
    cstmt.setInt(2, 20);
    cstmt.addBatch();
    // Id 3's value will be updated to 30.
    cstmt.setInt(1, 3);
    cstmt.setInt(2, 30);
    cstmt.addBatch();
    // Two rows will be updated to 40 for id 4.
    cstmt.setInt(1, 4);
    cstmt.setInt(2, 40);
    cstmt.addBatch();
    // No rows updated (no id 5).
    cstmt.setInt(1, 5);
    cstmt.setInt(2, 50);
    cstmt.addBatch();
    int[] updateCount = null;
    try {
        updateCount = cstmt.executeBatch();
        assertEquals("updateCount length", 4, updateCount.length);
        for (int i = 0; i < updateCount.length; i++) {
            if (usingEmbedded()) {
                assertEquals("Batch updateCount", 0, updateCount[0]);
            } else if (usingDerbyNetClient()) {
                assertEquals("Batch updateCount", -1, updateCount[0]);
            }
        }
    } catch (BatchUpdateException b) {
        assertSQLState("Unexpected SQL State", b.getSQLState(), b);
    }
    // Retrieve the updated values and verify they are correct.
    ResultSet rs = stmt.executeQuery("SELECT id, tag, idval FROM BATCH_TABLE order by id, tag");
    assertNotNull("SELECT from BATCH_TABLE", rs);
    while (rs.next()) {
        assertEquals(rs.getString(2), rs.getInt(1) * 10, rs.getInt(3));
    }
}
Also used : PreparedStatement(java.sql.PreparedStatement) Statement(java.sql.Statement) CallableStatement(java.sql.CallableStatement) CallableStatement(java.sql.CallableStatement) ResultSet(java.sql.ResultSet) BatchUpdateException(java.sql.BatchUpdateException)

Example 43 with BatchUpdateException

use of java.sql.BatchUpdateException in project derby by apache.

the class CallableTest method xtestBatchUpdateError.

/**
 * Batches up many calls to a SQL procedure that updates a value in a table.
 * All calls should succeed, except for one that should fail with a check
 * constraint violation.
 * Uses DriverManager and Batch calls, so requires JDBC 2 support.
 * @throws SQLException
 */
public void xtestBatchUpdateError() throws SQLException {
    // Setup table data
    Statement stmt = createStatement();
    stmt.executeUpdate("INSERT INTO BATCH_TABLE VALUES(1, 'STRING_1',0)");
    stmt.executeUpdate("INSERT INTO BATCH_TABLE VALUES(2, 'STRING_2',0)");
    stmt.executeUpdate("INSERT INTO BATCH_TABLE VALUES(3, 'STRING_3',0)");
    stmt.executeUpdate("INSERT INTO BATCH_TABLE VALUES(4, 'STRING_4',0)");
    // Setup batch to modify values.
    CallableStatement cstmt = prepareCall("CALL BATCH_UPDATE_PROC(?,?)");
    // Set id 1's value to 10
    cstmt.setInt(1, 1);
    cstmt.setInt(2, 10);
    cstmt.addBatch();
    // Set id 2's value to -5 (should fail)
    cstmt.setInt(1, 2);
    cstmt.setInt(2, -5);
    cstmt.addBatch();
    // Set id 3's value to 30.
    cstmt.setInt(1, 3);
    cstmt.setInt(2, 30);
    cstmt.addBatch();
    // Set id 4's value to 40.
    cstmt.setInt(1, 4);
    cstmt.setInt(2, 40);
    cstmt.addBatch();
    int[] updateCount = null;
    try {
        updateCount = cstmt.executeBatch();
        fail("Expected batchExecute to fail");
    } catch (BatchUpdateException b) {
        if (usingEmbedded()) {
            assertSQLState("38000", b.getSQLState(), b);
        } else if (usingDerbyNetClient()) {
            assertSQLState("XJ208", b.getSQLState(), b);
        }
        updateCount = b.getUpdateCounts();
        /* The updateCount is different for embedded and client because
             * the embedded driver stops processing the batch after the
             * failure, while the client driver continues processing (see
             * DERBY-2301).
             */
        if (usingEmbedded()) {
            assertEquals("updateCount length", 1, updateCount.length);
            assertEquals("Batch updateCount", 0, updateCount[0]);
        } else if (usingDerbyNetClient()) {
            assertEquals("updateCount length", 4, updateCount.length);
            for (int i = 0; i < updateCount.length; i++) {
                if (// The second command in the batch failed.
                i == 1)
                    assertEquals("Batch updateCount", -3, updateCount[i]);
                else
                    assertEquals("Batch updateCount", -1, updateCount[i]);
            }
        }
    }
    // Make sure the right rows in the table were updated.
    ResultSet rs = stmt.executeQuery("SELECT id, tag, idval FROM BATCH_TABLE order by id, tag");
    assertNotNull("SELECT from BATCH_TABLE", rs);
    while (rs.next()) {
        /* Embedded and client results should be the same for the first
             * two rows (the changed row for the first successful command in 
             * the batch, followed by the unchanged row for the second command,
             * which failed).
             * After the first two rows, results are different because the
             * rest of the commands in the batch executed for client, but not
             * for embedded.
             */
        switch(rs.getInt(1)) {
            case 1:
                assertEquals(rs.getString(2), 10, rs.getInt(3));
                break;
            case 2:
                assertEquals(rs.getString(2), 0, rs.getInt(3));
                break;
            default:
                if (usingEmbedded()) {
                    assertEquals(rs.getString(2), 0, rs.getInt(3));
                } else if (usingDerbyNetClient()) {
                    assertEquals(rs.getString(2), rs.getInt(1) * 10, rs.getInt(3));
                }
                break;
        }
    }
}
Also used : PreparedStatement(java.sql.PreparedStatement) Statement(java.sql.Statement) CallableStatement(java.sql.CallableStatement) CallableStatement(java.sql.CallableStatement) ResultSet(java.sql.ResultSet) BatchUpdateException(java.sql.BatchUpdateException)

Example 44 with BatchUpdateException

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

the class DataSourceWrapper method translate.

public DataAccessException translate(String sql, SQLException ex) {
    ParamUtil.requireNonNull("ex", ex);
    if (sql == null) {
        sql = "";
    }
    SQLException sqlEx = ex;
    if (sqlEx instanceof BatchUpdateException && sqlEx.getNextException() != null) {
        SQLException nestedSqlEx = sqlEx.getNextException();
        if (nestedSqlEx.getErrorCode() > 0 || nestedSqlEx.getSQLState() != null) {
            LOG.debug("Using nested SQLException from the BatchUpdateException");
            sqlEx = nestedSqlEx;
        }
    }
    // Check SQLErrorCodes with corresponding error code, if available.
    String errorCode;
    String sqlState;
    if (sqlErrorCodes.useSqlStateForTranslation) {
        errorCode = sqlEx.getSQLState();
        sqlState = null;
    } else {
        // Try to find SQLException with actual error code, looping through the causes.
        // E.g. applicable to java.sql.DataTruncation as of JDK 1.6.
        SQLException current = sqlEx;
        while (current.getErrorCode() == 0 && current.getCause() instanceof SQLException) {
            current = (SQLException) current.getCause();
        }
        errorCode = Integer.toString(current.getErrorCode());
        sqlState = current.getSQLState();
    }
    if (errorCode != null) {
        // look for grouped error codes.
        if (sqlErrorCodes.badSqlGrammarCodes.contains(errorCode)) {
            logTranslation(sql, sqlEx);
            return new DataAccessException(Reason.BadSqlGrammar, buildMessage(sql, sqlEx), sqlEx);
        } else if (sqlErrorCodes.invalidResultSetAccessCodes.contains(errorCode)) {
            logTranslation(sql, sqlEx);
            return new DataAccessException(Reason.InvalidResultSetAccess, buildMessage(sql, sqlEx), sqlEx);
        } else if (sqlErrorCodes.duplicateKeyCodes.contains(errorCode)) {
            logTranslation(sql, sqlEx);
            return new DataAccessException(Reason.DuplicateKey, buildMessage(sql, sqlEx), sqlEx);
        } else if (sqlErrorCodes.dataIntegrityViolationCodes.contains(errorCode)) {
            logTranslation(sql, sqlEx);
            return new DataAccessException(Reason.DataIntegrityViolation, buildMessage(sql, sqlEx), sqlEx);
        } else if (sqlErrorCodes.permissionDeniedCodes.contains(errorCode)) {
            logTranslation(sql, sqlEx);
            return new DataAccessException(Reason.PermissionDeniedDataAccess, buildMessage(sql, sqlEx), sqlEx);
        } else if (sqlErrorCodes.dataAccessResourceFailureCodes.contains(errorCode)) {
            logTranslation(sql, sqlEx);
            return new DataAccessException(Reason.DataAccessResourceFailure, buildMessage(sql, sqlEx), sqlEx);
        } else if (sqlErrorCodes.transientDataAccessResourceCodes.contains(errorCode)) {
            logTranslation(sql, sqlEx);
            return new DataAccessException(Reason.TransientDataAccessResource, buildMessage(sql, sqlEx), sqlEx);
        } else if (sqlErrorCodes.cannotAcquireLockCodes.contains(errorCode)) {
            logTranslation(sql, sqlEx);
            return new DataAccessException(Reason.CannotAcquireLock, buildMessage(sql, sqlEx), sqlEx);
        } else if (sqlErrorCodes.deadlockLoserCodes.contains(errorCode)) {
            logTranslation(sql, sqlEx);
            return new DataAccessException(Reason.DeadlockLoserDataAccess, buildMessage(sql, sqlEx), sqlEx);
        } else if (sqlErrorCodes.cannotSerializeTransactionCodes.contains(errorCode)) {
            logTranslation(sql, sqlEx);
            return new DataAccessException(Reason.CannotSerializeTransaction, buildMessage(sql, sqlEx), sqlEx);
        }
    }
    // try SQLState
    if (sqlState != null && sqlState.length() >= 2) {
        String classCode = sqlState.substring(0, 2);
        if (sqlStateCodes.badSqlGrammarCodes.contains(classCode)) {
            return new DataAccessException(Reason.BadSqlGrammar, buildMessage(sql, sqlEx), ex);
        } else if (sqlStateCodes.dataIntegrityViolationCodes.contains(classCode)) {
            return new DataAccessException(Reason.DataIntegrityViolation, buildMessage(sql, ex), ex);
        } else if (sqlStateCodes.dataAccessResourceFailureCodes.contains(classCode)) {
            return new DataAccessException(Reason.DataAccessResourceFailure, buildMessage(sql, ex), ex);
        } else if (sqlStateCodes.transientDataAccessResourceCodes.contains(classCode)) {
            return new DataAccessException(Reason.TransientDataAccessResource, buildMessage(sql, ex), ex);
        } else if (sqlStateCodes.concurrencyFailureCodes.contains(classCode)) {
            return new DataAccessException(Reason.ConcurrencyFailure, buildMessage(sql, ex), ex);
        }
    }
    // (since MySQL doesn't throw the JDBC 4 SQLTimeoutException)
    if (ex.getClass().getName().contains("Timeout")) {
        return new DataAccessException(Reason.QueryTimeout, buildMessage(sql, ex), ex);
    }
    // We couldn't identify it more precisely
    if (LOG.isDebugEnabled()) {
        String codes;
        if (sqlErrorCodes.useSqlStateForTranslation) {
            codes = StringUtil.concatObjectsCap(60, "SQL state '", sqlEx.getSQLState(), "', error code '", sqlEx.getErrorCode());
        } else {
            codes = StringUtil.concat("Error code '", Integer.toString(sqlEx.getErrorCode()), "'");
        }
        LOG.debug("Unable to translate SQLException with " + codes);
    }
    return new DataAccessException(Reason.UncategorizedSql, buildMessage(sql, sqlEx), sqlEx);
}
Also used : SQLException(java.sql.SQLException) BatchUpdateException(java.sql.BatchUpdateException)

Example 45 with BatchUpdateException

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

the class PostgreSqlExceptionTranslator method doTranslate.

private MolgenisDataException doTranslate(SQLException sqlException) {
    if (sqlException instanceof BatchUpdateException) {
        sqlException = sqlException.getNextException();
    }
    if (!(sqlException instanceof PSQLException)) {
        throw new RuntimeException(format("Unexpected exception class [%s]", sqlException.getClass().getSimpleName()));
    }
    PSQLException pSqlException = (PSQLException) sqlException;
    MolgenisDataException molgenisDataException = doTranslate(pSqlException);
    if (molgenisDataException == null) {
        molgenisDataException = new MolgenisDataException(sqlException);
    }
    return molgenisDataException;
}
Also used : MolgenisDataException(org.molgenis.data.MolgenisDataException) PSQLException(org.postgresql.util.PSQLException) BatchUpdateException(java.sql.BatchUpdateException)

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