Search in sources :

Example 1 with BadSqlGrammarException

use of org.springframework.jdbc.BadSqlGrammarException in project spring-boot by spring-projects.

the class DataSourceInitializerTests method testInitializationDisabled.

@Test
public void testInitializationDisabled() throws Exception {
    this.context.register(DataSourceAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class);
    this.context.refresh();
    DataSource dataSource = this.context.getBean(DataSource.class);
    this.context.publishEvent(new DataSourceInitializedEvent(dataSource));
    assertThat(dataSource instanceof org.apache.tomcat.jdbc.pool.DataSource).isTrue();
    assertThat(dataSource).isNotNull();
    JdbcOperations template = new JdbcTemplate(dataSource);
    try {
        template.queryForObject("SELECT COUNT(*) from BAR", Integer.class);
        fail("Query should have failed as BAR table does not exist");
    } catch (BadSqlGrammarException ex) {
        SQLException sqlException = ex.getSQLException();
        // user lacks privilege or object not found
        int expectedCode = -5501;
        assertThat(sqlException.getErrorCode()).isEqualTo(expectedCode);
    }
}
Also used : BadSqlGrammarException(org.springframework.jdbc.BadSqlGrammarException) SQLException(java.sql.SQLException) JdbcOperations(org.springframework.jdbc.core.JdbcOperations) JdbcTemplate(org.springframework.jdbc.core.JdbcTemplate) DataSource(javax.sql.DataSource) Test(org.junit.Test)

Example 2 with BadSqlGrammarException

use of org.springframework.jdbc.BadSqlGrammarException in project spring-framework by spring-projects.

the class SQLErrorCodeSQLExceptionTranslator method doTranslate.

@Override
protected DataAccessException doTranslate(String task, String sql, SQLException ex) {
    SQLException sqlEx = ex;
    if (sqlEx instanceof BatchUpdateException && sqlEx.getNextException() != null) {
        SQLException nestedSqlEx = sqlEx.getNextException();
        if (nestedSqlEx.getErrorCode() > 0 || nestedSqlEx.getSQLState() != null) {
            logger.debug("Using nested SQLException from the BatchUpdateException");
            sqlEx = nestedSqlEx;
        }
    }
    // First, try custom translation from overridden method.
    DataAccessException dex = customTranslate(task, sql, sqlEx);
    if (dex != null) {
        return dex;
    }
    // Next, try the custom SQLException translator, if available.
    if (this.sqlErrorCodes != null) {
        SQLExceptionTranslator customTranslator = this.sqlErrorCodes.getCustomSqlExceptionTranslator();
        if (customTranslator != null) {
            DataAccessException customDex = customTranslator.translate(task, sql, sqlEx);
            if (customDex != null) {
                return customDex;
            }
        }
    }
    // Check SQLErrorCodes with corresponding error code, if available.
    if (this.sqlErrorCodes != null) {
        String errorCode;
        if (this.sqlErrorCodes.isUseSqlStateForTranslation()) {
            errorCode = sqlEx.getSQLState();
        } else {
            // Try to find SQLException with actual error code, looping through the causes.
            // E.g. applicable to java.sql.DataTruncation as of JDK 1.6.
            SQLException current = sqlEx;
            while (current.getErrorCode() == 0 && current.getCause() instanceof SQLException) {
                current = (SQLException) current.getCause();
            }
            errorCode = Integer.toString(current.getErrorCode());
        }
        if (errorCode != null) {
            // Look for defined custom translations first.
            CustomSQLErrorCodesTranslation[] customTranslations = this.sqlErrorCodes.getCustomTranslations();
            if (customTranslations != null) {
                for (CustomSQLErrorCodesTranslation customTranslation : customTranslations) {
                    if (Arrays.binarySearch(customTranslation.getErrorCodes(), errorCode) >= 0) {
                        if (customTranslation.getExceptionClass() != null) {
                            DataAccessException customException = createCustomException(task, sql, sqlEx, customTranslation.getExceptionClass());
                            if (customException != null) {
                                logTranslation(task, sql, sqlEx, true);
                                return customException;
                            }
                        }
                    }
                }
            }
            // Next, look for grouped error codes.
            if (Arrays.binarySearch(this.sqlErrorCodes.getBadSqlGrammarCodes(), errorCode) >= 0) {
                logTranslation(task, sql, sqlEx, false);
                return new BadSqlGrammarException(task, sql, sqlEx);
            } else if (Arrays.binarySearch(this.sqlErrorCodes.getInvalidResultSetAccessCodes(), errorCode) >= 0) {
                logTranslation(task, sql, sqlEx, false);
                return new InvalidResultSetAccessException(task, sql, sqlEx);
            } else if (Arrays.binarySearch(this.sqlErrorCodes.getDuplicateKeyCodes(), errorCode) >= 0) {
                logTranslation(task, sql, sqlEx, false);
                return new DuplicateKeyException(buildMessage(task, sql, sqlEx), sqlEx);
            } else if (Arrays.binarySearch(this.sqlErrorCodes.getDataIntegrityViolationCodes(), errorCode) >= 0) {
                logTranslation(task, sql, sqlEx, false);
                return new DataIntegrityViolationException(buildMessage(task, sql, sqlEx), sqlEx);
            } else if (Arrays.binarySearch(this.sqlErrorCodes.getPermissionDeniedCodes(), errorCode) >= 0) {
                logTranslation(task, sql, sqlEx, false);
                return new PermissionDeniedDataAccessException(buildMessage(task, sql, sqlEx), sqlEx);
            } else if (Arrays.binarySearch(this.sqlErrorCodes.getDataAccessResourceFailureCodes(), errorCode) >= 0) {
                logTranslation(task, sql, sqlEx, false);
                return new DataAccessResourceFailureException(buildMessage(task, sql, sqlEx), sqlEx);
            } else if (Arrays.binarySearch(this.sqlErrorCodes.getTransientDataAccessResourceCodes(), errorCode) >= 0) {
                logTranslation(task, sql, sqlEx, false);
                return new TransientDataAccessResourceException(buildMessage(task, sql, sqlEx), sqlEx);
            } else if (Arrays.binarySearch(this.sqlErrorCodes.getCannotAcquireLockCodes(), errorCode) >= 0) {
                logTranslation(task, sql, sqlEx, false);
                return new CannotAcquireLockException(buildMessage(task, sql, sqlEx), sqlEx);
            } else if (Arrays.binarySearch(this.sqlErrorCodes.getDeadlockLoserCodes(), errorCode) >= 0) {
                logTranslation(task, sql, sqlEx, false);
                return new DeadlockLoserDataAccessException(buildMessage(task, sql, sqlEx), sqlEx);
            } else if (Arrays.binarySearch(this.sqlErrorCodes.getCannotSerializeTransactionCodes(), errorCode) >= 0) {
                logTranslation(task, sql, sqlEx, false);
                return new CannotSerializeTransactionException(buildMessage(task, sql, sqlEx), sqlEx);
            }
        }
    }
    // We couldn't identify it more precisely - let's hand it over to the SQLState fallback translator.
    if (logger.isDebugEnabled()) {
        String codes;
        if (this.sqlErrorCodes != null && this.sqlErrorCodes.isUseSqlStateForTranslation()) {
            codes = "SQL state '" + sqlEx.getSQLState() + "', error code '" + sqlEx.getErrorCode();
        } else {
            codes = "Error code '" + sqlEx.getErrorCode() + "'";
        }
        logger.debug("Unable to translate SQLException with " + codes + ", will now try the fallback translator");
    }
    return null;
}
Also used : BadSqlGrammarException(org.springframework.jdbc.BadSqlGrammarException) TransientDataAccessResourceException(org.springframework.dao.TransientDataAccessResourceException) CannotAcquireLockException(org.springframework.dao.CannotAcquireLockException) SQLException(java.sql.SQLException) DataAccessResourceFailureException(org.springframework.dao.DataAccessResourceFailureException) PermissionDeniedDataAccessException(org.springframework.dao.PermissionDeniedDataAccessException) InvalidResultSetAccessException(org.springframework.jdbc.InvalidResultSetAccessException) DuplicateKeyException(org.springframework.dao.DuplicateKeyException) DataIntegrityViolationException(org.springframework.dao.DataIntegrityViolationException) CannotSerializeTransactionException(org.springframework.dao.CannotSerializeTransactionException) DeadlockLoserDataAccessException(org.springframework.dao.DeadlockLoserDataAccessException) DataAccessException(org.springframework.dao.DataAccessException) DeadlockLoserDataAccessException(org.springframework.dao.DeadlockLoserDataAccessException) PermissionDeniedDataAccessException(org.springframework.dao.PermissionDeniedDataAccessException) BatchUpdateException(java.sql.BatchUpdateException)

Example 3 with BadSqlGrammarException

use of org.springframework.jdbc.BadSqlGrammarException in project dhis2-core by dhis2.

the class JdbcAnalyticsManager method getAggregatedDataValues.

// -------------------------------------------------------------------------
// AnalyticsManager implementation
// -------------------------------------------------------------------------
@Override
@Async
public Future<Map<String, Object>> getAggregatedDataValues(DataQueryParams params, int maxLimit) {
    try {
        ListMap<DimensionalItemObject, DimensionalItemObject> dataPeriodAggregationPeriodMap = params.getDataPeriodAggregationPeriodMap();
        if (params.isDisaggregation() && params.hasDataPeriodType()) {
            params = DataQueryParams.newBuilder(params).withDataPeriodsForAggregationPeriods(dataPeriodAggregationPeriodMap).build();
        }
        String sql = getSelectClause(params);
        if (params.spansMultiplePartitions()) {
            sql += getFromWhereClauseMultiplePartitionFilters(params);
        } else {
            sql += getFromWhereClause(params, params.getPartitions().getSinglePartition());
        }
        sql += getGroupByClause(params);
        if (params.isDataType(DataType.NUMERIC) && !params.getMeasureCriteria().isEmpty()) {
            sql += getMeasureCriteriaSql(params);
        }
        log.debug(sql);
        Map<String, Object> map = null;
        try {
            map = getKeyValueMap(params, sql, maxLimit);
        } catch (BadSqlGrammarException ex) {
            log.info("Query failed, likely because the requested analytics table does not exist", ex);
            return new AsyncResult<>(new HashMap<String, Object>());
        }
        replaceDataPeriodsWithAggregationPeriods(map, params, dataPeriodAggregationPeriodMap);
        return new AsyncResult<>(map);
    } catch (RuntimeException ex) {
        log.error(DebugUtils.getStackTrace(ex));
        throw ex;
    }
}
Also used : BadSqlGrammarException(org.springframework.jdbc.BadSqlGrammarException) DateUtils.getMediumDateString(org.hisp.dhis.system.util.DateUtils.getMediumDateString) AsyncResult(org.springframework.scheduling.annotation.AsyncResult) Async(org.springframework.scheduling.annotation.Async)

Example 4 with BadSqlGrammarException

use of org.springframework.jdbc.BadSqlGrammarException in project dhis2-core by dhis2.

the class JdbcEventAnalyticsManager method getAggregatedEventData.

// -------------------------------------------------------------------------
// EventAnalyticsManager implementation
// -------------------------------------------------------------------------
@Override
public Grid getAggregatedEventData(EventQueryParams params, Grid grid, int maxLimit) {
    String countClause = getAggregateClause(params);
    String sql = "select " + countClause + " as value," + StringUtils.join(getSelectColumns(params), ",") + " ";
    // ---------------------------------------------------------------------
    // Criteria
    // ---------------------------------------------------------------------
    sql += getFromWhereClause(params, Lists.newArrayList("psi"));
    // ---------------------------------------------------------------------
    // Group by
    // ---------------------------------------------------------------------
    sql += "group by " + StringUtils.join(getSelectColumns(params), ",") + " ";
    if (params.hasSortOrder()) {
        sql += "order by value " + params.getSortOrder().toString().toLowerCase() + " ";
    }
    if (params.hasLimit()) {
        sql += "limit " + params.getLimit();
    } else if (maxLimit > 0) {
        sql += "limit " + (maxLimit + 1);
    }
    try {
        getAggregatedEventData(grid, params, sql);
    } catch (BadSqlGrammarException ex) {
        log.info(QUERY_ERR_MSG, ex);
    }
    return grid;
}
Also used : BadSqlGrammarException(org.springframework.jdbc.BadSqlGrammarException) DateUtils.getMediumDateString(org.hisp.dhis.system.util.DateUtils.getMediumDateString)

Example 5 with BadSqlGrammarException

use of org.springframework.jdbc.BadSqlGrammarException in project dhis2-core by dhis2.

the class AbstractJdbcEventAnalyticsManager method getAggregatedEventData.

public Grid getAggregatedEventData(EventQueryParams params, Grid grid, int maxLimit) {
    String countClause = getAggregateClause(params);
    String sql = TextUtils.removeLastComma("select " + countClause + " as value," + StringUtils.join(getSelectColumns(params), ",") + " ");
    // ---------------------------------------------------------------------
    // Criteria
    // ---------------------------------------------------------------------
    sql += getFromClause(params);
    sql += getWhereClause(params);
    // ---------------------------------------------------------------------
    // Group by
    // ---------------------------------------------------------------------
    List<String> selectColumnNames = getGroupByColumnNames(params);
    if (selectColumnNames.size() > 0) {
        sql += "group by " + StringUtils.join(selectColumnNames, ",") + " ";
    }
    if (params.hasSortOrder()) {
        sql += "order by value " + params.getSortOrder().toString().toLowerCase() + " ";
    }
    if (params.hasLimit()) {
        sql += "limit " + params.getLimit();
    } else if (maxLimit > 0) {
        sql += "limit " + (maxLimit + 1);
    }
    try {
        if (params.analyzeOnly()) {
            executionPlanStore.addExecutionPlan(params.getExplainOrderId(), sql);
        } else {
            getAggregatedEventData(grid, params, sql);
        }
    } catch (BadSqlGrammarException ex) {
        log.info(AnalyticsUtils.ERR_MSG_TABLE_NOT_EXISTING, ex);
    } catch (DataAccessResourceFailureException ex) {
        log.warn(ErrorCode.E7131.getMessage(), ex);
        throw new QueryRuntimeException(ErrorCode.E7131, ex);
    }
    return grid;
}
Also used : BadSqlGrammarException(org.springframework.jdbc.BadSqlGrammarException) DataAccessResourceFailureException(org.springframework.dao.DataAccessResourceFailureException) QueryRuntimeException(org.hisp.dhis.common.QueryRuntimeException)

Aggregations

BadSqlGrammarException (org.springframework.jdbc.BadSqlGrammarException)16 SQLException (java.sql.SQLException)7 DataAccessResourceFailureException (org.springframework.dao.DataAccessResourceFailureException)6 QueryRuntimeException (org.hisp.dhis.common.QueryRuntimeException)4 DateUtils.getMediumDateString (org.hisp.dhis.system.util.DateUtils.getMediumDateString)4 Test (org.junit.jupiter.api.Test)4 DataAccessException (org.springframework.dao.DataAccessException)4 TextUtils.getQuotedCommaDelimitedString (org.hisp.dhis.commons.util.TextUtils.getQuotedCommaDelimitedString)3 DataIntegrityViolationException (org.springframework.dao.DataIntegrityViolationException)3 TransientDataAccessResourceException (org.springframework.dao.TransientDataAccessResourceException)3 BatchUpdateException (java.sql.BatchUpdateException)2 DateUtils.getMediumDateString (org.hisp.dhis.util.DateUtils.getMediumDateString)2 DeadlockLoserDataAccessException (org.springframework.dao.DeadlockLoserDataAccessException)2 PermissionDeniedDataAccessException (org.springframework.dao.PermissionDeniedDataAccessException)2 InvalidResultSetAccessException (org.springframework.jdbc.InvalidResultSetAccessException)2 JdbcTemplate (org.springframework.jdbc.core.JdbcTemplate)2 Async (org.springframework.scheduling.annotation.Async)2 AsyncResult (org.springframework.scheduling.annotation.AsyncResult)2 IOException (java.io.IOException)1 PrintWriter (java.io.PrintWriter)1