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

The following examples show how to use com.alibaba.druid.sql.ast.statement.SQLSelectItem. 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: 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 2
Source Project: Zebra   Source File: MysqlCountOutputVisitor.java    License: Apache License 2.0 6 votes vote down vote up
private boolean visitSelectItems(List<SQLSelectItem> selectItems, boolean distinct) {
	boolean rewriteDistinct = false;
	if (this.subSelect) {
		// sub select
		print0(ucase ? "SELECT " : "select ");
		if (distinct) {
			print0(ucase ? "DISTINCT " : "distinct ");
		}
		printSelectItems(selectItems);
	} else {
		if (distinct) {
			// select distinct a,b,... from xxx
			print0(ucase ? "SELECT COUNT(*) FROM (SELECT DISTINCT " : "select count(*) from (select distinct ");
			printSelectItems(selectItems);
			rewriteDistinct = true;
		} else {
			// normal select
			print0(ucase ? "SELECT COUNT(*) " : "select count(*) ");
		}
	}
	this.subSelect = true;
	return rewriteDistinct;
}
 
Example 3
Source Project: elasticsearch-sql   Source File: ElasticSqlSelectParser.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void parseFrom(SQLSelectQueryBlock queryBlock) {
    if (lexer.token() != Token.FROM) {
        return;
    }

    lexer.nextTokenIdent();

    if (lexer.token() == Token.UPDATE) { // taobao returning to urgly syntax
        updateStmt = this.parseUpdateStatment();
        List<SQLExpr> returnning = updateStmt.getReturning();
        for (SQLSelectItem item : queryBlock.getSelectList()) {
            SQLExpr itemExpr = item.getExpr();
            itemExpr.setParent(updateStmt);
            returnning.add(itemExpr);
        }
        returningFlag = true;
        return;
    }

    queryBlock.setFrom(parseTableSource());
}
 
Example 4
Source Project: Mycat2   Source File: JoinParser.java    License: GNU General Public License v3.0 5 votes vote down vote up
private String getFieldName(SQLSelectItem item){
	if (item.getExpr() instanceof SQLPropertyExpr) {			
		return item.getExpr().toString();//字段别名
	}
	else {
		return item.toString();
	}
}
 
Example 5
Source Project: Mycat2   Source File: JoinParser.java    License: GNU General Public License v3.0 5 votes vote down vote up
private String getMethodInvokeFieldName(SQLSelectItem item){
	SQLMethodInvokeExpr invoke = (SQLMethodInvokeExpr)item.getExpr();
	List<SQLExpr> itemExprs = invoke.getParameters();
	for(SQLExpr itemExpr:itemExprs){
		if (itemExpr instanceof SQLPropertyExpr) {
			return itemExpr.toString();//字段别名
		}
	}
	return item.toString();
}
 
Example 6
Source Project: Mycat2   Source File: JoinParser.java    License: GNU General Public License v3.0 5 votes vote down vote up
private void parserFields(List<SQLSelectItem> mysqlSelectList){
		//显示的字段
		String key="";
		String value ="";
		String exprfield = "";
		for(SQLSelectItem item : mysqlSelectList) {
			if (item.getExpr() instanceof SQLAllColumnExpr) {
				//*解析
				setField(item.toString(), item.toString());
			}
			else {
				if (item.getExpr() instanceof SQLAggregateExpr) {
					SQLAggregateExpr expr =(SQLAggregateExpr)item.getExpr();
					 key = getExprFieldName(expr);
					 setField(key, value);
				}else if(item.getExpr() instanceof SQLMethodInvokeExpr){
					key = getMethodInvokeFieldName(item);
					exprfield=getFieldName(item);
//					value=item.getAlias();
					setField(key, value,exprfield);
				}else {					
					key=getFieldName(item);
					value=item.getAlias();
					setField(key, value);
				}			
				
			}
		}			
	}
 
Example 7
private static FieldPacket[] generateFieldPacket(List<SQLSelectItem> selectList) {
    FieldPacket[] fields = new FieldPacket[selectList.size()];
    for (int i = 0; i < selectList.size(); i++) {
        String columnName;
        SQLSelectItem selectItem = selectList.get(i);
        if (selectItem.getAlias() != null) {
            columnName = StringUtil.removeBackQuote(selectList.get(i).getAlias());
        } else {
            columnName = StringUtil.removeBackQuote(selectItem.toString());
        }
        fields[i] = PacketUtil.getField(columnName, Fields.FIELD_TYPE_VAR_STRING);
    }
    return fields;
}
 
Example 8
Source Project: baymax   Source File: MySqlSelectParser.java    License: Apache License 2.0 5 votes vote down vote up
protected String getFieldName(SQLSelectItem item){
    if ((item.getExpr() instanceof SQLPropertyExpr)||(item.getExpr() instanceof SQLMethodInvokeExpr)
            || (item.getExpr() instanceof SQLIdentifierExpr) || item.getExpr() instanceof SQLBinaryOpExpr) {
        return item.getExpr().toString();//字段别名
    }else {
        return item.toString();
    }
}
 
Example 9
Source Project: baymax   Source File: MySqlSelectParser.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 解析Orderby
 * @param result
 * @param plan
 * @param mysqlSelectQuery
 */
protected void parseOrderby(ParseResult result, ExecutePlan plan, MySqlSelectQueryBlock mysqlSelectQuery){
    if (mysqlSelectQuery.getOrderBy() == null){
        return;
    }
    List<SQLSelectOrderByItem> orderByItems = mysqlSelectQuery.getOrderBy().getItems();
    if (orderByItems == null || orderByItems.size() == 0){
        return;
    }
    List<SQLSelectItem> selectList      = mysqlSelectQuery.getSelectList();
    List<OrderbyColumn> orderbyColumns  = new ArrayList<OrderbyColumn>(orderByItems.size());
    for(SQLSelectOrderByItem item : orderByItems){
        String name = StringUtil.removeDot(item.getExpr().toString());
        if (result.getAliaColumns() != null){
            String alias = result.getAliaColumns().get(name);
            if (alias != null){
                // select user_id as uid ....order by user_id
                // 要把oderby的user_id转换为uid,以便结果集合并
                orderbyColumns.add(new OrderbyColumn(alias, OrderbyColumn.buildOrderbyType(item.getType())));
                continue;
            }
        }
        if (!result.isHasAllColumnExpr()){
            // select列表中没有orderby的字段 添加,用于后面做合并
            SQLIdentifierExpr exp = new SQLIdentifierExpr(name);

            // item
            SQLSelectItem addItem = new SQLSelectItem();
            addItem.setExpr(exp);
            exp.setParent(item);
            selectList.add(addItem);
        }
        orderbyColumns.add(new OrderbyColumn(name, OrderbyColumn.buildOrderbyType(item.getType())));
    }
    plan.setOrderbyColumns(orderbyColumns);
}
 
Example 10
Source Project: Zebra   Source File: MysqlCountOutputVisitor.java    License: Apache License 2.0 5 votes vote down vote up
private void printSelectItems(List<SQLSelectItem> selectItems) {
	for (int i = 0; i < selectItems.size(); ++i) {
		SQLSelectItem item = selectItems.get(i);
		if (i > 0) {
			print0(",");
		}
		item.accept(this);
	}
}
 
Example 11
Source Project: elasticsearch-sql   Source File: SqlParser.java    License: Apache License 2.0 5 votes vote down vote up
private void findSelect(MySqlSelectQueryBlock query, Select select, String tableAlias) throws SqlParseException {
    List<SQLSelectItem> selectList = query.getSelectList();
    for (SQLSelectItem sqlSelectItem : selectList) {
        Field field = FieldMaker.makeField(sqlSelectItem.getExpr(), sqlSelectItem.getAlias(), tableAlias);
        select.addField(field);
    }
}
 
Example 12
Source Project: Mycat2   Source File: MycatExprParser.java    License: GNU General Public License v3.0 4 votes vote down vote up
@Override
public SQLSelectItem parseSelectItem()
{
    parseTop();
    return super.parseSelectItem();
}
 
Example 13
Source Project: baymax   Source File: MySqlSelectParser.java    License: Apache License 2.0 4 votes vote down vote up
/**
 * 解析聚合函数
 * @param result
 * @param plan
 * @param mysqlSelectQuery
 */
protected void parseAggregate(ParseResult result, ExecutePlan plan, MySqlSelectQueryBlock mysqlSelectQuery){
    // 要合并的列
    Map<String, MergeColumn.MergeType>      aggrColumns         = new HashMap<String, MergeColumn.MergeType>();
    Map<String/*field*/, String/*alias*/>   aliaColumns         = new HashMap<String, String>();
    // 查询的列
    List<SQLSelectItem>                     selectList          = mysqlSelectQuery.getSelectList();
    int                                     size                = selectList.size();
    //boolean                               isDistinct          = mysqlSelectQuery.getDistionOption() == 2;
    List<String>                            avgColumns          = null;

    for (int i = 0; i < size; i++){
        SQLSelectItem item = selectList.get(i);
        if (item.getExpr() instanceof SQLAggregateExpr) {
            SQLAggregateExpr expr = (SQLAggregateExpr) item.getExpr();
            String method = expr.getMethodName();
            // 只处理有别名的情况,无别名添加别名,否则某些数据库会得不到正确结果处理
            MergeColumn.MergeType mergeType = MergeColumn.buildMergeType(method);

            if (MergeColumn.MergeType.MERGE_UNSUPPORT == mergeType) {
                continue;
            }

            // 没有别名的 增加别名
            if (item.getAlias() == null || item.getAlias().length() <= 0) {
                item.setAlias(method + i);
            }

            // 保存合并列
            aggrColumns.put(item.getAlias(), mergeType);

            if (MergeColumn.MergeType.MERGE_AVG == mergeType) {
                if (avgColumns == null) {
                    avgColumns = new ArrayList<String>();
                }
                avgColumns.add(item.getAlias());

                //sum
                // 表达式
                SQLAggregateExpr sumExp = new SQLAggregateExpr("SUM");
                ReflectionUtils.copyProperties(expr, sumExp);
                sumExp.getArguments().addAll(expr.getArguments());
                sumExp.setMethodName("SUM");

                // item
                SQLSelectItem sum = new SQLSelectItem();
                String sumColName = item.getAlias() + "SUM";
                sum.setAlias(sumColName);
                sum.setExpr(sumExp);

                // 替换
                selectList.add(sum);
                aggrColumns.put(sumColName, MergeColumn.MergeType.MERGE_SUM);

                // count
                // 表达式
                SQLAggregateExpr countExp = new SQLAggregateExpr("COUNT");
                ReflectionUtils.copyProperties(expr, countExp);
                countExp.getArguments().addAll(expr.getArguments());
                countExp.setMethodName("COUNT");

                // item
                SQLSelectItem count = new SQLSelectItem();
                String countColName = item.getAlias() + "COUNT";
                count.setAlias(countColName);
                count.setExpr(countExp);

                // 替换
                selectList.add(count);
                aggrColumns.put(countColName, MergeColumn.MergeType.MERGE_COUNT);

                // 原始avg
                aggrColumns.put(item.getAlias(), MergeColumn.MergeType.MERGE_AVG);
            }
        }else
        // 所有select字段的别名
        if (item.getExpr() instanceof SQLAllColumnExpr){
            // select *
            result.setHasAllColumnExpr(true);
        }else if(item.getExpr() instanceof SQLIdentifierExpr){
            // 只有普通select list的字段才放到别名列表中,用于orderby groupby的取值比较
            String alia = item.getAlias();
            //String field = getFieldName(item);
            String field = item.getExpr().toString();
            alia = alia == null ? field : alia;
            aliaColumns.put(field, alia);
        }
    }
    plan.setMergeColumns(aggrColumns);
    result.setAliaColumns(aliaColumns);
}
 
Example 14
Source Project: baymax   Source File: MySqlSelectParser.java    License: Apache License 2.0 4 votes vote down vote up
/**
 * 解析groupby
 * @param result
 * @param plan
 * @param mysqlSelectQuery
 */
protected void parseGroupBy(ParseResult result, ExecutePlan plan, MySqlSelectQueryBlock mysqlSelectQuery){
    if(mysqlSelectQuery.getGroupBy() == null) {
        return;
    }
    List<SQLExpr> groupByItems = mysqlSelectQuery.getGroupBy().getItems();
    if (groupByItems == null || groupByItems.size() == 0){
        return;
    }
    List<SQLSelectItem> selectList      = mysqlSelectQuery.getSelectList();
    List<String> groupbyColumns  = new ArrayList<String>(groupByItems.size());
    for(SQLExpr item : groupByItems){
        String name = null;
        if (item instanceof MySqlSelectGroupByExpr){
            name = StringUtil.removeDot(((MySqlSelectGroupByExpr) item).getExpr().toString());
        }else if (item instanceof SQLIdentifierExpr){
            name = item.toString();
        }else if (item instanceof SQLName){
            name = ((SQLName) item).getSimpleName();
        }else {
            throw new BayMaxException("group by 不支持的表达式:" + item.toString());
        }
        if (result.getAliaColumns() != null){
            // 有别名,说明在select list中使用了别名
            String alias = result.getAliaColumns().get(name);
            if (alias != null){
                // select user_id as uid ....order by user_id
                // 要把oderby的user_id转换为uid,以便结果集合并,这个替换是等价的
                // 因为合并的时候需要根据orderby的字段,取值,比较
                groupbyColumns.add(alias);
                continue;
            }
        }
        if (!result.isHasAllColumnExpr()){
            // select列表中没有orderby的字段 添加,用于后面做合并
            SQLIdentifierExpr exp = new SQLIdentifierExpr(name);
            // item
            SQLSelectItem addItem = new SQLSelectItem();
            addItem.setExpr(exp);
            exp.setParent(item);
            selectList.add(addItem);
        }
        groupbyColumns.add(name);
    }
    plan.setGroupbyColumns(groupbyColumns);
}
 
Example 15
Source Project: Zebra   Source File: ShardLimitSqlWithConditionRewrite.java    License: Apache License 2.0 4 votes vote down vote up
private void initConditionExpr() {
	SQLBinaryOperator startOperator, endOperator;
	// 上下线每个条件的边际表达式
	SQLBinaryOpExpr startBoundaryExpr = null, endBoundaryExpr = null;

	for (SQLSelectOrderByItem orderByEle : context.getOrderBy().getItems()) {
		if (orderByEle.getType() == null || ((SQLOrderingSpecification) orderByEle.getType()).name().equals("ASC")) {
			startOperator = SQLBinaryOperator.GreaterThan;
			endOperator = SQLBinaryOperator.LessThan;
		} else {
			startOperator = SQLBinaryOperator.LessThan;
			endOperator = SQLBinaryOperator.GreaterThan;
		}
		try {
			SQLExpr starColumnExpr = convertColumnDataToSQLExpr(startData.get(orderByEle.getExpr().toString()));
			SQLExpr endColumnExpr = convertColumnDataToSQLExpr(endData.get(orderByEle.getExpr().toString()));
			SQLExpr compareExpr = orderByEle.getExpr();
			// 如果orderby的column是一个表达式的结果,则把表达式作为新条件的比较变量
			SQLObjectImpl selectItem = context.getSelectItemMap().get(orderByEle.getExpr().toString());
			if (selectItem == null) {
				selectItem = context.getSelectItemMap().get(orderByEle.getExpr().toString().toLowerCase());

				if (selectItem == null) {
					selectItem = context.getSelectItemMap().get(orderByEle.getExpr().toString().toUpperCase());
				}
			}

			if (selectItem != null) {
				if (selectItem instanceof SQLSelectItem) {
					compareExpr = ((SQLSelectItem) selectItem).getExpr();
				}
			}

			SQLBinaryOpExpr startExpr = new SQLBinaryOpExpr(compareExpr, startOperator, starColumnExpr);
			SQLBinaryOpExpr endExpr = new SQLBinaryOpExpr(compareExpr, endOperator, endColumnExpr);

			if (startBoundaryExpr != null) {
				// 在上一个边际表达式的基础上加上and条件
				addStartConditionExpr(new SQLBinaryOpExpr(startBoundaryExpr, SQLBinaryOperator.BooleanAnd, startExpr));
				addEndConditionExpr(new SQLBinaryOpExpr(endBoundaryExpr, SQLBinaryOperator.BooleanAnd, endExpr));
				startBoundaryExpr = new SQLBinaryOpExpr(startBoundaryExpr, SQLBinaryOperator.BooleanAnd,
				      new SQLBinaryOpExpr(compareExpr, SQLBinaryOperator.Equality, starColumnExpr));
				endBoundaryExpr = new SQLBinaryOpExpr(endBoundaryExpr, SQLBinaryOperator.BooleanAnd,
				      new SQLBinaryOpExpr(compareExpr, SQLBinaryOperator.Equality, endColumnExpr));
			} else {
				addStartConditionExpr(startExpr);
				addEndConditionExpr(endExpr);
				startBoundaryExpr = new SQLBinaryOpExpr(compareExpr, SQLBinaryOperator.Equality, starColumnExpr);
				endBoundaryExpr = new SQLBinaryOpExpr(compareExpr, SQLBinaryOperator.Equality, endColumnExpr);
			}
		} catch (SQLException ignore) {
		}
	}
	// 最后补上边际条件
	addStartConditionExpr(startBoundaryExpr);
	addEndConditionExpr(endBoundaryExpr);
}
 
Example 16
Source Project: Zebra   Source File: MySQLSelectASTVisitor.java    License: Apache License 2.0 4 votes vote down vote up
@Override
public boolean visit(MySqlSelectQueryBlock x) {
	result.getMergeContext().increQueryCount();
	Map<String, SQLObjectImpl> selectItemMap = result.getMergeContext().getSelectItemMap();
	Map<String, String> columnNameAliasMapping = result.getMergeContext().getColumnNameAliasMapping();

	for (SQLSelectItem column : x.getSelectList()) {
		String name = null;
		if (column.getExpr() instanceof SQLAggregateExpr) {
			SQLAggregateExpr expr = (SQLAggregateExpr) column.getExpr();
			SQLExpr argument = expr.getArguments().get(0);
			if (argument instanceof SQLAllColumnExpr) {
				name = expr.getMethodName() + "(*)";
			} else if (argument instanceof SQLIntegerExpr) {
				name = expr.getMethodName() + "(1)";
			} else {
				name = expr.getMethodName() + "(" + argument.toString() + ")";
				if (column.getAlias() != null) {
					columnNameAliasMapping.put(name, column.getAlias());
				}
			}

			result.getMergeContext().setAggregate(true);
		} else if (column.getExpr() instanceof SQLIdentifierExpr || column.getExpr() instanceof SQLPropertyExpr) {
			name = ((SQLName) column.getExpr()).getSimpleName();

			if (column.getAlias() != null) {
				SQLName identifier = (SQLName) column.getExpr();
				columnNameAliasMapping.put(identifier.getSimpleName(), column.getAlias());
			}
		} else {
			// ignore SQLAllColumnExpr,SQLMethodInvokeExpr and etc.
		}

		selectItemMap.put(column.getAlias() == null ? name : column.getAlias(), column);
	}

	if (x.getDistionOption() == 2) {
		result.getMergeContext().setDistinct(true);
	}

	return true;
}