Java Code Examples for com.alibaba.druid.sql.ast.statement.SQLSelectStatement

The following examples show how to use com.alibaba.druid.sql.ast.statement.SQLSelectStatement. 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
Source Project: dts   Source File: SelectParser.java    License: Apache License 2.0 6 votes vote down vote up
@Override
protected String getTableName(SQLSelectStatement parseSqlStatement) {
    SQLSelectQueryBlock selectQueryBlock = parseSqlStatement.getSelect().getQueryBlock();
    SQLTableSource tableSource = selectQueryBlock.getFrom();
    StringBuffer sb = new StringBuffer();
    MySqlOutputVisitor visitor = new MySqlOutputVisitor(sb) {

        @Override
        public boolean visit(SQLExprTableSource x) {
            printTableSourceExpr(x.getExpr());
            return false;
        }
    };
    visitor.visit((SQLExprTableSource)tableSource);
    return sb.toString();
}
 
Example 2
private void sqlserverParse(SchemaConfig schema, RouteResultset rrs)
{
    //使用sqlserver的解析,否则会有部分语法识别错误
    SQLServerStatementParser oracleParser = new SQLServerStatementParser(getCtx().getSql());
    SQLSelectStatement oracleStmt = (SQLSelectStatement) oracleParser.parseStatement();
    SQLSelectQuery oracleSqlSelectQuery = oracleStmt.getSelect().getQuery();
    if(oracleSqlSelectQuery instanceof SQLServerSelectQueryBlock)
    {
        parseSqlServerPageSql(oracleStmt, rrs, (SQLServerSelectQueryBlock) oracleSqlSelectQuery, schema);
        if(isNeedParseOrderAgg)
        {
            parseOrderAggGroupSqlServer(schema, oracleStmt,rrs, (SQLServerSelectQueryBlock) oracleSqlSelectQuery);
        }
    }

}
 
Example 3
Source Project: dble   Source File: SelectHandler.java    License: GNU General Public License v2.0 6 votes vote down vote up
private static boolean isSupportSelect(String stmt) {
    SQLStatementParser parser = new MySqlStatementParser(stmt);
    SQLStatement statement = parser.parseStatement();
    if (!(statement instanceof SQLSelectStatement)) {
        return false;
    }

    SQLSelectQuery sqlSelectQuery = ((SQLSelectStatement) statement).getSelect().getQuery();
    if (!(sqlSelectQuery instanceof MySqlSelectQueryBlock)) {
        return false;
    }
    MySqlSelectQueryBlock selectQueryBlock = (MySqlSelectQueryBlock) sqlSelectQuery;
    SQLTableSource mysqlFrom = selectQueryBlock.getFrom();
    if (mysqlFrom != null) {
        return false;
    }
    for (SQLSelectItem item : selectQueryBlock.getSelectList()) {
        SQLExpr selectItem = item.getExpr();
        if (!isVariantRef(selectItem)) {
            return false;
        }
    }
    return true;
}
 
Example 4
Source Project: dble   Source File: ExplainHandler.java    License: GNU General Public License v2.0 6 votes vote down vote up
private static BaseHandlerBuilder buildNodes(RouteResultset rrs, ServerConnection c) {
    SQLSelectStatement ast = (SQLSelectStatement) rrs.getSqlStatement();
    MySQLPlanNodeVisitor visitor = new MySQLPlanNodeVisitor(c.getSchema(), c.getCharset().getResultsIndex(), ProxyMeta.getInstance().getTmManager(), false, c.getUsrVariables());
    visitor.visit(ast);
    PlanNode node = visitor.getTableNode();
    node.setSql(rrs.getStatement());
    node.setUpFields();
    PlanUtil.checkTablesPrivilege(c, node, ast);
    node = MyOptimizer.optimize(node);

    if (!PlanUtil.containsSubQuery(node) && !visitor.isContainSchema()) {
        node.setAst(ast);
    }
    HandlerBuilder builder = new HandlerBuilder(node, c.getSession2());
    return builder.getBuilder(c.getSession2(), node, true);
}
 
Example 5
Source Project: dble   Source File: MergeBuilder.java    License: GNU General Public License v2.0 6 votes vote down vote up
RouteResultset constructByStatement(String sql, Map<String, String> mapTableToSimple, SQLSelectStatement select, SchemaConfig schemaConfig) throws SQLException {
    RouteResultset rrs = new RouteResultset(sql, ServerParse.SELECT);
    String pushDownSQL = rrs.getStatement();
    for (Map.Entry<String, String> tableToSimple : mapTableToSimple.entrySet()) {
        pushDownSQL = pushDownSQL.replace(tableToSimple.getKey(), tableToSimple.getValue());
    }
    rrs.setStatement(pushDownSQL);
    rrs.setComplexSQL(true);
    Map<Pair<String, String>, SchemaConfig> tableConfigMap = new HashMap<>();
    for (TableNode tn : node.getReferedTableNodes()) {
        if (schemaConfigMap.get(tn.getSchema()) != null) {
            tableConfigMap.put(new Pair<>(tn.getSchema(), tn.getTableName()), schemaConfigMap.get(tn.getSchema()));
        }
    }
    DruidSingleUnitSelectParser druidParser = new DruidSingleUnitSelectParser();
    druidParser.setSchemaMap(tableConfigMap);
    return RouterUtil.routeFromParserComplex(schemaConfig, druidParser, tableConfigMap, rrs, select, new ServerSchemaStatVisitor(), session.getSource());
}
 
Example 6
Source Project: dble   Source File: DruidInsertParser.java    License: GNU General Public License v2.0 6 votes vote down vote up
private boolean parserNoSharding(ServerConnection sc, String contextSchema, SchemaInfo schemaInfo, RouteResultset rrs,
                                 MySqlInsertStatement insert) throws SQLException {
    String noShardingNode = RouterUtil.isNoSharding(schemaInfo.getSchemaConfig(), schemaInfo.getTable());
    if (noShardingNode != null) {
        // table with single datanode and has autoIncrement property
        TableConfig tbConfig = schemaInfo.getSchemaConfig().getTables().get(schemaInfo.getTable());
        if (tbConfig != null && tbConfig.isAutoIncrement()) {
            return false;
        }
        StringPtr noShardingNodePr = new StringPtr(noShardingNode);
        Set<String> schemas = new HashSet<>();
        if (insert.getQuery() != null) {
            SQLSelectStatement selectStmt = new SQLSelectStatement(insert.getQuery());
            if (!SchemaUtil.isNoSharding(sc, insert.getQuery().getQuery(), insert, selectStmt, contextSchema, schemas, noShardingNodePr)) {
                return false;
            }
        }
        routeToNoSharding(schemaInfo.getSchemaConfig(), rrs, schemas, noShardingNodePr);
        return true;
    }
    return false;
}
 
Example 7
Source Project: Zebra   Source File: MySQLDialect.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public String getCountSql(String sql) {
	SQLStatementParser parser = new MySqlStatementParser(sql);
	List<SQLStatement> stmtList = parser.parseStatementList();

	// 将AST通过visitor输出
	StringBuilder out = new StringBuilder();
	MysqlCountOutputVisitor visitor = new MysqlCountOutputVisitor(out);

	for (SQLStatement stmt : stmtList) {
		if (stmt instanceof SQLSelectStatement) {
			stmt.accept(visitor);
			out.append(";");
		}
	}

	return out.toString();
}
 
Example 8
Source Project: dts   Source File: SelectParser.java    License: Apache License 2.0 5 votes vote down vote up
@Override
protected String getWhere(SQLSelectStatement parseSqlStatement) {
    SQLSelectQueryBlock selectQueryBlock = parseSqlStatement.getSelect().getQueryBlock();
    SQLExpr where = selectQueryBlock.getWhere();
    if (where == null) {
        return "";
    }
    return SQLUtils.toSQLString(where);

}
 
Example 9
Source Project: dts   Source File: SelectParser.java    License: Apache License 2.0 5 votes vote down vote up
@Override
protected List<Object> getWhereParams(List<Object> sqlParamsList, SQLSelectStatement parseSqlStatement) {
    if (sqlParamsList != null && !sqlParamsList.isEmpty()) {
        return sqlParamsList;
    }
    return Lists.newArrayList();
}
 
Example 10
Source Project: dts   Source File: SelectParser.java    License: Apache License 2.0 5 votes vote down vote up
@Override
protected String selectSql(SQLSelectStatement mySqlSelectStatement, Set<String> primaryKeyNameSet) {
    StringBuffer stringBuffer = new StringBuffer();
    stringBuffer.append("SELECT ");
    stringBuffer.append(String.join(",", primaryKeyNameSet));
    stringBuffer.append(" from ").append(getTableName(mySqlSelectStatement)).append(" where ");
    stringBuffer.append(getWhere(mySqlSelectStatement));
    return stringBuffer.toString();
}
 
Example 11
Source Project: Mycat2   Source File: ShareJoin.java    License: GNU General Public License v3.0 5 votes vote down vote up
public void route(SystemConfig sysConfig, SchemaConfig schema,int sqlType, String realSQL, String charset, ServerConnection sc,	LayerCachePool cachePool) {
	int rs = ServerParse.parse(realSQL);
	this.sqltype = rs & 0xff;
	this.sysConfig=sysConfig; 
	this.schema=schema;
	this.charset=charset; 
	this.sc=sc;	
	this.cachePool=cachePool;		
	try {
	 //  RouteStrategy routes=RouteStrategyFactory.getRouteStrategy();	
	  // rrs =RouteStrategyFactory.getRouteStrategy().route(sysConfig, schema, sqlType2, realSQL,charset, sc, cachePool);		   
		MySqlStatementParser parser = new MySqlStatementParser(realSQL);			
		SQLStatement statement = parser.parseStatement();
		if(statement instanceof SQLSelectStatement) {
		   SQLSelectStatement st=(SQLSelectStatement)statement;
		   SQLSelectQuery sqlSelectQuery =st.getSelect().getQuery();
			if(sqlSelectQuery instanceof MySqlSelectQueryBlock) {
				MySqlSelectQueryBlock mysqlSelectQuery = (MySqlSelectQueryBlock)sqlSelectQuery;
				joinParser=new JoinParser(mysqlSelectQuery,realSQL);
				joinParser.parser();
			}	
		}
	   /*	
	   if (routes instanceof DruidMysqlRouteStrategy) {
		   SQLSelectStatement st=((DruidMysqlRouteStrategy) routes).getSQLStatement();
		   SQLSelectQuery sqlSelectQuery =st.getSelect().getQuery();
			if(sqlSelectQuery instanceof MySqlSelectQueryBlock) {
				MySqlSelectQueryBlock mysqlSelectQuery = (MySqlSelectQueryBlock)st.getSelect().getQuery();
				joinParser=new JoinParser(mysqlSelectQuery,realSQL);
				joinParser.parser();
			}
	   }
	   */
	} catch (Exception e) {
	
	}
}
 
Example 12
Source Project: Mycat2   Source File: PreparedStatement.java    License: GNU General Public License v3.0 5 votes vote down vote up
private static String[] getColumns(String sql) {
    String[] columnNames;
    try {
        SQLStatementParser sqlStatementParser = SQLParserUtils.createSQLStatementParser(sql, JdbcUtils.MYSQL);
        SQLStatement statement = sqlStatementParser.parseStatement();
        if (statement instanceof SQLSelectStatement) {
            SQLSelect select = ((SQLSelectStatement) statement).getSelect();
            com.alibaba.druid.sql.dialect.mysql.ast.statement.MySqlSelectQueryBlock query = (com.alibaba.druid.sql.dialect.mysql.ast.statement.MySqlSelectQueryBlock) select.getQuery();
            int size = query.getSelectList().size();
            if (size == 1){
                if("*".equalsIgnoreCase(   query.getSelectList().get(0).toString())){
                    throw new Exception("unsupport * in select items:"+sql);
                }
            } {
                columnNames = new String[size];
                for (int i = 0; i < size; i++) {
                    columnNames[i] = query.getSelectList().get(i).toString();
                }
                return columnNames;
            }

        }
    }catch (Exception e){
        LOGGER.error("can not get column count",e);
    }
    return new String[]{};
}
 
Example 13
Source Project: Mycat2   Source File: MycatStatementParser.java    License: GNU General Public License v3.0 5 votes vote down vote up
@Override
public SQLSelectStatement parseSelect()
{

    MycatSelectParser selectParser = new MycatSelectParser(this.selectExprParser);
    return new SQLSelectStatement(selectParser.select(), JdbcConstants.MYSQL);
}
 
Example 14
@Override
    public boolean visit(SQLSelectStatement x) {
        setAliasMap();
//        getAliasMap().put("DUAL", null);

        return true;
    }
 
Example 15
@Override
public void statementParse(SchemaConfig schema, RouteResultset rrs, SQLStatement stmt) {
	SQLSelectStatement selectStmt = (SQLSelectStatement)stmt;
	SQLSelectQuery sqlSelectQuery = selectStmt.getSelect().getQuery();
      //从mysql解析过来
	if(sqlSelectQuery instanceof MySqlSelectQueryBlock) {
		MySqlSelectQueryBlock mysqlSelectQuery = (MySqlSelectQueryBlock)selectStmt.getSelect().getQuery();
		MySqlSelectQueryBlock.Limit limit=mysqlSelectQuery.getLimit();
		if(limit==null)
		{
			  //使用oracle的解析,否则会有部分oracle语法识别错误
			  OracleStatementParser oracleParser = new OracleStatementParser(getCtx().getSql());
			  SQLSelectStatement oracleStmt = (SQLSelectStatement) oracleParser.parseStatement();
               selectStmt= oracleStmt;
			  SQLSelectQuery oracleSqlSelectQuery = oracleStmt.getSelect().getQuery();
			  if(oracleSqlSelectQuery instanceof OracleSelectQueryBlock)
			  {
				  parseNativePageSql(oracleStmt, rrs, (OracleSelectQueryBlock) oracleSqlSelectQuery, schema);
			  }



		  }
		if(isNeedParseOrderAgg)
		{
			parseOrderAggGroupMysql(schema, selectStmt,rrs, mysqlSelectQuery);
			//更改canRunInReadDB属性
			if ((mysqlSelectQuery.isForUpdate() || mysqlSelectQuery.isLockInShareMode()) && rrs.isAutocommit() == false)
			{
				rrs.setCanRunInReadDB(false);
			}
		}

	}


}
 
Example 16
@Override
public void statementParse(SchemaConfig schema, RouteResultset rrs, SQLStatement stmt) {
	SQLSelectStatement selectStmt = (SQLSelectStatement)stmt;
	SQLSelectQuery sqlSelectQuery = selectStmt.getSelect().getQuery();
	//从mysql解析过来
	if(sqlSelectQuery instanceof MySqlSelectQueryBlock) {
		MySqlSelectQueryBlock mysqlSelectQuery = (MySqlSelectQueryBlock)selectStmt.getSelect().getQuery();
		MySqlSelectQueryBlock.Limit limit=mysqlSelectQuery.getLimit();
		if(limit==null)
		{
               sqlserverParse(schema, rrs);


           }
		if(isNeedParseOrderAgg)
		{
			parseOrderAggGroupMysql(schema, stmt,rrs, mysqlSelectQuery);
			//更改canRunInReadDB属性
			if ((mysqlSelectQuery.isForUpdate() || mysqlSelectQuery.isLockInShareMode()) && rrs.isAutocommit() == false)
			{
				rrs.setCanRunInReadDB(false);
			}
		}

	}


}
 
Example 17
Source Project: Mycat2   Source File: DruidParserFactory.java    License: GNU General Public License v3.0 5 votes vote down vote up
public static DruidParser create(SchemaConfig schema, SQLStatement statement, SchemaStatVisitor visitor)
{
    DruidParser parser = null;
    if (statement instanceof SQLSelectStatement)
    {
        if(schema.isNeedSupportMultiDBType())
        {
            parser = getDruidParserForMultiDB(schema, statement, visitor);

        }

        if (parser == null)
        {
            parser = new DruidSelectParser();
        }
    } else if (statement instanceof MySqlInsertStatement)
    {
        parser = new DruidInsertParser();
    } else if (statement instanceof MySqlDeleteStatement)
    {
        parser = new DruidDeleteParser();
    } else if (statement instanceof MySqlCreateTableStatement)
    {
        parser = new DruidCreateTableParser();
    } else if (statement instanceof MySqlUpdateStatement)
    {
        parser = new DruidUpdateParser();
    } else if (statement instanceof SQLAlterTableStatement)
    {
        parser = new DruidAlterTableParser();
    } else if (statement instanceof MySqlLockTableStatement) {
    	parser = new DruidLockTableParser();
    } else
    {
        parser = new DefaultDruidParser();
    }

    return parser;
}
 
Example 18
/**
 * SELECT 语句
 */
private boolean isSelect(SQLStatement statement) {
	if(statement instanceof SQLSelectStatement) {
		return true;
	}
	return false;
}
 
Example 19
Source Project: dble   Source File: ViewMeta.java    License: GNU General Public License v2.0 5 votes vote down vote up
private void parseSelectInView() throws SQLException {
    SQLSelectStatement selectStatement = (SQLSelectStatement) RouteStrategyFactory.getRouteStrategy().parserSQL(selectSql);
    MySQLPlanNodeVisitor msv = new MySQLPlanNodeVisitor(this.schema, 63, tmManager, false, null);
    msv.visit(selectStatement.getSelect().getQuery());
    PlanNode selNode = msv.getTableNode();

    HashSet<String> schemas = new HashSet<>(4, 1);
    for (TableNode tableNode : selNode.getReferedTableNodes()) {
        if (DbleServer.getInstance().getConfig().getSchemas().get(tableNode.getSchema()).isNoSharding()) {
            schemas.add(tableNode.getSchema());
        } else {
            break;
        }
    }

    if (schemas.size() == 1 && schemas.iterator().next().equals(schema)) {
        if (viewColumnMeta == null) {
            selNode.setUpFields();
            List<Item> selectItems = selNode.getColumnsSelected();
            viewColumnMeta = new ArrayList<>(selectItems.size());
            for (Item item : selectItems) {
                String alias = item.getAlias() == null ? item.getItemName() : item.getAlias();
                viewColumnMeta.add(StringUtil.removeBackQuote(alias));
            }
        }
        viewQuery = new TableNode(schema, viewName, viewColumnMeta);
    } else {
        if (selNode instanceof MergeNode) {
            this.setFieldsAlias(selNode, true);
            selNode.setUpFields();
        } else {
            selNode.setUpFields();
            this.setFieldsAlias(selNode, false);
        }
        viewQuery = new QueryNode(selNode);
    }
}
 
Example 20
Source Project: dble   Source File: NonBlockingSession.java    License: GNU General Public License v2.0 5 votes vote down vote up
public void executeMultiSelect(RouteResultset rrs) {
    SQLSelectStatement ast = (SQLSelectStatement) rrs.getSqlStatement();
    MySQLPlanNodeVisitor visitor = new MySQLPlanNodeVisitor(this.getSource().getSchema(), this.getSource().getCharset().getResultsIndex(), ProxyMeta.getInstance().getTmManager(), false, this.getSource().getUsrVariables());
    visitor.visit(ast);
    PlanNode node = visitor.getTableNode();
    if (node.isCorrelatedSubQuery()) {
        throw new MySQLOutPutException(ErrorCode.ER_UNKNOWN_ERROR, "", "Correlated Sub Queries is not supported ");
    }
    node.setSql(rrs.getStatement());
    node.setUpFields();
    PlanUtil.checkTablesPrivilege(source, node, ast);
    node = MyOptimizer.optimize(node);

    if (PauseDatanodeManager.getInstance().getIsPausing().get() &&
            !PauseDatanodeManager.getInstance().checkTarget(target) &&
            PauseDatanodeManager.getInstance().checkReferedTableNodes(node.getReferedTableNodes())) {
        if (PauseDatanodeManager.getInstance().waitForResume(rrs, this.source, CONTINUE_TYPE_MULTIPLE)) {
            return;
        }
    }
    setPreExecuteEnd(true);
    if (PlanUtil.containsSubQuery(node)) {
        setSubQuery();
        final PlanNode finalNode = node;
        //sub Query build will be blocked, so use ComplexQueryExecutor
        DbleServer.getInstance().getComplexQueryExecutor().execute(() -> {
            executeMultiResultSet(finalNode);
        });
    } else {
        if (!visitor.isContainSchema()) {
            node.setAst(ast);
        }
        executeMultiResultSet(node);
    }
}
 
Example 21
Source Project: dble   Source File: PlanUtil.java    License: GNU General Public License v2.0 5 votes vote down vote up
public static void checkTablesPrivilege(ServerConnection source, PlanNode node, SQLSelectStatement stmt) {
    for (TableNode tn : node.getReferedTableNodes()) {
        if (!ServerPrivileges.checkPrivilege(source, tn.getSchema(), tn.getTableName(), ServerPrivileges.CheckType.SELECT)) {
            String msg = "The statement DML privilege check is not passed, sql:" + stmt.toString().replaceAll("[\\t\\n\\r]", " ");
            throw new MySQLOutPutException(ErrorCode.ER_PARSE_ERROR, "", msg);
        }
    }
}
 
Example 22
private PlanNode getPlanNode(String sql) {
    SQLStatementParser parser = new MySqlStatementParser(sql);
    SQLSelectStatement ast = (SQLSelectStatement) parser.parseStatement();
    MySQLPlanNodeVisitor visitor = new MySQLPlanNodeVisitor("TESTDB", 33, null, true, null);
    visitor.visit(ast);
    return visitor.getTableNode();
}
 
Example 23
Source Project: baymax   Source File: MySqlSelectParser.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void changeSql(ParseResult result, ExecutePlan plan) {
    // 解析聚合函数的
    parseStatement(result, plan, (SQLSelectStatement)statement);
    // TODO 设置读写分离
    super.changeSql(result, plan);
}
 
Example 24
Source Project: baymax   Source File: MySqlSelectParser.java    License: Apache License 2.0 5 votes vote down vote up
protected void parseStatement(ParseResult result, ExecutePlan plan, SQLSelectStatement statement){
     // 单库单表
     if (plan.getSqlList().size() <= 1){
         return;
     }

     SQLSelectQuery sqlSelectQuery = statement.getSelect().getQuery();
     if(sqlSelectQuery instanceof MySqlSelectQueryBlock) {
         // mysql查询
         parseMysqlQueary(result, plan, (MySqlSelectQueryBlock) sqlSelectQuery);
     } else if (sqlSelectQuery instanceof MySqlUnionQuery) {
         throw new BayMaxException("Union暂不支持发送到多库多表上执行,只能在单库单表执行!");
         // TODO 测试
/*
MySqlUnionQuery unionQuery = (MySqlUnionQuery)sqlSelectQuery;
         SQLSelectQuery left = unionQuery.getLeft();
         SQLSelectQuery right = unionQuery.getLeft();
         if (left instanceof MySqlSelectQueryBlock){
             parseMysqlQueary(result, plan, (MySqlSelectQueryBlock) left);
         }
         if (right instanceof MySqlSelectQueryBlock){
             parseMysqlQueary(result, plan, (MySqlSelectQueryBlock) right);
         }
         */
         //if (left.getFrom().getAlias().equalsIgnoreCase(plan.getSqlList().get(0).getLogicTableName())){

         //}
     }
 }
 
Example 25
Source Project: baymax   Source File: MySqlSelectAggParserTest.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * //agg
 * getMergeColumns
 * getAliaColumns
 *
 * //group by
 * setGroupbyColumns
 *
 * @param sql
 */
public void test(String sql){
    ParseResult result = new ParseResult();
    ExecutePlan plan = new ExecutePlan();

    parser.init(sql, null);
    parser.parse(result);

    plan.setExecuteType(ExecuteType.PARTITION);

    SQLSelectStatement stmt = (SQLSelectStatement) parser.statement;

    parser.parseMysqlQueary(result, plan, (MySqlSelectQueryBlock) stmt.getSelect().getQuery());

    StringBuilder out = new StringBuilder();
    MySqlOutputVisitor outPutVisitor = new MySqlOutputVisitor(out);
    stmt.accept(outPutVisitor);

    System.out.println();
    System.out.println("/***********************agg*************************/");
    System.out.println(plan.getMergeColumns());
    System.out.println("setHasAllColumnExpr:" + result.isHasAllColumnExpr());
    System.out.println(out.toString());
    PrintUtil.printFildAlisMap(result.getAliaColumns());
    System.out.println("/*********************group by**********************/");
    System.out.println(plan.getGroupbyColumns());
    System.out.println("/*********************order by**********************/");
    System.out.println(plan.getOrderbyColumns());

}
 
Example 26
Source Project: Zebra   Source File: ShardPreparedStatement.java    License: Apache License 2.0 5 votes vote down vote up
private void replaceLimitParams(SQLParsedResult parseResult) {
	if (parseResult != null) {
		SQLStatement sqlStatement = parseResult.getStmt();
		if (parseResult.getStmt() != null && sqlStatement instanceof SQLSelectStatement) {
			SQLSelect sqlSelect = ((SQLSelectStatement) sqlStatement).getSelect();
			if (sqlSelect != null) {
				SQLSelectQuery sqlSelectQuery = sqlSelect.getQuery();
				if (sqlSelectQuery != null && sqlSelectQuery instanceof MySqlSelectQueryBlock) {
					MySqlSelectQueryBlock sqlSelectQueryBlock = (MySqlSelectQueryBlock) sqlSelectQuery;
					MySqlSelectQueryBlock.Limit limitExpr = sqlSelectQueryBlock.getLimit();
					if (limitExpr != null) {
						int offsetRefIndex = -1;
						int countRefIndex = -1;
						if (limitExpr.getOffset() instanceof SQLVariantRefExpr
						      && limitExpr.getRowCount() instanceof SQLVariantRefExpr) {
							SQLVariantRefExpr offsetExpr = (SQLVariantRefExpr) limitExpr.getOffset();
							SQLVariantRefExpr countExpr = (SQLVariantRefExpr) limitExpr.getRowCount();

							offsetRefIndex = offsetExpr.getIndex();
							countRefIndex = countExpr.getIndex();

							if (offsetRefIndex > countRefIndex && offsetRefIndex != -1 && countRefIndex != -1) {
								offsetExpr.setIndex(countRefIndex);
								countExpr.setIndex(offsetRefIndex);
							}
						}
					}
				}
			}
		}
	}
}
 
Example 27
Source Project: Zebra   Source File: ShardColumnValueUtil.java    License: Apache License 2.0 5 votes vote down vote up
private static SQLExpr getWhere(SQLParsedResult parseResult) {
	SQLExpr expr = null;
	SQLStatement stmt = parseResult.getStmt();

	if (parseResult.getType() == SqlType.SELECT || parseResult.getType() == SqlType.SELECT_FOR_UPDATE) {
		MySqlSelectQueryBlock query = (MySqlSelectQueryBlock) (((SQLSelectStatement) stmt).getSelect()).getQuery();
		expr = query.getWhere();
	} else if (parseResult.getType() == SqlType.UPDATE) {
		expr = ((MySqlUpdateStatement) stmt).getWhere();
	} else if (parseResult.getType() == SqlType.DELETE) {
		expr = ((MySqlDeleteStatement) stmt).getWhere();
	} else if (parseResult.getType() == SqlType.REPLACE) { // add for replace
		MySqlReplaceStatement replaceStatement = (MySqlReplaceStatement) stmt;
		SQLQueryExpr queryExpr = replaceStatement.getQuery();
		if (queryExpr != null) {
			SQLSelect sqlSelect = queryExpr.getSubQuery();
			sqlSelect.getQuery();
			if (sqlSelect != null) {
				MySqlSelectQueryBlock queryBlock = (MySqlSelectQueryBlock) sqlSelect.getQuery();
				if (queryBlock != null) {
					expr = queryBlock.getWhere();
				}
			}
		}
	}

	return expr;
}
 
Example 28
private void oracleValidationQueryCheck() {
    if (validationQuery == null) {
        return;
    }
    if (validationQuery.length() == 0) {
        return;
    }

    SQLStatementParser sqlStmtParser = SQLParserUtils.createSQLStatementParser(validationQuery, this.dbType);
    List<SQLStatement> stmtList = sqlStmtParser.parseStatementList();

    if (stmtList.size() != 1) {
        return;
    }

    SQLStatement stmt = stmtList.get(0);
    if (!(stmt instanceof SQLSelectStatement)) {
        return;
    }

    SQLSelectQuery query = ((SQLSelectStatement) stmt).getSelect().getQuery();
    if (query instanceof SQLSelectQueryBlock) {
        if (((SQLSelectQueryBlock) query).getFrom() == null) {
            LOG.error("invalid oracle validationQuery. " + validationQuery + ", may should be : " + validationQuery
                    + " FROM DUAL");
        }
    }
}
 
Example 29
private void db2ValidationQueryCheck() {
    if (validationQuery == null) {
        return;
    }
    if (validationQuery.length() == 0) {
        return;
    }

    SQLStatementParser sqlStmtParser = SQLParserUtils.createSQLStatementParser(validationQuery, this.dbType);
    List<SQLStatement> stmtList = sqlStmtParser.parseStatementList();

    if (stmtList.size() != 1) {
        return;
    }

    SQLStatement stmt = stmtList.get(0);
    if (!(stmt instanceof SQLSelectStatement)) {
        return;
    }

    SQLSelectQuery query = ((SQLSelectStatement) stmt).getSelect().getQuery();
    if (query instanceof SQLSelectQueryBlock) {
        if (((SQLSelectQueryBlock) query).getFrom() == null) {
            LOG.error("invalid db2 validationQuery. " + validationQuery + ", may should be : " + validationQuery
                    + " FROM SYSDUMMY");
        }
    }
}
 
Example 30
Source Project: dts   Source File: SelectParser.java    License: Apache License 2.0 4 votes vote down vote up
@Override
public TableDataInfo getOriginValue(List<Object> whereParamsList, SQLSelectStatement parseSqlStatement,
    Connection connection, TableMetaInfo tableMetaInfo) throws SQLException {
    Savepoint sp = null;
    TableDataInfo txcTable = new TableDataInfo();
    txcTable.setTableName(getTableName(parseSqlStatement));
    Set<String> primaryKeyNameSet = tableMetaInfo.getPrimaryKeyName();
    String selectSql = selectSql(parseSqlStatement, primaryKeyNameSet);
    LockRetryExecutor lockRetryExecutor = new LockRetryExecutor();
    Connection conn = ((ConnectionAdapter)connection).getSourceConnection();
    boolean originalAutoCommit = conn.getAutoCommit();
    try {
        if (originalAutoCommit) {
            conn.setAutoCommit(false);
        }
        sp = conn.setSavepoint();
        while (true) {

            PreparedStatement preparedStatement = null;
            ResultSet resultSet = null;
            try {
                preparedStatement = conn.prepareStatement(selectSql);
                if (whereParamsList != null && !whereParamsList.isEmpty()) {
                    for (int i = 1; i <= whereParamsList.size(); i++) {
                        preparedStatement.setObject(i, whereParamsList.get(i - 1));
                    }
                }
                resultSet = preparedStatement.executeQuery();
                List<TableDataInfo.TxcLine> txcLines =
                    ResultConvertUtils.convertWithPrimary(resultSet, primaryKeyNameSet, getSqlType());
                txcTable.setLine(txcLines);
                boolean allLocked = true;
                for (TableDataInfo.TxcLine txcLine : txcLines) {
                    String row_key = ResourceRowLockHelper.buildRowKey(txcLine.getPrimaryKeyValues());
                    boolean locked = ResourceRowLockHelper.rowLocked(((ConnectionAdapter)connection),
                        ((ConnectionAdapter)connection).getConnectionRuntimeContext(), txcTable.getTableName(),
                        row_key);
                    if (locked) {
                        conn.rollback(sp);
                        lockRetryExecutor.sleep();
                        allLocked = false;
                        break;
                    }
                }
                if (allLocked) {
                    break;
                }
            } catch (Throwable e) {
                logger.error("Global lock for select failed", e);
                conn.rollback(sp);
                throw e;
            } finally {
                if (resultSet != null) {
                    resultSet.close();
                }
                if (preparedStatement != null) {
                    preparedStatement.close();
                }
            }
        }

    } finally {
        if (sp != null) {
            conn.releaseSavepoint(sp);
        }
        if (originalAutoCommit) {
            conn.setAutoCommit(true);
        }
    }
    return null;
}