Java Code Examples for com.alibaba.druid.sql.ast.expr.SQLBinaryOpExpr

The following examples show how to use com.alibaba.druid.sql.ast.expr.SQLBinaryOpExpr. 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: Mycat2   Source File: JoinParser.java    License: GNU General Public License v3.0 6 votes vote down vote up
private void opSQLExpr(SQLBinaryOpExpr expr,String Operator) {
	   if (expr==null) {
		   return;
	   }
	   SQLExpr exprL=expr.getLeft();
	   if (!(exprL instanceof SQLBinaryOpExpr))
	   {
		   String field=exprL.toString(); //获取表达式 左边的值
		   String value=getExpValue(expr.getRight()).toString(); //获取表达式右边的值
		   if (expr.getOperator()==SQLBinaryOperator.Equality) {  
			 if (checkJoinField(value)) {//设置joinKey
				//joinLkey=field;
				//joinRkey=value; 
				tableFilter.setJoinKey(field,value);
			 }
			 else {
				 tableFilter.addWhere(field, value, expr.getOperator().getName(), Operator);
			 }
		   }
		   else {
			   tableFilter.addWhere(field, value, expr.getOperator().getName(), Operator);
		   }
	   }		
}
 
Example 2
Source Project: Mycat2   Source File: MycatSubQueryVisitor.java    License: GNU General Public License v3.0 6 votes vote down vote up
@Override
public boolean visit(SQLBinaryOpExpr x) {

	switch (x.getOperator()) {
            case Equality:
            case LessThanOrEqualOrGreaterThan:
            case GreaterThan:
            case GreaterThanOrEqual:
            case LessThan:
            case LessThanOrEqual:
            case NotLessThan:
            case LessThanOrGreater:
  			 	case NotEqual:
  			 	case NotGreaterThan:	            	
                break;
            case BooleanOr:
            	relationOr = true;
            	break;
            case Like:
            case NotLike:
            default:
                break;
        }
        return true;
}
 
Example 3
/**
	 * 递归拆分OR
	 * 
	 * @param whereUnit
	 * TODO:考虑嵌套or语句,条件中有子查询、 exists等很多种复杂情况是否能兼容
	 */
	private void splitUntilNoOr(WhereUnit whereUnit) {
		if(whereUnit.isFinishedParse()) {
			if(whereUnit.getSubWhereUnit().size() > 0) {
				for(int i = 0; i < whereUnit.getSubWhereUnit().size(); i++) {
					splitUntilNoOr(whereUnit.getSubWhereUnit().get(i));
				}
			} 
		} else {
			SQLBinaryOpExpr expr = whereUnit.getCanSplitExpr();
			if(expr.getOperator() == SQLBinaryOperator.BooleanOr) {
//				whereUnit.addSplitedExpr(expr.getRight());
				addExprIfNotFalse(whereUnit, expr.getRight());
				if(expr.getLeft() instanceof SQLBinaryOpExpr) {
					whereUnit.setCanSplitExpr((SQLBinaryOpExpr)expr.getLeft());
					splitUntilNoOr(whereUnit);
				} else {
					addExprIfNotFalse(whereUnit, expr.getLeft());
				}
			} else {
				addExprIfNotFalse(whereUnit, expr);
				whereUnit.setFinishedParse(true);
			}
		}
    }
 
Example 4
Source Project: Mycat2   Source File: DruidSelectParser.java    License: GNU General Public License v3.0 6 votes vote down vote up
protected void setLimitIFChange(SQLStatement stmt, RouteResultset rrs, SchemaConfig schema, SQLBinaryOpExpr one, int firstrownum, int lastrownum)
{
	rrs.setLimitStart(firstrownum);
	rrs.setLimitSize(lastrownum - firstrownum);
	LayerCachePool tableId2DataNodeCache = (LayerCachePool) MycatServer.getInstance().getCacheService().getCachePool("TableID2DataNodeCache");
	try
	{
		tryRoute(schema, rrs, tableId2DataNodeCache);
	} catch (SQLNonTransientException e)
	{
		throw new RuntimeException(e);
	}
	if (isNeedChangeLimit(rrs))
	{
		one.setRight(new SQLIntegerExpr(0));
		String curentDbType ="db2".equalsIgnoreCase(this.getCurentDbType())?"oracle":getCurentDbType();
		String sql =   SQLUtils.toSQLString(stmt, curentDbType);;
		rrs.changeNodeSqlAfterAddLimit(schema,getCurentDbType(), sql,0,lastrownum, false);
		//设置改写后的sql
		getCtx().setSql(sql);
	}
}
 
Example 5
Source Project: dble   Source File: DruidInsertParser.java    License: GNU General Public License v2.0 6 votes vote down vote up
private void genDuplicate(StringBuilder sb, List<SQLExpr> dku) throws SQLNonTransientException {
    sb.append(" on duplicate key update ");
    for (int i = 0; i < dku.size(); i++) {
        SQLExpr exp = dku.get(i);
        if (!(exp instanceof SQLBinaryOpExpr)) {
            String msg = "not supported! on duplicate key update exp is " + exp.getClass();
            LOGGER.info(msg);
            throw new SQLNonTransientException(msg);
        }
        SQLBinaryOpExpr binaryOpExpr = (SQLBinaryOpExpr) exp;
        sb.append(binaryOpExpr.toString());
        if (i < dku.size() - 1) {
            sb.append(",");
        }
    }
}
 
Example 6
Source Project: baymax   Source File: SqlVisitor.java    License: Apache License 2.0 6 votes vote down vote up
/**
    * 二元表达
    * @param x
    * @return
    */
   @Override
public boolean visit(SQLBinaryOpExpr x) {
       x.getLeft().setParent(x);
       x.getRight().setParent(x);
       switch (x.getOperator()) {
           case Equality:
               // a=1 and a=2 or a=3
               handleCondition(x.getLeft(), x.getOperator().name, x.getRight());
               // a=b 转化为 b=a
               // a=1 不用转化
               handleCondition(x.getRight(), x.getOperator().name, x.getLeft());
               handleRelationship(x.getLeft(), x.getOperator().name, x.getRight());
               break;
           case BooleanOr:
               this.hasOrCondition = true;
               break;
           default:
               break;
       }
       return true;
   }
 
Example 7
Source Project: baymax   Source File: OrVisitor.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public boolean visit(SQLBinaryOpExpr x) {
       x.getLeft().setParent(x);
       x.getRight().setParent(x);

       if (!SQLBinaryOperator.BooleanOr.equals(x.getOperator())) {
           return super.visit(x);
       }

       // true * (a and b) = (a and b) 没有意义
       if (Boolean.TRUE.equals(WallVisitorUtils.getValue(x))) {
           return false;
       }

       // 这是一个Or表达式 这个or代表的集合是要和当前已经获取的Condition列表 相乘的.
       orEntity.add(new OrEntity(this, x));
       return false;
   }
 
Example 8
Source Project: elasticsearch-sql   Source File: Util.java    License: Apache License 2.0 6 votes vote down vote up
public static Object getScriptValueWithQuote(SQLExpr expr, String quote) throws SqlParseException {
    if (expr instanceof SQLIdentifierExpr || expr instanceof SQLPropertyExpr || expr instanceof SQLVariantRefExpr) {
        return "doc['" + expr.toString() + "'].value";
    }  else if (expr instanceof SQLCharExpr) {
        return quote + ((SQLCharExpr) expr).getValue() + quote;
    } else if (expr instanceof SQLIntegerExpr) {
        return ((SQLIntegerExpr) expr).getValue();
    } else if (expr instanceof SQLNumericLiteralExpr) {
        return ((SQLNumericLiteralExpr) expr).getNumber();
    } else if (expr instanceof SQLNullExpr) {
        return ((SQLNullExpr) expr).toString().toLowerCase();
    } else if (expr instanceof  SQLBinaryOpExpr) {
        //zhongshu-comment 该分支由忠树添加
        String left = "doc['" + ((SQLBinaryOpExpr) expr).getLeft().toString() + "'].value";
        String operator = ((SQLBinaryOpExpr) expr).getOperator().getName();
        String right = "doc['" + ((SQLBinaryOpExpr) expr).getRight().toString() + "'].value";
        return left + operator + right;
    }
    throw new SqlParseException("could not parse sqlBinaryOpExpr need to be identifier/valuable got " + expr.getClass().toString() + " with value:" + expr.toString());
}
 
Example 9
Source Project: elasticsearch-sql   Source File: WhereParser.java    License: Apache License 2.0 6 votes vote down vote up
private boolean explanSpecialCondWithBothSidesAreLiterals(SQLBinaryOpExpr bExpr, Where where) throws SqlParseException {
    if ((bExpr.getLeft() instanceof SQLNumericLiteralExpr || bExpr.getLeft() instanceof SQLCharExpr) &&
            (bExpr.getRight() instanceof SQLNumericLiteralExpr || bExpr.getRight() instanceof SQLCharExpr)
            ) {
        SQLMethodInvokeExpr sqlMethodInvokeExpr = new SQLMethodInvokeExpr("script", null);
        String operator = bExpr.getOperator().getName();
        if (operator.equals("=")) {
            operator = "==";
        }
        sqlMethodInvokeExpr.addParameter(
                new SQLCharExpr(Util.expr2Object(bExpr.getLeft(), "'") +
                        " " + operator + " " +
                        Util.expr2Object(bExpr.getRight(), "'"))
        );

        explanCond("AND", sqlMethodInvokeExpr, where);
        return true;
    }
    return false;
}
 
Example 10
Source Project: elasticsearch-sql   Source File: FieldMaker.java    License: Apache License 2.0 6 votes vote down vote up
private static Field makeScriptMethodField(SQLBinaryOpExpr binaryExpr, String alias, String tableAlias) throws SqlParseException {
    List<SQLExpr> params = new ArrayList<>();

    String scriptFieldAlias;
    if (alias == null || alias.equals(""))
        scriptFieldAlias = binaryExpr.toString();
    else
        scriptFieldAlias = alias;
    params.add(new SQLCharExpr(scriptFieldAlias));

    Object left = getScriptValue(binaryExpr.getLeft());
    Object right = getScriptValue(binaryExpr.getRight());

    //added by xzb 修复 if 条件的 value 被去除单引号问题
  /*  String tmp = binaryExpr.getRight().toString().trim();
    if (tmp.startsWith("'") && tmp.endsWith("'")) {
        right = "'" + right + "'";
    }*/

    String script = String.format("%s %s %s", left, binaryExpr.getOperator().getName(), right);

    params.add(new SQLCharExpr(script));

    return makeMethodField("script", params, null, null, tableAlias, false);
}
 
Example 11
Source Project: Mycat2   Source File: DruidSelectParser.java    License: GNU General Public License v3.0 5 votes vote down vote up
private HavingCols buildGroupByHaving(SQLExpr having,Map<String, String> aliaColumns ){
	if (having == null) {
		return null;
	}

	SQLBinaryOpExpr expr  = ((SQLBinaryOpExpr) having);
	SQLExpr left = expr.getLeft();
	SQLBinaryOperator operator = expr.getOperator();
	SQLExpr right = expr.getRight();

	String leftValue = null;;
	if (left instanceof SQLAggregateExpr) {
		leftValue = ((SQLAggregateExpr) left).getMethodName() + "("
				+ ((SQLAggregateExpr) left).getArguments().get(0) + ")";
		String aggrColumnAlias = getAliaColumn(aliaColumns,leftValue);
		if(aggrColumnAlias != null) { // having聚合函数存在别名
			expr.setLeft(new SQLIdentifierExpr(aggrColumnAlias));
			leftValue = aggrColumnAlias;
		}
	} else if (left instanceof SQLIdentifierExpr) {
		leftValue = ((SQLIdentifierExpr) left).getName();
	}

	String rightValue = null;
	if (right instanceof  SQLNumericLiteralExpr) {
		rightValue = right.toString();
	}else if(right instanceof SQLTextLiteralExpr){
		rightValue = StringUtil.removeBackquote(right.toString());
	}

	return new HavingCols(leftValue,rightValue,operator.getName());
}
 
Example 12
Source Project: Mycat2   Source File: DruidSelectParser.java    License: GNU General Public License v3.0 5 votes vote down vote up
private 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 if (!StringUtil.isEmpty(item.getAlias())) { // add by hehuang 20181205 如果SelectItem存在别名,则认为表达式为字段名,sql语法支持常量作为字段
		return item.getExpr().toString();
	} else {
		return item.toString();
	}
}
 
Example 13
private void parseThreeLevelPageSql(SQLStatement stmt, RouteResultset rrs, SchemaConfig schema, SQLSubqueryTableSource from, SQLBinaryOpExpr one, SQLBinaryOperator operator)
{
       SQLIntegerExpr right = (SQLIntegerExpr) one.getRight();
	int firstrownum = right.getNumber().intValue();
	if (operator == SQLBinaryOperator.GreaterThanOrEqual&&firstrownum!=0) {
		firstrownum = firstrownum - 1;
	}
	SQLSelectQuery subSelect = from.getSelect().getQuery();
	if (subSelect instanceof OracleSelectQueryBlock)
       {  //第二层子查询
           OracleSelectQueryBlock twoSubSelect = (OracleSelectQueryBlock) subSelect;
           if (twoSubSelect.getWhere() instanceof SQLBinaryOpExpr && twoSubSelect.getFrom() instanceof SQLSubqueryTableSource)
           {
               SQLBinaryOpExpr twoWhere = (SQLBinaryOpExpr) twoSubSelect.getWhere();
               boolean isRowNum = "rownum".equalsIgnoreCase(twoWhere.getLeft().toString());
               boolean isLess = twoWhere.getOperator() == SQLBinaryOperator.LessThanOrEqual || twoWhere.getOperator() == SQLBinaryOperator.LessThan;
               if (isRowNum && twoWhere.getRight() instanceof SQLIntegerExpr && isLess)
               {
                   int lastrownum = ((SQLIntegerExpr) twoWhere.getRight()).getNumber().intValue();
                   if (operator == SQLBinaryOperator.LessThan&&lastrownum!=0) {
					lastrownum = lastrownum - 1;
				}
                   SQLSelectQuery finalQuery = ((SQLSubqueryTableSource) twoSubSelect.getFrom()).getSelect().getQuery();
                   if (finalQuery instanceof OracleSelectQueryBlock)
                   {
					setLimitIFChange(stmt, rrs, schema, one, firstrownum, lastrownum);
                       parseOrderAggGroupOracle(stmt,rrs, (OracleSelectQueryBlock) finalQuery, schema);
                       isNeedParseOrderAgg=false;
                   }

               }

           }

       }
}
 
Example 14
Source Project: Mycat2   Source File: DruidUpdateParserTest.java    License: GNU General Public License v3.0 5 votes vote down vote up
public static void printWhereClauseAST(SQLExpr sqlExpr) {
    // where子句的AST sqlExpr可以通过 MySqlUpdateStatement.getWhere(); 获得
    if (sqlExpr == null)
        return;
    ArrayList<SQLExpr> exprNode = new ArrayList<>();
    int i = 0, curLevel = 1, nextLevel = 0;
    SQLExpr iterExpr;
    exprNode.add(sqlExpr);
    while (true) {
        iterExpr = exprNode.get(i++);
        if (iterExpr == null)
            break;

        if (iterExpr instanceof SQLBinaryOpExpr) {
            System.out.print(((SQLBinaryOpExpr) iterExpr).getOperator());
        } else {
            System.out.print(iterExpr.toString());
        }
        System.out.print("\t");
        curLevel--;

        if (iterExpr instanceof SQLBinaryOpExpr) {
            if (((SQLBinaryOpExpr) iterExpr).getLeft() != null) {
                exprNode.add(((SQLBinaryOpExpr) iterExpr).getLeft());
                nextLevel++;
            }
            if (((SQLBinaryOpExpr) iterExpr).getRight() != null) {
                exprNode.add(((SQLBinaryOpExpr) iterExpr).getRight());
                nextLevel++;
            }
        }
        if (curLevel == 0) {
            System.out.println("\t\tNum of nodes in next level: " + nextLevel);
            curLevel = nextLevel;
            nextLevel = 0;
        }
        if (exprNode.size() == i)
            break;
    }
}
 
Example 15
Source Project: dble   Source File: ShowConnection.java    License: GNU General Public License v2.0 5 votes vote down vote up
static void getWhereCondition(SQLExpr whereExpr, Map<String, String> whereInfo) {
    if (whereExpr instanceof SQLBinaryOpExpr) {
        SQLBinaryOpExpr tmp = (SQLBinaryOpExpr) whereExpr;
        if (tmp.getLeft() instanceof SQLBinaryOpExpr) {
            getWhereCondition(tmp.getLeft(), whereInfo);
            getWhereCondition(tmp.getRight(), whereInfo);
        } else {
            whereInfo.put(tmp.getLeft().toString().toLowerCase(), StringUtil.removeApostrophe(tmp.getRight().toString()));
        }
    }
}
 
Example 16
Source Project: dble   Source File: ExpressionUtil.java    License: GNU General Public License v2.0 5 votes vote down vote up
/**
 * convert Expression to DNF Expression
 *
 * @param expr
 * @return
 */
public static SQLExpr toDNF(SQLExpr expr) {
    if (expr == null)
        return null;

    while (!isDNF(expr)) {
        SQLBinaryOpExpr binOpExpr = (SQLBinaryOpExpr) expr;
        if (binOpExpr.getOperator() == SQLBinaryOperator.BooleanOr) {
            expr = expandOrExpression(binOpExpr);
        } else if (binOpExpr.getOperator() == SQLBinaryOperator.BooleanAnd) {
            expr = expandAndExpression(binOpExpr);
        }
    }
    return expr;
}
 
Example 17
Source Project: dble   Source File: ExpressionUtil.java    License: GNU General Public License v2.0 5 votes vote down vote up
/**
 * (A OR B) AND C OR B OR (E OR F) AND G = ((A AND C ) OR (A AND B)) OR B OR
 * ((E AND G) OR (F AND G))
 *
 * @param expr
 * @return
 */
private static SQLBinaryOpExpr expandOrExpression(SQLBinaryOpExpr expr) {
    SQLExpr left = expr.getLeft();
    SQLExpr right = expr.getRight();
    SQLExpr leftOp = toDNF(left);
    SQLExpr rightOp = toDNF(right);
    return new SQLBinaryOpExpr(leftOp, SQLBinaryOperator.BooleanOr, rightOp);
}
 
Example 18
Source Project: dble   Source File: ExpressionUtil.java    License: GNU General Public License v2.0 5 votes vote down vote up
/**
 * allow (A and B) and C
 *
 * @param expr
 * @return
 */
public static boolean isDNF(SQLExpr expr) {
    if (!isLogicalExpression(expr)) {
        return true;
    }
    SQLBinaryOpExpr binOpExpr = (SQLBinaryOpExpr) expr;
    SQLExpr left = binOpExpr.getLeft();
    SQLExpr right = binOpExpr.getRight();
    if (binOpExpr.getOperator() == SQLBinaryOperator.BooleanAnd) {
        boolean isAllNonLogicExpr = true;
        if (left instanceof SQLBinaryOpExpr) {
            SQLBinaryOpExpr leftBinaryOp = (SQLBinaryOpExpr) left;
            if (leftBinaryOp.getOperator() == SQLBinaryOperator.BooleanOr) {
                return false;
            }
            if (isLogicalExpression(leftBinaryOp)) {
                isAllNonLogicExpr = false;
            }
        }
        if (right instanceof SQLBinaryOpExpr) {
            SQLBinaryOpExpr rightBinaryOp = (SQLBinaryOpExpr) right;
            if (rightBinaryOp.getOperator() == SQLBinaryOperator.BooleanOr) {
                return false;
            }
            if (isLogicalExpression(rightBinaryOp)) {
                isAllNonLogicExpr = false;
            }
        }
        if (isAllNonLogicExpr) {
            return true;
        }
    }

    if (!isDNF(left)) {
        return false;
    }
    return isDNF(right);
}
 
Example 19
Source Project: dble   Source File: ExpressionUtil.java    License: GNU General Public License v2.0 5 votes vote down vote up
private static boolean isLogicalExpression(SQLExpr expr) { //XOR?
    if (!(expr instanceof SQLBinaryOpExpr)) {
        return false;
    }
    SQLBinaryOpExpr binOpExpr = (SQLBinaryOpExpr) expr;
    return binOpExpr.getOperator() == SQLBinaryOperator.BooleanAnd || binOpExpr.getOperator() == SQLBinaryOperator.BooleanOr;
}
 
Example 20
Source Project: dble   Source File: DruidUpdateParserTest.java    License: GNU General Public License v2.0 5 votes vote down vote up
public static void printWhereClauseAST(SQLExpr sqlExpr) {
    if (sqlExpr == null)
        return;
    ArrayList<SQLExpr> exprNode = new ArrayList<>();
    int i = 0, curLevel = 1, nextLevel = 0;
    SQLExpr iterExpr;
    exprNode.add(sqlExpr);
    while (true) {
        iterExpr = exprNode.get(i++);
        if (iterExpr == null)
            break;

        if (iterExpr instanceof SQLBinaryOpExpr) {
            System.out.print(((SQLBinaryOpExpr) iterExpr).getOperator());
        } else {
            System.out.print(iterExpr.toString());
        }
        System.out.print("\t");
        curLevel--;

        if (iterExpr instanceof SQLBinaryOpExpr) {
            if (((SQLBinaryOpExpr) iterExpr).getLeft() != null) {
                exprNode.add(((SQLBinaryOpExpr) iterExpr).getLeft());
                nextLevel++;
            }
            if (((SQLBinaryOpExpr) iterExpr).getRight() != null) {
                exprNode.add(((SQLBinaryOpExpr) iterExpr).getRight());
                nextLevel++;
            }
        }
        if (curLevel == 0) {
            System.out.println("\t\tNum of nodes in next level: " + nextLevel);
            curLevel = nextLevel;
            nextLevel = 0;
        }
        if (exprNode.size() == i)
            break;
    }
}
 
Example 21
Source Project: elasticsearch-sql   Source File: WhereParser.java    License: Apache License 2.0 5 votes vote down vote up
private boolean explanSpecialCondWithBothSidesAreProperty(SQLBinaryOpExpr bExpr, Where where) throws SqlParseException {
    //join is not support
    if ((bExpr.getLeft() instanceof SQLPropertyExpr || bExpr.getLeft() instanceof SQLIdentifierExpr) &&
            (bExpr.getRight() instanceof SQLPropertyExpr || bExpr.getRight() instanceof SQLIdentifierExpr) &&
            Sets.newHashSet("=", "<", ">", ">=", "<=","<>","!=").contains(bExpr.getOperator().getName()) &&
            !Util.isFromJoinOrUnionTable(bExpr)

            ) {
        SQLMethodInvokeExpr sqlMethodInvokeExpr = new SQLMethodInvokeExpr("script", null);
        String operator = bExpr.getOperator().getName();
        if (operator.equals("=")) {
            operator = "==";
        }else
        if (operator.equals("<>")) {
            operator = "!=";
        }

        String leftProperty = Util.expr2Object(bExpr.getLeft()).toString();
        String rightProperty = Util.expr2Object(bExpr.getRight()).toString();
        if (leftProperty.split("\\.").length > 1) {

            leftProperty = leftProperty.substring(leftProperty.split("\\.")[0].length() + 1);
        }

        if (rightProperty.split("\\.").length > 1) {
            rightProperty = rightProperty.substring(rightProperty.split("\\.")[0].length() + 1);
        }

        sqlMethodInvokeExpr.addParameter(new SQLCharExpr(
                "doc['" + leftProperty + "'].value " +
                        operator +
                        " doc['" + rightProperty + "'].value"));


        explanCond("AND", sqlMethodInvokeExpr, where);
        return true;
    }
    return false;
}
 
Example 22
Source Project: elasticsearch-sql   Source File: WhereParser.java    License: Apache License 2.0 5 votes vote down vote up
private boolean isCond(SQLBinaryOpExpr expr) {
    SQLExpr leftSide = expr.getLeft();
    if (leftSide instanceof SQLMethodInvokeExpr) {
        return isAllowedMethodOnConditionLeft((SQLMethodInvokeExpr) leftSide, expr.getOperator());
    }
    return leftSide instanceof SQLIdentifierExpr ||
            leftSide instanceof SQLPropertyExpr ||
            leftSide instanceof SQLVariantRefExpr ||
            leftSide instanceof SQLCastExpr;
}
 
Example 23
Source Project: elasticsearch-sql   Source File: ScriptFilter.java    License: Apache License 2.0 5 votes vote down vote up
public boolean tryParseFromMethodExpr(SQLMethodInvokeExpr expr) throws SqlParseException {
    if (!expr.getMethodName().toLowerCase().equals("script")) {
        return false;
    }
    List<SQLExpr> methodParameters = expr.getParameters();
    if (methodParameters.size() == 0) {
        return false;
    }
    script = Util.extendedToString(methodParameters.get(0));

    if (methodParameters.size() == 1) {
        return true;
    }

    args = new HashMap<>();
    for (int i = 1; i < methodParameters.size(); i++) {

        SQLExpr innerExpr = methodParameters.get(i);
        if (!(innerExpr instanceof SQLBinaryOpExpr)) {
            return false;
        }
        SQLBinaryOpExpr binaryOpExpr = (SQLBinaryOpExpr) innerExpr;
        if (!binaryOpExpr.getOperator().getName().equals("=")) {
            return false;
        }

        SQLExpr right = binaryOpExpr.getRight();
        Object value = Util.expr2Object(right);
        String key = Util.extendedToString(binaryOpExpr.getLeft());
        if(key.equals("script_type")){
            parseAndUpdateScriptType(value.toString());
        }
        else {
            args.put(key, value);
        }

    }
    return true;
}
 
Example 24
Source Project: elasticsearch-sql   Source File: FieldMaker.java    License: Apache License 2.0 5 votes vote down vote up
public static SQLMethodInvokeExpr makeBinaryMethodField(SQLBinaryOpExpr expr, String alias, boolean first) throws SqlParseException {
    List<SQLExpr> params = new ArrayList<>();

    String scriptFieldAlias;
    if (first && (alias == null || alias.equals(""))) {
        scriptFieldAlias = "field_" + SQLFunctions.random();
    } else {
        scriptFieldAlias = alias;
    }
    params.add(new SQLCharExpr(scriptFieldAlias));

    switch (expr.getOperator()) {
        case Add:
            return convertBinaryOperatorToMethod("add", expr);
        case Multiply:
            return convertBinaryOperatorToMethod("multiply", expr);

        case Divide:
            return convertBinaryOperatorToMethod("divide", expr);

        case Modulus:
            return convertBinaryOperatorToMethod("modulus", expr);

        case Subtract:
            return convertBinaryOperatorToMethod("subtract", expr);
        default:
            throw new SqlParseException(expr.getOperator().getName() + " is not support");
    }
}
 
Example 25
Source Project: Mycat2   Source File: WhereUnit.java    License: GNU General Public License v3.0 4 votes vote down vote up
public WhereUnit(SQLBinaryOpExpr whereExpr) {
	this.whereExpr = whereExpr;
	this.canSplitExpr = whereExpr;
}
 
Example 26
Source Project: Mycat2   Source File: WhereUnit.java    License: GNU General Public License v3.0 4 votes vote down vote up
public SQLBinaryOpExpr getWhereExpr() {
	return whereExpr;
}
 
Example 27
Source Project: Mycat2   Source File: WhereUnit.java    License: GNU General Public License v3.0 4 votes vote down vote up
public void setWhereExpr(SQLBinaryOpExpr whereExpr) {
	this.whereExpr = whereExpr;
}
 
Example 28
Source Project: Mycat2   Source File: WhereUnit.java    License: GNU General Public License v3.0 4 votes vote down vote up
public SQLBinaryOpExpr getCanSplitExpr() {
	return canSplitExpr;
}
 
Example 29
Source Project: Mycat2   Source File: WhereUnit.java    License: GNU General Public License v3.0 4 votes vote down vote up
public void setCanSplitExpr(SQLBinaryOpExpr canSplitExpr) {
	this.canSplitExpr = canSplitExpr;
}
 
Example 30
/**
     * 从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 "";
    }