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

The following examples show how to use com.alibaba.druid.sql.ast.statement.SQLJoinTableSource. 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: 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 #2
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 #3
Source File: SqlParser.java    From elasticsearch-sql with Apache License 2.0 6 votes vote down vote up
public JoinSelect parseJoinSelect(SQLQueryExpr sqlExpr) throws SqlParseException {

        MySqlSelectQueryBlock query = (MySqlSelectQueryBlock) sqlExpr.getSubQuery().getQuery();

        List<From> joinedFrom = findJoinedFrom(query.getFrom());
        if (joinedFrom.size() != 2)
            throw new RuntimeException("currently supports only 2 tables join");

        JoinSelect joinSelect = createBasicJoinSelectAccordingToTableSource((SQLJoinTableSource) query.getFrom());
        List<Hint> hints = parseHints(query.getHints());
        joinSelect.setHints(hints);
        String firstTableAlias = joinedFrom.get(0).getAlias();
        String secondTableAlias = joinedFrom.get(1).getAlias();
        Map<String, Where> aliasToWhere = splitAndFindWhere(query.getWhere(), firstTableAlias, secondTableAlias);
        Map<String, List<SQLSelectOrderByItem>> aliasToOrderBy = splitAndFindOrder(query.getOrderBy(), firstTableAlias, secondTableAlias);
        List<Condition> connectedConditions = getConditionsFlatten(joinSelect.getConnectedWhere());
        joinSelect.setConnectedConditions(connectedConditions);
        fillTableSelectedJoin(joinSelect.getFirstTable(), query, joinedFrom.get(0), aliasToWhere.get(firstTableAlias), aliasToOrderBy.get(firstTableAlias), connectedConditions);
        fillTableSelectedJoin(joinSelect.getSecondTable(), query, joinedFrom.get(1), aliasToWhere.get(secondTableAlias), aliasToOrderBy.get(secondTableAlias), connectedConditions);

        updateJoinLimit(query.getLimit(), joinSelect);

        //todo: throw error feature not supported:  no group bys on joins ?
        return joinSelect;
    }
 
Example #4
Source File: HashJoinElasticExecutor.java    From elasticsearch-sql with Apache License 2.0 5 votes vote down vote up
public List<SearchHit> innerRun() throws IOException, SqlParseException {

        Map<String, Map<String, List<Object>>> optimizationTermsFilterStructure =
                initOptimizationStructure();

        updateFirstTableLimitIfNeeded();
        TableInJoinRequestBuilder firstTableRequest = requestBuilder.getFirstTable();
        createKeyToResultsAndFillOptimizationStructure(optimizationTermsFilterStructure, firstTableRequest);

        TableInJoinRequestBuilder secondTableRequest = requestBuilder.getSecondTable();
        if (needToOptimize(optimizationTermsFilterStructure)) {
            updateRequestWithTermsFilter(optimizationTermsFilterStructure, secondTableRequest);
        }

        List<SearchHit> combinedResult = createCombinedResults(secondTableRequest);

        int currentNumOfResults = combinedResult.size();
        int totalLimit = requestBuilder.getTotalLimit();
        if (requestBuilder.getJoinType() == SQLJoinTableSource.JoinType.LEFT_OUTER_JOIN && currentNumOfResults < totalLimit) {
            String t1Alias = requestBuilder.getFirstTable().getAlias();
            String t2Alias = requestBuilder.getSecondTable().getAlias();
            //todo: for each till Limit
            addUnmatchedResults(combinedResult, this.hashJoinComparisonStructure.getAllSearchHits(),
                    requestBuilder.getSecondTable().getReturnedFields(),
                    currentNumOfResults, totalLimit,
                    t1Alias,
                    t2Alias);
        }
        if(firstTableRequest.getOriginalSelect().isOrderdSelect()){
            Collections.sort(combinedResult,new Comparator<SearchHit>() {
                @Override
                public int compare(SearchHit o1, SearchHit o2) {
                    return o1.docId() - o2.docId();
                }
            });

        }
        return combinedResult;
    }
 
Example #5
Source File: HashJoinElasticExecutor.java    From elasticsearch-sql with Apache License 2.0 5 votes vote down vote up
private void updateFirstTableLimitIfNeeded() {
    if (requestBuilder.getJoinType() == SQLJoinTableSource.JoinType.LEFT_OUTER_JOIN) {
        Integer firstTableHintLimit = requestBuilder.getFirstTable().getHintLimit();
        int totalLimit = requestBuilder.getTotalLimit();
        if (firstTableHintLimit == null || firstTableHintLimit > totalLimit) {
            requestBuilder.getFirstTable().setHintLimit(totalLimit);
        }
    }
}
 
Example #6
Source File: NestedLoopsElasticExecutor.java    From elasticsearch-sql with Apache License 2.0 5 votes vote down vote up
private int combineResultsFromMultiResponses(List<SearchHit> combinedResults, int totalLimit, int currentCombinedResults, SearchHit[] hits, int currentIndex, MultiSearchRequest multiSearchRequest) {
    MultiSearchResponse.Item[] responses = client.multiSearch(multiSearchRequest).actionGet().getResponses();
    String t1Alias = nestedLoopsRequest.getFirstTable().getAlias();
    String t2Alias = nestedLoopsRequest.getSecondTable().getAlias();

    for(int j =0 ; j < responses.length && currentCombinedResults < totalLimit ; j++){
        SearchHit hitFromFirstTable = hits[currentIndex+j];
        onlyReturnedFields(hitFromFirstTable.getSourceAsMap(), nestedLoopsRequest.getFirstTable().getReturnedFields(),nestedLoopsRequest.getFirstTable().getOriginalSelect().isSelectAll());

        SearchResponse multiItemResponse = responses[j].getResponse();
        updateMetaSearchResults(multiItemResponse);

        //todo: if responseForHit.getHits.length < responseForHit.getTotalHits(). need to fetch more!
        SearchHits responseForHit = multiItemResponse.getHits();

        if(responseForHit.getHits().length == 0 && nestedLoopsRequest.getJoinType() == SQLJoinTableSource.JoinType.LEFT_OUTER_JOIN){
            SearchHit unmachedResult = createUnmachedResult(nestedLoopsRequest.getSecondTable().getReturnedFields(), currentCombinedResults, t1Alias, t2Alias, hitFromFirstTable);
            combinedResults.add(unmachedResult);
            currentCombinedResults++;
            continue;
        }

        for(SearchHit matchedHit : responseForHit.getHits() ){
            SearchHit searchHit = getMergedHit(currentCombinedResults, t1Alias, t2Alias, hitFromFirstTable, matchedHit);
            combinedResults.add(searchHit);
            currentCombinedResults++;
            if(currentCombinedResults >= totalLimit) break;
        }
        if(currentCombinedResults >= totalLimit) break;

    }
    return currentCombinedResults;
}
 
Example #7
Source File: SqlParser.java    From elasticsearch-sql with Apache License 2.0 5 votes vote down vote up
private JoinSelect createBasicJoinSelectAccordingToTableSource(SQLJoinTableSource joinTableSource) throws SqlParseException {
    JoinSelect joinSelect = new JoinSelect();
    if (joinTableSource.getCondition() != null) {
        Where where = Where.newInstance();
        WhereParser whereParser = new WhereParser(this, joinTableSource.getCondition());
        whereParser.parseWhere(joinTableSource.getCondition(), where);
        joinSelect.setConnectedWhere(where);
    }
    SQLJoinTableSource.JoinType joinType = joinTableSource.getJoinType();
    joinSelect.setJoinType(joinType);
    return joinSelect;
}
 
Example #8
Source File: SqlParser.java    From elasticsearch-sql with Apache License 2.0 5 votes vote down vote up
private List<Condition> getJoinConditionsFlatten(SQLJoinTableSource from) throws SqlParseException {
    List<Condition> conditions = new ArrayList<>();
    if (from.getCondition() == null) return conditions;
    Where where = Where.newInstance();
    WhereParser whereParser = new WhereParser(this, from.getCondition());
    whereParser.parseWhere(from.getCondition(), where);
    addIfConditionRecursive(where, conditions);
    return conditions;
}
 
Example #9
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 #10
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 #11
Source File: MySQLSelectASTVisitor.java    From Zebra with Apache License 2.0 4 votes vote down vote up
@Override
public boolean visit(SQLJoinTableSource x) {
	result.getMergeContext().increJoinCount();
	return super.visit(x);
}
 
Example #12
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 #13
Source File: JoinRequestBuilder.java    From elasticsearch-sql with Apache License 2.0 4 votes vote down vote up
public SQLJoinTableSource.JoinType getJoinType() {
    return joinType;
}
 
Example #14
Source File: JoinRequestBuilder.java    From elasticsearch-sql with Apache License 2.0 4 votes vote down vote up
public void setJoinType(SQLJoinTableSource.JoinType joinType) {
    this.joinType = joinType;
}
 
Example #15
Source File: JoinSelect.java    From elasticsearch-sql with Apache License 2.0 4 votes vote down vote up
public SQLJoinTableSource.JoinType getJoinType() {
    return joinType;
}
 
Example #16
Source File: JoinSelect.java    From elasticsearch-sql with Apache License 2.0 4 votes vote down vote up
public void setJoinType(SQLJoinTableSource.JoinType joinType) {
    this.joinType = joinType;
}