Search in sources :

Example 31 with BatchUpdateException

use of java.sql.BatchUpdateException in project openmrs-core by openmrs.

the class DuplicateEncounterTypeNameChangeSet method execute.

/**
 * Method to perform validation and resolution of duplicate EncounterType names
 */
@Override
public void execute(Database database) throws CustomChangeException {
    JdbcConnection connection = (JdbcConnection) database.getConnection();
    Map<String, HashSet<Integer>> duplicates = new HashMap<>();
    Statement stmt = null;
    PreparedStatement pStmt = null;
    ResultSet rs = null;
    Boolean initialAutoCommit = null;
    try {
        initialAutoCommit = connection.getAutoCommit();
        // set auto commit mode to false for UPDATE action
        connection.setAutoCommit(false);
        stmt = connection.createStatement();
        rs = stmt.executeQuery("SELECT * FROM encounter_type INNER JOIN (SELECT name FROM encounter_type GROUP BY name HAVING count(name) > 1) dup ON encounter_type.name = dup.name");
        Integer id;
        String name;
        while (rs.next()) {
            id = rs.getInt("encounter_type_id");
            name = rs.getString("name");
            if (duplicates.get(name) == null) {
                HashSet<Integer> results = new HashSet<>();
                results.add(id);
                duplicates.put(name, results);
            } else {
                HashSet<Integer> results = duplicates.get(name);
                results.add(id);
            }
        }
        for (Object o : duplicates.entrySet()) {
            Map.Entry pairs = (Map.Entry) o;
            HashSet values = (HashSet) pairs.getValue();
            List<Integer> ids = new ArrayList<Integer>(values);
            int duplicateNameId = 1;
            for (int i = 1; i < ids.size(); i++) {
                String newName = pairs.getKey() + "_" + duplicateNameId;
                List<List<Object>> duplicateResult;
                boolean duplicateName;
                Connection con = DatabaseUpdater.getConnection();
                do {
                    String sqlValidatorString = "select * from encounter_type where name = '" + newName + "'";
                    duplicateResult = DatabaseUtil.executeSQL(con, sqlValidatorString, true);
                    if (!duplicateResult.isEmpty()) {
                        duplicateNameId += 1;
                        newName = pairs.getKey() + "_" + duplicateNameId;
                        duplicateName = true;
                    } else {
                        duplicateName = false;
                    }
                } while (duplicateName);
                pStmt = connection.prepareStatement("update encounter_type set name = ? where encounter_type_id = ?");
                pStmt.setString(1, newName);
                pStmt.setInt(2, ids.get(i));
                duplicateNameId += 1;
                pStmt.executeUpdate();
            }
        }
    } catch (BatchUpdateException e) {
        log.warn("Error generated while processsing batch insert", e);
        try {
            log.debug("Rolling back batch", e);
            connection.rollback();
        } catch (Exception rbe) {
            log.warn("Error generated while rolling back batch insert", e);
        }
        // marks the changeset as a failed one
        throw new CustomChangeException("Failed to update one or more duplicate EncounterType names", e);
    } catch (Exception e) {
        throw new CustomChangeException(e);
    } finally {
        // set auto commit to its initial state
        try {
            if (initialAutoCommit != null) {
                connection.setAutoCommit(initialAutoCommit);
            }
        } catch (DatabaseException e) {
            log.warn("Failed to set auto commit to ids initial state", e);
        }
        if (rs != null) {
            try {
                rs.close();
            } catch (SQLException e) {
                log.warn("Failed to close the resultset object");
            }
        }
        if (stmt != null) {
            try {
                stmt.close();
            } catch (SQLException e) {
                log.warn("Failed to close the select statement used to identify duplicate EncounterType object names");
            }
        }
        if (pStmt != null) {
            try {
                pStmt.close();
            } catch (SQLException e) {
                log.warn("Failed to close the prepared statement used to update duplicate EncounterType object names");
            }
        }
    }
}
Also used : HashMap(java.util.HashMap) SQLException(java.sql.SQLException) ArrayList(java.util.ArrayList) CustomChangeException(liquibase.exception.CustomChangeException) JdbcConnection(liquibase.database.jvm.JdbcConnection) ResultSet(java.sql.ResultSet) ArrayList(java.util.ArrayList) List(java.util.List) HashSet(java.util.HashSet) BatchUpdateException(java.sql.BatchUpdateException) PreparedStatement(java.sql.PreparedStatement) Statement(java.sql.Statement) Connection(java.sql.Connection) JdbcConnection(liquibase.database.jvm.JdbcConnection) PreparedStatement(java.sql.PreparedStatement) BatchUpdateException(java.sql.BatchUpdateException) DatabaseException(liquibase.exception.DatabaseException) CustomChangeException(liquibase.exception.CustomChangeException) SetupException(liquibase.exception.SetupException) SQLException(java.sql.SQLException) HashMap(java.util.HashMap) Map(java.util.Map) DatabaseException(liquibase.exception.DatabaseException)

Example 32 with BatchUpdateException

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

the class TestBatchUpdates method testExecuteBatch07.

private void testExecuteBatch07() throws SQLException {
    trace("testExecuteBatch07");
    boolean batchExceptionFlag = false;
    String selectCoffee = COFFEE_SELECT1;
    trace("selectCoffee = " + selectCoffee);
    Statement stmt = conn.createStatement();
    stmt.addBatch(selectCoffee);
    try {
        int[] updateCount = stmt.executeBatch();
        trace("updateCount Length : " + updateCount.length);
    } catch (BatchUpdateException be) {
        batchExceptionFlag = true;
    }
    if (batchExceptionFlag) {
        trace("executeBatch select");
    } else {
        fail("executeBatch");
    }
}
Also used : Statement(java.sql.Statement) CallableStatement(java.sql.CallableStatement) PreparedStatement(java.sql.PreparedStatement) BatchUpdateException(java.sql.BatchUpdateException)

Example 33 with BatchUpdateException

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

the class TestPreparedStatement method testBatchedUpdateExecution.

/**
 * Verify that the <code>executeBatch()</code> method of <code>
 * MMPreparedStatement</code> is resulting in the correct command,
 * parameter values for each command of the batch, and the request type
 * are being set in the request message that would normally be sent to the
 * server.
 *
 * @throws Exception
 */
@Test
public void testBatchedUpdateExecution() throws Exception {
    // Build up a fake connection instance for use with the prepared statement
    ConnectionImpl conn = Mockito.mock(ConnectionImpl.class);
    Mockito.stub(conn.getConnectionProps()).toReturn(new Properties());
    DQP dqp = Mockito.mock(DQP.class);
    ServerConnection serverConn = Mockito.mock(ServerConnection.class);
    LogonResult logonResult = Mockito.mock(LogonResult.class);
    // stub methods
    Mockito.stub(conn.getServerConnection()).toReturn(serverConn);
    Mockito.stub(serverConn.getLogonResult()).toReturn(logonResult);
    Mockito.stub(logonResult.getTimeZone()).toReturn(TimeZone.getDefault());
    // a dummy result message that is specific to this test case
    final ResultsFuture<ResultsMessage> results = new ResultsFuture<ResultsMessage>();
    final int[] count = new int[1];
    final ResultsMessage rm = new ResultsMessage();
    Mockito.stub(dqp.executeRequest(Matchers.anyLong(), (RequestMessage) Matchers.anyObject())).toAnswer(new Answer<ResultsFuture<ResultsMessage>>() {

        @Override
        public ResultsFuture<ResultsMessage> answer(InvocationOnMock invocation) throws Throwable {
            RequestMessage requestMessage = (RequestMessage) invocation.getArguments()[1];
            count[0] += requestMessage.getParameterValues().size();
            if (count[0] == 100000) {
                rm.setException(new TeiidException());
                rm.setResults(new List<?>[] { Arrays.asList(Statement.EXECUTE_FAILED) });
            } else {
                List<?>[] vals = new List<?>[requestMessage.getParameterValues().size()];
                Arrays.fill(vals, Arrays.asList(0));
                rm.setResults(Arrays.asList(vals));
            }
            return results;
        }
    });
    rm.setUpdateResult(true);
    results.getResultsReceiver().receiveResults(rm);
    Mockito.stub(conn.getDQP()).toReturn(dqp);
    // some update SQL
    // $NON-NLS-1$
    String sqlCommand = "delete from table where col=?";
    TestableMMPreparedStatement statement = (TestableMMPreparedStatement) getMMPreparedStatement(conn, sqlCommand);
    ArrayList<ArrayList<Object>> expectedParameterValues = new ArrayList<ArrayList<Object>>(3);
    // Add some batches and their parameter values
    expectedParameterValues.add(new ArrayList<Object>(Arrays.asList(new Object[] { new Integer(1) })));
    statement.setInt(1, new Integer(1));
    statement.addBatch();
    expectedParameterValues.add(new ArrayList<Object>(Arrays.asList(new Object[] { new Integer(2) })));
    statement.setInt(1, new Integer(2));
    statement.addBatch();
    expectedParameterValues.add(new ArrayList<Object>(Arrays.asList(new Object[] { new Integer(3) })));
    statement.setInt(1, new Integer(3));
    statement.addBatch();
    // execute the batch and verify that it matches our dummy results
    // message set earlier
    assertTrue(Arrays.equals(new int[] { 0, 0, 0 }, statement.executeBatch()));
    // Now verify the statement's RequestMessage is what we expect
    // $NON-NLS-1$
    assertEquals("Command does not match", sqlCommand, statement.requestMessage.getCommandString());
    // $NON-NLS-1$
    assertEquals("Parameter values do not match", expectedParameterValues, statement.requestMessage.getParameterValues());
    // $NON-NLS-1$
    assertTrue("RequestMessage.isBatchedUpdate should be true", statement.requestMessage.isBatchedUpdate());
    // $NON-NLS-1$
    assertFalse("RequestMessage.isCallableStatement should be false", statement.requestMessage.isCallableStatement());
    // $NON-NLS-1$
    assertTrue("RequestMessage.isPreparedStatement should be true", statement.requestMessage.isPreparedStatement());
    count[0] = 0;
    // large batch handling - should split into 5
    for (int i = 0; i < 100000; i++) {
        statement.setInt(1, new Integer(1));
        statement.addBatch();
    }
    try {
        statement.executeBatch();
        fail();
    } catch (BatchUpdateException e) {
        assertEquals(100000, count[0]);
        assertEquals(95309, e.getUpdateCounts().length);
        assertEquals(Statement.EXECUTE_FAILED, e.getUpdateCounts()[95308]);
    }
}
Also used : ResultsMessage(org.teiid.client.ResultsMessage) LogonResult(org.teiid.client.security.LogonResult) ArrayList(java.util.ArrayList) Properties(java.util.Properties) RequestMessage(org.teiid.client.RequestMessage) ArrayList(java.util.ArrayList) List(java.util.List) BatchUpdateException(java.sql.BatchUpdateException) DQP(org.teiid.client.DQP) ServerConnection(org.teiid.net.ServerConnection) TeiidException(org.teiid.core.TeiidException) ResultsFuture(org.teiid.client.util.ResultsFuture) InvocationOnMock(org.mockito.invocation.InvocationOnMock) Test(org.junit.Test)

Example 34 with BatchUpdateException

use of java.sql.BatchUpdateException in project JavaForFun by gumartinm.

the class ReuseBatchExecutor method doFlushStatements.

@Override
public List<BatchResult> doFlushStatements(boolean isRollback) throws SQLException {
    try {
        final List<BatchResult> results = new ArrayList<>();
        if (isRollback) {
            return Collections.emptyList();
        } else {
            long count = 0;
            for (Map.Entry<String, Statement> entry : statementMap.entrySet()) {
                final Statement stmt = entry.getValue();
                final String sql = entry.getKey();
                final BatchResult batchResult = batchResultMap.get(sql);
                if (batchResult != null) {
                    try {
                        batchResult.setUpdateCounts(stmt.executeBatch());
                        MappedStatement ms = batchResult.getMappedStatement();
                        List<Object> parameterObjects = batchResult.getParameterObjects();
                        KeyGenerator keyGenerator = ms.getKeyGenerator();
                        if (Jdbc3KeyGenerator.class.equals(keyGenerator.getClass())) {
                            Jdbc3KeyGenerator jdbc3KeyGenerator = (Jdbc3KeyGenerator) keyGenerator;
                            jdbc3KeyGenerator.processBatch(ms, stmt, parameterObjects);
                        } else if (!NoKeyGenerator.class.equals(keyGenerator.getClass())) {
                            // issue #141
                            for (Object parameter : parameterObjects) {
                                keyGenerator.processAfter(this, ms, stmt, parameter);
                            }
                        }
                    } catch (BatchUpdateException e) {
                        StringBuilder message = new StringBuilder();
                        message.append(batchResult.getMappedStatement().getId()).append(" (batch index #").append(count + 1).append(")").append(" failed.");
                        if (count > 0) {
                            message.append(" ").append(count).append(" prior sub executor(s) completed successfully, but will be rolled back.");
                        }
                        throw new BatchExecutorException(message.toString(), e, results, batchResult);
                    }
                    results.add(batchResult);
                }
                count = count + 1;
            }
            return results;
        }
    } finally {
        for (Statement stmt : statementMap.values()) {
            closeStatement(stmt);
        }
        statementMap.clear();
        batchResultMap.clear();
    }
}
Also used : MappedStatement(org.apache.ibatis.mapping.MappedStatement) Statement(java.sql.Statement) ArrayList(java.util.ArrayList) BatchExecutorException(org.apache.ibatis.executor.BatchExecutorException) BatchResult(org.apache.ibatis.executor.BatchResult) Jdbc3KeyGenerator(org.apache.ibatis.executor.keygen.Jdbc3KeyGenerator) MappedStatement(org.apache.ibatis.mapping.MappedStatement) HashMap(java.util.HashMap) Map(java.util.Map) NoKeyGenerator(org.apache.ibatis.executor.keygen.NoKeyGenerator) Jdbc3KeyGenerator(org.apache.ibatis.executor.keygen.Jdbc3KeyGenerator) KeyGenerator(org.apache.ibatis.executor.keygen.KeyGenerator) BatchUpdateException(java.sql.BatchUpdateException)

Example 35 with BatchUpdateException

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

the class JDBCUpdateExecution method execute.

public int[] execute(BatchedUpdates batchedCommand) throws TranslatorException {
    boolean succeeded = false;
    boolean commitType = false;
    if (batchedCommand.isSingleResult()) {
        commitType = getAutoCommit(null);
    }
    Command[] commands = batchedCommand.getUpdateCommands().toArray(new Command[batchedCommand.getUpdateCommands().size()]);
    result = new int[commands.length];
    TranslatedCommand tCommand = null;
    int batchStart = 0;
    int i = 0;
    try {
        // before at the end of the command execution.
        if (commitType) {
            connection.setAutoCommit(false);
        }
        List<TranslatedCommand> executedCmds = new ArrayList<TranslatedCommand>();
        TranslatedCommand previousCommand = null;
        for (; i < commands.length; i++) {
            tCommand = translateCommand(commands[i]);
            if (tCommand.isPrepared()) {
                PreparedStatement pstmt = null;
                if (previousCommand != null && previousCommand.isPrepared() && previousCommand.getSql().equals(tCommand.getSql())) {
                    pstmt = (PreparedStatement) statement;
                } else {
                    if (!executedCmds.isEmpty()) {
                        executeBatch(i, result, executedCmds);
                        batchStart = i;
                    }
                    pstmt = getPreparedStatement(tCommand.getSql());
                }
                bind(pstmt, tCommand.getPreparedValues(), null);
                pstmt.addBatch();
            } else {
                if (previousCommand != null && previousCommand.isPrepared()) {
                    executeBatch(i, result, executedCmds);
                    batchStart = i;
                    getStatement();
                }
                if (statement == null) {
                    getStatement();
                }
                statement.addBatch(tCommand.getSql());
            }
            executedCmds.add(tCommand);
            previousCommand = tCommand;
        }
        if (!executedCmds.isEmpty()) {
            executeBatch(commands.length, result, executedCmds);
        }
        succeeded = true;
    } catch (TranslatorException e) {
        if (batchedCommand.isSingleResult()) {
            throw e;
        }
        int size = i + 1;
        // if there is a BatchUpdateException, there are more update counts to accumulate
        if (e.getCause() instanceof BatchUpdateException) {
            BatchUpdateException bue = (BatchUpdateException) e.getCause();
            int[] batchResults = bue.getUpdateCounts();
            for (int j = 0; j < batchResults.length; j++) {
                result[batchStart + j] = batchResults[j];
            }
            size = batchStart + batchResults.length;
        } else {
            size = batchStart;
        }
        // resize the result and throw exception
        throw new TranslatorBatchException(e, Arrays.copyOf(result, size));
    } catch (SQLException e) {
        if (batchedCommand.isSingleResult()) {
            throw new JDBCExecutionException(JDBCPlugin.Event.TEIID11011, e, tCommand);
        }
        // resize the result and throw exception
        throw new TranslatorBatchException(e, Arrays.copyOf(result, batchStart));
    } finally {
        if (commitType) {
            restoreAutoCommit(!succeeded, null);
        }
    }
    return result;
}
Also used : SQLException(java.sql.SQLException) ArrayList(java.util.ArrayList) PreparedStatement(java.sql.PreparedStatement) TranslatorBatchException(org.teiid.translator.TranslatorBatchException) Command(org.teiid.language.Command) BulkCommand(org.teiid.language.BulkCommand) TranslatorException(org.teiid.translator.TranslatorException) 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