Java Code Examples for java.sql.BatchUpdateException

The following examples show how to use java.sql.BatchUpdateException. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
/**
 * 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));
}
 
Example 2
Source Project: hop   Source File: Database.java    License: Apache License 2.0 6 votes vote down vote up
public static HopDatabaseBatchException createHopDatabaseBatchException( String message, SQLException ex ) {
  HopDatabaseBatchException kdbe = new HopDatabaseBatchException( message, ex );
  if ( ex instanceof BatchUpdateException ) {
    kdbe.setUpdateCounts( ( (BatchUpdateException) ex ).getUpdateCounts() );
  } else {
    // Null update count forces rollback of batch
    kdbe.setUpdateCounts( null );
  }
  List<Exception> exceptions = new ArrayList<>();
  SQLException nextException = ex.getNextException();
  SQLException oldException = null;

  // This construction is specifically done for some JDBC drivers, these
  // drivers
  // always return the same exception on getNextException() (and thus go
  // into an infinite loop).
  // So it's not "equals" but != (comments from Sven Boden).
  while ( ( nextException != null ) && ( oldException != nextException ) ) {
    exceptions.add( nextException );
    oldException = nextException;
    nextException = nextException.getNextException();
  }
  kdbe.setExceptionsList( exceptions );
  return kdbe;
}
 
Example 3
protected void addWorkContentRelationsRecord(Content content, Connection conn) throws ApsSystemException {
	PreparedStatement stat = null;
	try {
		stat = conn.prepareStatement(ADD_WORK_CONTENT_REL_RECORD);
		this.addCategoryRelationsRecord(content, false, stat);
		stat.executeBatch();
	} catch (BatchUpdateException e) {
		_logger.error("Error saving record into workcontentrelations {}", content.getId(), e.getNextException());
		throw new RuntimeException("Error saving record into workcontentrelations " + content.getId(), e);
	} catch (Throwable t) {
		_logger.error("Error saving record into workcontentrelations {}", content.getId(), t);
		throw new RuntimeException("Error saving record into workcontentrelations " + content.getId(), t);
	} finally {
		closeDaoResources(null, stat);
	}
}
 
Example 4
Source Project: ignite   Source File: JdbcThinBulkLoadSelfTest.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Verifies exception thrown if COPY is added into a packet.
 *
 * @throws SQLException If failed.
 */
@Test
public void testMultipleStatement() throws SQLException {
    GridTestUtils.assertThrows(log, new Callable<Object>() {
        @Override public Object call() throws Exception {
            stmt.addBatch(BASIC_SQL_COPY_STMT);

            stmt.addBatch("copy from '" + BULKLOAD_ONE_LINE_CSV_FILE + "' into " + TBL_NAME +
                " (_key, age, firstName, lastName)" +
                " format csv");

            stmt.addBatch("copy from '" + BULKLOAD_UTF8_CSV_FILE + "' into " + TBL_NAME +
                " (_key, age, firstName, lastName)" +
                " format csv");

            stmt.executeBatch();

            return null;
        }
    }, BatchUpdateException.class, "COPY command cannot be executed in batch mode.");
}
 
Example 5
private static void testDiffError(JdbcTemplate jdbcTemplate) {
  String[] sqls = {
      "delete from test_0.types_bak where id = 2125",
      "delete from test_0.types_bak where id = 2122",
      "insert into `test_0`.`types_bak` (`double`,`varchar`,`char`,`tinyint`,`id`,`text`,`decimal`,`bigint`,`timestamp`) values (0.6055158,'D5v','k',26,2125,'/>$Kf',19265911.19,1366022492355224397,'2017-12-01 22:30:24.0')",
      "insert into `test_0`.`types_bak` (`double`,`varchar`,`char`,`tinyint`,`id`,`text`,`decimal`,`bigint`,`timestamp`) values (0.6055158,'D5v','k',26,2125,'/>$Kf',19265911.19,1366022492355224397,'2017-12-01 22:30:24.0')",
      "insert into `test_0`.`types_bak` (`double`,`varchar`,`char`,`tinyint`,`id`,`text`,`decimal`,`bigint`,`timestamp`) values (0.47148514,'v[e|','6P{N(hb=8C6!t5oAfLv2',161,2122,'Qria3&&V',19265911.19,3128612873388751949,'2005-06-07 08:46:12.0')",
      "insert into `test_0`.`not_exists` (`double`) VALUES (1)",
      };
  try {
    jdbcTemplate.batchUpdate(sqls);
  } catch (DataAccessException e) {
    int[] updateCounts = ((BatchUpdateException) e.getCause()).getUpdateCounts();
    System.out.println(Arrays.toString(updateCounts));
    e.printStackTrace();
  }
}
 
Example 6
/**
 * 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));
}
 
Example 7
/**
 * 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();
    }
}
 
Example 8
Source Project: gemfirexd-oss   Source File: BatchUpdateTest.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 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);
    }
}
 
Example 9
private DataAccessException doTranslate(Throwable sourceThrowable, SQLException sqlException) {
  SQLException relevantSqlException;
  if (sqlException instanceof BatchUpdateException) {
    relevantSqlException = sqlException.getNextException();
  } else {
    relevantSqlException = sqlException;
  }

  DataAccessException translatedException;
  if (relevantSqlException instanceof PSQLException) {
    translatedException = doTranslate(sourceThrowable, (PSQLException) relevantSqlException);
  } else {
    translatedException = null;
  }
  return translatedException;
}
 
Example 10
Source Project: Komondor   Source File: StatementImpl.java    License: GNU General Public License v3.0 6 votes vote down vote up
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());
}
 
Example 11
Source Project: FoxTelem   Source File: StatementImpl.java    License: GNU General Public License v3.0 6 votes vote down vote up
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());
}
 
Example 12
/**
 * 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));
}
 
Example 13
private void addContentReports(NewsletterReport newsletterReport, Connection conn) {
	PreparedStatement stat = null;
	try {
		stat = conn.prepareStatement(ADD_CONTENT_REPORT);
		int reportId = newsletterReport.getId();
		for (ContentReport contentReport : newsletterReport.getContentReports().values()) {
			stat.setInt(1, contentReport.getId());
			stat.setInt(2, reportId);
			stat.setString(3, contentReport.getContentId());
			stat.setString(4, contentReport.getTextBody());
			stat.setString(5, contentReport.getHtmlBody());
			stat.addBatch();
			stat.clearParameters();
		}
		stat.executeBatch();
	} catch (BatchUpdateException e) {
		this.processDaoException(e.getNextException(), "Error adding contents for sent newsletter", 
				"addContentReports");
	} catch (Throwable t) {
		this.processDaoException(t, "Error adding contents for sent newsletter", "addContentReports");
	} finally {
		closeDaoResources(null, stat);
	}
}
 
Example 14
Source Project: ignite   Source File: OdbcRequestHandler.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Extract batching error from general exception.
 * @param e Exception
 * @param rowsAffected List containing the number of affected rows for every query in batch.
 * @param err Error tuple containing error code and error message.
 */
private static void extractBatchError(Exception e, List<Long> rowsAffected, IgniteBiTuple<Integer, String> err) {
    if (e instanceof IgniteSQLException) {
        BatchUpdateException batchCause = X.cause(e, BatchUpdateException.class);

        if (batchCause != null) {
            if (rowsAffected != null) {
                for (long cnt : batchCause.getLargeUpdateCounts())
                    rowsAffected.add(cnt);
            }

            err.set(batchCause.getErrorCode(), batchCause.getMessage());
        }
        else
            err.set(((IgniteSQLException)e).statusCode(), OdbcUtils.tryRetrieveH2ErrorMessage(e));
    }
    else
        err.set(IgniteQueryErrorCode.UNKNOWN, e.getMessage());
}
 
Example 15
/**
 * Add a record in the table 'dataobjectrelations' for every resource, page,
 * other dataobject, role and category associated to the given dataobject).
 *
 * @param dataobject The current dataobject.
 * @param conn The connection to the database.
 * @throws ApsSystemException when connection error are detected.
 */
protected void addDataObjectRelationsRecord(DataObject dataobject, Connection conn) throws ApsSystemException {
    PreparedStatement stat = null;
    try {
        stat = conn.prepareStatement(ADD_DATAOBJECT_REL_RECORD);
        this.addCategoryRelationsRecord(dataobject, true, stat);
        this.addGroupRelationsRecord(dataobject, stat);
        EntityAttributeIterator attributeIter = new EntityAttributeIterator(dataobject);
        while (attributeIter.hasNext()) {
            AttributeInterface currAttribute = (AttributeInterface) attributeIter.next();
        }
        stat.executeBatch();
    } catch (BatchUpdateException e) {
        _logger.error("Error saving record into dataobjectrelations {}", dataobject.getId(), e.getNextException());
        throw new RuntimeException("Error saving record into dataobjectrelations " + dataobject.getId(), e.getNextException());
    } catch (Throwable t) {
        _logger.error("Error saving record into dataobjectrelations {}", dataobject.getId(), t);
        throw new RuntimeException("Error saving record into dataobjectrelations " + dataobject.getId(), t);
    } finally {
        closeDaoResources(null, stat);
    }
}
 
Example 16
/**
 * 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();
    }
}
 
Example 17
Source Project: spring4-understanding   Source File: JdbcTemplateTests.java    License: Apache License 2.0 6 votes vote down vote up
@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"));
	}
}
 
Example 18
/**
 * 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));
}
 
Example 19
Source Project: crate   Source File: PostgresITest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void test_numeric_types_arrays() throws Exception {
    try (Connection conn = DriverManager.getConnection(url(RW), properties)) {
        conn.createStatement().executeUpdate(
            "CREATE TABLE t (" +
            "   ints array(int)," +
            "   floats array(float)" +
            ") " +
            "WITH (number_of_replicas = 0)");

        PreparedStatement preparedStatement = conn.prepareStatement(
            "INSERT INTO t (ints, floats) VALUES (?, ?)");
        preparedStatement.setArray(1, conn.createArrayOf("int4", new Integer[]{10, 20}));
        preparedStatement.setArray(2, conn.createArrayOf("float4", new Float[]{1.2f, 3.5f}));
        preparedStatement.executeUpdate();
        conn.createStatement().execute("REFRESH TABLE t");

        ResultSet rs = conn.createStatement().executeQuery("SELECT ints, floats FROM t");
        assertThat(rs.next(), is(true));
        assertThat(rs.getArray(1).getArray(), is(new Integer[]{10, 20}));
        assertThat(rs.getArray(2).getArray(), is(new Float[]{1.2f, 3.5f}));
    } catch (BatchUpdateException e) {
        throw e.getNextException();
    }
}
 
Example 20
/**
 * 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();
    }
}
 
Example 21
/**
 *
 */
@Test
public void testErrorNestedTxAutocommitOffBatched() {
    GridTestUtils.assertThrows(null, new Callable<Void>() {
        @Override public Void call() throws Exception {
            try (Connection c = c(false, NestedTxMode.ERROR)) {
                doNestedTxStart(c, true);
            }

            throw new AssertionError();
        }
    }, BatchUpdateException.class, "Transaction has already been started.");
}
 
Example 22
/**
 * Create BatchUpdateException with message, SQLState, errorCode code
 * Throwable, and long [] update counts
 */
@Test
public void test9() {
    BatchUpdateException ex = new BatchUpdateException(reason, state, errorCode,
            luc, t);
    assertTrue(ex.getMessage().equals(reason)
            && ex.getSQLState().equals(state)
            && cause.equals(ex.getCause().toString())
            && ex.getErrorCode() == errorCode
            && Arrays.equals(ex.getUpdateCounts(), uc)
            && Arrays.equals(ex.getLargeUpdateCounts(), luc)
    );
}
 
Example 23
/**
 * Create BatchUpdateException and setting all objects to null
 */
@Test
public void test() {
    BatchUpdateException be = new BatchUpdateException(null,
            null, errorCode, (int[]) null, null);
    assertTrue(be.getMessage() == null && be.getSQLState() == null
            && be.getUpdateCounts() == null && be.getCause() == null
            && be.getLargeUpdateCounts() == null
            && be.getErrorCode() == errorCode);
}
 
Example 24
/**
 * Create BatchUpdateException with no-arg constructor
 */
@Test
public void test1() {
    BatchUpdateException ex = new BatchUpdateException();
    assertTrue(ex.getMessage() == null
            && ex.getSQLState() == null
            && ex.getCause() == null
            && ex.getErrorCode() == 0
            && ex.getUpdateCounts() == null
            && ex.getLargeUpdateCounts() == null);
}
 
Example 25
public void testBatchExceptionTranslation() {
	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);
	assertEquals("SQL", bsgex.getSql());
	assertEquals(badSqlEx, bsgex.getSQLException());
}
 
Example 26
@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);
	assertEquals("SQL", bsgex.getSql());
	assertEquals(badSqlEx, bsgex.getSQLException());
}
 
Example 27
Source Project: entando-core   Source File: I18nDAO.java    License: GNU Lesser General Public License v3.0 5 votes vote down vote up
private void addLabelGroup(String key, ApsProperties labels, Connection conn) throws ApsSystemException {
	PreparedStatement stat = null;
	try {
		stat = conn.prepareStatement(ADD_LABEL);
		Iterator<Object> labelKeysIter = labels.keySet().iterator();
		while (labelKeysIter.hasNext()) {
			String labelLangCode = (String) labelKeysIter.next();
			String label = labels.getProperty(labelLangCode);
			stat.setString(1, key);
			stat.setString(2, labelLangCode);
			stat.setString(3, label);
			stat.addBatch();
			stat.clearParameters();
		}
		stat.executeBatch();
	} catch (BatchUpdateException e) {
		_logger.error("Error adding a new label record",  e.getNextException());
		throw new RuntimeException("Error adding a new label record", e.getNextException());
		//processDaoException(e.getNextException(), "Error adding a new label record", "addLabel");
	} catch (Throwable t) {
		_logger.error("Error while adding a new label",  t);
		throw new RuntimeException("Error while adding a new label", t);
		//processDaoException(t, "Error while adding a new label", "addLabel");
	} finally {
		closeDaoResources(null, stat);
	}
}
 
Example 28
Source Project: core-ng-project   Source File: UncheckedSQLExceptionTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
void errorType() {
    var exception = new UncheckedSQLException(new SQLException("connection abort", "08S01", 1152));
    assertThat(exception.errorType).isEqualTo(UncheckedSQLException.ErrorType.CONNECTION_ERROR);

    // mimic exception case of mysql, refer to com.mysql.cj.jdbc.exceptions.SQLError.createBatchUpdateException
    var cause = new SQLIntegrityConstraintViolationException("Duplicate entry", "23000", 1062);
    exception = new UncheckedSQLException(new BatchUpdateException(cause.getMessage(), cause.getSQLState(), cause.getErrorCode(), new int[0], cause));
    assertThat(exception.errorType).isEqualTo(UncheckedSQLException.ErrorType.INTEGRITY_CONSTRAINT_VIOLATION);
}
 
Example 29
/**
 * Create BatchUpdateException with message, SQLState, Throwable, and update
 * counts
 */
@Test
public void test7() {
    BatchUpdateException ex = new BatchUpdateException(reason, state, uc, t);
    assertTrue(ex.getMessage().equals(reason)
            && ex.getSQLState().equals(state)
            && cause.equals(ex.getCause().toString())
            && ex.getErrorCode() == 0
            && Arrays.equals(ex.getUpdateCounts(), uc)
            && Arrays.equals(ex.getLargeUpdateCounts(), luc)
    );
}
 
Example 30
Source Project: dal   Source File: DalCommandTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testFourLayerExceptionTransaction() throws Exception {
    DalClient client = DalClientFactory.getClient(dbName);
    try {
        client.execute(new TwoLayerExceptionDalCommand(), new DalHints());
        Assert.fail();
    } catch (Throwable e) {
        System.out.println(e.getMessage());
        Assert.assertTrue(e instanceof BatchUpdateException);
        Assert.assertTrue(e.getMessage().equals("Data truncation: Data too long for column 'Name' at row 1"));
        Assert.assertTrue(isCurrentTransactionNull());
    }
}