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

The following examples show how to use com.alibaba.druid.sql.ast.expr.SQLIdentifierExpr. 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: ElasticSqlExprParser.java    From elasticsearch-sql with Apache License 2.0 6 votes vote down vote up
public SQLName nameRest(SQLName name) {
    if (lexer.token() == Token.VARIANT && "@".equals(lexer.stringVal())) {
        lexer.nextToken();
        MySqlUserName userName = new MySqlUserName();
        userName.setUserName(((SQLIdentifierExpr) name).getName());

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

        if (lexer.token() == Token.IDENTIFIED) {
            lexer.nextToken();
            accept(Token.BY);
            userName.setIdentifiedBy(lexer.stringVal());
            lexer.nextToken();
        }

        return userName;
    }
    return super.nameRest(name);
}
 
Example #2
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 #3
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 #4
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 #5
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 #6
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 #7
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 #8
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 #9
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 #10
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 #11
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 #12
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 #13
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 #14
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 #15
Source File: ReplaceTableNameVisitor.java    From baymax with Apache License 2.0 5 votes vote down vote up
@Override
public boolean visit(SQLExprTableSource astNode) {
    if (StringUtil.removeBackquote(astNode.toString()).equals(originalName)){
        if (isReplase){
            throw new BayMaxException("分区表名在一个Sql中只能出现一次:" + originalName + "," +newName);
        }else {
            node = (SQLIdentifierExpr) astNode.getExpr();
            node.setName(newName);
            isReplase = true;
        }
    }
    return true;
}
 
Example #16
Source File: DruidMysqlCreateTableTest.java    From dble with GNU General Public License v2.0 5 votes vote down vote up
private boolean isInsertHasSlot(String sql) {
    MySqlStatementParser parser = new MySqlStatementParser(sql);
    MySqlInsertStatement insertStatement = (MySqlInsertStatement) parser.parseStatement();
    List<SQLExpr> cc = insertStatement.getColumns();
    for (SQLExpr sqlExpr : cc) {
        SQLIdentifierExpr c = (SQLIdentifierExpr) sqlExpr;
        if ("_slot".equalsIgnoreCase(c.getName()) && cc.size() == insertStatement.getValues().getValues().size())
            return true;
    }
    return false;
}
 
Example #17
Source File: DruidSelectParserTest.java    From dble with GNU General Public License v2.0 5 votes vote down vote up
public Object invokeGroupBy(String functionColumn) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
    Map<String, String> aliaColumns = new TreeMap<>();
    SQLIdentifierExpr sqlExpr = new SQLIdentifierExpr(functionColumn);
    List<SQLExpr> groupByItems = new ArrayList<>();
    groupByItems.add(sqlExpr);
    Class c = DruidSelectParser.class;
    Method method = c.getDeclaredMethod("buildGroupByCols", new Class[]{List.class, Map.class});
    method.setAccessible(true);
    return method.invoke(druidSelectParser, groupByItems, aliaColumns);
}
 
Example #18
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 #19
Source File: ElasticSqlSelectParser.java    From elasticsearch-sql with Apache License 2.0 5 votes vote down vote up
private void parseIndexHint(MySqlIndexHintImpl hint) {
    if (lexer.token() == Token.INDEX) {
        lexer.nextToken();
    } else {
        accept(Token.KEY);
    }

    if (lexer.token() == Token.FOR) {
        lexer.nextToken();

        if (lexer.token() == Token.JOIN) {
            lexer.nextToken();
            hint.setOption(MySqlIndexHint.Option.JOIN);
        } else if (lexer.token() == Token.ORDER) {
            lexer.nextToken();
            accept(Token.BY);
            hint.setOption(MySqlIndexHint.Option.ORDER_BY);
        } else {
            accept(Token.GROUP);
            accept(Token.BY);
            hint.setOption(MySqlIndexHint.Option.GROUP_BY);
        }
    }

    accept(Token.LPAREN);
    if (lexer.token() == Token.PRIMARY) {
        lexer.nextToken();
        hint.getIndexList().add(new SQLIdentifierExpr("PRIMARY"));
    } else {
        this.exprParser.names(hint.getIndexList());
    }
    accept(Token.RPAREN);
}
 
Example #20
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 #21
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 #22
Source File: ItemDatetimeTypeConvert.java    From dble with GNU General Public License v2.0 5 votes vote down vote up
@Override
public SQLExpr toExpression() {
    SQLMethodInvokeExpr method = new SQLMethodInvokeExpr();
    method.setMethodName("CONVERT");
    method.addParameter(args.get(0).toExpression());
    if (decimals != NOT_FIXED_DEC) {
        SQLMethodInvokeExpr dataType = new SQLMethodInvokeExpr();
        dataType.setMethodName("DATETIME");
        dataType.addParameter(new SQLIntegerExpr(decimals));
        method.addParameter(dataType);
    } else {
        method.addParameter(new SQLIdentifierExpr("DATETIME"));
    }
    return method;
}
 
Example #23
Source File: ItemFuncUnsignedConvert.java    From dble with GNU General Public License v2.0 5 votes vote down vote up
@Override
public SQLExpr toExpression() {
    SQLMethodInvokeExpr method = new SQLMethodInvokeExpr();
    method.setMethodName("CONVERT");
    method.addParameter(args.get(0).toExpression());
    method.addParameter(new SQLIdentifierExpr("UNSIGNED"));
    return method;
}
 
Example #24
Source File: DruidSelectParserTest.java    From Mycat2 with GNU General Public License v3.0 5 votes vote down vote up
public Object invokeGroupBy(String functionColumn) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
    Map<String, String> aliaColumns = new TreeMap<>();
    SQLIdentifierExpr sqlExpr = mock(SQLIdentifierExpr.class);
    SQLIdentifierExpr expr = mock(SQLIdentifierExpr.class);
    List<SQLExpr> groupByItems = new ArrayList<>();
    groupByItems.add(sqlExpr);
    when((sqlExpr).getName()).thenReturn(functionColumn);
    Class c = DruidSelectParser.class;
    Method method = c.getDeclaredMethod("buildGroupByCols", new Class[]{List.class, Map.class});
    method.setAccessible(true);
    return  method.invoke(druidSelectParser, groupByItems, aliaColumns);
}
 
Example #25
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 #26
Source File: ParseUtil.java    From Mycat2 with GNU General Public License v3.0 5 votes vote down vote up
public static String changeInsertAddSlot(String sql,int slotValue)
{
    SQLStatementParser parser = new MycatStatementParser(sql);
    MySqlInsertStatement insert = (MySqlInsertStatement) parser.parseStatement();
    insert.getColumns().add(new SQLIdentifierExpr("_slot") );
    insert.getValues().getValues().add(new SQLIntegerExpr(slotValue))  ;
    return insert.toString();
}
 
Example #27
Source File: DruidSelectParser.java    From Mycat2 with 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 #28
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 #29
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 #30
Source File: DruidMycatRouteStrategy.java    From Mycat2 with GNU General Public License v3.0 5 votes vote down vote up
private SQLExprTableSource getDisTable(SQLTableSource tableSource,RouteResultsetNode node) throws SQLSyntaxErrorException{
	if(node.getSubTableName()==null){
		String msg = " sub table not exists for " + node.getName() + " on " + tableSource;
		LOGGER.error("DruidMycatRouteStrategyError " + msg);
		throw new SQLSyntaxErrorException(msg);
	}

	SQLIdentifierExpr sqlIdentifierExpr = new SQLIdentifierExpr();
	sqlIdentifierExpr.setParent(tableSource.getParent());
	sqlIdentifierExpr.setName(node.getSubTableName());
	SQLExprTableSource from2 = new SQLExprTableSource(sqlIdentifierExpr);
	return from2;
}