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

The following examples show how to use com.alibaba.druid.sql.ast.expr.SQLPropertyExpr. 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: SqlParser.java    From elasticsearch-sql with Apache License 2.0 6 votes vote down vote up
private List<Field> getConnectedFields(List<Condition> conditions, String alias) throws SqlParseException {
    List<Field> fields = new ArrayList<>();
    String prefix = alias + ".";
    for (Condition condition : conditions) {
        if (condition.getName().startsWith(prefix)) {
            fields.add(new Field(condition.getName().replaceFirst(prefix, ""), null));
        } else {
            if (!((condition.getValue() instanceof SQLPropertyExpr) || (condition.getValue() instanceof SQLIdentifierExpr) || (condition.getValue() instanceof String))) {
                throw new SqlParseException("conditions on join should be one side is firstTable second Other , condition was:" + condition.toString());
            }
            String aliasDotValue = condition.getValue().toString();
            int indexOfDot = aliasDotValue.indexOf(".");
            String owner = aliasDotValue.substring(0, indexOfDot);
            if (owner.equals(alias))
                fields.add(new Field(aliasDotValue.substring(indexOfDot + 1), null));
        }
    }
    return fields;
}
 
Example #2
Source File: ShowCreateView.java    From dble with GNU General Public License v2.0 6 votes vote down vote up
public static void response(ServerConnection c, String stmt) {
    try {
        MySqlShowCreateViewStatement statement = (MySqlShowCreateViewStatement) RouteStrategyFactory.getRouteStrategy().parserSQL(stmt);
        String schema = null;
        String view = null;
        if (statement.getName() instanceof SQLPropertyExpr) {
            //show create view with schema
            SQLPropertyExpr sqlPropertyExpr = (SQLPropertyExpr) statement.getName();
            //protocol not equals the nomul things
            schema = sqlPropertyExpr.getOwner().toString();
            view = sqlPropertyExpr.getName();
        } else if (statement.getName() instanceof SQLIdentifierExpr) {
            schema = c.getSchema();
            view = statement.getName().toString();
        }
        sendOutTheViewInfo(c, schema, view);
    } catch (SQLException e) {
        c.writeErrMessage(e.getSQLState(), e.getMessage(), e.getErrorCode());
    }
}
 
Example #3
Source File: Util.java    From elasticsearch-sql with 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 #4
Source File: Util.java    From elasticsearch-sql with Apache License 2.0 6 votes vote down vote up
public static Object expr2Object(SQLExpr expr, String charWithQuote) {
    Object value = null;
    if (expr instanceof SQLNumericLiteralExpr) {
        value = ((SQLNumericLiteralExpr) expr).getNumber();
    } else if (expr instanceof SQLCharExpr) {
        value = charWithQuote + ((SQLCharExpr) expr).getText() + charWithQuote;
    } else if (expr instanceof SQLIdentifierExpr) {
        value = expr.toString();
    } else if (expr instanceof SQLPropertyExpr) {
        value = expr.toString();
    } else if (expr instanceof SQLVariantRefExpr) {
        value = expr.toString();
    } else if (expr instanceof SQLAllColumnExpr) {
        value = "*";
    } else if (expr instanceof SQLValuableExpr) {
        value = ((SQLValuableExpr) expr).getValue();
    } else if (expr instanceof SQLBooleanExpr) {
        value = ((SQLBooleanExpr) expr).getValue();
    } else {
        //throw new SqlParseException("can not support this type " + expr.getClass());
    }
    return value;
}
 
Example #5
Source File: Util.java    From elasticsearch-sql with Apache License 2.0 5 votes vote down vote up
public static Object getScriptValue(SQLExpr expr) throws SqlParseException {
    if (expr instanceof SQLIdentifierExpr || expr instanceof SQLPropertyExpr || expr instanceof SQLVariantRefExpr) {
        return "doc['" + expr.toString() + "'].value";
    } else if (expr instanceof SQLValuableExpr) {
        return ((SQLValuableExpr) expr).getValue();
    }
    throw new SqlParseException("could not parse sqlBinaryOpExpr need to be identifier/valuable got" + expr.getClass().toString() + " with value:" + expr.toString());
}
 
Example #6
Source File: SqlParser.java    From elasticsearch-sql with Apache License 2.0 5 votes vote down vote up
private void addIfConditionRecursive(Where where, List<Condition> conditions) throws SqlParseException {
    if (where instanceof Condition) {
        Condition cond = (Condition) where;
        if (!((cond.getValue() instanceof SQLIdentifierExpr) || (cond.getValue() instanceof SQLPropertyExpr) || (cond.getValue() instanceof String))) {
            throw new SqlParseException("conditions on join should be one side is secondTable OPEAR firstTable, condition was:" + cond.toString());
        }
        conditions.add(cond);
    }
    for (Where innerWhere : where.getWheres()) {
        addIfConditionRecursive(innerWhere, conditions);
    }
}
 
Example #7
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 #8
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 #9
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 #10
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 #11
Source File: JoinParser.java    From Mycat2 with GNU General Public License v3.0 5 votes vote down vote up
private String getFieldName(SQLSelectItem item){
	if (item.getExpr() instanceof SQLPropertyExpr) {			
		return item.getExpr().toString();//字段别名
	}
	else {
		return item.toString();
	}
}
 
Example #12
Source File: Util.java    From elasticsearch-sql with Apache License 2.0 5 votes vote down vote up
public static Object removeTableAilasFromField(Object expr, String tableAlias) {

        if (expr instanceof SQLIdentifierExpr || expr instanceof SQLPropertyExpr || expr instanceof SQLVariantRefExpr) {
            String name = expr.toString().replace("`", "");
            if (tableAlias != null) {
                String aliasPrefix = tableAlias + ".";
                if (name.startsWith(aliasPrefix)) {
                    String newFieldName = name.replaceFirst(aliasPrefix, "");
                    return new SQLIdentifierExpr(newFieldName);
                }
            }
        }
        return expr;
    }
 
Example #13
Source File: ItemField.java    From dble with GNU General Public License v2.0 5 votes vote down vote up
@Override
public SQLExpr toExpression() {
    SQLIdentifierExpr parent = StringUtil.isEmpty(tableName) ? null : new SQLIdentifierExpr(tableName);
    if (parent != null) {
        return new SQLPropertyExpr(parent, itemName);
    } else return new SQLIdentifierExpr(itemName);
}
 
Example #14
Source File: SelectHandler.java    From dble with GNU General Public License v2.0 5 votes vote down vote up
private static boolean isVariantRef(SQLExpr expr) {
    if (expr instanceof SQLVariantRefExpr) {
        return true;
    } else if (expr instanceof SQLPropertyExpr) {
        return isVariantRef(((SQLPropertyExpr) expr).getOwner());
    } else {
        return false;
    }
}
 
Example #15
Source File: DruidSelectParser.java    From Mycat2 with 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 #16
Source File: JoinParser.java    From Mycat2 with GNU General Public License v3.0 5 votes vote down vote up
private String getMethodInvokeFieldName(SQLSelectItem item){
	SQLMethodInvokeExpr invoke = (SQLMethodInvokeExpr)item.getExpr();
	List<SQLExpr> itemExprs = invoke.getParameters();
	for(SQLExpr itemExpr:itemExprs){
		if (itemExpr instanceof SQLPropertyExpr) {
			return itemExpr.toString();//字段别名
		}
	}
	return item.toString();
}
 
Example #17
Source File: SQLFunctions.java    From elasticsearch-sql with Apache License 2.0 4 votes vote down vote up
private static boolean isProperty(SQLExpr expr) {
    return (expr instanceof SQLIdentifierExpr || expr instanceof SQLPropertyExpr || expr instanceof SQLVariantRefExpr);
}
 
Example #18
Source File: WhereParser.java    From elasticsearch-sql with Apache License 2.0 4 votes vote down vote up
private SQLMethodInvokeExpr parseSQLBinaryOpExprWhoIsConditionInWhere(SQLBinaryOpExpr soExpr) throws SqlParseException {

        if (!(soExpr.getLeft() instanceof SQLCastExpr || soExpr.getRight() instanceof SQLCastExpr)) {
            if (!(soExpr.getLeft() instanceof SQLMethodInvokeExpr ||
                soExpr.getRight() instanceof SQLMethodInvokeExpr)) {
                return null;
            }

            if (soExpr.getLeft() instanceof SQLMethodInvokeExpr) {
                if (!SQLFunctions.buildInFunctions.contains(((SQLMethodInvokeExpr) soExpr.getLeft()).getMethodName())) {
                    return null;
                }
            }

            if (soExpr.getRight() instanceof SQLMethodInvokeExpr) {
                if (!SQLFunctions.buildInFunctions.contains(((SQLMethodInvokeExpr) soExpr.getRight()).getMethodName())) {
                    return null;
                }
            }
        }

        MethodField leftMethod = new MethodField(null, Lists.newArrayList(new KVValue("", Util.expr2Object(soExpr.getLeft(), "'"))), null, null);
        if (soExpr.getLeft() instanceof SQLIdentifierExpr || soExpr.getLeft() instanceof SQLPropertyExpr) {
            leftMethod = new MethodField(null, Lists.newArrayList(new KVValue("", "doc['" + Util.expr2Object(soExpr.getLeft(), "'") + "'].value")), null, null);
        } else if (soExpr.getLeft() instanceof SQLMethodInvokeExpr) {
            leftMethod = parseSQLMethodInvokeExprWithFunctionInWhere((SQLMethodInvokeExpr) soExpr.getLeft());
        } else if (soExpr.getLeft() instanceof SQLCastExpr) {
            leftMethod = parseSQLCastExprInWhere((SQLCastExpr) soExpr.getLeft());
        }

        MethodField rightMethod = new MethodField(null, Lists.newArrayList(new KVValue("", Util.expr2Object(soExpr.getRight(), "'"))), null, null);
        if (soExpr.getRight() instanceof SQLIdentifierExpr || soExpr.getRight() instanceof SQLPropertyExpr) {
            rightMethod = new MethodField(null, Lists.newArrayList(new KVValue("", "doc['" + Util.expr2Object(soExpr.getRight(), "'") + "'].value")), null, null);
        } else if (soExpr.getRight() instanceof SQLMethodInvokeExpr) {
            rightMethod = parseSQLMethodInvokeExprWithFunctionInWhere((SQLMethodInvokeExpr) soExpr.getRight());
        } else if (soExpr.getRight() instanceof SQLCastExpr) {
            rightMethod = parseSQLCastExprInWhere((SQLCastExpr) soExpr.getRight());
        }

        String v1 = leftMethod.getParams().get(0).value.toString();
        String v1Dec = leftMethod.getParams().size() == 2 ? leftMethod.getParams().get(1).value.toString() + ";" : "";

        String v2 = rightMethod.getParams().get(0).value.toString();
        String v2Dec = rightMethod.getParams().size() == 2 ? rightMethod.getParams().get(1).value.toString() + ";" : "";

        String operator = soExpr.getOperator().getName();

        if ("=".equals(operator)) {
            operator = "==";
        }

        String finalStr = String.format("%s%s((Comparable)%s).compareTo(%s) %s 0", v1Dec, v2Dec, v1, v2, operator);

        SQLMethodInvokeExpr scriptMethod = new SQLMethodInvokeExpr("script", null);
        scriptMethod.addParameter(new SQLCharExpr(finalStr));
        return scriptMethod;

    }
 
Example #19
Source File: DruidSelectParser.java    From Mycat2 with GNU General Public License v3.0 4 votes vote down vote up
private String[] buildGroupByCols(List<SQLExpr> groupByItems,Map<String, String> aliaColumns) {
	String[] groupByCols = new String[groupByItems.size()];
	for(int i= 0; i < groupByItems.size(); i++) {
		SQLExpr sqlExpr = groupByItems.get(i);
		String column = null;
		if(sqlExpr instanceof SQLIdentifierExpr )
		{
			column=((SQLIdentifierExpr) sqlExpr).getName();
		} else if(sqlExpr instanceof SQLMethodInvokeExpr){
			column = ((SQLMethodInvokeExpr) sqlExpr).toString();
		} else if(sqlExpr instanceof MySqlOrderingExpr){
			//todo czn
			SQLExpr expr = ((MySqlOrderingExpr) sqlExpr).getExpr();

			if (expr instanceof SQLName)
			{
				column = StringUtil.removeBackquote(((SQLName) expr).getSimpleName());//不要转大写 2015-2-10 sohudo StringUtil.removeBackquote(expr.getSimpleName().toUpperCase());
			} else
			{
				column = StringUtil.removeBackquote(expr.toString());
			}
		} else if(sqlExpr instanceof SQLPropertyExpr){
			/**
			 * 针对子查询别名,例如select id from (select h.id from hotnews h  union select h.title from hotnews h ) as t1 group by t1.id;
			 */
			column = sqlExpr.toString();
		}
		if(column == null){
			column = sqlExpr.toString();
		}
		int dotIndex=column.indexOf(".") ;
		int bracketIndex=column.indexOf("(") ;
		//通过判断含有括号来决定是否为函数列
		if(dotIndex!=-1&&bracketIndex==-1)
		{
			//此步骤得到的column必须是不带.的,有别名的用别名,无别名的用字段名
			column=column.substring(dotIndex+1) ;
		}
		groupByCols[i] = getAliaColumn(aliaColumns,column);//column;
	}
	return groupByCols;
}
 
Example #20
Source File: NestedType.java    From elasticsearch-sql with Apache License 2.0 4 votes vote down vote up
public boolean tryFillFromExpr(SQLExpr expr) throws SqlParseException {
    if (!(expr instanceof SQLMethodInvokeExpr)) return false;
    SQLMethodInvokeExpr method = (SQLMethodInvokeExpr) expr;
    String methodNameLower = method.getMethodName().toLowerCase();
    if (!(methodNameLower.equals("nested") || methodNameLower.equals("reverse_nested"))) return false;

    reverse = methodNameLower.equals("reverse_nested");

    List<SQLExpr> parameters = method.getParameters();
    int size = parameters.size();
    if (size != 3 && size != 2 && size != 1)
        throw new SqlParseException("on nested object only allowed 3 parameters (path,conditions..,inner_hits) or 2 parameters (field,path)/(path,conditions..) or 1 parameter (field) ");

    // inner_hits
    if (size == 3) {
        this.innerHits = Util.extendedToString(parameters.remove(--size));
    }

    String field = Util.extendedToString(parameters.get(0));
    this.field = field;
    if (size == 1) {
        //calc path myself..
        if (!field.contains(".")) {
            if (!reverse)
                throw new SqlParseException("nested should contain . on their field name");
            else {
                this.path = null;
                this.simple = true;
            }
        } else {
            int lastDot = field.lastIndexOf(".");
            this.path = field.substring(0, lastDot);
            this.simple = true;

        }

    } else if (size == 2) {
        SQLExpr secondParameter = parameters.get(1);
        if(secondParameter instanceof SQLTextLiteralExpr || secondParameter instanceof SQLIdentifierExpr || secondParameter instanceof SQLPropertyExpr) {

            String pathString = Util.extendedToString(secondParameter);
            if(pathString.equals(""))
                this.path = null;
            else
                this.path = pathString;
            this.simple = true;
        }
        else {
            this.path = field;
            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;
}