protected SQLException handleExceptionForBatch(int endOfBatchIndex, int numValuesPerBatch, long[] updateCounts, SQLException ex) throws BatchUpdateException, SQLException { for (int j = endOfBatchIndex; j > endOfBatchIndex - numValuesPerBatch; j--) { updateCounts[j] = EXECUTE_FAILED; } if (this.continueBatchOnError && !(ex instanceof MySQLTimeoutException) && !(ex instanceof MySQLStatementCancelledException) && !hasDeadlockOrTimeoutRolledBackTx(ex)) { return ex; } // else: throw the exception immediately long[] newUpdateCounts = new long[endOfBatchIndex]; System.arraycopy(updateCounts, 0, newUpdateCounts, 0, endOfBatchIndex); throw SQLError.createBatchUpdateException(ex, newUpdateCounts, getExceptionInterceptor()); }
/** * De-Serialize a BatchUpdateException from JDBC 4.0 and make sure you can * read it back properly */ @Test public void test13() throws Exception { String reason1 = "This was the error msg"; String state1 = "user defined sqlState"; String cause1 = "java.lang.Throwable: throw 1"; int errorCode1 = 99999; Throwable t = new Throwable("throw 1"); int[] uc1 = {1, 2, 21}; long[] luc1 = {1, 2, 21}; ObjectInputStream ois = new ObjectInputStream( new ByteArrayInputStream(SerializedBatchUpdateException.DATA)); BatchUpdateException bue = (BatchUpdateException) ois.readObject(); assertTrue(reason1.equals(bue.getMessage()) && bue.getSQLState().equals(state1) && bue.getErrorCode() == errorCode1 && cause1.equals(bue.getCause().toString()) && Arrays.equals(bue.getLargeUpdateCounts(), luc1) && Arrays.equals(bue.getUpdateCounts(), uc1)); }
/** * Serialize a BatchUpdateException with an Integer.MAX_VALUE + 1 and * validate you can read it back properly */ @Test public void test14() throws Exception { int[] uc1 = {Integer.MAX_VALUE, Integer.MAX_VALUE + 1}; long[] luc1 = {Integer.MAX_VALUE, Integer.MAX_VALUE + 1}; BatchUpdateException be = new BatchUpdateException(reason, state, errorCode, luc1, t); BatchUpdateException bue = createSerializedException(be); assertTrue(reason.equals(bue.getMessage()) && bue.getSQLState().equals(state) && cause.equals(bue.getCause().toString()) && bue.getErrorCode() == errorCode && Arrays.equals(bue.getLargeUpdateCounts(), luc1) && Arrays.equals(bue.getUpdateCounts(), uc1)); }
/** * Validate that the ordering of the returned Exceptions is correct * using traditional while loop */ @Test public void test16() { BatchUpdateException ex = new BatchUpdateException("Exception 1", uc, t1); BatchUpdateException ex1 = new BatchUpdateException("Exception 2", uc); BatchUpdateException ex2 = new BatchUpdateException("Exception 3", uc, t2); ex.setNextException(ex1); ex.setNextException(ex2); SQLException sqe = ex; int num = 0; while (sqe != null) { assertTrue(msgs[num++].equals(sqe.getMessage())); Throwable c = sqe.getCause(); while (c != null) { assertTrue(msgs[num++].equals(c.getMessage())); c = c.getCause(); } sqe = sqe.getNextException(); } }
private void testException() throws SQLException { deleteDb("batchUpdates"); conn = getConnection("batchUpdates"); stat = conn.createStatement(); stat.execute("create table test(id int primary key)"); prep = conn.prepareStatement("insert into test values(?)"); for (int i = 0; i < 700; i++) { prep.setString(1, "x"); prep.addBatch(); } try { prep.executeBatch(); } catch (BatchUpdateException e) { PrintStream temp = System.err; try { ByteArrayOutputStream buff = new ByteArrayOutputStream(); PrintStream p = new PrintStream(buff); System.setErr(p); e.printStackTrace(); } finally { System.setErr(temp); } } conn.close(); }
private void testExecuteBatch03() throws SQLException { trace("testExecuteBatch03"); boolean batchExceptionFlag = false; String sPrepStmt = COFFEE_SELECT; trace("Prepared Statement String :" + sPrepStmt); prep = conn.prepareStatement(sPrepStmt); prep.setInt(1, 1); prep.addBatch(); try { int[] updateCount = prep.executeBatch(); trace("Update Count" + updateCount.length); } catch (BatchUpdateException b) { batchExceptionFlag = true; } if (batchExceptionFlag) { trace("select not allowed; correct"); } else { fail("executeBatch select"); } }
private void testExecuteBatch06() throws SQLException { trace("testExecuteBatch06"); boolean batchExceptionFlag = false; // Insert a row which is already Present String sInsCoffee = COFFEE_INSERT1; String sDelCoffee = COFFEE_DELETE1; stat.addBatch(sInsCoffee); stat.addBatch(sInsCoffee); stat.addBatch(sDelCoffee); try { stat.executeBatch(); } catch (BatchUpdateException b) { batchExceptionFlag = true; for (int uc : b.getUpdateCounts()) { trace("Update counts:" + uc); } } if (batchExceptionFlag) { trace("executeBatch insert duplicate; correct"); } else { fail("executeBatch"); } }
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"); } }
private void printIfBad(int seed, int id, int objectId, Throwable t) { if (t instanceof BatchUpdateException) { // do nothing } else if (t.getClass().getName().contains("SQLClientInfoException")) { // do nothing } else if (t instanceof SQLException) { SQLException s = (SQLException) t; int errorCode = s.getErrorCode(); if (errorCode == 0) { printError(seed, id, s); } else if (errorCode == ErrorCode.OBJECT_CLOSED) { if (objectId >= 0 && objects.size() > 0) { // TODO at least call a few more times after close - maybe // there is still an error objects.remove(objectId); } } else if (errorCode == ErrorCode.GENERAL_ERROR_1) { // General error [HY000] printError(seed, id, s); } } else { printError(seed, id, t); } }
@Test public void testBatchUpdateWithBatchFailure() throws Exception { final String[] sql = {"A", "B", "C", "D"}; given(this.statement.executeBatch()).willThrow( new BatchUpdateException(new int[] { 1, Statement.EXECUTE_FAILED, 1, Statement.EXECUTE_FAILED })); mockDatabaseMetaData(true); given(this.connection.createStatement()).willReturn(this.statement); JdbcTemplate template = new JdbcTemplate(this.dataSource, false); try { template.batchUpdate(sql); } catch (UncategorizedSQLException ex) { assertThat(ex.getSql(), equalTo("B; D")); } }
/** * helper method to evaluate negative tests where we expect a * batchExecuteException to be returned. * @exception SQLException Thrown if the expected error occurs * We expect a BatchUpdateException, and * verify it is so. * * @param expectedError The sqlstate to look for. * @param stmt The Statement that contains the Batch to * be executed. * @param expectedUpdateCount The expectedUpdateCount array. */ protected void assertBatchExecuteError( String expectedError, Statement stmt, int[] expectedUpdateCount) throws SQLException { int[] updateCount; try { updateCount = stmt.executeBatch(); fail("Expected batchExecute to fail"); } catch (BatchUpdateException bue) { assertSQLState(expectedError, bue); updateCount = bue.getUpdateCounts(); assertBatchUpdateCounts(expectedUpdateCount, updateCount); } }
/** * Creates an error xml result String using the information from the passed in Throwable. * * @param t * the Throwable used to set the error message * @return the xml error String, e.g. <error><message>An error occurred</message></error> */ public String createErrorXML(Throwable t) { Throwable x = t; final StringBuilder sb = new StringBuilder(t.getMessage()); // prevent infinite cycling while (x.getCause() != null || (x instanceof BatchUpdateException && ((BatchUpdateException) x).getNextException() != null)) { final Throwable prevX = x; if (x instanceof BatchUpdateException) { x = ((BatchUpdateException) x).getNextException(); } else { x = x.getCause(); } if (x == prevX) { break; } sb.append("\nCaused by: " + x.getMessage()); } return "<ob:error xmlns:ob=\"" + XMLConstants.OPENBRAVO_NAMESPACE + "\"><message>" + sb + "</message></ob:error>"; }
protected SQLException handleExceptionForBatch(int endOfBatchIndex, int numValuesPerBatch, int[] updateCounts, SQLException ex) throws BatchUpdateException { SQLException sqlEx; for (int j = endOfBatchIndex; j > endOfBatchIndex - numValuesPerBatch; j--) { updateCounts[j] = EXECUTE_FAILED; } if (this.continueBatchOnError && !(ex instanceof MySQLTimeoutException) && !(ex instanceof MySQLStatementCancelledException) && !hasDeadlockOrTimeoutRolledBackTx(ex)) { sqlEx = ex; } else { int[] newUpdateCounts = new int[endOfBatchIndex]; System.arraycopy(updateCounts, 0, newUpdateCounts, 0, endOfBatchIndex); BatchUpdateException batchException = new BatchUpdateException(ex.getMessage(), ex.getSQLState(), ex.getErrorCode(), newUpdateCounts); batchException.initCause(ex); throw batchException; } return sqlEx; }
protected void processBatch() { logger.debug("start {} end {}", batchStartIdx, tuples.size()); try { for (int i = batchStartIdx; i < tuples.size(); i++) { setStatementParameters(updateCommand, tuples.get(i)); updateCommand.addBatch(); } updateCommand.executeBatch(); updateCommand.clearBatch(); batchStartIdx += tuples.size() - batchStartIdx; } catch (BatchUpdateException bue) { logger.error(bue.getMessage()); processUpdateCounts(bue.getUpdateCounts(), tuples.size() - batchStartIdx); } catch (SQLException e) { throw new RuntimeException("processing batch", e); } }
@Override protected void processBatch() { logger.debug("start {} end {}", batchStartIdx, tuples.size()); try { for (int i = batchStartIdx; i < tuples.size(); i++) { String copyStmt = generateCopyStatement(tuples.get(i)); stmt.addBatch(copyStmt); } stmt.executeBatch(); stmt.clearBatch(); batchStartIdx += tuples.size() - batchStartIdx; } catch (BatchUpdateException bue) { logger.error(bue.getMessage()); processUpdateCounts(bue.getUpdateCounts(), tuples.size() - batchStartIdx); } catch (SQLException e) { throw new RuntimeException("processing batch", e); } }
/** * Test error code for the case when error is caused on batch execution. * @throws SQLException if failed. */ @SuppressWarnings("MagicConstant") 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()); } } }
/** * @throws SQLException if failed. */ public void testSingleItemBatchError() throws SQLException { formBatch(1, 2); prepStmt.executeBatch(); formBatch(1, 2); // Duplicate key BatchUpdateException reason = (BatchUpdateException) GridTestUtils.assertThrows(log, new Callable<Object>() { @Override public Object call() throws Exception { return prepStmt.executeBatch(); } }, BatchUpdateException.class, "Failed to INSERT some keys because they are already in cache"); // Check update counts in the exception. assertTrue(F.isEmpty(reason.getUpdateCounts())); }
/** * @throws SQLException if failed. */ public void testErrorAmidstBatch() throws SQLException { formBatch(1, 2); formBatch(3, 1); // Duplicate key BatchUpdateException reason = (BatchUpdateException) GridTestUtils.assertThrows(log, new Callable<Object>() { @Override public Object call() throws Exception { return prepStmt.executeBatch(); } }, BatchUpdateException.class, "Failed to INSERT some keys because they are already in cache"); // Check update counts in the exception. int[] counts = reason.getUpdateCounts(); assertNotNull(counts); assertEquals(1, counts.length); assertEquals(2, counts[0]); }
/** {@inheritDoc} */ @Override public int[] executeBatch() throws SQLException { ensureNotClosed(); closeResults(); if (batch == null || batch.isEmpty()) throw new SQLException("Batch is empty."); try { JdbcBatchExecuteResult res = conn.sendRequest(new JdbcBatchExecuteRequest(conn.getSchema(), batch)); if (res.errorCode() != ClientListenerResponse.STATUS_SUCCESS) { throw new BatchUpdateException(res.errorMessage(), IgniteQueryErrorCode.codeToSqlState(res.errorCode()), res.errorCode(), res.updateCounts()); } return res.updateCounts(); } finally { batch = null; } }
/** * Gets the exception message. * * @param e * the e * @return the exception message */ public void getExceptionMessage(UserMessages uem, Exception e,String errorCode ) { Throwable throwable = e; if (throwable.getCause() != null) { throwable = throwable.getCause(); } String title = ResourceBundleHelper.getString("error.code." + errorCode); if(AppUtils.isNotBlank(title)){ uem.setTitle(title); }else{ String errCode = null; if ((throwable instanceof ConstraintViolationException) || (throwable instanceof BatchUpdateException) || (throwable instanceof DataIntegrityViolationException)) { errCode = ErrorCodes.RESOURCE_CONFLICT; }else if (throwable instanceof NullPointerException) { errCode = ErrorCodes.ENTITY_NO_FOUND; } uem.setTitle(ResourceBundleHelper.getString("error.code." + errCode)); } uem.setDesc(throwable.getMessage()); }
public static void insertDemocracitConsultationMinister(TreeMap<Integer, String> consultationCountersign, TreeMap<Integer, String> consultationCounterrole) throws SQLException { try { String sql = "INSERT INTO consultations_ner " + "(id,countersigned_name, countersigned_position) VALUES " + "(?,?,?)"; PreparedStatement prepStatement = connection.prepareStatement(sql); for (int consId : consultationCountersign.keySet()) { prepStatement.setInt(1, consId); prepStatement.setString(2, consultationCountersign.get(consId)); if(consultationCounterrole.get(consId)!=null){ prepStatement.setString(3, consultationCounterrole.get(consId)); }else{ prepStatement.setString(3, ""); } prepStatement.addBatch(); } prepStatement.executeBatch(); prepStatement.close(); } catch (BatchUpdateException ex) { // ex.printStackTrace(); System.out.println(ex.getNextException()); } }