Search in sources :

Example 51 with SQLSyntaxErrorException

use of java.sql.SQLSyntaxErrorException in project midpoint by Evolveum.

the class ConnIdUtil method lookForKnownCause.

private static Exception lookForKnownCause(Throwable ex, OperationResult parentResult) {
    if (ex.getClass().getPackage().equals(SchemaException.class.getPackage())) {
        // Common midPoint exceptions, pass through
        // Those may get here from the inner calls of handle() methods from the connector.
        parentResult.recordFatalError(ex.getMessage(), ex);
        return (Exception) ex;
    }
    if (ex instanceof FileNotFoundException) {
        // fix MID-2711 consider FileNotFoundException as CommunicationException
        Exception newEx = new com.evolveum.midpoint.util.exception.CommunicationException(createMessageFromAllExceptions(null, ex));
        parentResult.recordFatalError("File not found: " + ex.getMessage(), newEx);
        return newEx;
    } else if (ex instanceof NameAlreadyBoundException) {
        // This is thrown by LDAP connector and may be also throw by similar
        // connectors
        Exception newEx = new ObjectAlreadyExistsException(createMessageFromAllExceptions(null, ex));
        parentResult.recordFatalError("Object already exists: " + ex.getMessage(), newEx);
        return newEx;
    } else if (ex instanceof javax.naming.CommunicationException) {
        // This is thrown by LDAP connector and may be also throw by similar
        // connectors
        Exception newEx = new CommunicationException(createMessageFromAllExceptions("Communication error", ex));
        parentResult.recordFatalError("Communication error: " + ex.getMessage(), newEx);
        return newEx;
    } else if (ex instanceof ServiceUnavailableException) {
        // In some cases (e.g. JDK 1.6.0_31) this is thrown by LDAP connector and may be also throw by similar
        // connectors
        Exception newEx = new CommunicationException(createMessageFromAllExceptions("Communication error", ex));
        parentResult.recordFatalError("Communication error: " + ex.getMessage(), newEx);
        return newEx;
    } else if (ex instanceof SchemaViolationException) {
        // This is thrown by LDAP connector and may be also throw by similar
        // connectors
        Exception newEx = new SchemaException(createMessageFromAllExceptions("Schema violation", ex));
        parentResult.recordFatalError("Schema violation: " + ex.getMessage(), newEx);
        return newEx;
    } else if (ex instanceof javax.naming.directory.InvalidAttributeValueException) {
        // This is thrown by LDAP connector and may be also throw by similar
        // connectors
        javax.naming.directory.InvalidAttributeValueException e = (javax.naming.directory.InvalidAttributeValueException) ex;
        Exception newEx;
        if (e.getExplanation().contains("unique attribute conflict")) {
            newEx = new ObjectAlreadyExistsException(createMessageFromAllExceptions("Invalid attribute", ex));
        } else {
            newEx = new SchemaException(createMessageFromAllExceptions("Invalid attribute", ex));
        }
        parentResult.recordFatalError("Invalid attribute: " + ex.getMessage(), newEx);
        return newEx;
    } else if (ex instanceof ConnectException) {
        // Buried deep in many exceptions, usually connection refused or
        // similar errors
        // Note: needs to be after javax.naming.CommunicationException as the
        // javax.naming exception has more info (e.g. hostname)
        Exception newEx = new CommunicationException(createMessageFromAllExceptions("Connect error", ex));
        parentResult.recordFatalError("Connect error: " + ex.getMessage(), newEx);
        return newEx;
    } else if (ex instanceof SQLSyntaxErrorException) {
        // Buried deep in many exceptions, usually DB schema problems of
        // DB-based connectors
        Exception newEx = new SchemaException(createMessageFromAllExceptions("DB syntax error", ex));
        parentResult.recordFatalError("DB syntax error: " + ex.getMessage(), newEx);
        return newEx;
    } else if (ex instanceof SQLException) {
        // Buried deep in many exceptions, usually DB connection problems
        Exception newEx = new GenericFrameworkException(createMessageFromAllExceptions("DB error", ex));
        parentResult.recordFatalError("DB error: " + ex.getMessage(), newEx);
        return newEx;
    } else if (ex instanceof NoPermissionException) {
        Exception newEx = new SecurityViolationException(createMessageFromAllExceptions(null, ex));
        parentResult.recordFatalError("Object not found: " + ex.getMessage(), newEx);
        return newEx;
    } else if (ex instanceof AttributeInUseException) {
        Exception newEx = new SchemaException(createMessageFromAllExceptions(null, ex));
        parentResult.recordFatalError("Attribute in use: " + ex.getMessage(), newEx);
        return newEx;
    } else if (ex instanceof NoSuchAttributeException) {
        Exception newEx = new SchemaException(createMessageFromAllExceptions(null, ex));
        parentResult.recordFatalError("No such attribute: " + ex.getMessage(), newEx);
        return newEx;
    } else if (ex instanceof ConnectorException && !ex.getClass().equals(ConnectorException.class)) {
        // we have non generic connector exception
        Exception newEx = processConnectorException((ConnectorException) ex, parentResult);
        if (newEx != null) {
            return newEx;
        }
    }
    if (ex.getCause() == null) {
        // found nothing
        return null;
    } else {
        // Otherwise go one level deeper ...
        return lookForKnownCause(ex.getCause(), parentResult);
    }
}
Also used : SchemaException(com.evolveum.midpoint.util.exception.SchemaException) CommunicationException(com.evolveum.midpoint.util.exception.CommunicationException) GenericFrameworkException(com.evolveum.midpoint.provisioning.ucf.api.GenericFrameworkException) SecurityViolationException(com.evolveum.midpoint.util.exception.SecurityViolationException) SQLException(java.sql.SQLException) FileNotFoundException(java.io.FileNotFoundException) SQLSyntaxErrorException(java.sql.SQLSyntaxErrorException) ServiceUnavailableException(javax.naming.ServiceUnavailableException) SchemaException(com.evolveum.midpoint.util.exception.SchemaException) AttributeInUseException(javax.naming.directory.AttributeInUseException) NoSuchAttributeException(javax.naming.directory.NoSuchAttributeException) RemoteWrappedException(org.identityconnectors.framework.impl.api.remote.RemoteWrappedException) ObjectNotFoundException(com.evolveum.midpoint.util.exception.ObjectNotFoundException) ObjectAlreadyExistsException(com.evolveum.midpoint.util.exception.ObjectAlreadyExistsException) FileNotFoundException(java.io.FileNotFoundException) GenericFrameworkException(com.evolveum.midpoint.provisioning.ucf.api.GenericFrameworkException) InvocationTargetException(java.lang.reflect.InvocationTargetException) ServiceUnavailableException(javax.naming.ServiceUnavailableException) SystemException(com.evolveum.midpoint.util.exception.SystemException) SchemaViolationException(javax.naming.directory.SchemaViolationException) CommunicationException(com.evolveum.midpoint.util.exception.CommunicationException) NoPermissionException(javax.naming.NoPermissionException) PolicyViolationException(com.evolveum.midpoint.util.exception.PolicyViolationException) SQLSyntaxErrorException(java.sql.SQLSyntaxErrorException) EncryptionException(com.evolveum.midpoint.prism.crypto.EncryptionException) SQLException(java.sql.SQLException) SecurityViolationException(com.evolveum.midpoint.util.exception.SecurityViolationException) ConnectException(java.net.ConnectException) NameAlreadyBoundException(javax.naming.NameAlreadyBoundException) NoSuchAttributeException(javax.naming.directory.NoSuchAttributeException) NameAlreadyBoundException(javax.naming.NameAlreadyBoundException) NoPermissionException(javax.naming.NoPermissionException) SchemaViolationException(javax.naming.directory.SchemaViolationException) ObjectAlreadyExistsException(com.evolveum.midpoint.util.exception.ObjectAlreadyExistsException) ConnectException(java.net.ConnectException) AttributeInUseException(javax.naming.directory.AttributeInUseException)

Example 52 with SQLSyntaxErrorException

use of java.sql.SQLSyntaxErrorException in project zipkin by openzipkin.

the class SchemaTest method hasErrorCount_falseWhenKnownSQLState.

@Test
public void hasErrorCount_falseWhenKnownSQLState() throws SQLException {
    SQLSyntaxErrorException sqlException = new SQLSyntaxErrorException("Unknown column 'zipkin_dependencies.error_count' in 'field list'", "42S22", 1054);
    // cheats to lower mock count: this exception is really thrown during execution of the query
    when(dataSource.getConnection()).thenThrow(new DataAccessException(sqlException.getMessage(), sqlException));
    assertThat(schema.hasErrorCount).isFalse();
}
Also used : SQLSyntaxErrorException(java.sql.SQLSyntaxErrorException) DataAccessException(org.jooq.exception.DataAccessException) Test(org.junit.Test)

Example 53 with SQLSyntaxErrorException

use of java.sql.SQLSyntaxErrorException in project Mycat-Server by MyCATApache.

the class DruidMycatRouteStrategy method routeNormalSqlWithAST.

@Override
public RouteResultset routeNormalSqlWithAST(SchemaConfig schema, String stmt, RouteResultset rrs, String charset, LayerCachePool cachePool, int sqlType, ServerConnection sc) throws SQLNonTransientException {
    /**
     *  只有mysql时只支持mysql语法
     */
    SQLStatementParser parser = null;
    if (schema.isNeedSupportMultiDBType()) {
        parser = new MycatStatementParser(stmt);
    } else {
        parser = new MySqlStatementParser(stmt);
    }
    MycatSchemaStatVisitor visitor = null;
    SQLStatement statement;
    /**
     * 解析出现问题统一抛SQL语法错误
     */
    try {
        statement = parser.parseStatement();
        visitor = new MycatSchemaStatVisitor();
    } catch (Exception t) {
        LOGGER.error("DruidMycatRouteStrategyError", t);
        throw new SQLSyntaxErrorException(t);
    }
    /**
     * 检验unsupported statement
     */
    checkUnSupportedStatement(statement);
    DruidParser druidParser = DruidParserFactory.create(schema, statement, visitor);
    druidParser.parser(schema, rrs, statement, stmt, cachePool, visitor);
    DruidShardingParseInfo ctx = druidParser.getCtx();
    rrs.setTables(ctx.getTables());
    if (visitor.isSubqueryRelationOr()) {
        String err = "In subQuery,the or condition is not supported.";
        LOGGER.error(err);
        throw new SQLSyntaxErrorException(err);
    }
    /* 按照以下情况路由
			1.2.1 可以直接路由.
       		1.2.2 两个表夸库join的sql.调用calat
       		1.2.3 需要先执行subquery 的sql.把subquery拆分出来.获取结果后,与outerquery
		 */
    // add huangyiming 分片规则不一样的且表中带查询条件的则走Catlet
    List<String> tables = ctx.getTables();
    SchemaConfig schemaConf = MycatServer.getInstance().getConfig().getSchemas().get(schema.getName());
    int index = 0;
    RuleConfig firstRule = null;
    boolean directRoute = true;
    Set<String> firstDataNodes = new HashSet<String>();
    Map<String, TableConfig> tconfigs = schemaConf == null ? null : schemaConf.getTables();
    Map<String, RuleConfig> rulemap = new HashMap<>();
    if (tconfigs != null) {
        for (String tableName : tables) {
            TableConfig tc = tconfigs.get(tableName);
            if (tc == null) {
                // add 别名中取
                Map<String, String> tableAliasMap = ctx.getTableAliasMap();
                if (tableAliasMap != null && tableAliasMap.get(tableName) != null) {
                    tc = schemaConf.getTables().get(tableAliasMap.get(tableName));
                }
            }
            if (index == 0) {
                if (tc != null) {
                    firstRule = tc.getRule();
                    // 没有指定分片规则时,不做处理
                    if (firstRule == null) {
                        continue;
                    }
                    firstDataNodes.addAll(tc.getDataNodes());
                    rulemap.put(tc.getName(), firstRule);
                }
            } else {
                if (tc != null) {
                    // ER关系表的时候是可能存在字表中没有tablerule的情况,所以加上判断
                    RuleConfig ruleCfg = tc.getRule();
                    if (ruleCfg == null) {
                        // 没有指定分片规则时,不做处理
                        continue;
                    }
                    Set<String> dataNodes = new HashSet<String>();
                    dataNodes.addAll(tc.getDataNodes());
                    rulemap.put(tc.getName(), ruleCfg);
                    // 如果匹配规则不相同或者分片的datanode不相同则需要走子查询处理
                    if (firstRule != null && ((ruleCfg != null && !ruleCfg.getRuleAlgorithm().equals(firstRule.getRuleAlgorithm())) || (!dataNodes.equals(firstDataNodes)))) {
                        directRoute = false;
                        break;
                    }
                }
            }
            index++;
        }
    }
    RouteResultset rrsResult = rrs;
    if (directRoute) {
        // 直接路由
        if (!RouterUtil.isAllGlobalTable(ctx, schemaConf)) {
            if (rulemap.size() > 1 && !checkRuleField(rulemap, visitor)) {
                String err = "In case of slice table,there is no rule field in the relationship condition!";
                LOGGER.error(err);
                throw new SQLSyntaxErrorException(err);
            }
        }
        rrsResult = directRoute(rrs, ctx, schema, druidParser, statement, cachePool);
    } else {
        int subQuerySize = visitor.getSubQuerys().size();
        if (subQuerySize == 0 && ctx.getTables().size() == 2) {
            // 两表关联,考虑使用catlet
            if (!visitor.getRelationships().isEmpty()) {
                rrs.setCacheAble(false);
                rrs.setFinishedRoute(true);
                rrsResult = catletRoute(schema, ctx.getSql(), charset, sc);
            } else {
                rrsResult = directRoute(rrs, ctx, schema, druidParser, statement, cachePool);
            }
        } else if (subQuerySize == 1) {
            // 只涉及一张表的子查询,使用  MiddlerResultHandler 获取中间结果后,改写原有 sql 继续执行 TODO 后期可能会考虑多个子查询的情况.
            SQLSelect sqlselect = visitor.getSubQuerys().iterator().next();
            if (!visitor.getRelationships().isEmpty()) {
                // 当 inner query  和 outer  query  有关联条件时,暂不支持
                String err = "In case of slice table,sql have different rules,the relationship condition is not supported.";
                LOGGER.error(err);
                throw new SQLSyntaxErrorException(err);
            } else {
                SQLSelectQuery sqlSelectQuery = sqlselect.getQuery();
                if (((MySqlSelectQueryBlock) sqlSelectQuery).getFrom() instanceof SQLExprTableSource) {
                    rrs.setCacheAble(false);
                    rrs.setFinishedRoute(true);
                    rrsResult = middlerResultRoute(schema, charset, sqlselect, sqlType, statement, sc);
                }
            }
        } else if (subQuerySize >= 2) {
            String err = "In case of slice table,sql has different rules,currently only one subQuery is supported.";
            LOGGER.error(err);
            throw new SQLSyntaxErrorException(err);
        }
    }
    return rrsResult;
}
Also used : SchemaConfig(io.mycat.config.model.SchemaConfig) MycatStatementParser(io.mycat.route.parser.druid.MycatStatementParser) MycatSchemaStatVisitor(io.mycat.route.parser.druid.MycatSchemaStatVisitor) HashMap(java.util.HashMap) SQLSyntaxErrorException(java.sql.SQLSyntaxErrorException) SQLSelectQuery(com.alibaba.druid.sql.ast.statement.SQLSelectQuery) SQLStatement(com.alibaba.druid.sql.ast.SQLStatement) TableConfig(io.mycat.config.model.TableConfig) MySqlStatementParser(com.alibaba.druid.sql.dialect.mysql.parser.MySqlStatementParser) HashSet(java.util.HashSet) RouteResultset(io.mycat.route.RouteResultset) DruidShardingParseInfo(io.mycat.route.parser.druid.DruidShardingParseInfo) SQLStatementParser(com.alibaba.druid.sql.parser.SQLStatementParser) SQLSelect(com.alibaba.druid.sql.ast.statement.SQLSelect) MySqlSelectQueryBlock(com.alibaba.druid.sql.dialect.mysql.ast.statement.MySqlSelectQueryBlock) SQLNonTransientException(java.sql.SQLNonTransientException) SQLSyntaxErrorException(java.sql.SQLSyntaxErrorException) DruidParser(io.mycat.route.parser.druid.DruidParser) SQLExprTableSource(com.alibaba.druid.sql.ast.statement.SQLExprTableSource) RuleConfig(io.mycat.config.model.rule.RuleConfig)

Example 54 with SQLSyntaxErrorException

use of java.sql.SQLSyntaxErrorException in project Mycat-Server by MyCATApache.

the class RouteService method route.

public RouteResultset route(SystemConfig sysconf, SchemaConfig schema, int sqlType, String stmt, String charset, ServerConnection sc) throws SQLNonTransientException {
    RouteResultset rrs = null;
    String cacheKey = null;
    /**
     *  SELECT 类型的SQL, 检测
     */
    if (sqlType == ServerParse.SELECT) {
        cacheKey = schema.getName() + stmt;
        rrs = (RouteResultset) sqlRouteCache.get(cacheKey);
        if (rrs != null) {
            checkMigrateRule(schema.getName(), rrs, sqlType);
            return rrs;
        }
    }
    /*!mycat: sql = select name from aa */
    /*!mycat: schema = test */
    // boolean isMatchOldHint = stmt.startsWith(OLD_MYCAT_HINT);
    // boolean isMatchNewHint = stmt.startsWith(NEW_MYCAT_HINT);
    // if (isMatchOldHint || isMatchNewHint ) {
    int hintLength = RouteService.isHintSql(stmt);
    if (hintLength != -1) {
        int endPos = stmt.indexOf("*/");
        if (endPos > 0) {
            // 用!mycat:内部的语句来做路由分析
            // int hintLength = isMatchOldHint ? OLD_MYCAT_HINT.length() : NEW_MYCAT_HINT.length();
            String hint = stmt.substring(hintLength, endPos).trim();
            int firstSplitPos = hint.indexOf(HINT_SPLIT);
            if (firstSplitPos > 0) {
                Map hintMap = parseHint(hint);
                String hintType = (String) hintMap.get(MYCAT_HINT_TYPE);
                String hintSql = (String) hintMap.get(hintType);
                if (hintSql.length() == 0) {
                    LOGGER.warn("comment int sql must meet :/*!mycat:type=value*/ or /*#mycat:type=value*/ or /*mycat:type=value*/: " + stmt);
                    throw new SQLSyntaxErrorException("comment int sql must meet :/*!mycat:type=value*/ or /*#mycat:type=value*/ or /*mycat:type=value*/: " + stmt);
                }
                String realSQL = stmt.substring(endPos + "*/".length()).trim();
                HintHandler hintHandler = HintHandlerFactory.getHintHandler(hintType);
                if (hintHandler != null) {
                    if (hintHandler instanceof HintSQLHandler) {
                        /**
                         * 修复 注解SQL的 sqlType 与 实际SQL的 sqlType 不一致问题, 如: hint=SELECT,real=INSERT
                         * fixed by zhuam
                         */
                        int hintSqlType = ServerParse.parse(hintSql) & 0xff;
                        rrs = hintHandler.route(sysconf, schema, sqlType, realSQL, charset, sc, tableId2DataNodeCache, hintSql, hintSqlType, hintMap);
                    } else {
                        rrs = hintHandler.route(sysconf, schema, sqlType, realSQL, charset, sc, tableId2DataNodeCache, hintSql, sqlType, hintMap);
                    }
                } else {
                    LOGGER.warn("TODO , support hint sql type : " + hintType);
                }
            } else {
                // fixed by runfriends@126.com
                LOGGER.warn("comment in sql must meet :/*!mycat:type=value*/ or /*#mycat:type=value*/ or /*mycat:type=value*/: " + stmt);
                throw new SQLSyntaxErrorException("comment in sql must meet :/*!mcat:type=value*/ or /*#mycat:type=value*/ or /*mycat:type=value*/: " + stmt);
            }
        }
    } else {
        stmt = stmt.trim();
        rrs = RouteStrategyFactory.getRouteStrategy().route(sysconf, schema, sqlType, stmt, charset, sc, tableId2DataNodeCache);
    }
    if (rrs != null && sqlType == ServerParse.SELECT && rrs.isCacheAble()) {
        sqlRouteCache.putIfAbsent(cacheKey, rrs);
    }
    checkMigrateRule(schema.getName(), rrs, sqlType);
    return rrs;
}
Also used : HintHandler(io.mycat.route.handler.HintHandler) SQLSyntaxErrorException(java.sql.SQLSyntaxErrorException) HintSQLHandler(io.mycat.route.handler.HintSQLHandler) HashMap(java.util.HashMap) ConcurrentMap(java.util.concurrent.ConcurrentMap) Map(java.util.Map)

Example 55 with SQLSyntaxErrorException

use of java.sql.SQLSyntaxErrorException in project Mycat-Server by MyCATApache.

the class DQLRouteTest method test.

@Test
public void test() throws Exception {
    String stmt = "select * from `offer` where id = 100";
    SchemaConfig schema = schemaMap.get("mysqldb");
    RouteResultset rrs = new RouteResultset(stmt, 7);
    SQLStatementParser parser = null;
    if (schema.isNeedSupportMultiDBType()) {
        parser = new MycatStatementParser(stmt);
    } else {
        parser = new MySqlStatementParser(stmt);
    }
    SQLStatement statement;
    MycatSchemaStatVisitor visitor = null;
    try {
        statement = parser.parseStatement();
        visitor = new MycatSchemaStatVisitor();
    } catch (Exception t) {
        throw new SQLSyntaxErrorException(t);
    }
    ctx = new DruidShardingParseInfo();
    ctx.setSql(stmt);
    List<RouteCalculateUnit> taskList = visitorParse(rrs, statement, visitor);
    Assert.assertEquals(true, !taskList.get(0).getTablesAndConditions().isEmpty());
}
Also used : DruidShardingParseInfo(io.mycat.route.parser.druid.DruidShardingParseInfo) RouteCalculateUnit(io.mycat.route.parser.druid.RouteCalculateUnit) SchemaConfig(io.mycat.config.model.SchemaConfig) SQLStatementParser(com.alibaba.druid.sql.parser.SQLStatementParser) MycatStatementParser(io.mycat.route.parser.druid.MycatStatementParser) MycatSchemaStatVisitor(io.mycat.route.parser.druid.MycatSchemaStatVisitor) SQLSyntaxErrorException(java.sql.SQLSyntaxErrorException) SQLStatement(com.alibaba.druid.sql.ast.SQLStatement) SQLSyntaxErrorException(java.sql.SQLSyntaxErrorException) MySqlStatementParser(com.alibaba.druid.sql.dialect.mysql.parser.MySqlStatementParser) Test(org.junit.Test)

Aggregations

SQLSyntaxErrorException (java.sql.SQLSyntaxErrorException)55 Test (org.junit.Test)14 Test (org.testng.annotations.Test)14 BaseTest (util.BaseTest)14 DataAccessException (org.jooq.exception.DataAccessException)9 HashMap (java.util.HashMap)7 SQLStatement (com.alibaba.druid.sql.ast.SQLStatement)6 MySqlStatementParser (com.alibaba.druid.sql.dialect.mysql.parser.MySqlStatementParser)6 SQLStatementParser (com.alibaba.druid.sql.parser.SQLStatementParser)6 TableConfig (io.mycat.config.model.TableConfig)6 SQLNonTransientException (java.sql.SQLNonTransientException)6 Expression (com.alibaba.cobar.parser.ast.expression.Expression)5 Identifier (com.alibaba.cobar.parser.ast.expression.primary.Identifier)4 SQLExprTableSource (com.alibaba.druid.sql.ast.statement.SQLExprTableSource)4 SchemaConfig (io.mycat.config.model.SchemaConfig)4 DruidShardingParseInfo (io.mycat.route.parser.druid.DruidShardingParseInfo)4 MycatSchemaStatVisitor (io.mycat.route.parser.druid.MycatSchemaStatVisitor)4 MycatStatementParser (io.mycat.route.parser.druid.MycatStatementParser)4 SQLException (java.sql.SQLException)4 DataSource (javax.sql.DataSource)4