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

The following examples show how to use com.alibaba.druid.sql.ast.expr.SQLCharExpr. 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 Object getExpValue(SQLExpr expr){
	if (expr instanceof SQLIntegerExpr){
		return ((SQLIntegerExpr)expr).getNumber().longValue();
	}
	if (expr instanceof SQLNumberExpr){
		return ((SQLNumberExpr)expr).getNumber().doubleValue();
	}		
	if (expr instanceof SQLCharExpr){
		String va=((SQLCharExpr)expr).toString();
		return va;//remove(va,'\'');
	}
	if (expr instanceof SQLBooleanExpr){			
		return ((SQLBooleanExpr)expr).getValue();
	}			
	if (expr instanceof SQLNullExpr){
		return null;
	}

	return expr;		
}
 
Example #2
Source File: FieldMaker.java    From elasticsearch-sql with 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 #3
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 #4
Source File: DruidCreateTableParser.java    From Mycat2 with GNU General Public License v3.0 6 votes vote down vote up
@Override
public void statementParse(SchemaConfig schema, RouteResultset rrs, SQLStatement stmt) throws SQLNonTransientException {
	MySqlCreateTableStatement createStmt = (MySqlCreateTableStatement)stmt;
	if(createStmt.getQuery() != null) {
		String msg = "create table from other table not supported :" + stmt;
		LOGGER.warn(msg);
		throw new SQLNonTransientException(msg);
	}
	String tableName = StringUtil.removeBackquote(createStmt.getTableSource().toString().toUpperCase());
	if(schema.getTables().containsKey(tableName)) {
		TableConfig tableConfig = schema.getTables().get(tableName);
		AbstractPartitionAlgorithm algorithm = tableConfig.getRule().getRuleAlgorithm();
		if(algorithm instanceof SlotFunction){
			SQLColumnDefinition column = new SQLColumnDefinition();
			column.setDataType(new SQLCharacterDataType("int"));
			column.setName(new SQLIdentifierExpr("_slot"));
			column.setComment(new SQLCharExpr("自动迁移算法slot,禁止修改"));
			((SQLCreateTableStatement)stmt).getTableElementList().add(column);
			String sql = createStmt.toString();
			rrs.setStatement(sql);
			ctx.setSql(sql);
		}
	}
	ctx.addTable(tableName);
	
}
 
Example #5
Source File: RouterUtil.java    From Mycat2 with GNU General Public License v3.0 6 votes vote down vote up
private  static String changeCreateTable(SchemaConfig schema,String tableName,String sql) {
	if (schema.getTables().containsKey(tableName)) {
		MySqlStatementParser parser = new MySqlStatementParser(sql);
		SQLStatement insertStatement = parser.parseStatement();
		if (insertStatement instanceof MySqlCreateTableStatement) {
			TableConfig tableConfig = schema.getTables().get(tableName);
			AbstractPartitionAlgorithm algorithm = tableConfig.getRule().getRuleAlgorithm();
			if (algorithm instanceof SlotFunction) {
				SQLColumnDefinition column = new SQLColumnDefinition();
				column.setDataType(new SQLCharacterDataType("int"));
				column.setName(new SQLIdentifierExpr("_slot"));
				column.setComment(new SQLCharExpr("自动迁移算法slot,禁止修改"));
				((SQLCreateTableStatement) insertStatement).getTableElementList().add(column);
				return insertStatement.toString();

			}
		}

	}
	return sql;
}
 
Example #6
Source File: ItemFuncGroupConcat.java    From dble with GNU General Public License v2.0 6 votes vote down vote up
@Override
public SQLExpr toExpression() {
    SQLAggregateExpr aggregate = new SQLAggregateExpr(funcName());
    if (hasWithDistinct()) {
        aggregate.setOption(SQLAggregateOption.DISTINCT);
    }
    if (orders != null) {
        SQLOrderBy orderBy = new SQLOrderBy();
        for (Order order : orders) {
            SQLSelectOrderByItem orderItem = new SQLSelectOrderByItem(order.getItem().toExpression());
            orderItem.setType(order.getSortOrder());
            orderBy.addItem(orderItem);
        }
        aggregate.putAttribute(ItemFuncKeyWord.ORDER_BY, orderBy);
    }
    for (Item arg : args) {
        aggregate.addArgument(arg.toExpression());
    }
    if (seperator != null) {
        SQLCharExpr sep = new SQLCharExpr(seperator);
        aggregate.putAttribute(ItemFuncKeyWord.SEPARATOR, sep);
    }
    return aggregate;
}
 
Example #7
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 #8
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 #9
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 #10
Source File: GlobalTableUtil.java    From Mycat2 with GNU General Public License v3.0 5 votes vote down vote up
static String addColumnIfCreate(String sql, SQLStatement statement) {
	if (isCreate(statement) && sql.trim().toUpperCase().startsWith("CREATE TABLE ") && !hasGlobalColumn(statement)) {
		SQLColumnDefinition column = new SQLColumnDefinition();
		column.setDataType(new SQLCharacterDataType("bigint"));
		column.setName(new SQLIdentifierExpr(GLOBAL_TABLE_MYCAT_COLUMN));
		column.setComment(new SQLCharExpr("全局表保存修改时间戳的字段名"));
		((SQLCreateTableStatement)statement).getTableElementList().add(column);
	}
	return statement.toString();
}
 
Example #11
Source File: FieldMaker.java    From elasticsearch-sql with Apache License 2.0 5 votes vote down vote up
private static Field handleIdentifier(SQLExpr expr, String alias, String tableAlias) throws SqlParseException {
    String name = expr.toString().replace("`", "");
    String newFieldName = name;
    Field field = null;
    if (tableAlias != null) {
        String aliasPrefix = tableAlias + ".";
        if (name.startsWith(aliasPrefix)) {
            newFieldName = name.replaceFirst(aliasPrefix, "");
            field = new Field(newFieldName, alias);
        }
    }

    if (tableAlias == null) {
        field = new Field(newFieldName, alias);
    }

    //zhongshu-comment 字段的别名不为空 && 别名和字段名不一样
    if (alias != null && !alias.equals(name) && !Util.isFromJoinOrUnionTable(expr)) {

        /*
        zhongshu-comment newFieldName是字段原来的名字,这句话应该是用于es dsl的
        使用别名有很多种情况:
            1、最简单的就是select field_1 as a from tbl
            2、调用函数处理字段之后,select floor(field_1) as a from tbl
            3、执行表达式,select field_1 + field_2 as a from tbl
            4、case when field_1='a' then 'haha' else 'hehe' end as a
            5、........
        所以这个if分支就是为了处理以上这些情况的
         */
        List<SQLExpr> paramers = Lists.newArrayList();
        paramers.add(new SQLCharExpr(alias)); //zhongshu-comment 别名
        paramers.add(new SQLCharExpr("doc['" + newFieldName + "'].value"));
        field = makeMethodField("script", paramers, null, alias, tableAlias, true);
    }
    return field;
}
 
Example #12
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 #13
Source File: SqlParser.java    From elasticsearch-sql with Apache License 2.0 5 votes vote down vote up
private ScriptSortBuilder.ScriptSortType judgeIsStringSort(SQLExpr expr) {
    if (expr instanceof SQLCaseExpr) {
        List<SQLCaseExpr.Item> itemList = ((SQLCaseExpr) expr).getItems();
        for (SQLCaseExpr.Item item : itemList) {
            if (item.getValueExpr() instanceof SQLCharExpr) {
                return ScriptSortBuilder.ScriptSortType.STRING;
            }
        }
    }
    return ScriptSortBuilder.ScriptSortType.NUMBER;
}
 
Example #14
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 #15
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 #16
Source File: DruidInsertReplaceParser.java    From dble with GNU General Public License v2.0 5 votes vote down vote up
static String shardingValueToSting(SQLExpr valueExpr) throws SQLNonTransientException {
    String shardingValue = null;
    if (valueExpr instanceof SQLIntegerExpr) {
        SQLIntegerExpr intExpr = (SQLIntegerExpr) valueExpr;
        shardingValue = intExpr.getNumber() + "";
    } else if (valueExpr instanceof SQLCharExpr) {
        SQLCharExpr charExpr = (SQLCharExpr) valueExpr;
        shardingValue = charExpr.getText();
    }

    if (shardingValue == null && !(valueExpr instanceof SQLNullExpr)) {
        throw new SQLNonTransientException("Not Supported of Sharding Value EXPR :" + valueExpr.toString());
    }
    return shardingValue;
}
 
Example #17
Source File: ShardingValuesHandler.java    From dble with GNU General Public License v2.0 5 votes vote down vote up
private Integer handleShardingColumn(DumpFileContext context, List<SQLExpr> values) throws SQLNonTransientException {
    AbstractPartitionAlgorithm algorithm = context.getTableConfig().getRule().getRuleAlgorithm();
    SQLExpr expr = values.get(context.getPartitionColumnIndex());
    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();
    }

    if (shardingValue == null && !(expr instanceof SQLNullExpr)) {
        throw new SQLNonTransientException("Not Supported of Sharding Value EXPR :" + values.toString());
    }

    Integer nodeIndex;
    try {
        nodeIndex = algorithm.calculate(shardingValue);
        // null means can't find any valid index
        if (nodeIndex == null || nodeIndex >= context.getTableConfig().getDataNodes().size()) {
            throw new SQLNonTransientException("can't find any valid datanode shardingValue" + values.toString());
        }
    } catch (Exception e) {
        throw new SQLNonTransientException("can't calculate valid datanode shardingValue" + values.toString() + ",due to " + e.getMessage());
    }
    return nodeIndex;
}
 
Example #18
Source File: ServerLoadDataInfileHandler.java    From Mycat2 with GNU General Public License v3.0 5 votes vote down vote up
private RouteResultset buildResultSet(Map<String, LoadData> routeMap)
{
    statement.setLocal(true);//强制local
    SQLLiteralExpr fn = new SQLCharExpr(fileName);    //默认druid会过滤掉路径的分隔符,所以这里重新设置下
    statement.setFileName(fn);
    String srcStatement = statement.toString();
    RouteResultset rrs = new RouteResultset(srcStatement, ServerParse.LOAD_DATA_INFILE_SQL);
    rrs.setLoadData(true);
    rrs.setStatement(srcStatement);
    rrs.setAutocommit(serverConnection.isAutocommit());
    rrs.setFinishedRoute(true);
    int size = routeMap.size();
    RouteResultsetNode[] routeResultsetNodes = new RouteResultsetNode[size];
    int index = 0;
    for (String dn : routeMap.keySet())
    {
        RouteResultsetNode rrNode = new RouteResultsetNode(dn, ServerParse.LOAD_DATA_INFILE_SQL, srcStatement);
        rrNode.setSource(rrs);
        rrNode.setTotalNodeSize(size);
        rrNode.setStatement(srcStatement);
        LoadData newLoadData = new LoadData();
        ObjectUtil.copyProperties(loadData, newLoadData);
        newLoadData.setLocal(true);
        LoadData loadData1 = routeMap.get(dn);
      //  if (isHasStoreToFile)
        if (loadData1.getFileName()!=null)//此处判断是否有保存分库load的临时文件dn1.txt/dn2.txt,不是判断是否有clientTemp.txt
        {
            newLoadData.setFileName(loadData1.getFileName());
        } else
        {
            newLoadData.setData(loadData1.getData());
        }
        rrNode.setLoadData(newLoadData);

        routeResultsetNodes[index] = rrNode;
        index++;
    }
    rrs.setNodes(routeResultsetNodes);
    return rrs;
}
 
Example #19
Source File: ItemString.java    From dble with GNU General Public License v2.0 4 votes vote down vote up
@Override
public SQLExpr toExpression() {
    return new SQLCharExpr(value); //LiteralString(null, value, false);
}
 
Example #20
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 #21
Source File: MysqlMethodInvocationHandler.java    From Mycat2 with GNU General Public License v3.0 4 votes vote down vote up
private SQLExpr invokeAddDate(SQLMethodInvokeExpr expr, boolean negative) throws SQLNonTransientException {
    List<SQLExpr> parameters = expr.getParameters();
    if (parameters.size() != 2) {
        throwSyntaxError(expr);
    }
    SQLExpr p1 = parameters.get(0);
    SQLExpr p2 = parameters.get(1);
    if (p1 instanceof SQLMethodInvokeExpr) {
        p1 = doInvoke((SQLMethodInvokeExpr) p1);
    }
    if (p1 instanceof SQLCharExpr) {
        String time = ((SQLCharExpr) p1).getText();
        Integer delta = null;
        String unit = null;
        if (p2 instanceof SQLIntegerExpr) {
            delta = (Integer) ((SQLIntegerExpr) p2).getNumber();
            unit = "DAY";
        } else if (p2 instanceof MySqlIntervalExpr) {
            SQLIntegerExpr value = (SQLIntegerExpr) ((MySqlIntervalExpr) p2).getValue();
            delta = (Integer) value.getNumber();
            unit = ((MySqlIntervalExpr) p2).getUnit().name();
        } else {
            throwSyntaxError(p2);
        }
        try {
            Date date = DateUtils.parseDate(time, SUPPORT_PATTERNS);
            Date result;
            delta = negative ? -delta : delta;
            if ("MONTH".equals(unit)) {
                result = DateUtils.addMonths(date, delta);
            } else if ("DAY".equals(unit)) {
                result = DateUtils.addDays(date, delta);
            } else if ("HOUR".equals(unit)) {
                result = DateUtils.addHours(date, delta);
            } else if ("MINUTE".equals(unit)) {
                result = DateUtils.addMinutes(date, delta);
            } else if ("SECOND".equals(unit)) {
                result = DateUtils.addSeconds(date, delta);
            } else {
                return null;
            }
            String ret = DateFormatUtils.format(result, "yyyy-MM-dd HH:mm:ss");
            return new SQLIdentifierExpr(ret);
        } catch (ParseException e) {
            LOGGER.error("",e);
        }
    }
    return null;
}
 
Example #22
Source File: ElasticSqlExprParser.java    From elasticsearch-sql with Apache License 2.0 4 votes vote down vote up
private SQLExpr userNameRest(SQLExpr expr) {
    if (lexer.token() != Token.VARIANT || !lexer.stringVal().startsWith("@")) {
        return expr;
    }

    MySqlUserName userName = new MySqlUserName();
    if (expr instanceof SQLCharExpr) {
        userName.setUserName(((SQLCharExpr) expr).toString());
    } else {
        userName.setUserName(((SQLIdentifierExpr) expr).getName());
    }


    String strVal = lexer.stringVal();
    lexer.nextToken();

    if (strVal.length() > 1) {
        userName.setHost(strVal.substring(1));
        return userName;
    }

    if (lexer.token() == Token.LITERAL_CHARS) {
        userName.setHost("'" + lexer.stringVal() + "'");
    } else {
        userName.setHost(lexer.stringVal());
    }
    lexer.nextToken();

    if (lexer.token() == Token.IDENTIFIED) {
        Lexer.SavePoint mark = lexer.mark();

        lexer.nextToken();
        if (lexer.token() == Token.BY) {
            lexer.nextToken();
            if (lexer.identifierEquals(FnvHash.Constants.PASSWORD)) {
                lexer.reset(mark);
            } else {
                userName.setIdentifiedBy(lexer.stringVal());
                lexer.nextToken();
            }
        } else {
            lexer.reset(mark);
        }
    }

    return userName;
}
 
Example #23
Source File: ElasticSqlExprParser.java    From elasticsearch-sql with Apache License 2.0 4 votes vote down vote up
protected SQLExpr parseAliasExpr(String alias) {
    String chars = alias.substring(1, alias.length() - 1);
    return new SQLCharExpr(chars);
}
 
Example #24
Source File: MiddlerQueryResultHandler.java    From Mycat2 with GNU General Public License v3.0 4 votes vote down vote up
@Override
public void add(T t ) {
		reusult.add(new SQLCharExpr(t==null?null:t.toString()));
	}
 
Example #25
Source File: MiddlerQueryResultHandler.java    From Mycat2 with GNU General Public License v3.0 4 votes vote down vote up
@Override
public List<SQLCharExpr> getResult() {
		return reusult;
}
 
Example #26
Source File: Paramer.java    From elasticsearch-sql with Apache License 2.0 4 votes vote down vote up
public static Paramer parseParamer(SQLMethodInvokeExpr method) throws SqlParseException {
	Paramer instance = new Paramer();
	List<SQLExpr> parameters = method.getParameters();
       for (SQLExpr expr : parameters) {
           if (expr instanceof SQLCharExpr) {
               if (instance.value == null) {
                   instance.value = ((SQLCharExpr) expr).getText();
               } else {
                   instance.analysis = ((SQLCharExpr) expr).getText();
               }
           } else if (expr instanceof SQLNumericLiteralExpr) {
               instance.boost = ((SQLNumericLiteralExpr) expr).getNumber().floatValue();
           } else if (expr instanceof SQLBinaryOpExpr) {
               SQLBinaryOpExpr sqlExpr = (SQLBinaryOpExpr) expr;
               switch (Util.expr2Object(sqlExpr.getLeft()).toString()) {
                   case "query":
                       instance.value = Util.expr2Object(sqlExpr.getRight()).toString();
                       break;
                   case "analyzer":
                       instance.analysis = Util.expr2Object(sqlExpr.getRight()).toString();
                       break;
                   case "boost":
                       instance.boost = Float.parseFloat(Util.expr2Object(sqlExpr.getRight()).toString());
                       break;
                   case "slop":
                       instance.slop = Integer.parseInt(Util.expr2Object(sqlExpr.getRight()).toString());
                       break;

                   case "fields":
                       int index;
                       for (String f : Strings.splitStringByCommaToArray(Util.expr2Object(sqlExpr.getRight()).toString())) {
                           index = f.lastIndexOf('^');
                           if (-1 < index) {
                               instance.fieldsBoosts.put(f.substring(0, index), Float.parseFloat(f.substring(index + 1)));
                           } else {
                               instance.fieldsBoosts.put(f, 1.0F);
                           }
                       }
                       break;
                   case "type":
                       instance.type = Util.expr2Object(sqlExpr.getRight()).toString();
                       break;
                   case "tie_breaker":
                       instance.tieBreaker = Float.parseFloat(Util.expr2Object(sqlExpr.getRight()).toString());
                       break;
                   case "operator":
                       instance.operator = Operator.fromString(Util.expr2Object(sqlExpr.getRight()).toString());
                       break;

                   case "default_field":
                       instance.defaultField = Util.expr2Object(sqlExpr.getRight()).toString();
                       break;

                   case "in_order":
                       instance.inOrder = Boolean.valueOf(Util.expr2Object(sqlExpr.getRight()).toString());
                       break;
                   case "clauses":
                       instance.clauses = Util.expr2Object(sqlExpr.getRight()).toString();
                       break;
                   case "minimum_should_match":
                       instance.minimumShouldMatch = Util.expr2Object(sqlExpr.getRight()).toString();
                       break;

                   default:
                       break;
               }
           }
       }

	return instance;
}
 
Example #27
Source File: MiddlerResultHandler.java    From Mycat2 with GNU General Public License v3.0 votes vote down vote up
public List<SQLCharExpr> getResult();