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

The following examples show how to use com.alibaba.druid.sql.dialect.mysql.ast.statement.MySqlSelectQueryBlock#getFrom() . 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: ServerSchemaStatVisitor.java    From dble with GNU General Public License v2.0 5 votes vote down vote up
/**
 * get table name of field in between expr
 *
 */
private String getOwnerTableName(SQLBetweenExpr betweenExpr, String column) {
    if (aliasMap.size() == 1) { //only has 1 table
        return aliasMap.keySet().iterator().next();
    } else if (aliasMap.size() == 0) { //no table
        return "";
    } else { // multi tables
        for (Column col : columns.values()) {
            if (col.getName().equals(column)) {
                return col.getTable();
            }
        }

        //parser from parent
        SQLObject parent = betweenExpr.getParent();
        if (parent instanceof SQLBinaryOpExpr) {
            parent = parent.getParent();
        }

        if (parent instanceof MySqlSelectQueryBlock) {
            MySqlSelectQueryBlock select = (MySqlSelectQueryBlock) parent;
            if (select.getFrom() instanceof SQLJoinTableSource) {
                SQLJoinTableSource joinTableSource = (SQLJoinTableSource) select.getFrom();
                //FIXME :left as driven table
                return joinTableSource.getLeft().toString();
            } else if (select.getFrom() instanceof SQLExprTableSource) {
                return select.getFrom().toString();
            }
        } else if (parent instanceof SQLUpdateStatement) {
            SQLUpdateStatement update = (SQLUpdateStatement) parent;
            return update.getTableName().getSimpleName();
        } else if (parent instanceof SQLDeleteStatement) {
            SQLDeleteStatement delete = (SQLDeleteStatement) parent;
            return delete.getTableName().getSimpleName();
        }
    }
    return "";
}
 
Example 3
Source File: TestMySQLItemVisitor.java    From dble with GNU General Public License v2.0 5 votes vote down vote up
@Test
public void testJoinCondition() {
    MySqlSelectQueryBlock query = getQuery("select a.col1,b.col2  from table1 a inner join table2 b on a.id =b.id");
    SQLJoinTableSource from = (SQLJoinTableSource) query.getFrom();

    MySQLItemVisitor v = new MySQLItemVisitor(this.currentDb, utf8Charset,null, null);
    from.getCondition().accept(v);
    Item item = v.getItem();
    Assert.assertEquals(true, "a.id = b.id".equals(item.getItemName()));
}
 
Example 4
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 5
Source File: MycatSchemaStatVisitor.java    From Mycat2 with GNU General Public License v3.0 4 votes vote down vote up
/**
     * 从between语句中获取字段所属的表名。
     * 对于容易出现ambiguous的(字段不知道到底属于哪个表),实际应用中必须使用别名来避免歧义
     * @param betweenExpr
     * @param column
     * @return
     */
    private String getOwnerTableName(SQLBetweenExpr betweenExpr,String column) {
        if(tableStats.size() == 1) {//只有一个表,直接返回这一个表名
            return tableStats.keySet().iterator().next().getName();
        } else if(tableStats.size() == 0) {//一个表都没有,返回空串
            return "";
        } else {//多个表名
            for (Column col : columns.keySet())
            {
                if(col.getName().equals(column)) {
                    return col.getTable();
                }
            }
//            for(Column col : columns) {//从columns中找表名
//                if(col.getName().equals(column)) {
//                    return col.getTable();
//                }
//            }

            //前面没找到表名的,自己从parent中解析

            SQLObject parent = betweenExpr.getParent();
            if(parent instanceof SQLBinaryOpExpr)
            {
                parent=parent.getParent();
            }

            if(parent instanceof MySqlSelectQueryBlock) {
                MySqlSelectQueryBlock select = (MySqlSelectQueryBlock) parent;
                if(select.getFrom() instanceof SQLJoinTableSource) {//多表连接
                    SQLJoinTableSource joinTableSource = (SQLJoinTableSource)select.getFrom();
                    return joinTableSource.getLeft().toString();//将left作为主表,此处有不严谨处,但也是实在没有办法,如果要准确,字段前带表名或者表的别名即可
                } else if(select.getFrom() instanceof SQLExprTableSource) {//单表
                    return select.getFrom().toString();
                }
            }
            else if(parent instanceof SQLUpdateStatement) {
                SQLUpdateStatement update = (SQLUpdateStatement) parent;
                return update.getTableName().getSimpleName();
            } else if(parent instanceof SQLDeleteStatement) {
                SQLDeleteStatement delete = (SQLDeleteStatement) parent;
                return delete.getTableName().getSimpleName();
            } else {
                
            }
        }
        return "";
    }
 
Example 6
Source File: DruidSelectParser.java    From dble with GNU General Public License v2.0 4 votes vote down vote up
@Override
public SchemaConfig visitorParse(SchemaConfig schema, RouteResultset rrs, SQLStatement stmt,
                                 ServerSchemaStatVisitor visitor, ServerConnection sc, boolean isExplain) throws SQLException {
    SQLSelectStatement selectStmt = (SQLSelectStatement) stmt;
    SQLSelectQuery sqlSelectQuery = selectStmt.getSelect().getQuery();
    String schemaName = schema == null ? null : schema.getName();
    if (sqlSelectQuery instanceof MySqlSelectQueryBlock) {
        //check the select into sql is not supported
        MySqlSelectQueryBlock mysqlSelectQuery = (MySqlSelectQueryBlock) sqlSelectQuery;
        if (mysqlSelectQuery.getInto() != null) {
            throw new SQLNonTransientException("select ... into is not supported!");
        }

        //three types of select route according to the from item in select sql
        SQLTableSource mysqlFrom = mysqlSelectQuery.getFrom();
        if (mysqlFrom == null) {
            routeForNoFrom(schema, rrs, visitor, isExplain, sc, selectStmt);
            return schema;
        } else if (mysqlFrom instanceof SQLExprTableSource) {
            SQLExprTableSource fromSource = (SQLExprTableSource) mysqlFrom;
            SchemaInfo schemaInfo = SchemaUtil.getSchemaInfo(sc.getUser(), schemaName, fromSource);
            if (schemaInfo.isDual()) {
                //dual just route for a Random dataNode
                RouterUtil.routeNoNameTableToSingleNode(rrs, schema);
                return schema;
            } else if (SchemaUtil.MYSQL_SYS_SCHEMA.contains(schemaInfo.getSchema().toUpperCase())) {
                //sys_schema just use a special handler to response
                MysqlSystemSchemaHandler.handle(sc, schemaInfo, mysqlSelectQuery);
                rrs.setFinishedExecute(true);
                return schema;
            } else {
                //normal schema in config
                if (!ServerPrivileges.checkPrivilege(sc, schemaInfo.getSchema(), schemaInfo.getTable(), CheckType.SELECT)) {
                    String msg = "The statement DML privilege check is not passed, sql:" + stmt.toString().replaceAll("[\\t\\n\\r]", " ");
                    throw new SQLNonTransientException(msg);
                }
                super.visitorParse(schema != null ? schema : schemaInfo.getSchemaConfig(), rrs, stmt, visitor, sc, isExplain);
                //check to route for complex
                if (ProxyMeta.getInstance().getTmManager().getSyncView(schemaInfo.getSchemaConfig().getName(), schemaInfo.getTable()) != null ||
                        hasInnerFuncSelect(visitor.getFunctions())) {
                    rrs.setNeedOptimizer(true);
                    rrs.setSqlStatement(selectStmt);
                    return schemaInfo.getSchemaConfig();
                }
                if (visitor.getSubQueryList().size() > 0) {
                    return executeComplexSQL(schemaName, schema, rrs, selectStmt, sc, visitor.getSelectTableList().size(), visitor.isContainsInnerFunction());
                }

                //route for single table
                routeSingleTable(rrs, schemaInfo, mysqlSelectQuery, selectStmt, sc);
                return schema;
            }

        } else if (mysqlFrom instanceof SQLSubqueryTableSource ||
                mysqlFrom instanceof SQLJoinTableSource ||
                mysqlFrom instanceof SQLUnionQueryTableSource) {
            super.visitorParse(schema, rrs, stmt, visitor, sc, isExplain);
            return executeComplexSQL(schemaName, schema, rrs, selectStmt, sc, visitor.getSelectTableList().size(), visitor.isContainsInnerFunction());
        }
    } else if (sqlSelectQuery instanceof SQLUnionQuery) {
        super.visitorParse(schema, rrs, stmt, visitor, sc, isExplain);
        return executeComplexSQL(schemaName, schema, rrs, selectStmt, sc, visitor.getSelectTableList().size(), visitor.isContainsInnerFunction());
    }
    return schema;
}
 
Example 7
Source File: ESActionFactory.java    From elasticsearch-sql with Apache License 2.0 4 votes vote down vote up
private static boolean isJoin(SQLQueryExpr sqlExpr,String sql) {
    MySqlSelectQueryBlock query = (MySqlSelectQueryBlock) sqlExpr.getSubQuery().getQuery();
    return query.getFrom() instanceof SQLJoinTableSource && ((SQLJoinTableSource) query.getFrom()).getJoinType() != SQLJoinTableSource.JoinType.COMMA && sql.toLowerCase().contains("join");
}
 
Example 8
Source File: SqlParser.java    From elasticsearch-sql with Apache License 2.0 4 votes vote down vote up
private void findGroupBy(MySqlSelectQueryBlock query, Select select) throws SqlParseException {
    SQLSelectGroupByClause groupBy = query.getGroupBy();

    //modified by xzb group by 增加Having语法
    if (null != query.getGroupBy() && null != query.getGroupBy().getHaving()) {
        select.setHaving(query.getGroupBy().getHaving().toString());
    }

    SQLTableSource sqlTableSource = query.getFrom();
    if (groupBy == null) {
        return;
    }
    List<SQLExpr> items = groupBy.getItems();

    List<SQLExpr> standardGroupBys = new ArrayList<>();
    for (SQLExpr sqlExpr : items) {
        //todo: mysql expr patch
        if (sqlExpr instanceof MySqlOrderingExpr) {
            MySqlOrderingExpr sqlSelectGroupByExpr = (MySqlOrderingExpr) sqlExpr;
            sqlExpr = sqlSelectGroupByExpr.getExpr();
        }
        if ((sqlExpr instanceof SQLParensIdentifierExpr || !(sqlExpr instanceof SQLIdentifierExpr || sqlExpr instanceof SQLMethodInvokeExpr)) && !standardGroupBys.isEmpty()) {
            // flush the standard group bys
            // zhongshu-comment 先将standardGroupBys里面的字段传到select对象的groupBys字段中,然后给standardGroupBys分配一个没有元素的新的list
            select.addGroupBy(convertExprsToFields(standardGroupBys, sqlTableSource));
            standardGroupBys = new ArrayList<>();
        }

        if (sqlExpr instanceof SQLParensIdentifierExpr) {
            // single item with parens (should get its own aggregation)
            select.addGroupBy(FieldMaker.makeField(((SQLParensIdentifierExpr) sqlExpr).getExpr(), null, sqlTableSource.getAlias()));
        } else if (sqlExpr instanceof SQLListExpr) {
            // multiple items in their own list
            SQLListExpr listExpr = (SQLListExpr) sqlExpr;
            select.addGroupBy(convertExprsToFields(listExpr.getItems(), sqlTableSource));
        } else {
            // everything else gets added to the running list of standard group bys
            standardGroupBys.add(sqlExpr);
        }
    }
    if (!standardGroupBys.isEmpty()) {
        select.addGroupBy(convertExprsToFields(standardGroupBys, sqlTableSource));
    }
}