Java Code Examples for org.springframework.jdbc.BadSqlGrammarException

The following examples show how to use org.springframework.jdbc.BadSqlGrammarException. 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
@Test
@SuppressWarnings("resource")
public void customErrorCodeTranslation() {
	new ClassPathXmlApplicationContext("test-custom-translators-context.xml",
			CustomSQLExceptionTranslatorRegistrarTests.class);

	SQLErrorCodes codes = SQLErrorCodesFactory.getInstance().getErrorCodes("H2");
	SQLErrorCodeSQLExceptionTranslator sext = new SQLErrorCodeSQLExceptionTranslator();
	sext.setSqlErrorCodes(codes);

	DataAccessException exFor4200 = sext.doTranslate("", "", new SQLException("Ouch", "42000", 42000));
	assertNotNull("Should have been translated", exFor4200);
	assertTrue("Should have been instance of BadSqlGrammarException",
		BadSqlGrammarException.class.isAssignableFrom(exFor4200.getClass()));

	DataAccessException exFor2 = sext.doTranslate("", "", new SQLException("Ouch", "42000", 2));
	assertNotNull("Should have been translated", exFor2);
	assertTrue("Should have been instance of TransientDataAccessResourceException",
		TransientDataAccessResourceException.class.isAssignableFrom(exFor2.getClass()));

	DataAccessException exFor3 = sext.doTranslate("", "", new SQLException("Ouch", "42000", 3));
	assertNull("Should not have been translated", exFor3);
}
 
Example 2
Source Project: effectivejava   Source File: SimpleJdbcCallTests.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testNoSuchStoredProcedure() throws Exception {
	final String NO_SUCH_PROC = "x";
	SQLException sqlException = new SQLException("Syntax error or access violation exception", "42000");
	given(databaseMetaData.getDatabaseProductName()).willReturn("MyDB");
	given(databaseMetaData.getDatabaseProductName()).willReturn("MyDB");
	given(databaseMetaData.getUserName()).willReturn("me");
	given(databaseMetaData.storesLowerCaseIdentifiers()).willReturn(true);
	given(callableStatement.execute()).willThrow(sqlException);
	given(connection.prepareCall("{call " + NO_SUCH_PROC + "()}")).willReturn(callableStatement);
	SimpleJdbcCall sproc = new SimpleJdbcCall(dataSource).withProcedureName(NO_SUCH_PROC);
	thrown.expect(BadSqlGrammarException.class);
	thrown.expect(exceptionCause(sameInstance(sqlException)));
	try {
		sproc.execute();
	}
	finally {
		verify(callableStatement).close();
		verify(connection, atLeastOnce()).close();
	}
}
 
Example 3
@Test
public void createAndDestroy() throws Exception {
	ClassPathXmlApplicationContext context = context("jdbc-destroy-config.xml");
	try {
		DataSource dataSource = context.getBean(DataSource.class);
		JdbcTemplate template = new JdbcTemplate(dataSource);
		assertNumRowsInTestTable(template, 1);
		context.getBean(DataSourceInitializer.class).destroy();
		// Table has been dropped
		assertThatExceptionOfType(BadSqlGrammarException.class).isThrownBy(() ->
				assertNumRowsInTestTable(template, 1));
	}
	finally {
		context.close();
	}
}
 
Example 4
@Test
public void createAndDestroyNestedWithHsql() throws Exception {
	ClassPathXmlApplicationContext context = context("jdbc-destroy-nested-config.xml");
	try {
		DataSource dataSource = context.getBean(DataSource.class);
		JdbcTemplate template = new JdbcTemplate(dataSource);
		assertNumRowsInTestTable(template, 1);
		context.getBean(EmbeddedDatabaseFactoryBean.class).destroy();
		// Table has been dropped
		assertThatExceptionOfType(BadSqlGrammarException.class).isThrownBy(() ->
				assertNumRowsInTestTable(template, 1));
	}
	finally {
		context.close();
	}
}
 
Example 5
@Test
public void createAndDestroyNestedWithH2() throws Exception {
	ClassPathXmlApplicationContext context = context("jdbc-destroy-nested-config-h2.xml");
	try {
		DataSource dataSource = context.getBean(DataSource.class);
		JdbcTemplate template = new JdbcTemplate(dataSource);
		assertNumRowsInTestTable(template, 1);
		context.getBean(EmbeddedDatabaseFactoryBean.class).destroy();
		 // Table has been dropped
		assertThatExceptionOfType(BadSqlGrammarException.class).isThrownBy(() ->
				assertNumRowsInTestTable(template, 1));
	}
	finally {
		context.close();
	}
}
 
Example 6
Source Project: spring-analysis-note   Source File: JdbcTemplateTests.java    License: MIT License 6 votes vote down vote up
@Test
public void testSQLErrorCodeTranslation() throws Exception {
	final SQLException sqlException = new SQLException("I have a known problem", "99999", 1054);
	final String sql = "SELECT ID FROM CUSTOMER";

	given(this.resultSet.next()).willReturn(true);
	mockDatabaseMetaData(false);
	given(this.connection.createStatement()).willReturn(this.preparedStatement);

	assertThatExceptionOfType(BadSqlGrammarException.class).isThrownBy(() ->
			this.template.query(sql, (RowCallbackHandler) rs -> {
				throw sqlException;
			}))
		.withCause(sqlException);
	verify(this.resultSet).close();
	verify(this.preparedStatement).close();
	verify(this.connection, atLeastOnce()).close();
}
 
Example 7
Source Project: spring-analysis-note   Source File: JdbcTemplateTests.java    License: MIT License 6 votes vote down vote up
@Test
public void testSQLErrorCodeTranslationWithSpecifiedDbName() throws Exception {
	final SQLException sqlException = new SQLException("I have a known problem", "99999", 1054);
	final String sql = "SELECT ID FROM CUSTOMER";

	given(this.resultSet.next()).willReturn(true);
	given(this.connection.createStatement()).willReturn(this.preparedStatement);

	JdbcTemplate template = new JdbcTemplate();
	template.setDataSource(this.dataSource);
	template.setDatabaseProductName("MySQL");
	template.afterPropertiesSet();

	assertThatExceptionOfType(BadSqlGrammarException.class).isThrownBy(() ->
			template.query(sql, (RowCallbackHandler) rs -> {
				throw sqlException;
			}))
		.withCause(sqlException);
	verify(this.resultSet).close();
	verify(this.preparedStatement).close();
	verify(this.connection).close();
}
 
Example 8
Source Project: spring-analysis-note   Source File: JdbcTemplateTests.java    License: MIT License 6 votes vote down vote up
/**
 * Test that we see an SQLException translated using Error Code.
 * If we provide the SQLExceptionTranslator, we shouldn't use a connection
 * to get the metadata
 */
@Test
public void testUseCustomSQLErrorCodeTranslator() throws Exception {
	// Bad SQL state
	final SQLException sqlException = new SQLException("I have a known problem", "07000", 1054);
	final String sql = "SELECT ID FROM CUSTOMER";

	given(this.resultSet.next()).willReturn(true);
	given(this.connection.createStatement()).willReturn(this.preparedStatement);

	JdbcTemplate template = new JdbcTemplate();
	template.setDataSource(this.dataSource);
	// Set custom exception translator
	template.setExceptionTranslator(new SQLStateSQLExceptionTranslator());
	template.afterPropertiesSet();

	assertThatExceptionOfType(BadSqlGrammarException.class).isThrownBy(() ->
			template.query(sql, (RowCallbackHandler) rs -> {
				throw sqlException;
			}))
		.withCause(sqlException);
	verify(this.resultSet).close();
	verify(this.preparedStatement).close();
	verify(this.connection).close();
}
 
Example 9
Source Project: spring-analysis-note   Source File: SimpleJdbcCallTests.java    License: MIT License 6 votes vote down vote up
@Test
public void testNoSuchStoredProcedure() throws Exception {
	final String NO_SUCH_PROC = "x";
	SQLException sqlException = new SQLException("Syntax error or access violation exception", "42000");
	given(databaseMetaData.getDatabaseProductName()).willReturn("MyDB");
	given(databaseMetaData.getDatabaseProductName()).willReturn("MyDB");
	given(databaseMetaData.getUserName()).willReturn("me");
	given(databaseMetaData.storesLowerCaseIdentifiers()).willReturn(true);
	given(callableStatement.execute()).willThrow(sqlException);
	given(connection.prepareCall("{call " + NO_SUCH_PROC + "()}")).willReturn(callableStatement);
	SimpleJdbcCall sproc = new SimpleJdbcCall(dataSource).withProcedureName(NO_SUCH_PROC);
	try {
		assertThatExceptionOfType(BadSqlGrammarException.class).isThrownBy(() ->
				sproc.execute())
			.withCause(sqlException);
	}
	finally {
		verify(callableStatement).close();
		verify(connection, atLeastOnce()).close();
	}
}
 
Example 10
Source Project: effectivejava   Source File: JdbcTemplateTests.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testSQLErrorCodeTranslation() throws Exception {
	final SQLException sqlException = new SQLException("I have a known problem", "99999", 1054);
	final String sql = "SELECT ID FROM CUSTOMER";

	given(this.resultSet.next()).willReturn(true);
	mockDatabaseMetaData(false);
	given(this.connection.createStatement()).willReturn(this.preparedStatement);

	this.thrown.expect(BadSqlGrammarException.class);
	this.thrown.expect(exceptionCause(sameInstance(sqlException)));
	try {
		this.template.query(sql, new RowCallbackHandler() {
			@Override
			public void processRow(ResultSet rs) throws SQLException {
				throw sqlException;
			}
		});
		fail("Should have thrown BadSqlGrammarException");
	}
	finally {
		verify(this.resultSet).close();
		verify(this.preparedStatement).close();
		verify(this.connection, atLeastOnce()).close();
	}
}
 
Example 11
Source Project: java-technology-stack   Source File: JdbcTemplateTests.java    License: MIT License 6 votes vote down vote up
@Test
public void testSQLErrorCodeTranslation() throws Exception {
	final SQLException sqlException = new SQLException("I have a known problem", "99999", 1054);
	final String sql = "SELECT ID FROM CUSTOMER";

	given(this.resultSet.next()).willReturn(true);
	mockDatabaseMetaData(false);
	given(this.connection.createStatement()).willReturn(this.preparedStatement);

	this.thrown.expect(BadSqlGrammarException.class);
	this.thrown.expect(exceptionCause(sameInstance(sqlException)));
	try {
		this.template.query(sql, (RowCallbackHandler) rs -> {
			throw sqlException;
		});
		fail("Should have thrown BadSqlGrammarException");
	}
	finally {
		verify(this.resultSet).close();
		verify(this.preparedStatement).close();
		verify(this.connection, atLeastOnce()).close();
	}
}
 
Example 12
Source Project: syncer   Source File: MysqlChannel.java    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Override
public ErrorLevel level(Throwable e, SyncWrapper wrapper, int maxTry) {
  /*
   * Possible reasons for DuplicateKey
   * 1. the first failed, the second succeed. Then restart, then the second will send again and cause this
   * 2. duplicate entry in binlog file: load data into db multiple time
   * 3. the data is sync to mysql but not receive response before syncer shutdown
   */
  if (e instanceof DuplicateKeyException) {
    return ErrorLevel.WARN;
  }
  if (e instanceof BadSqlGrammarException) {
    return ErrorLevel.SYNCER_BUG;
  }
  return BufferedChannel.super.level(e, wrapper, maxTry);
}
 
Example 13
Source Project: wetech-admin   Source File: GlobalExceptionHandler.java    License: MIT License 6 votes vote down vote up
/**
 * 捕获sql语法异常,原生的Message不适合中文环境
 *
 * @param request
 * @param e
 * @return
 */
@ExceptionHandler(BadSqlGrammarException.class)
public Result handleSQLSyntaxErrorException(HttpServletRequest request, BadSqlGrammarException e) {
    String message = e.getSQLException().getMessage();
    Map<String, String> regexMap = new HashMap<>();
    //数据表不存在
    regexMap.put("Table '(\\S+)' doesn't exist", "表($1)不存在");
    //唯一键
    regexMap.put("Duplicate entry '(\\S+)' for key '(\\S+)'", "$1已经存在了");
    for (Map.Entry<String, String> entry : regexMap.entrySet()) {
        if (message.matches(entry.getKey())) {
            message = message.replaceAll(entry.getKey(), entry.getValue());
            break;
        }
    }
    log.warn(">>> Handle SQLSyntaxErrorException, url is {}, message is {}", request.getRequestURI(), message);
    return Result.failure(CommonResultStatus.INTERNAL_SERVER_ERROR, message);
}
 
Example 14
@Test
@SuppressWarnings("resource")
public void customErrorCodeTranslation() {
	new ClassPathXmlApplicationContext("test-custom-translators-context.xml",
			CustomSQLExceptionTranslatorRegistrarTests.class);

	SQLErrorCodes codes = SQLErrorCodesFactory.getInstance().getErrorCodes("H2");
	SQLErrorCodeSQLExceptionTranslator sext = new SQLErrorCodeSQLExceptionTranslator();
	sext.setSqlErrorCodes(codes);

	DataAccessException exFor4200 = sext.doTranslate("", "", new SQLException("Ouch", "42000", 42000));
	assertNotNull("Should have been translated", exFor4200);
	assertTrue("Should have been instance of BadSqlGrammarException",
		BadSqlGrammarException.class.isAssignableFrom(exFor4200.getClass()));

	DataAccessException exFor2 = sext.doTranslate("", "", new SQLException("Ouch", "42000", 2));
	assertNotNull("Should have been translated", exFor2);
	assertTrue("Should have been instance of TransientDataAccessResourceException",
		TransientDataAccessResourceException.class.isAssignableFrom(exFor2.getClass()));

	DataAccessException exFor3 = sext.doTranslate("", "", new SQLException("Ouch", "42000", 3));
	assertNull("Should not have been translated", exFor3);
}
 
Example 15
Source Project: spring4-understanding   Source File: JdbcTemplateTests.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testSQLErrorCodeTranslation() throws Exception {
	final SQLException sqlException = new SQLException("I have a known problem", "99999", 1054);
	final String sql = "SELECT ID FROM CUSTOMER";

	given(this.resultSet.next()).willReturn(true);
	mockDatabaseMetaData(false);
	given(this.connection.createStatement()).willReturn(this.preparedStatement);

	this.thrown.expect(BadSqlGrammarException.class);
	this.thrown.expect(exceptionCause(sameInstance(sqlException)));
	try {
		this.template.query(sql, new RowCallbackHandler() {
			@Override
			public void processRow(ResultSet rs) throws SQLException {
				throw sqlException;
			}
		});
		fail("Should have thrown BadSqlGrammarException");
	}
	finally {
		verify(this.resultSet).close();
		verify(this.preparedStatement).close();
		verify(this.connection, atLeastOnce()).close();
	}
}
 
Example 16
Source Project: spring4-understanding   Source File: SimpleJdbcCallTests.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testNoSuchStoredProcedure() throws Exception {
	final String NO_SUCH_PROC = "x";
	SQLException sqlException = new SQLException("Syntax error or access violation exception", "42000");
	given(databaseMetaData.getDatabaseProductName()).willReturn("MyDB");
	given(databaseMetaData.getDatabaseProductName()).willReturn("MyDB");
	given(databaseMetaData.getUserName()).willReturn("me");
	given(databaseMetaData.storesLowerCaseIdentifiers()).willReturn(true);
	given(callableStatement.execute()).willThrow(sqlException);
	given(connection.prepareCall("{call " + NO_SUCH_PROC + "()}")).willReturn(callableStatement);
	SimpleJdbcCall sproc = new SimpleJdbcCall(dataSource).withProcedureName(NO_SUCH_PROC);
	thrown.expect(BadSqlGrammarException.class);
	thrown.expect(exceptionCause(sameInstance(sqlException)));
	try {
		sproc.execute();
	}
	finally {
		verify(callableStatement).close();
		verify(connection, atLeastOnce()).close();
	}
}
 
Example 17
@Override
public String createViewTable( SqlView sqlView )
{
    dropViewTable( sqlView );

    final String sql = TYPE_CREATE_PREFIX_MAP.get( sqlView.getType() ) + statementBuilder.columnQuote( sqlView.getViewName() ) + " AS " + sqlView.getSqlQuery();

    log.debug( "Create view SQL: " + sql );

    try
    {
        jdbcTemplate.execute( sql );

        return null;
    }
    catch ( BadSqlGrammarException ex )
    {
        return ex.getCause().getMessage();
    }
}
 
Example 18
@Override
public String testSqlGrammar( String sql )
{
    String viewName = SqlView.PREFIX_VIEWNAME + System.currentTimeMillis();

    sql = "CREATE VIEW " + viewName + " AS " + sql;

    log.debug( "Test view SQL: " + sql );

    try
    {
        jdbcTemplate.execute( sql );

        jdbcTemplate.execute( "DROP VIEW IF EXISTS " + viewName );
    }
    catch ( BadSqlGrammarException | UncategorizedSQLException ex )
    {
        return ex.getCause().getMessage();
    }

    return null;
}
 
Example 19
Source Project: syncope   Source File: SchedulerDBInit.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void afterPropertiesSet() throws Exception {
    Assert.state(this.dataSource != null, "DataSource must be set");
    Assert.state(this.databasePopulator != null, "DatabasePopulator must be set");

    JdbcTemplate jdbcTemplate = new JdbcTemplate(this.dataSource);
    boolean existingData;
    try {
        existingData = jdbcTemplate.queryForObject("SELECT COUNT(0) FROM QRTZ_SCHEDULER_STATE", Integer.class) > 0;
    } catch (BadSqlGrammarException e) {
        LOG.debug("Could not access to table QRTZ_SCHEDULER_STATE", e);
        existingData = false;
    }

    if (existingData) {
        LOG.info("Quartz tables found in the database, leaving untouched");
    } else {
        LOG.info("No Quartz tables found, creating");

        DatabasePopulatorUtils.execute(databasePopulator, this.dataSource);
    }
}
 
Example 20
@Test
public void testCustomErrorCodeTranslation() {

	SQLExceptionTranslator sext = new SQLErrorCodeSQLExceptionTranslator(ERROR_CODES);

	SQLException dataIntegrityViolationEx = SQLExceptionSubclassFactory.newSQLDataException("", "", 1);
	DataAccessException daeex = sext.translate("task", "SQL", dataIntegrityViolationEx);
	assertEquals(dataIntegrityViolationEx, daeex.getCause());
	assertTrue(daeex instanceof BadSqlGrammarException);

	SQLException dataAccessResourceEx = SQLExceptionSubclassFactory.newSQLDataException("", "", 2);
	DataAccessException darex = sext.translate("task", "SQL", dataAccessResourceEx);
	assertEquals(dataIntegrityViolationEx, daeex.getCause());
	assertTrue(darex instanceof TransientDataAccessResourceException);

}
 
Example 21
@Override
@Nullable
protected DataAccessException doTranslate(String task, @Nullable String sql, SQLException ex) {
	// First, the getSQLState check...
	String sqlState = getSqlState(ex);
	if (sqlState != null && sqlState.length() >= 2) {
		String classCode = sqlState.substring(0, 2);
		if (logger.isDebugEnabled()) {
			logger.debug("Extracted SQL state class '" + classCode + "' from value '" + sqlState + "'");
		}
		if (BAD_SQL_GRAMMAR_CODES.contains(classCode)) {
			return new BadSqlGrammarException(task, (sql != null ? sql : ""), ex);
		}
		else if (DATA_INTEGRITY_VIOLATION_CODES.contains(classCode)) {
			return new DataIntegrityViolationException(buildMessage(task, sql, ex), ex);
		}
		else if (DATA_ACCESS_RESOURCE_FAILURE_CODES.contains(classCode)) {
			return new DataAccessResourceFailureException(buildMessage(task, sql, ex), ex);
		}
		else if (TRANSIENT_DATA_ACCESS_RESOURCE_CODES.contains(classCode)) {
			return new TransientDataAccessResourceException(buildMessage(task, sql, ex), ex);
		}
		else if (CONCURRENCY_FAILURE_CODES.contains(classCode)) {
			return new ConcurrencyFailureException(buildMessage(task, sql, ex), ex);
		}
	}

	// For MySQL: exception class name indicating a timeout?
	// (since MySQL doesn't throw the JDBC 4 SQLTimeoutException)
	if (ex.getClass().getName().contains("Timeout")) {
		return new QueryTimeoutException(buildMessage(task, sql, ex), ex);
	}

	// Couldn't resolve anything proper - resort to UncategorizedSQLException.
	return null;
}
 
Example 22
@Test
public void errorCodeTranslation() {
	SQLExceptionTranslator sext = new SQLErrorCodeSQLExceptionTranslator(ERROR_CODES);

	SQLException badSqlEx = new SQLException("", "", 1);
	BadSqlGrammarException bsgex = (BadSqlGrammarException) sext.translate("task", "SQL", badSqlEx);
	assertEquals("SQL", bsgex.getSql());
	assertEquals(badSqlEx, bsgex.getSQLException());

	SQLException invResEx = new SQLException("", "", 4);
	InvalidResultSetAccessException irsex = (InvalidResultSetAccessException) sext.translate("task", "SQL", invResEx);
	assertEquals("SQL", irsex.getSql());
	assertEquals(invResEx, irsex.getSQLException());

	checkTranslation(sext, 5, DataAccessResourceFailureException.class);
	checkTranslation(sext, 6, DataIntegrityViolationException.class);
	checkTranslation(sext, 7, CannotAcquireLockException.class);
	checkTranslation(sext, 8, DeadlockLoserDataAccessException.class);
	checkTranslation(sext, 9, CannotSerializeTransactionException.class);
	checkTranslation(sext, 10, DuplicateKeyException.class);

	SQLException dupKeyEx = new SQLException("", "", 10);
	DataAccessException dksex = sext.translate("task", "SQL", dupKeyEx);
	assertTrue("Not instance of DataIntegrityViolationException",
			DataIntegrityViolationException.class.isAssignableFrom(dksex.getClass()));

	// Test fallback. We assume that no database will ever return this error code,
	// but 07xxx will be bad grammar picked up by the fallback SQLState translator
	SQLException sex = new SQLException("", "07xxx", 666666666);
	BadSqlGrammarException bsgex2 = (BadSqlGrammarException) sext.translate("task", "SQL2", sex);
	assertEquals("SQL2", bsgex2.getSql());
	assertEquals(sex, bsgex2.getSQLException());
}
 
Example 23
@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 24
@Test
public void badSqlGrammar() {
	SQLException sex = new SQLException("Message", "42001", 1);
	try {
		throw this.trans.translate("task", sql, sex);
	}
	catch (BadSqlGrammarException ex) {
		// OK
		assertTrue("SQL is correct", sql.equals(ex.getSql()));
		assertTrue("Exception matches", sex.equals(ex.getSQLException()));
	}
}
 
Example 25
Source Project: spring-analysis-note   Source File: StoredProcedureTests.java    License: MIT License 5 votes vote down vote up
@Test
public void testNoSuchStoredProcedure() throws Exception {
	SQLException sqlException = new SQLException(
			"Syntax error or access violation exception", "42000");
	given(callableStatement.execute()).willThrow(sqlException);
	given(connection.prepareCall("{call " + NoSuchStoredProcedure.SQL + "()}")).willReturn(
			callableStatement);

	NoSuchStoredProcedure sproc = new NoSuchStoredProcedure(dataSource);
	assertThatExceptionOfType(BadSqlGrammarException.class).isThrownBy(
			sproc::execute);
}
 
Example 26
@AfterTransaction
public void afterTransaction() {
	if ("test01".equals(testName.getMethodName())) {
		try {
			assertNumUsers(99);
			fail("Should throw a BadSqlGrammarException after test01, assuming 'drop-schema.sql' was executed");
		}
		catch (BadSqlGrammarException e) {
			/* expected */
		}
	}
}
 
Example 27
@Override
@Nullable
protected DataAccessException doTranslate(String task, @Nullable String sql, SQLException ex) {
	// First, the getSQLState check...
	String sqlState = getSqlState(ex);
	if (sqlState != null && sqlState.length() >= 2) {
		String classCode = sqlState.substring(0, 2);
		if (logger.isDebugEnabled()) {
			logger.debug("Extracted SQL state class '" + classCode + "' from value '" + sqlState + "'");
		}
		if (BAD_SQL_GRAMMAR_CODES.contains(classCode)) {
			return new BadSqlGrammarException(task, (sql != null ? sql : ""), ex);
		}
		else if (DATA_INTEGRITY_VIOLATION_CODES.contains(classCode)) {
			return new DataIntegrityViolationException(buildMessage(task, sql, ex), ex);
		}
		else if (DATA_ACCESS_RESOURCE_FAILURE_CODES.contains(classCode)) {
			return new DataAccessResourceFailureException(buildMessage(task, sql, ex), ex);
		}
		else if (TRANSIENT_DATA_ACCESS_RESOURCE_CODES.contains(classCode)) {
			return new TransientDataAccessResourceException(buildMessage(task, sql, ex), ex);
		}
		else if (CONCURRENCY_FAILURE_CODES.contains(classCode)) {
			return new ConcurrencyFailureException(buildMessage(task, sql, ex), ex);
		}
	}

	// For MySQL: exception class name indicating a timeout?
	// (since MySQL doesn't throw the JDBC 4 SQLTimeoutException)
	if (ex.getClass().getName().contains("Timeout")) {
		return new QueryTimeoutException(buildMessage(task, sql, ex), ex);
	}

	// Couldn't resolve anything proper - resort to UncategorizedSQLException.
	return null;
}
 
Example 28
@Test
public void errorCodeTranslation() {
	SQLExceptionTranslator sext = new SQLErrorCodeSQLExceptionTranslator(ERROR_CODES);

	SQLException badSqlEx = new SQLException("", "", 1);
	BadSqlGrammarException bsgex = (BadSqlGrammarException) sext.translate("task", "SQL", badSqlEx);
	assertEquals("SQL", bsgex.getSql());
	assertEquals(badSqlEx, bsgex.getSQLException());

	SQLException invResEx = new SQLException("", "", 4);
	InvalidResultSetAccessException irsex = (InvalidResultSetAccessException) sext.translate("task", "SQL", invResEx);
	assertEquals("SQL", irsex.getSql());
	assertEquals(invResEx, irsex.getSQLException());

	checkTranslation(sext, 5, DataAccessResourceFailureException.class);
	checkTranslation(sext, 6, DataIntegrityViolationException.class);
	checkTranslation(sext, 7, CannotAcquireLockException.class);
	checkTranslation(sext, 8, DeadlockLoserDataAccessException.class);
	checkTranslation(sext, 9, CannotSerializeTransactionException.class);
	checkTranslation(sext, 10, DuplicateKeyException.class);

	SQLException dupKeyEx = new SQLException("", "", 10);
	DataAccessException dksex = sext.translate("task", "SQL", dupKeyEx);
	assertTrue("Not instance of DataIntegrityViolationException",
			DataIntegrityViolationException.class.isAssignableFrom(dksex.getClass()));

	// Test fallback. We assume that no database will ever return this error code,
	// but 07xxx will be bad grammar picked up by the fallback SQLState translator
	SQLException sex = new SQLException("", "07xxx", 666666666);
	BadSqlGrammarException bsgex2 = (BadSqlGrammarException) sext.translate("task", "SQL2", sex);
	assertEquals("SQL2", bsgex2.getSql());
	assertEquals(sex, bsgex2.getSQLException());
}
 
Example 29
@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 30
@Test
public void badSqlGrammar() {
	SQLException sex = new SQLException("Message", "42001", 1);
	try {
		throw this.trans.translate("task", sql, sex);
	}
	catch (BadSqlGrammarException ex) {
		// OK
		assertTrue("SQL is correct", sql.equals(ex.getSql()));
		assertTrue("Exception matches", sex.equals(ex.getSQLException()));
	}
}