com.alibaba.druid.sql.ast.expr.SQLMethodInvokeExpr Java Examples

The following examples show how to use com.alibaba.druid.sql.ast.expr.SQLMethodInvokeExpr. 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: ItemFuncTrim.java    From dble with GNU General Public License v2.0 6 votes vote down vote up
@Override
public SQLExpr toExpression() {
    SQLMethodInvokeExpr method = new SQLMethodInvokeExpr();
    if (mTrimMode == TrimTypeEnum.LTRIM) {
        method.setMethodName("LTRIM");
        method.addParameter(args.get(0).toExpression());

    } else if (mTrimMode == TrimTypeEnum.RTRIM) {
        method.setMethodName("RTRIM");
        method.addParameter(args.get(0).toExpression());

    } else {
        method.setMethodName("TRIM");
        method.addParameter(args.get(0).toExpression());
        if (this.getArgCount() > 1) {
            method.setFrom(args.get(1).toExpression());
        }
        if (mTrimMode != TrimTypeEnum.DEFAULT) {
            method.setTrimOption(mTrimMode.toString());
        }
    }
    return method;
}
 
Example #2
Source File: ItemDecimalTypeConvert.java    From dble with GNU General Public License v2.0 6 votes vote down vote up
@Override
public SQLExpr toExpression() {
    SQLMethodInvokeExpr method = new SQLMethodInvokeExpr();
    method.setMethodName("CONVERT");
    method.addParameter(args.get(0).toExpression());
    if (precision >= 0 || dec > 0) {
        SQLMethodInvokeExpr dataType = new SQLMethodInvokeExpr();
        dataType.setMethodName("DECIMAL");
        if (precision >= 0) {
            dataType.addParameter(new SQLIntegerExpr(precision));
        }
        if (dec > 0) {
            dataType.addParameter(new SQLIntegerExpr(dec));
        }
        method.addParameter(dataType);
    } else {
        method.addParameter(new SQLIdentifierExpr("DECIMAL"));
    }
    return method;
}
 
Example #3
Source File: WhereParser.java    From elasticsearch-sql with 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 #4
Source File: Maker.java    From elasticsearch-sql with Apache License 2.0 6 votes vote down vote up
/**
 * 构建过滤条件
 * 
 * @param cond
 * @return
 * @throws SqlParseException
 */
protected ToXContent make(Condition cond) throws SqlParseException {

       String name = cond.getName();
       Object value = cond.getValue();

       ToXContent x = null;

       if (value instanceof SQLMethodInvokeExpr) {
           x = make(cond, name, (SQLMethodInvokeExpr) value);
       }
       else if (value instanceof SubQueryExpression){
           x = make(cond,name,((SubQueryExpression)value).getValues());
       } else {
		x = make(cond, name, value);
	}


	return x;
}
 
Example #5
Source File: MySQLPlanNodeVisitor.java    From dble with GNU General Public License v2.0 6 votes vote down vote up
private String createInnerFuncSelectSQL(List<SQLSelectItem> items) {
    StringBuffer sb = new StringBuffer("SELECT ");
    if (items != null) {
        for (SQLSelectItem si : items) {
            if (si.getExpr() instanceof SQLMethodInvokeExpr &&
                    ItemCreate.getInstance().isInnerFunc(((SQLMethodInvokeExpr) si.getExpr()).getMethodName())) {
                sb.append(si.getExpr().toString() + ",");
            }
        }
        if (sb.length() > 7) {
            sb.setLength(sb.length() - 1);
            return sb.toString();
        }
    }
    return null;
}
 
Example #6
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 #7
Source File: MysqlMethodInvocationHandler.java    From Mycat2 with GNU General Public License v3.0 6 votes vote down vote up
private SQLExpr doInvoke(SQLMethodInvokeExpr expr) throws SQLNonTransientException {
    String methodName = expr.getMethodName().toUpperCase();
    switch (methodName) {
        case "NOW":
        case "SYSDATE":
        case "CURRENT_TIMESTAMP":
            return invokeNow();
        case "ADDDATE":
        case "DATE_ADD":
            return invokeAddDate(expr, false);
        case "SUBDATE":
        case "DATE_SUB":
            return invokeAddDate(expr, true);
    }
    return null;
}
 
Example #8
Source File: ElasticSqlExprParser.java    From elasticsearch-sql with Apache License 2.0 6 votes vote down vote up
protected SQLExpr bracketRest(SQLExpr expr) {
    Number index;

    if (lexer.token() == Token.LITERAL_INT) {
        index = lexer.integerValue();
        lexer.nextToken();
    } else {
        throw new ParserException("error : " + lexer.stringVal());
    }

    if (expr instanceof SQLMethodInvokeExpr) {
        SQLMethodInvokeExpr methodInvokeExpr = (SQLMethodInvokeExpr) expr;
        methodInvokeExpr.getParameters().add(new SQLIntegerExpr(index));
    }
    lexer.nextToken();
    expr = primaryRest(expr);
    return expr;
}
 
Example #9
Source File: DruidInsertParser.java    From Mycat2 with GNU General Public License v3.0 6 votes vote down vote up
private String getShardingValue(SQLExpr expr) throws SQLNonTransientException {
	String shardingValue = null;
	if(expr instanceof SQLIntegerExpr) {
		SQLIntegerExpr intExpr = (SQLIntegerExpr)expr;
		shardingValue = intExpr.getNumber() + "";
	} else if (expr instanceof SQLCharExpr) {
		SQLCharExpr charExpr = (SQLCharExpr)expr;
		shardingValue = charExpr.getText();
	} else if (expr instanceof SQLMethodInvokeExpr) {
		SQLMethodInvokeExpr methodInvokeExpr = (SQLMethodInvokeExpr)expr;
		try {
			shardingValue = tryInvokeSQLMethod(methodInvokeExpr);
		}catch (Exception e){
			LOGGER.error("",e);
		}
		if (shardingValue == null){
			shardingValue = expr.toString();
		}
	} else {
		shardingValue = expr.toString();
	}
	return shardingValue;
}
 
Example #10
Source File: FieldMaker.java    From elasticsearch-sql with Apache License 2.0 6 votes vote down vote up
private static Field makeFilterMethodField(SQLMethodInvokeExpr filterMethod, String alias) throws SqlParseException {
    List<SQLExpr> parameters = filterMethod.getParameters();
    int parametersSize = parameters.size();
    if (parametersSize != 1 && parametersSize != 2) {
        throw new SqlParseException("filter group by field should only have one or 2 parameters filter(Expr) or filter(name,Expr)");
    }
    String filterAlias = filterMethod.getMethodName();
    SQLExpr exprToCheck = null;
    if (parametersSize == 1) {
        exprToCheck = parameters.get(0);
        filterAlias = "filter(" + exprToCheck.toString().replaceAll("\n", " ") + ")";
    }
    if (parametersSize == 2) {
        filterAlias = Util.extendedToString(parameters.get(0));
        exprToCheck = parameters.get(1);
    }
    Where where = Where.newInstance();
    new WhereParser(new SqlParser()).parseWhere(exprToCheck, where);
    if (where.getWheres().size() == 0)
        throw new SqlParseException("unable to parse filter where.");
    List<KVValue> methodParameters = new ArrayList<>();
    methodParameters.add(new KVValue("where", where));
    methodParameters.add(new KVValue("alias", filterAlias + "@FILTER"));
    return new MethodField("filter", methodParameters, null, alias);
}
 
Example #11
Source File: ItemSumStd.java    From dble with GNU General Public License v2.0 5 votes vote down vote up
@Override
public SQLExpr toExpression() {
    SQLMethodInvokeExpr method = new SQLMethodInvokeExpr(funcName());
    for (Item arg : args) {
        method.addParameter(arg.toExpression());
    }
    return method;
}
 
Example #12
Source File: ItemSumAnd.java    From dble with GNU General Public License v2.0 5 votes vote down vote up
@Override
public SQLExpr toExpression() {
    SQLMethodInvokeExpr method = new SQLMethodInvokeExpr(funcName());
    for (Item arg : args) {
        method.addParameter(arg.toExpression());
    }
    return method;
}
 
Example #13
Source File: ItemSumOr.java    From dble with GNU General Public License v2.0 5 votes vote down vote up
@Override
public SQLExpr toExpression() {
    SQLMethodInvokeExpr method = new SQLMethodInvokeExpr(funcName());
    for (Item arg : args) {
        method.addParameter(arg.toExpression());
    }
    return method;
}
 
Example #14
Source File: ItemDateAddInterval.java    From dble with GNU General Public License v2.0 5 votes vote down vote up
@Override
public SQLExpr toExpression() {
    String funcName = funcName();
    if (dateSubInterval) {
        funcName = "date_sub";
    }
    SQLMethodInvokeExpr method = new SQLMethodInvokeExpr(funcName);
    method.addParameter(args.get(0).toExpression());
    SQLIntervalExpr intervalExpr = new SQLIntervalExpr();
    intervalExpr.setValue(args.get(1).toExpression());
    intervalExpr.setUnit(intType);
    method.addParameter(intervalExpr);
    return method;
}
 
Example #15
Source File: ItemSumXor.java    From dble with GNU General Public License v2.0 5 votes vote down vote up
@Override
public SQLExpr toExpression() {
    SQLMethodInvokeExpr method = new SQLMethodInvokeExpr(funcName());
    for (Item arg : args) {
        method.addParameter(arg.toExpression());
    }
    return method;
}
 
Example #16
Source File: ItemSumVariance.java    From dble with GNU General Public License v2.0 5 votes vote down vote up
@Override
public SQLExpr toExpression() {
    SQLMethodInvokeExpr method = new SQLMethodInvokeExpr(funcName());
    for (Item arg : args) {
        method.addParameter(arg.toExpression());
    }
    return method;
}
 
Example #17
Source File: ItemFuncTimestampDiff.java    From dble with GNU General Public License v2.0 5 votes vote down vote up
@Override
public SQLExpr toExpression() {
    SQLMethodInvokeExpr method = new SQLMethodInvokeExpr(funcName());
    method.addParameter(new SQLIdentifierExpr(intType.toString()));
    for (Item arg : args) {
        method.addParameter(arg.toExpression());
    }
    return method;
}
 
Example #18
Source File: ItemFuncConvCharset.java    From dble with GNU General Public License v2.0 5 votes vote down vote up
@Override
public SQLExpr toExpression() {
    SQLMethodInvokeExpr method = new SQLMethodInvokeExpr(funcName());
    method.addParameter(args.get(0).toExpression());
    method.setUsing(new SQLIdentifierExpr(mysqlCharset));
    return method;
}
 
Example #19
Source File: WhereParser.java    From elasticsearch-sql with Apache License 2.0 5 votes vote down vote up
private boolean isAllowedMethodOnConditionLeft(SQLMethodInvokeExpr method, SQLBinaryOperator operator) {
    return (method.getMethodName().toLowerCase().equals("nested") ||
            method.getMethodName().toLowerCase().equals("children") ||
            SQLFunctions.buildInFunctions.contains(method.getMethodName().toLowerCase())
    ) &&
            !operator.isLogical();
}
 
Example #20
Source File: WhereParser.java    From elasticsearch-sql with 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 #21
Source File: WhereParser.java    From elasticsearch-sql with 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 #22
Source File: JoinParser.java    From Mycat2 with GNU General Public License v3.0 5 votes vote down vote up
private void parserFields(List<SQLSelectItem> mysqlSelectList){
		//显示的字段
		String key="";
		String value ="";
		String exprfield = "";
		for(SQLSelectItem item : mysqlSelectList) {
			if (item.getExpr() instanceof SQLAllColumnExpr) {
				//*解析
				setField(item.toString(), item.toString());
			}
			else {
				if (item.getExpr() instanceof SQLAggregateExpr) {
					SQLAggregateExpr expr =(SQLAggregateExpr)item.getExpr();
					 key = getExprFieldName(expr);
					 setField(key, value);
				}else if(item.getExpr() instanceof SQLMethodInvokeExpr){
					key = getMethodInvokeFieldName(item);
					exprfield=getFieldName(item);
//					value=item.getAlias();
					setField(key, value,exprfield);
				}else {					
					key=getFieldName(item);
					value=item.getAlias();
					setField(key, value);
				}			
				
			}
		}			
	}
 
Example #23
Source File: WhereParser.java    From elasticsearch-sql with Apache License 2.0 5 votes vote down vote up
private MethodField parseSQLMethodInvokeExprWithFunctionInWhere(SQLMethodInvokeExpr soExpr) throws SqlParseException {

        MethodField methodField = FieldMaker.makeMethodField(soExpr.getMethodName(),
                soExpr.getParameters(),
                null,
                null,
                query != null ? query.getFrom().getAlias() : null,
                false);
        return methodField;
    }
 
Example #24
Source File: WhereParser.java    From elasticsearch-sql with Apache License 2.0 5 votes vote down vote up
private Object[] getMethodValuesWithSubQueries(SQLMethodInvokeExpr method) throws SqlParseException {
    List<Object> values = new ArrayList<>();
    for (SQLExpr innerExpr : method.getParameters()) {
        if (innerExpr instanceof SQLQueryExpr) {
            Select select = sqlParser.parseSelect((MySqlSelectQueryBlock) ((SQLQueryExpr) innerExpr).getSubQuery().getQuery());
            values.add(new SubQueryExpression(select));
        } else if (innerExpr instanceof SQLTextLiteralExpr) {
            values.add(((SQLTextLiteralExpr) innerExpr).getText());
        } else {
            values.add(innerExpr);
        }

    }
    return values.toArray();
}
 
Example #25
Source File: WhereParser.java    From elasticsearch-sql with Apache License 2.0 5 votes vote down vote up
private Object parseValue(SQLExpr expr) throws SqlParseException {
    if (expr instanceof SQLNumericLiteralExpr) {
        Number number = ((SQLNumericLiteralExpr) expr).getNumber();
        if(number instanceof BigDecimal){
            return number.doubleValue();
        }
        if(number instanceof BigInteger){
            return number.longValue();
        }
        return ((SQLNumericLiteralExpr) expr).getNumber();
    } else if (expr instanceof SQLCharExpr) {
        return ((SQLCharExpr) expr).getText();
    } else if (expr instanceof SQLMethodInvokeExpr) {
        return expr;
    } else if (expr instanceof SQLNullExpr) {
        return null;
    } else if (expr instanceof SQLIdentifierExpr) {
        return expr;
    } else if (expr instanceof SQLPropertyExpr) {
        return expr;
    } else {
        /*
        zhongshu-comment 解析where子查询时会抛出这样的异常:
        Failed to parse SqlExpression of type class com.alibaba.druid.sql.ast.expr.SQLQueryExpr. expression value: com.alibaba.druid.sql.ast.statement.SQLSelect@1d60737e
         */
        throw new SqlParseException(
                String.format("Failed to parse SqlExpression of type %s. expression value: %s", expr.getClass(), expr)
        );
    }
}
 
Example #26
Source File: ScriptFilter.java    From elasticsearch-sql with 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 #27
Source File: ElasticSqlExprParser.java    From elasticsearch-sql with Apache License 2.0 5 votes vote down vote up
protected SQLExpr parsePosition() {

        SQLExpr subStr = this.primary();
        accept(Token.IN);
        SQLExpr str = this.expr();
        accept(Token.RPAREN);

        SQLMethodInvokeExpr locate = new SQLMethodInvokeExpr("LOCATE");
        locate.addParameter(subStr);
        locate.addParameter(str);

        return primaryRest(locate);
    }
 
Example #28
Source File: ChildrenType.java    From elasticsearch-sql with Apache License 2.0 5 votes vote down vote up
public boolean tryFillFromExpr(SQLExpr expr) throws SqlParseException {
    if (!(expr instanceof SQLMethodInvokeExpr)) return false;
    SQLMethodInvokeExpr method = (SQLMethodInvokeExpr) expr;

    String methodName = method.getMethodName();

    if (!methodName.toLowerCase().equals("children")) return false;

    List<SQLExpr> parameters = method.getParameters();

    if (parameters.size() != 2)
        throw new SqlParseException("on children object only allowed 2 parameters (type, field)/(type, conditions...) ");

    String type = Util.extendedToString(parameters.get(0));
    this.childType = type;
    
    SQLExpr secondParameter = parameters.get(1);
    if(secondParameter instanceof SQLTextLiteralExpr || secondParameter instanceof SQLIdentifierExpr || secondParameter instanceof SQLPropertyExpr) {
        this.field = Util.extendedToString(secondParameter);
        this.simple = true;
    } else {
        Where where = Where.newInstance();
        new WhereParser(new SqlParser()).parseWhere(secondParameter,where);
        if(where.getWheres().size() == 0)
            throw new SqlParseException("unable to parse filter where.");
        this.where = where;
        simple = false;
    }
    
    return true;
}
 
Example #29
Source File: FieldMaker.java    From elasticsearch-sql with 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 #30
Source File: ItemFuncOrd.java    From dble with GNU General Public License v2.0 5 votes vote down vote up
@Override
public SQLExpr toExpression() {
    SQLMethodInvokeExpr method = new SQLMethodInvokeExpr(funcName());
    for (Item arg : args) {
        method.addParameter(arg.toExpression());
    }
    return method;
}