Java Code Examples for com.alibaba.druid.sql.dialect.mysql.ast.statement.MySqlSelectQueryBlock#getSelectList()

The following examples show how to use com.alibaba.druid.sql.dialect.mysql.ast.statement.MySqlSelectQueryBlock#getSelectList() . 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 File: SelectHandler.java    From dble with 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 File: SchemaUtil.java    From dble with GNU General Public License v2.0 6 votes vote down vote up
public static boolean isNoSharding(ServerConnection source, SQLSelectQuery sqlSelectQuery, SQLStatement selectStmt, SQLStatement childSelectStmt, String contextSchema, Set<String> schemas, StringPtr dataNode)
        throws SQLException {
    if (sqlSelectQuery instanceof MySqlSelectQueryBlock) {
        MySqlSelectQueryBlock mySqlSelectQueryBlock = (MySqlSelectQueryBlock) sqlSelectQuery;
        //CHECK IF THE SELECT LIST HAS INNER_FUNC IN,WITCH SHOULD BE DEAL BY DBLE
        for (SQLSelectItem item : mySqlSelectQueryBlock.getSelectList()) {
            if (item.getExpr() instanceof SQLMethodInvokeExpr) {
                if (ItemCreate.getInstance().isInnerFunc(((SQLMethodInvokeExpr) item.getExpr()).getMethodName())) {
                    return false;
                }
            }
        }
        return isNoSharding(source, mySqlSelectQueryBlock.getFrom(), selectStmt, childSelectStmt, contextSchema, schemas, dataNode);
    } else if (sqlSelectQuery instanceof SQLUnionQuery) {
        return isNoSharding(source, (SQLUnionQuery) sqlSelectQuery, selectStmt, contextSchema, schemas, dataNode);
    } else {
        return false;
    }
}
 
Example 3
Source File: TestMySQLItemVisitor.java    From dble with GNU General Public License v2.0 5 votes vote down vote up
@Test
public void testSelectItem() {
    MySqlSelectQueryBlock query = getQuery("select sum(col1) from table1 where a >1 ");
    List<SQLSelectItem> items = query.getSelectList();

    MySQLItemVisitor v = new MySQLItemVisitor(this.currentDb, utf8Charset,null, null);
    items.get(0).accept(v);
    Item item = v.getItem();
    Assert.assertEquals(true, "SUM(col1)".equals(item.getItemName()));
}
 
Example 4
Source File: MySqlSelectParser.java    From baymax with 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 5
Source File: MysqlCountOutputVisitor.java    From Zebra with Apache License 2.0 5 votes vote down vote up
public boolean visit(MySqlSelectQueryBlock x) {
	if (x.getOrderBy() != null) {
		x.getOrderBy().setParent(x);
	}

	boolean rewriteDistinct = false;
	if (x.getSelectList() != null) {
		rewriteDistinct = visitSelectItems(x.getSelectList(), SQLSetQuantifier.DISTINCT == x.getDistionOption());
	}

	if (x.getFrom() != null) {
		println();
		print0(ucase ? "FROM " : "from ");
		x.getFrom().accept(this);
	}

	if (x.getWhere() != null) {
		println();
		print0(ucase ? "WHERE " : "where ");
		x.getWhere().setParent(x);
		x.getWhere().accept(this);
	}

	if (x.getGroupBy() != null) {
		println();
		x.getGroupBy().accept(this);
	}

	if (x.getOrderBy() != null) {
		println();
		x.getOrderBy().accept(this);
	}

	if (rewriteDistinct) {
		print0(") ZebraDaoDistinctTable");
	}

	return false;
}
 
Example 6
Source File: SqlParser.java    From elasticsearch-sql with 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 7
Source File: MySqlSelectParser.java    From baymax with 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 8
Source File: MySqlSelectParser.java    From baymax with 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 9
Source File: MySQLSelectASTVisitor.java    From Zebra with 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;
}