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

The following examples show how to use com.alibaba.druid.sql.ast.expr.SQLIdentifierExpr. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
@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 2
Source Project: Mycat2   Source File: RouterUtil.java    License: 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 3
Source Project: dble   Source File: ShowCreateView.java    License: 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 4
Source Project: dble   Source File: ItemDecimalTypeConvert.java    License: 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 5
Source Project: elasticsearch-sql   Source File: Util.java    License: 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 Project: elasticsearch-sql   Source File: Util.java    License: Apache License 2.0 6 votes vote down vote up
public static Object getScriptValueWithQuote(SQLExpr expr, String quote) throws SqlParseException {
    if (expr instanceof SQLIdentifierExpr || expr instanceof SQLPropertyExpr || expr instanceof SQLVariantRefExpr) {
        return "doc['" + expr.toString() + "'].value";
    }  else if (expr instanceof SQLCharExpr) {
        return quote + ((SQLCharExpr) expr).getValue() + quote;
    } else if (expr instanceof SQLIntegerExpr) {
        return ((SQLIntegerExpr) expr).getValue();
    } else if (expr instanceof SQLNumericLiteralExpr) {
        return ((SQLNumericLiteralExpr) expr).getNumber();
    } else if (expr instanceof SQLNullExpr) {
        return ((SQLNullExpr) expr).toString().toLowerCase();
    } else if (expr instanceof  SQLBinaryOpExpr) {
        //zhongshu-comment 该分支由忠树添加
        String left = "doc['" + ((SQLBinaryOpExpr) expr).getLeft().toString() + "'].value";
        String operator = ((SQLBinaryOpExpr) expr).getOperator().getName();
        String right = "doc['" + ((SQLBinaryOpExpr) expr).getRight().toString() + "'].value";
        return left + operator + right;
    }
    throw new SqlParseException("could not parse sqlBinaryOpExpr need to be identifier/valuable got " + expr.getClass().toString() + " with value:" + expr.toString());
}
 
Example 7
Source Project: elasticsearch-sql   Source File: ElasticSqlExprParser.java    License: 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 8
Source Project: elasticsearch-sql   Source File: SqlParser.java    License: 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 9
Source Project: Mycat2   Source File: GlobalTableUtil.java    License: 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 10
Source Project: Mycat2   Source File: ParseUtil.java    License: 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 11
Source Project: Mycat2   Source File: DruidSelectParser.java    License: GNU General Public License v3.0 5 votes vote down vote up
private HavingCols buildGroupByHaving(SQLExpr having,Map<String, String> aliaColumns ){
	if (having == null) {
		return null;
	}

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

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

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

	return new HavingCols(leftValue,rightValue,operator.getName());
}
 
Example 12
Source Project: Mycat2   Source File: DruidSelectParser.java    License: GNU General Public License v3.0 5 votes vote down vote up
private String getFieldName(SQLSelectItem item){
	if ((item.getExpr() instanceof SQLPropertyExpr)||(item.getExpr() instanceof SQLMethodInvokeExpr)
			|| (item.getExpr() instanceof SQLIdentifierExpr) || item.getExpr() instanceof SQLBinaryOpExpr) {
		return item.getExpr().toString();//字段别名
	}
	else if (!StringUtil.isEmpty(item.getAlias())) { // add by hehuang 20181205 如果SelectItem存在别名,则认为表达式为字段名,sql语法支持常量作为字段
		return item.getExpr().toString();
	} else {
		return item.toString();
	}
}
 
Example 13
private 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;
}
 
Example 14
Source Project: Mycat2   Source File: DruidSelectParserTest.java    License: 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 15
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 16
Source Project: dble   Source File: ItemNCharTypeConvert.java    License: 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 (castLength >= 0) {
        SQLMethodInvokeExpr dataType = new SQLMethodInvokeExpr();
        dataType.setMethodName("NCHAR");
        dataType.addParameter(new SQLIntegerExpr(castLength));
        method.addParameter(dataType);
    } else {
        method.addParameter(new SQLIdentifierExpr("NCHAR"));
    }
    return method;
}
 
Example 17
Source Project: dble   Source File: ItemFuncSignedConvert.java    License: 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("SIGNED"));
    return method;
}
 
Example 18
Source Project: dble   Source File: ItemTimeTypeConvert.java    License: 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("TIME");
        dataType.addParameter(new SQLIntegerExpr(decimals));
        method.addParameter(dataType);
    } else {
        method.addParameter(new SQLIdentifierExpr("TIME"));
    }
    return method;
}
 
Example 19
Source Project: dble   Source File: ItemFuncBinaryConvert.java    License: 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("BINARY");
        dataType.addParameter(new SQLIntegerExpr(decimals));
        method.addParameter(dataType);
    } else {
        method.addParameter(new SQLIdentifierExpr("BINARY"));
    }
    return method;
}
 
Example 20
Source Project: dble   Source File: ItemCharTypeConvert.java    License: 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 (castLength >= 0) {
        SQLMethodInvokeExpr dataType = new SQLMethodInvokeExpr();
        dataType.setMethodName("CHAR");
        dataType.addParameter(new SQLIntegerExpr(castLength));
        method.addParameter(dataType);
    } else {
        method.addParameter(new SQLIdentifierExpr("CHAR"));
    }
    return method;
}
 
Example 21
Source Project: dble   Source File: ItemDatetimeTypeConvert.java    License: 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 22
Source Project: dble   Source File: ItemDateTypeConvert.java    License: 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("DATE"));
    return method;
}
 
Example 23
Source Project: dble   Source File: ItemFuncUnsignedConvert.java    License: 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 Project: dble   Source File: ItemFuncTimestampDiff.java    License: 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 25
Source Project: dble   Source File: ItemFuncConvCharset.java    License: 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 26
Source Project: dble   Source File: ItemField.java    License: 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 27
Source Project: dble   Source File: DruidSelectParserTest.java    License: 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 28
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 29
Source Project: baymax   Source File: ReplaceTableNameVisitor.java    License: 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 30
Source Project: elasticsearch-sql   Source File: Util.java    License: 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;
    }