com.alibaba.druid.sql.ast.statement.SQLTableSource Java Examples

The following examples show how to use com.alibaba.druid.sql.ast.statement.SQLTableSource. 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: SelectParser.java    From dts with 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
Source File: JoinParser.java    From Mycat2 with GNU General Public License v3.0 6 votes vote down vote up
public void parser(){
	   masterTable="";	   
	   
	   SQLTableSource table=mysqlQuery.getFrom();	 //a 表  
	   parserTable(table,tableFilter,false); // 组成链表
	   
	   parserFields(mysqlQuery.getSelectList());  //查询字段放到各个查询表中。
	   parserMasterTable();	 //查询主表 别名   
	   
	   parserWhere(mysqlQuery.getWhere(),""); // where 条件放到各个查询表中。	   
	 // getJoinField();
	   parserOrderBy(mysqlQuery.getOrderBy());  // order 条件放到各个查询表中。
	   parserLimit(); // limit 
//	   LOGGER.info("field "+fieldAliasMap);	  	   
//	   LOGGER.info("master "+masterTable);
//	   LOGGER.info("join Lkey "+getJoinLkey()); 
//	   LOGGER.info("join Rkey "+getJoinRkey()); 	   
	   LOGGER.info("SQL: "+this.stmt);
	}
 
Example #3
Source File: JoinParser.java    From Mycat2 with GNU General Public License v3.0 6 votes vote down vote up
private void parserTable(SQLTableSource table,TableFilter tFilter,boolean isOutJoin){
	if(table instanceof SQLJoinTableSource){
		SQLJoinTableSource table1=(SQLJoinTableSource)table;	
		joinType=table1.getJoinType().toString();
		if ((table1.getJoinType()==JoinType.COMMA)||(table1.getJoinType()==JoinType.JOIN)||(table1.getJoinType()==JoinType.INNER_JOIN)
				||(table1.getJoinType()==JoinType.LEFT_OUTER_JOIN))	{					
			tFilter=setTableFilter(tFilter,getTableFilter(table1.getLeft(),isOutJoin));
			if (tableFilter==null){
				tableFilter=tFilter;
			}
		}
		//parserTable(table1.getLeft());	//SQLExprTableSource
		parserTable(table1.getRight(),tFilter,true);
		
		SQLExpr expr=table1.getCondition();//SQLBinaryOpExpr
		parserJoinKey(expr);
	}
	else {
		tFilter=setTableFilter(tFilter,getTableFilter(table,isOutJoin));
		LOGGER.info("table "+table.toString() +" Alias:"+table.getAlias()+" Hints:"+table.getHints());
	}
}
 
Example #4
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 #5
Source File: DruidCreateIndexParser.java    From dble with GNU General Public License v2.0 6 votes vote down vote up
@Override
public SchemaConfig visitorParse(SchemaConfig schema, RouteResultset rrs, SQLStatement stmt,
                                 ServerSchemaStatVisitor visitor, ServerConnection sc, boolean isExplain) throws SQLException {
    rrs.setOnline(true);
    SQLCreateIndexStatement createStmt = (SQLCreateIndexStatement) stmt;
    SQLTableSource tableSource = createStmt.getTable();
    if (tableSource instanceof SQLExprTableSource) {
        String schemaName = schema == null ? null : schema.getName();
        SchemaInfo schemaInfo = SchemaUtil.getSchemaInfo(sc.getUser(), schemaName, (SQLExprTableSource) tableSource);
        String statement = RouterUtil.removeSchema(rrs.getStatement(), schemaInfo.getSchema());
        rrs.setStatement(statement);
        String noShardingNode = RouterUtil.isNoShardingDDL(schemaInfo.getSchemaConfig(), schemaInfo.getTable());
        if (noShardingNode != null) {
            RouterUtil.routeToSingleDDLNode(schemaInfo, rrs, noShardingNode);
            return schemaInfo.getSchemaConfig();
        }
        RouterUtil.routeToDDLNode(schemaInfo, rrs);
        return schemaInfo.getSchemaConfig();
    } else {
        String msg = "The DDL is not supported, sql:" + stmt;
        throw new SQLNonTransientException(msg);
    }
}
 
Example #6
Source File: Util.java    From elasticsearch-sql with Apache License 2.0 6 votes vote down vote up
public static boolean isFromJoinOrUnionTable(SQLExpr expr) {
    SQLObject temp = expr;
    AtomicInteger counter = new AtomicInteger(10);
    while (temp != null &&
            !(expr instanceof SQLSelectQueryBlock) &&
            !(expr instanceof SQLJoinTableSource) && !(expr instanceof SQLUnionQuery) && counter.get() > 0) {
        counter.decrementAndGet();
        temp = temp.getParent();
        if (temp instanceof SQLSelectQueryBlock) {
            SQLTableSource from = ((SQLSelectQueryBlock) temp).getFrom();
            if (from instanceof SQLJoinTableSource || from instanceof SQLUnionQuery) {
                return true;
            }
        }
        if (temp instanceof SQLJoinTableSource || temp instanceof SQLUnionQuery) {
            return true;
        }
    }
    return false;
}
 
Example #7
Source File: ElasticSqlSelectParser.java    From elasticsearch-sql with Apache License 2.0 6 votes vote down vote up
@Override
protected SQLTableSource parseTableSourceRest(SQLTableSource tableSource) {
    if (lexer.identifierEquals(FnvHash.Constants.USING)) {
        return tableSource;
    }

    parseIndexHintList(tableSource);

    if (lexer.token() == Token.PARTITION) {
        lexer.nextToken();
        accept(Token.LPAREN);
        this.exprParser.names(((SQLExprTableSource) tableSource).getPartitions(), tableSource);
        accept(Token.RPAREN);
    }

    return super.parseTableSourceRest(tableSource);
}
 
Example #8
Source File: JoinParser.java    From Mycat2 with GNU General Public License v3.0 5 votes vote down vote up
private TableFilter getTableFilter(SQLTableSource table,boolean isOutJoin){	
	String key   ;
	String value = table.toString().trim();
	if (table.getAlias()==null) {
		key=value;
	}
	else {
		 key   = table.getAlias().trim();
	}
	return new TableFilter(value,key,isOutJoin);	
}
 
Example #9
Source File: DruidMycatRouteStrategy.java    From Mycat2 with GNU General Public License v3.0 5 votes vote down vote up
private SQLExprTableSource getDisTable(SQLTableSource tableSource,RouteResultsetNode node) throws SQLSyntaxErrorException{
	if(node.getSubTableName()==null){
		String msg = " sub table not exists for " + node.getName() + " on " + tableSource;
		LOGGER.error("DruidMycatRouteStrategyError " + msg);
		throw new SQLSyntaxErrorException(msg);
	}

	SQLIdentifierExpr sqlIdentifierExpr = new SQLIdentifierExpr();
	sqlIdentifierExpr.setParent(tableSource.getParent());
	sqlIdentifierExpr.setName(node.getSubTableName());
	SQLExprTableSource from2 = new SQLExprTableSource(sqlIdentifierExpr);
	return from2;
}
 
Example #10
Source File: ElasticSqlSelectParser.java    From elasticsearch-sql with Apache License 2.0 5 votes vote down vote up
protected SQLTableSource primaryTableSourceRest(SQLTableSource tableSource) {
    parseIndexHintList(tableSource);

    if (lexer.token() == Token.PARTITION) {
        lexer.nextToken();
        accept(Token.LPAREN);
        this.exprParser.names(((SQLExprTableSource) tableSource).getPartitions(), tableSource);
        accept(Token.RPAREN);
    }

    return tableSource;
}
 
Example #11
Source File: SqlParser.java    From elasticsearch-sql with Apache License 2.0 5 votes vote down vote up
private List<Field> convertExprsToFields(List<? extends SQLExpr> exprs, SQLTableSource sqlTableSource) throws SqlParseException {
    List<Field> fields = new ArrayList<>(exprs.size());
    for (SQLExpr expr : exprs) {
        //here we suppose groupby field will not have alias,so set null in second parameter
        //zhongshu-comment case when 有别名过不了语法解析,没有别名执行下面语句会报空指针
        fields.add(FieldMaker.makeField(expr, null, sqlTableSource.getAlias()));
    }
    return fields;
}
 
Example #12
Source File: SqlParser.java    From elasticsearch-sql with Apache License 2.0 5 votes vote down vote up
private List<From> findJoinedFrom(SQLTableSource from) {
    SQLJoinTableSource joinTableSource = ((SQLJoinTableSource) from);
    List<From> fromList = new ArrayList<>();
    fromList.addAll(findFrom(joinTableSource.getLeft()));
    fromList.addAll(findFrom(joinTableSource.getRight()));
    return fromList;
}
 
Example #13
Source File: ElasticSqlSelectParser.java    From elasticsearch-sql with Apache License 2.0 4 votes vote down vote up
protected MySqlUpdateStatement parseUpdateStatment() {
    MySqlUpdateStatement update = new MySqlUpdateStatement();

    lexer.nextToken();

    if (lexer.identifierEquals(FnvHash.Constants.LOW_PRIORITY)) {
        lexer.nextToken();
        update.setLowPriority(true);
    }

    if (lexer.identifierEquals(FnvHash.Constants.IGNORE)) {
        lexer.nextToken();
        update.setIgnore(true);
    }

    if (lexer.identifierEquals(FnvHash.Constants.COMMIT_ON_SUCCESS)) {
        lexer.nextToken();
        update.setCommitOnSuccess(true);
    }

    if (lexer.identifierEquals(FnvHash.Constants.ROLLBACK_ON_FAIL)) {
        lexer.nextToken();
        update.setRollBackOnFail(true);
    }

    if (lexer.identifierEquals(FnvHash.Constants.QUEUE_ON_PK)) {
        lexer.nextToken();
        update.setQueryOnPk(true);
    }

    if (lexer.identifierEquals(FnvHash.Constants.TARGET_AFFECT_ROW)) {
        lexer.nextToken();
        SQLExpr targetAffectRow = this.exprParser.expr();
        update.setTargetAffectRow(targetAffectRow);
    }

    if (lexer.identifierEquals(FnvHash.Constants.FORCE)) {
        lexer.nextToken();

        if (lexer.token() == Token.ALL) {
            lexer.nextToken();
            acceptIdentifier("PARTITIONS");
            update.setForceAllPartitions(true);
        } else if (lexer.identifierEquals(FnvHash.Constants.PARTITIONS)){
            lexer.nextToken();
            update.setForceAllPartitions(true);
        } else if (lexer.token() == Token.PARTITION) {
            lexer.nextToken();
            SQLName partition = this.exprParser.name();
            update.setForcePartition(partition);
        } else {
            throw new ParserException("TODO. " + lexer.info());
        }
    }

    while (lexer.token() == Token.HINT) {
        this.exprParser.parseHints(update.getHints());
    }

    SQLSelectParser selectParser = this.exprParser.createSelectParser();
    SQLTableSource updateTableSource = selectParser.parseTableSource();
    update.setTableSource(updateTableSource);

    accept(Token.SET);

    for (;;) {
        SQLUpdateSetItem item = this.exprParser.parseUpdateSetItem();
        update.addItem(item);

        if (lexer.token() != Token.COMMA) {
            break;
        }

        lexer.nextToken();
    }

    if (lexer.token() == (Token.WHERE)) {
        lexer.nextToken();
        update.setWhere(this.exprParser.expr());
    }

    update.setOrderBy(this.exprParser.parseOrderBy());
    update.setLimit(this.exprParser.parseLimit());

    return update;
}
 
Example #14
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));
    }
}