Search in sources :

Example 46 with BatchUpdateException

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

the class BatchUpdateOperation method evaluate.

@Override
public int[] evaluate(QueryElement<int[]> query) {
    int[] result = batchInStatement ? null : new int[length];
    try (Connection connection = configuration.getConnection()) {
        DefaultOutput generator = new DefaultOutput(configuration, query);
        String sql = generator.toSql();
        StatementListener listener = configuration.getStatementListener();
        try (PreparedStatement statement = prepare(sql, connection)) {
            for (int i = 0; i < length; i++) {
                E element = elements[i];
                parameterBinder.bindParameters(statement, element, null);
                if (batchInStatement) {
                    statement.addBatch();
                } else {
                    listener.beforeExecuteBatchUpdate(statement, sql);
                    result[i] = statement.executeUpdate();
                    listener.afterExecuteBatchUpdate(statement, result);
                    readGeneratedKeys(i, statement);
                }
            }
            if (batchInStatement) {
                listener.beforeExecuteBatchUpdate(statement, sql);
                result = statement.executeBatch();
                listener.afterExecuteBatchUpdate(statement, result);
                readGeneratedKeys(0, statement);
            }
        }
    } catch (BatchUpdateException e) {
        result = e.getUpdateCounts();
        if (result == null) {
            throw new PersistenceException(e);
        }
    } catch (SQLException e) {
        throw new PersistenceException(e);
    }
    return result;
}
Also used : SQLException(java.sql.SQLException) DefaultOutput(io.requery.sql.gen.DefaultOutput) Connection(java.sql.Connection) PersistenceException(io.requery.PersistenceException) PreparedStatement(java.sql.PreparedStatement) BatchUpdateException(java.sql.BatchUpdateException)

Example 47 with BatchUpdateException

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

the class SQLErrorCodeSQLExceptionTranslatorTests method batchExceptionTranslation.

@Test
public void batchExceptionTranslation() {
    SQLExceptionTranslator sext = new SQLErrorCodeSQLExceptionTranslator(ERROR_CODES);
    SQLException badSqlEx = new SQLException("", "", 1);
    BatchUpdateException batchUpdateEx = new BatchUpdateException();
    batchUpdateEx.setNextException(badSqlEx);
    BadSqlGrammarException bsgex = (BadSqlGrammarException) sext.translate("task", "SQL", batchUpdateEx);
    assertThat(bsgex.getSql()).isEqualTo("SQL");
    assertThat((Object) bsgex.getSQLException()).isEqualTo(badSqlEx);
}
Also used : BadSqlGrammarException(org.springframework.jdbc.BadSqlGrammarException) SQLException(java.sql.SQLException) BatchUpdateException(java.sql.BatchUpdateException) Test(org.junit.jupiter.api.Test)

Example 48 with BatchUpdateException

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

the class JdbcThinErrorsSelfTest method testBatchUpdateException.

/**
 * Test error code for the case when error is caused on batch execution.
 * @throws SQLException if failed.
 */
@Test
public void testBatchUpdateException() throws SQLException {
    try (final Connection conn = getConnection()) {
        try (Statement stmt = conn.createStatement()) {
            stmt.executeUpdate("CREATE TABLE test (id int primary key, val varchar)");
            stmt.addBatch("insert into test (id, val) values (1, 'val1')");
            stmt.addBatch("insert into test (id, val) values (2, 'val2')");
            stmt.addBatch("insert into test (id1, val1) values (3, 'val3')");
            stmt.executeBatch();
            fail("BatchUpdateException is expected");
        } catch (BatchUpdateException e) {
            assertEquals(3, e.getUpdateCounts().length);
            assertArrayEquals("", new int[] { 1, 1, Statement.EXECUTE_FAILED }, e.getUpdateCounts());
            assertEquals("42000", e.getSQLState());
            assertTrue("Unexpected error message: " + e.getMessage(), e.getMessage() != null && e.getMessage().contains("Failed to parse query. Column \"ID1\" not found"));
        }
    }
}
Also used : Statement(java.sql.Statement) Connection(java.sql.Connection) BatchUpdateException(java.sql.BatchUpdateException) Test(org.junit.Test) JdbcErrorsAbstractSelfTest(org.apache.ignite.jdbc.JdbcErrorsAbstractSelfTest)

Example 49 with BatchUpdateException

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

the class JdbcRequestHandler method executeBatchedQuery.

/**
 * Executes query and updates result counters.
 *
 * @param qry Query.
 * @param updCntsAcc Per query rows updates counter.
 * @param firstErr First error data - code and message.
 * @param cancel Hook for query cancellation.
 * @throws QueryCancelledException If query was cancelled during execution.
 */
@SuppressWarnings({ "ForLoopReplaceableByForEach" })
private void executeBatchedQuery(SqlFieldsQueryEx qry, List<Integer> updCntsAcc, IgniteBiTuple<Integer, String> firstErr, GridQueryCancel cancel) throws QueryCancelledException {
    try {
        if (cliCtx.isStream()) {
            List<Long> cnt = connCtx.kernalContext().query().streamBatchedUpdateQuery(qry.getSchema(), cliCtx, qry.getSql(), qry.batchedArguments(), connCtx.clientDescriptor());
            for (int i = 0; i < cnt.size(); i++) updCntsAcc.add(cnt.get(i).intValue());
            return;
        }
        List<FieldsQueryCursor<List<?>>> qryRes = connCtx.kernalContext().query().querySqlFields(null, qry, cliCtx, true, true, cancel);
        for (FieldsQueryCursor<List<?>> cur : qryRes) {
            if (cur instanceof BulkLoadContextCursor)
                throw new IgniteSQLException("COPY command cannot be executed in batch mode.");
            assert !((QueryCursorImpl) cur).isQuery();
            Iterator<List<?>> it = cur.iterator();
            if (it.hasNext()) {
                int val = ((Long) it.next().get(0)).intValue();
                updCntsAcc.add(val);
            }
        }
    } catch (Exception e) {
        int code;
        String msg;
        if (X.cause(e, QueryCancelledException.class) != null)
            throw new QueryCancelledException();
        else if (e instanceof IgniteSQLException) {
            BatchUpdateException batchCause = X.cause(e, BatchUpdateException.class);
            if (batchCause != null) {
                int[] updCntsOnErr = batchCause.getUpdateCounts();
                for (int i = 0; i < updCntsOnErr.length; i++) updCntsAcc.add(updCntsOnErr[i]);
                msg = batchCause.getMessage();
                code = batchCause.getErrorCode();
            } else {
                for (int i = 0; i < qry.batchedArguments().size(); i++) updCntsAcc.add(Statement.EXECUTE_FAILED);
                msg = e.getMessage();
                code = ((IgniteSQLException) e).statusCode();
            }
        } else {
            for (int i = 0; i < qry.batchedArguments().size(); i++) updCntsAcc.add(Statement.EXECUTE_FAILED);
            msg = e.getMessage();
            code = IgniteQueryErrorCode.UNKNOWN;
        }
        if (firstErr.isEmpty())
            firstErr.set(code, msg);
        else
            U.error(log, "Failed to execute batch query [qry=" + qry + ']', e);
    }
}
Also used : FieldsQueryCursor(org.apache.ignite.cache.query.FieldsQueryCursor) BulkLoadContextCursor(org.apache.ignite.cache.query.BulkLoadContextCursor) QueryCancelledException(org.apache.ignite.cache.query.QueryCancelledException) IgniteCheckedException(org.apache.ignite.IgniteCheckedException) BatchUpdateException(java.sql.BatchUpdateException) IgniteInterruptedCheckedException(org.apache.ignite.internal.IgniteInterruptedCheckedException) IgniteSQLException(org.apache.ignite.internal.processors.query.IgniteSQLException) IgniteSQLException(org.apache.ignite.internal.processors.query.IgniteSQLException) List(java.util.List) ArrayList(java.util.ArrayList) QueryCancelledException(org.apache.ignite.cache.query.QueryCancelledException) BatchUpdateException(java.sql.BatchUpdateException)

Example 50 with BatchUpdateException

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

the class JdbcThinStatement method executeBatch.

/**
 * {@inheritDoc}
 */
@Override
public int[] executeBatch() throws SQLException {
    ensureNotClosed();
    closeResults();
    checkStatementBatchEmpty();
    if (conn.isStream()) {
        int[] res = new int[batchSize];
        batchSize = 0;
        return res;
    }
    if (F.isEmpty(batch))
        return new int[0];
    JdbcBatchExecuteRequest req = new JdbcBatchExecuteRequest(conn.getSchema(), batch, conn.getAutoCommit(), false);
    try {
        JdbcBatchExecuteResult res = conn.sendRequest(req, this, null).response();
        if (res.errorCode() != ClientListenerResponse.STATUS_SUCCESS) {
            throw new BatchUpdateException(res.errorMessage(), IgniteQueryErrorCode.codeToSqlState(res.errorCode()), res.errorCode(), res.updateCounts());
        }
        return res.updateCounts();
    } finally {
        batchSize = 0;
        batch = null;
    }
}
Also used : JdbcBatchExecuteRequest(org.apache.ignite.internal.processors.odbc.jdbc.JdbcBatchExecuteRequest) JdbcBatchExecuteResult(org.apache.ignite.internal.processors.odbc.jdbc.JdbcBatchExecuteResult) 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