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

The following examples show how to use com.alibaba.druid.sql.ast.statement.SQLSelectQuery. 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
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 2
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 3
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 4
@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 5
private void parseThreeLevelPageSql(SQLStatement stmt, RouteResultset rrs, SchemaConfig schema, SQLSubqueryTableSource from, SQLBinaryOpExpr one, SQLBinaryOperator operator)
{
       SQLIntegerExpr right = (SQLIntegerExpr) one.getRight();
	int firstrownum = right.getNumber().intValue();
	if (operator == SQLBinaryOperator.GreaterThanOrEqual&&firstrownum!=0) {
		firstrownum = firstrownum - 1;
	}
	SQLSelectQuery subSelect = from.getSelect().getQuery();
	if (subSelect instanceof OracleSelectQueryBlock)
       {  //第二层子查询
           OracleSelectQueryBlock twoSubSelect = (OracleSelectQueryBlock) subSelect;
           if (twoSubSelect.getWhere() instanceof SQLBinaryOpExpr && twoSubSelect.getFrom() instanceof SQLSubqueryTableSource)
           {
               SQLBinaryOpExpr twoWhere = (SQLBinaryOpExpr) twoSubSelect.getWhere();
               boolean isRowNum = "rownum".equalsIgnoreCase(twoWhere.getLeft().toString());
               boolean isLess = twoWhere.getOperator() == SQLBinaryOperator.LessThanOrEqual || twoWhere.getOperator() == SQLBinaryOperator.LessThan;
               if (isRowNum && twoWhere.getRight() instanceof SQLIntegerExpr && isLess)
               {
                   int lastrownum = ((SQLIntegerExpr) twoWhere.getRight()).getNumber().intValue();
                   if (operator == SQLBinaryOperator.LessThan&&lastrownum!=0) {
					lastrownum = lastrownum - 1;
				}
                   SQLSelectQuery finalQuery = ((SQLSubqueryTableSource) twoSubSelect.getFrom()).getSelect().getQuery();
                   if (finalQuery instanceof OracleSelectQueryBlock)
                   {
					setLimitIFChange(stmt, rrs, schema, one, firstrownum, lastrownum);
                       parseOrderAggGroupOracle(stmt,rrs, (OracleSelectQueryBlock) finalQuery, schema);
                       isNeedParseOrderAgg=false;
                   }

               }

           }

       }
}
 
Example 6
@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 7
Source Project: dble   Source File: ItemScalarSubQuery.java    License: GNU General Public License v2.0 5 votes vote down vote up
public ItemScalarSubQuery(String currentDb, SQLSelectQuery query, ProxyMetaManager metaManager, Map<String, String> usrVariables) {
    super(currentDb, query, false, metaManager, usrVariables);
    if (this.planNode.getColumnsSelected().size() > 1) {
        throw new MySQLOutPutException(ErrorCode.ER_OPERAND_COLUMNS, "", "Operand should contain 1 column(s)");
    }
    if (!this.correlatedSubQuery) {
        if ((this.planNode.getLimitFrom() == -1)) {
            this.planNode.setLimitFrom(0);
            this.planNode.setLimitTo(2);
        } else if (this.planNode.getLimitTo() > 2) {
            this.planNode.setLimitTo(2);
        }
    }
}
 
Example 8
Source Project: dble   Source File: ItemSubQuery.java    License: GNU General Public License v2.0 5 votes vote down vote up
public ItemSubQuery(String currentDb, SQLSelectQuery query, ProxyMetaManager metaManager, Map<String, String> usrVariables) {
    this.query = query;
    this.currentDb = currentDb;
    this.metaManager = metaManager;
    this.usrVariables = usrVariables;
    init();
}
 
Example 9
Source Project: dble   Source File: ItemInSubQuery.java    License: GNU General Public License v2.0 5 votes vote down vote up
public ItemInSubQuery(String currentDb, SQLSelectQuery query, Item leftOperand, boolean isNeg, ProxyMetaManager metaManager, Map<String, String> usrVariables) {
    super(currentDb, query, metaManager, usrVariables);
    this.leftOperand = leftOperand;
    this.isNeg = isNeg;
    if (this.planNode.getColumnsSelected().size() > 1) {
        throw new MySQLOutPutException(ErrorCode.ER_OPERAND_COLUMNS, "", "Operand should contain 1 column(s)");
    }
    this.select = this.planNode.getColumnsSelected().get(0);
}
 
Example 10
Source Project: dble   Source File: ItemAllAnySubQuery.java    License: GNU General Public License v2.0 5 votes vote down vote up
public ItemAllAnySubQuery(String currentDb, SQLSelectQuery query, SQLBinaryOperator operator, boolean isAll, ProxyMetaManager metaManager, Map<String, String> usrVariables) {
    super(currentDb, query, metaManager, usrVariables);
    this.isAll = isAll;
    this.operator = operator;
    if (this.planNode.getColumnsSelected().size() > 1) {
        throw new MySQLOutPutException(ErrorCode.ER_OPERAND_COLUMNS, "", "Operand should contain 1 column(s)");
    }
    this.select = this.planNode.getColumnsSelected().get(0);
}
 
Example 11
Source Project: dble   Source File: ItemExistsSubQuery.java    License: GNU General Public License v2.0 5 votes vote down vote up
public ItemExistsSubQuery(String currentDb, SQLSelectQuery query, boolean isNot, ProxyMetaManager metaManager, Map<String, String> usrVariables) {
    super(currentDb, query, false, metaManager, usrVariables);
    this.isNot = isNot;
    if (!this.correlatedSubQuery) {
        if ((this.planNode.getLimitFrom() == -1)) {
            this.planNode.setLimitFrom(0);
            this.planNode.setLimitTo(1);
        } else if (this.planNode.getLimitTo() > 1) {
            this.planNode.setLimitTo(1);
        }
        this.select = new ItemInt(1L);
        this.planNode.getColumnsSelected().add(select);
    }
}
 
Example 12
Source Project: dble   Source File: PushDownVisitor.java    License: GNU General Public License v2.0 5 votes vote down vote up
private void buildForUpdate(TableNode query, StringBuilder sb) {
    if (query.getAst() != null) {
        SQLSelectQuery queryblock = query.getAst().getSelect().getQuery();
        if (queryblock instanceof MySqlSelectQueryBlock) {
            if (((MySqlSelectQueryBlock) queryblock).isForUpdate()) {
                sb.append(" FOR UPDATE");
            } else if (((MySqlSelectQueryBlock) queryblock).isLockInShareMode()) {
                sb.append(" LOCK IN SHARE MODE ");
            }

        }
    }
}
 
Example 13
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 14
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 15
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 16
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 17
Source Project: Mycat2   Source File: DefaultDruidParser.java    License: GNU General Public License v3.0 4 votes vote down vote up
/**
	 * 子类可覆盖(如果该方法解析得不到表名、字段等信息的,就覆盖该方法,覆盖成空方法,然后通过statementPparse去解析)
	 * 通过visitor解析:有些类型的Statement通过visitor解析得不到表名、
	 * @param stmt
	 */
	@Override
	public void visitorParse(RouteResultset rrs, SQLStatement stmt,MycatSchemaStatVisitor visitor) throws SQLNonTransientException{

		stmt.accept(visitor);
		ctx.setVisitor(visitor);

		if(stmt instanceof SQLSelectStatement){
			SQLSelectQuery query = ((SQLSelectStatement) stmt).getSelect().getQuery();
			if(query instanceof MySqlSelectQueryBlock){
				if(((MySqlSelectQueryBlock)query).isForUpdate()){
					rrs.setSelectForUpdate(true);
				}
			}
		}

		List<List<Condition>> mergedConditionList = new ArrayList<List<Condition>>();
		if(visitor.hasOrCondition()) {//包含or语句
			//TODO
			//根据or拆分
			mergedConditionList = visitor.splitConditions();
		} else {//不包含OR语句
			mergedConditionList.add(visitor.getConditions());
		}
		
		if(visitor.isHasChange()){	// 在解析的过程中子查询被改写了.需要更新ctx.
			ctx.setSql(stmt.toString());
			rrs.setStatement(ctx.getSql());
		}
		
		if(visitor.getAliasMap() != null) {
			for(Map.Entry<String, String> entry : visitor.getAliasMap().entrySet()) {
				String key = entry.getKey();
				String value = entry.getValue();
				if(key != null && key.indexOf("`") >= 0) {
					key = key.replaceAll("`", "");
				}
				if(value != null && value.indexOf("`") >= 0) {
					value = value.replaceAll("`", "");
				}
				//表名前面带database的,去掉
				if(key != null) {
					int pos = key.indexOf(".");
					if(pos> 0) {
						key = key.substring(pos + 1);
					}
					
					tableAliasMap.put(key.toUpperCase(), value);
				}
				

//				else {
//					tableAliasMap.put(key, value);
//				}

			}
			ctx.addTables(visitor.getTables());
			
			visitor.getAliasMap().putAll(tableAliasMap);
			ctx.setTableAliasMap(tableAliasMap);
		}
		ctx.setRouteCalculateUnits(this.buildRouteCalculateUnits(visitor, mergedConditionList));
	}
 
Example 18
Source Project: dble   Source File: ItemSingleRowSubQuery.java    License: GNU General Public License v2.0 4 votes vote down vote up
public ItemSingleRowSubQuery(String currentDb, SQLSelectQuery query, boolean isField, ProxyMetaManager metaManager, Map<String, String> usrVariables) {
    super(currentDb, query, metaManager, usrVariables);
    this.select = this.planNode.getColumnsSelected().get(0);
    this.isField = isField;
}
 
Example 19
Source Project: dble   Source File: ItemMultiRowSubQuery.java    License: GNU General Public License v2.0 2 votes vote down vote up
/**
 * @param currentDb
 * @param query
 */
public ItemMultiRowSubQuery(String currentDb, SQLSelectQuery query, ProxyMetaManager metaManager, Map<String, String> usrVariables) {
    super(currentDb, query, metaManager, usrVariables);
}