Search in sources :

Example 1 with BatchUpdateException

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

the class JDBCPreparedStatement method executeBatch.

//------------------------- JDBC 2.0 - overriden methods -------------------
/**
     * <!-- 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>
     * A driver is not required to implement this method.
     * 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. <p>
     * <!-- 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();
    checkStatementType(StatementTypes.RETURN_COUNT);
    if (!isBatch) {
        throw Util.sqlExceptionSQL(ErrorCode.X_07506);
    }
    generatedResult = null;
    int batchCount = resultOut.getNavigator().getSize();
    resultIn = null;
    try {
        resultIn = connection.sessionProxy.execute(resultOut);
    } catch (HsqlException e) {
        throw Util.sqlException(e);
    } finally {
        performPostExecute();
        resultOut.getNavigator().clear();
        isBatch = false;
    }
    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) SchemaObject(org.hsqldb_voltpatches.SchemaObject) HsqlException(org.hsqldb_voltpatches.HsqlException) BatchUpdateException(java.sql.BatchUpdateException)

Example 2 with BatchUpdateException

use of java.sql.BatchUpdateException in project spring-framework by spring-projects.

the class SQLErrorCodeSQLExceptionTranslator method doTranslate.

@Override
protected DataAccessException doTranslate(String task, String sql, SQLException ex) {
    SQLException sqlEx = ex;
    if (sqlEx instanceof BatchUpdateException && sqlEx.getNextException() != null) {
        SQLException nestedSqlEx = sqlEx.getNextException();
        if (nestedSqlEx.getErrorCode() > 0 || nestedSqlEx.getSQLState() != null) {
            logger.debug("Using nested SQLException from the BatchUpdateException");
            sqlEx = nestedSqlEx;
        }
    }
    // First, try custom translation from overridden method.
    DataAccessException dex = customTranslate(task, sql, sqlEx);
    if (dex != null) {
        return dex;
    }
    // Next, try the custom SQLException translator, if available.
    if (this.sqlErrorCodes != null) {
        SQLExceptionTranslator customTranslator = this.sqlErrorCodes.getCustomSqlExceptionTranslator();
        if (customTranslator != null) {
            DataAccessException customDex = customTranslator.translate(task, sql, sqlEx);
            if (customDex != null) {
                return customDex;
            }
        }
    }
    // Check SQLErrorCodes with corresponding error code, if available.
    if (this.sqlErrorCodes != null) {
        String errorCode;
        if (this.sqlErrorCodes.isUseSqlStateForTranslation()) {
            errorCode = sqlEx.getSQLState();
        } 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());
        }
        if (errorCode != null) {
            // Look for defined custom translations first.
            CustomSQLErrorCodesTranslation[] customTranslations = this.sqlErrorCodes.getCustomTranslations();
            if (customTranslations != null) {
                for (CustomSQLErrorCodesTranslation customTranslation : customTranslations) {
                    if (Arrays.binarySearch(customTranslation.getErrorCodes(), errorCode) >= 0) {
                        if (customTranslation.getExceptionClass() != null) {
                            DataAccessException customException = createCustomException(task, sql, sqlEx, customTranslation.getExceptionClass());
                            if (customException != null) {
                                logTranslation(task, sql, sqlEx, true);
                                return customException;
                            }
                        }
                    }
                }
            }
            // Next, look for grouped error codes.
            if (Arrays.binarySearch(this.sqlErrorCodes.getBadSqlGrammarCodes(), errorCode) >= 0) {
                logTranslation(task, sql, sqlEx, false);
                return new BadSqlGrammarException(task, sql, sqlEx);
            } else if (Arrays.binarySearch(this.sqlErrorCodes.getInvalidResultSetAccessCodes(), errorCode) >= 0) {
                logTranslation(task, sql, sqlEx, false);
                return new InvalidResultSetAccessException(task, sql, sqlEx);
            } else if (Arrays.binarySearch(this.sqlErrorCodes.getDuplicateKeyCodes(), errorCode) >= 0) {
                logTranslation(task, sql, sqlEx, false);
                return new DuplicateKeyException(buildMessage(task, sql, sqlEx), sqlEx);
            } else if (Arrays.binarySearch(this.sqlErrorCodes.getDataIntegrityViolationCodes(), errorCode) >= 0) {
                logTranslation(task, sql, sqlEx, false);
                return new DataIntegrityViolationException(buildMessage(task, sql, sqlEx), sqlEx);
            } else if (Arrays.binarySearch(this.sqlErrorCodes.getPermissionDeniedCodes(), errorCode) >= 0) {
                logTranslation(task, sql, sqlEx, false);
                return new PermissionDeniedDataAccessException(buildMessage(task, sql, sqlEx), sqlEx);
            } else if (Arrays.binarySearch(this.sqlErrorCodes.getDataAccessResourceFailureCodes(), errorCode) >= 0) {
                logTranslation(task, sql, sqlEx, false);
                return new DataAccessResourceFailureException(buildMessage(task, sql, sqlEx), sqlEx);
            } else if (Arrays.binarySearch(this.sqlErrorCodes.getTransientDataAccessResourceCodes(), errorCode) >= 0) {
                logTranslation(task, sql, sqlEx, false);
                return new TransientDataAccessResourceException(buildMessage(task, sql, sqlEx), sqlEx);
            } else if (Arrays.binarySearch(this.sqlErrorCodes.getCannotAcquireLockCodes(), errorCode) >= 0) {
                logTranslation(task, sql, sqlEx, false);
                return new CannotAcquireLockException(buildMessage(task, sql, sqlEx), sqlEx);
            } else if (Arrays.binarySearch(this.sqlErrorCodes.getDeadlockLoserCodes(), errorCode) >= 0) {
                logTranslation(task, sql, sqlEx, false);
                return new DeadlockLoserDataAccessException(buildMessage(task, sql, sqlEx), sqlEx);
            } else if (Arrays.binarySearch(this.sqlErrorCodes.getCannotSerializeTransactionCodes(), errorCode) >= 0) {
                logTranslation(task, sql, sqlEx, false);
                return new CannotSerializeTransactionException(buildMessage(task, sql, sqlEx), sqlEx);
            }
        }
    }
    // We couldn't identify it more precisely - let's hand it over to the SQLState fallback translator.
    if (logger.isDebugEnabled()) {
        String codes;
        if (this.sqlErrorCodes != null && this.sqlErrorCodes.isUseSqlStateForTranslation()) {
            codes = "SQL state '" + sqlEx.getSQLState() + "', error code '" + sqlEx.getErrorCode();
        } else {
            codes = "Error code '" + sqlEx.getErrorCode() + "'";
        }
        logger.debug("Unable to translate SQLException with " + codes + ", will now try the fallback translator");
    }
    return null;
}
Also used : BadSqlGrammarException(org.springframework.jdbc.BadSqlGrammarException) TransientDataAccessResourceException(org.springframework.dao.TransientDataAccessResourceException) CannotAcquireLockException(org.springframework.dao.CannotAcquireLockException) SQLException(java.sql.SQLException) DataAccessResourceFailureException(org.springframework.dao.DataAccessResourceFailureException) PermissionDeniedDataAccessException(org.springframework.dao.PermissionDeniedDataAccessException) InvalidResultSetAccessException(org.springframework.jdbc.InvalidResultSetAccessException) DuplicateKeyException(org.springframework.dao.DuplicateKeyException) DataIntegrityViolationException(org.springframework.dao.DataIntegrityViolationException) CannotSerializeTransactionException(org.springframework.dao.CannotSerializeTransactionException) DeadlockLoserDataAccessException(org.springframework.dao.DeadlockLoserDataAccessException) DataAccessException(org.springframework.dao.DataAccessException) DeadlockLoserDataAccessException(org.springframework.dao.DeadlockLoserDataAccessException) PermissionDeniedDataAccessException(org.springframework.dao.PermissionDeniedDataAccessException) BatchUpdateException(java.sql.BatchUpdateException)

Example 3 with BatchUpdateException

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

the class DmlStatementsProcessor method updateSqlFieldsBatched.

/**
 * Execute DML statement, possibly with few re-attempts in case of concurrent data modifications.
 *
 * @param schemaName Schema.
 * @param conn Connection.
 * @param prepared Prepared statement.
 * @param fieldsQry Original query.
 * @param loc Query locality flag.
 * @param filters Cache name and key filter.
 * @param cancel Cancel.
 * @return Update result (modified items count and failed keys).
 * @throws IgniteCheckedException if failed.
 */
private Collection<UpdateResult> updateSqlFieldsBatched(String schemaName, Connection conn, Prepared prepared, SqlFieldsQueryEx fieldsQry, boolean loc, IndexingQueryFilter filters, GridQueryCancel cancel) throws IgniteCheckedException {
    List<Object[]> argss = fieldsQry.batchedArguments();
    UpdatePlan plan = getPlanForStatement(schemaName, conn, prepared, fieldsQry, loc, null);
    if (plan.hasRows() && plan.mode() == UpdateMode.INSERT) {
        GridCacheContext<?, ?> cctx = plan.cacheContext();
        CacheOperationContext opCtx = setKeepBinaryContext(cctx);
        try {
            List<List<List<?>>> cur = plan.createRows(argss);
            List<UpdateResult> res = processDmlSelectResultBatched(plan, cur, fieldsQry.getPageSize());
            return res;
        } finally {
            cctx.operationContextPerCall(opCtx);
        }
    } else {
        // Fallback to previous mode.
        Collection<UpdateResult> ress = new ArrayList<>(argss.size());
        SQLException batchException = null;
        int[] cntPerRow = new int[argss.size()];
        int cntr = 0;
        for (Object[] args : argss) {
            SqlFieldsQueryEx qry0 = (SqlFieldsQueryEx) fieldsQry.copy();
            qry0.clearBatchedArgs();
            qry0.setArgs(args);
            UpdateResult res;
            try {
                res = updateSqlFields(schemaName, conn, prepared, qry0, loc, filters, cancel);
                cntPerRow[cntr++] = (int) res.counter();
                ress.add(res);
            } catch (Exception e) {
                String sqlState;
                int code;
                if (e instanceof IgniteSQLException) {
                    sqlState = ((IgniteSQLException) e).sqlState();
                    code = ((IgniteSQLException) e).statusCode();
                } else {
                    sqlState = SqlStateCode.INTERNAL_ERROR;
                    code = IgniteQueryErrorCode.UNKNOWN;
                }
                batchException = chainException(batchException, new SQLException(e.getMessage(), sqlState, code, e));
                cntPerRow[cntr++] = Statement.EXECUTE_FAILED;
            }
        }
        if (batchException != null) {
            BatchUpdateException e = new BatchUpdateException(batchException.getMessage(), batchException.getSQLState(), batchException.getErrorCode(), cntPerRow, batchException);
            throw new IgniteCheckedException(e);
        }
        return ress;
    }
}
Also used : CacheOperationContext(org.apache.ignite.internal.processors.cache.CacheOperationContext) SQLException(java.sql.SQLException) IgniteSQLException(org.apache.ignite.internal.processors.query.IgniteSQLException) ArrayList(java.util.ArrayList) IgniteQueryErrorCode.createJdbcSqlException(org.apache.ignite.internal.processors.cache.query.IgniteQueryErrorCode.createJdbcSqlException) IgniteCheckedException(org.apache.ignite.IgniteCheckedException) IgniteException(org.apache.ignite.IgniteException) BatchUpdateException(java.sql.BatchUpdateException) EntryProcessorException(javax.cache.processor.EntryProcessorException) SQLException(java.sql.SQLException) IgniteSQLException(org.apache.ignite.internal.processors.query.IgniteSQLException) IgniteCheckedException(org.apache.ignite.IgniteCheckedException) SqlFieldsQueryEx(org.apache.ignite.internal.processors.cache.query.SqlFieldsQueryEx) IgniteSQLException(org.apache.ignite.internal.processors.query.IgniteSQLException) List(java.util.List) ArrayList(java.util.ArrayList) UpdatePlan(org.apache.ignite.internal.processors.query.h2.dml.UpdatePlan) BatchUpdateException(java.sql.BatchUpdateException)

Example 4 with BatchUpdateException

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

the class JdbcThinConnection method executeBatch.

/**
 * @param lastBatch Whether open data streamers must be flushed and closed after this batch.
 * @throws SQLException if failed.
 */
private void executeBatch(boolean lastBatch) throws SQLException {
    JdbcBatchExecuteResult res = sendRequest(new JdbcBatchExecuteRequest(schema, streamBatch, lastBatch));
    streamBatch = null;
    lastStreamQry = null;
    if (res.errorCode() != ClientListenerResponse.STATUS_SUCCESS) {
        throw new BatchUpdateException(res.errorMessage(), IgniteQueryErrorCode.codeToSqlState(res.errorCode()), res.errorCode(), res.updateCounts());
    }
}
Also used : JdbcBatchExecuteRequest(org.apache.ignite.internal.processors.odbc.jdbc.JdbcBatchExecuteRequest) JdbcBatchExecuteResult(org.apache.ignite.internal.processors.odbc.jdbc.JdbcBatchExecuteResult) BatchUpdateException(java.sql.BatchUpdateException)

Example 5 with BatchUpdateException

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

the class OdbcRequestHandler method exceptionToBatchResult.

/**
 * Create {@link OdbcResponse} bearing appropriate Ignite specific result code if possible
 *     from given {@link Exception}.
 *
 * @param e Exception to convert.
 * @return resulting {@link OdbcResponse}.
 */
private OdbcResponse exceptionToBatchResult(Exception e) {
    int code;
    String msg;
    List<Long> rowsAffected = new ArrayList<>();
    if (e instanceof IgniteSQLException) {
        BatchUpdateException batchCause = X.cause(e, BatchUpdateException.class);
        if (batchCause != null) {
            for (long cnt : batchCause.getLargeUpdateCounts()) rowsAffected.add(cnt);
            msg = batchCause.getMessage();
            code = batchCause.getErrorCode();
        } else {
            msg = OdbcUtils.tryRetrieveH2ErrorMessage(e);
            code = ((IgniteSQLException) e).statusCode();
        }
    } else {
        msg = e.getMessage();
        code = IgniteQueryErrorCode.UNKNOWN;
    }
    OdbcQueryExecuteBatchResult res = new OdbcQueryExecuteBatchResult(rowsAffected, -1, code, msg);
    return new OdbcResponse(res);
}
Also used : AtomicLong(java.util.concurrent.atomic.AtomicLong) ArrayList(java.util.ArrayList) IgniteSQLException(org.apache.ignite.internal.processors.query.IgniteSQLException) 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