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

The following examples show how to use com.alibaba.druid.sql.ast.expr.SQLIntegerExpr. 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: 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 #2
Source File: ElasticSqlExprParser.java    From elasticsearch-sql with Apache License 2.0 6 votes vote down vote up
protected SQLExpr bracketRest(SQLExpr expr) {
    Number index;

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

    if (expr instanceof SQLMethodInvokeExpr) {
        SQLMethodInvokeExpr methodInvokeExpr = (SQLMethodInvokeExpr) expr;
        methodInvokeExpr.getParameters().add(new SQLIntegerExpr(index));
    }
    lexer.nextToken();
    expr = primaryRest(expr);
    return expr;
}
 
Example #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: 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 #5
Source File: DruidSelectParser.java    From Mycat2 with GNU General Public License v3.0 6 votes vote down vote up
protected void setLimitIFChange(SQLStatement stmt, RouteResultset rrs, SchemaConfig schema, SQLBinaryOpExpr one, int firstrownum, int lastrownum)
{
	rrs.setLimitStart(firstrownum);
	rrs.setLimitSize(lastrownum - firstrownum);
	LayerCachePool tableId2DataNodeCache = (LayerCachePool) MycatServer.getInstance().getCacheService().getCachePool("TableID2DataNodeCache");
	try
	{
		tryRoute(schema, rrs, tableId2DataNodeCache);
	} catch (SQLNonTransientException e)
	{
		throw new RuntimeException(e);
	}
	if (isNeedChangeLimit(rrs))
	{
		one.setRight(new SQLIntegerExpr(0));
		String curentDbType ="db2".equalsIgnoreCase(this.getCurentDbType())?"oracle":getCurentDbType();
		String sql =   SQLUtils.toSQLString(stmt, curentDbType);;
		rrs.changeNodeSqlAfterAddLimit(schema,getCurentDbType(), sql,0,lastrownum, false);
		//设置改写后的sql
		getCtx().setSql(sql);
	}
}
 
Example #6
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 #7
Source File: DruidSelectOracleParser.java    From Mycat2 with GNU General Public License v3.0 5 votes vote down vote up
private void parseThreeLevelPageSql(SQLStatement stmt, RouteResultset rrs, SchemaConfig schema, SQLSubqueryTableSource from, SQLBinaryOpExpr one, SQLBinaryOperator operator)
{
       SQLIntegerExpr right = (SQLIntegerExpr) one.getRight();
	int firstrownum = right.getNumber().intValue();
	if (operator == SQLBinaryOperator.GreaterThanOrEqual&&firstrownum!=0) {
		firstrownum = firstrownum - 1;
	}
	SQLSelectQuery subSelect = from.getSelect().getQuery();
	if (subSelect instanceof OracleSelectQueryBlock)
       {  //第二层子查询
           OracleSelectQueryBlock twoSubSelect = (OracleSelectQueryBlock) subSelect;
           if (twoSubSelect.getWhere() instanceof SQLBinaryOpExpr && twoSubSelect.getFrom() instanceof SQLSubqueryTableSource)
           {
               SQLBinaryOpExpr twoWhere = (SQLBinaryOpExpr) twoSubSelect.getWhere();
               boolean isRowNum = "rownum".equalsIgnoreCase(twoWhere.getLeft().toString());
               boolean isLess = twoWhere.getOperator() == SQLBinaryOperator.LessThanOrEqual || twoWhere.getOperator() == SQLBinaryOperator.LessThan;
               if (isRowNum && twoWhere.getRight() instanceof SQLIntegerExpr && isLess)
               {
                   int lastrownum = ((SQLIntegerExpr) twoWhere.getRight()).getNumber().intValue();
                   if (operator == SQLBinaryOperator.LessThan&&lastrownum!=0) {
					lastrownum = lastrownum - 1;
				}
                   SQLSelectQuery finalQuery = ((SQLSubqueryTableSource) twoSubSelect.getFrom()).getSelect().getQuery();
                   if (finalQuery instanceof OracleSelectQueryBlock)
                   {
					setLimitIFChange(stmt, rrs, schema, one, firstrownum, lastrownum);
                       parseOrderAggGroupOracle(stmt,rrs, (OracleSelectQueryBlock) finalQuery, schema);
                       isNeedParseOrderAgg=false;
                   }

               }

           }

       }
}
 
Example #8
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 #9
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 #10
Source File: ItemDecimalTypeCast.java    From dble with GNU General Public License v2.0 5 votes vote down vote up
@Override
public SQLExpr toExpression() {
    SQLCastExpr cast = new SQLCastExpr();
    cast.setExpr(args.get(0).toExpression());
    SQLDataTypeImpl dataType = new SQLDataTypeImpl("DECIMAL");
    if (precision >= 0) {
        dataType.addArgument(new SQLIntegerExpr(precision));
    }
    if (dec > 0) {
        dataType.addArgument(new SQLIntegerExpr(dec));
    }
    cast.setDataType(dataType);
    return cast;
}
 
Example #11
Source File: ItemNCharTypeCast.java    From dble with GNU General Public License v2.0 5 votes vote down vote up
@Override
public SQLExpr toExpression() {
    SQLCastExpr cast = new SQLCastExpr();
    cast.setExpr(args.get(0).toExpression());
    SQLDataTypeImpl dataType = new SQLDataTypeImpl("NCAHR");
    if (castLength >= 0) {
        dataType.addArgument(new SQLIntegerExpr(castLength));
    }
    cast.setDataType(dataType);

    return cast;
}
 
Example #12
Source File: ItemFuncBinaryCast.java    From dble with GNU General Public License v2.0 5 votes vote down vote up
@Override
public SQLExpr toExpression() {
    SQLCastExpr cast = new SQLCastExpr();
    cast.setExpr(args.get(0).toExpression());
    SQLDataTypeImpl dataType = new SQLDataTypeImpl("BINARY");
    if (castLength >= 0) {
        dataType.addArgument(new SQLIntegerExpr(castLength));
    }
    cast.setDataType(dataType);
    return cast;
}
 
Example #13
Source File: ItemTimeTypeCast.java    From dble with GNU General Public License v2.0 5 votes vote down vote up
@Override
public SQLExpr toExpression() {
    SQLCastExpr cast = new SQLCastExpr();
    cast.setExpr(args.get(0).toExpression());
    SQLDataTypeImpl dataType = new SQLDataTypeImpl("TIME");
    if (decimals != NOT_FIXED_DEC) {
        dataType.addArgument(new SQLIntegerExpr(decimals));
    }
    cast.setDataType(dataType);
    return cast;
}
 
Example #14
Source File: ItemDatetimeTypeCast.java    From dble with GNU General Public License v2.0 5 votes vote down vote up
@Override
public SQLExpr toExpression() {
    SQLCastExpr cast = new SQLCastExpr();
    cast.setExpr(args.get(0).toExpression());
    SQLDataTypeImpl dataType = new SQLDataTypeImpl("DATETIME");
    if (decimals != Item.NOT_FIXED_DEC) {
        dataType.addArgument(new SQLIntegerExpr(decimals));
    }
    cast.setDataType(dataType);
    return cast;
}
 
Example #15
Source File: ItemCharTypeCast.java    From dble with GNU General Public License v2.0 5 votes vote down vote up
@Override
public SQLExpr toExpression() {
    SQLCastExpr cast = new SQLCastExpr();
    cast.setExpr(args.get(0).toExpression());
    SQLCharacterDataType dataType = new SQLCharacterDataType(SQLCharacterDataType.CHAR_TYPE_CHAR);
    cast.setDataType(dataType);
    if (castLength >= 0) {
        dataType.addArgument(new SQLIntegerExpr(castLength));
    }
    if (charSetName != null) {
        dataType.setName(charSetName);
    }
    cast.setDataType(dataType);
    return cast;
}
 
Example #16
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 #17
Source File: ItemCharTypeConvert.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 (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 #18
Source File: ItemFuncBinaryConvert.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("BINARY");
        dataType.addParameter(new SQLIntegerExpr(decimals));
        method.addParameter(dataType);
    } else {
        method.addParameter(new SQLIdentifierExpr("BINARY"));
    }
    return method;
}
 
Example #19
Source File: ItemTimeTypeConvert.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("TIME");
        dataType.addParameter(new SQLIntegerExpr(decimals));
        method.addParameter(dataType);
    } else {
        method.addParameter(new SQLIdentifierExpr("TIME"));
    }
    return method;
}
 
Example #20
Source File: ItemNCharTypeConvert.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 (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 #21
Source File: MySQLPlanNodeVisitor.java    From dble with GNU General Public License v2.0 5 votes vote down vote up
private void handleLimit(SQLLimit limit) {
    long from = 0;
    SQLExpr offset = limit.getOffset();
    if (offset != null) {
        SQLIntegerExpr offsetExpr = (SQLIntegerExpr) offset;
        from = offsetExpr.getNumber().longValue();
    }
    SQLExpr rowCount = limit.getRowCount();
    long to = ((SQLIntegerExpr) rowCount).getNumber().longValue();
    if (to < 0) {
        throw new MySQLOutPutException(ErrorCode.ER_PARSE_ERROR, "", "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '" + to + "'");
    }
    tableNode.setLimitFrom(from);
    tableNode.setLimitTo(to);
}
 
Example #22
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 #23
Source File: InsertHandler.java    From dble with GNU General Public License v2.0 5 votes vote down vote up
private void processIncrementColumn(DumpFileContext context, List<SQLExpr> values) throws SQLNonTransientException {
    int incrementIndex = context.getIncrementColumnIndex();
    if (incrementIndex == -1) {
        return;
    }

    String tableKey = StringUtil.getFullName(context.getSchema(), context.getTable());
    long val = SequenceManager.getHandler().nextId(tableKey);
    SQLExpr value = values.get(incrementIndex);
    if (!StringUtil.isEmpty(SQLUtils.toMySqlString(value)) && !context.isNeedSkipError()) {
        context.addError("For table using global sequence, dble has set increment column values for you.");
        context.setNeedSkipError(true);
    }
    values.set(incrementIndex, new SQLIntegerExpr(val));
}
 
Example #24
Source File: DruidSelectParser.java    From Mycat2 with GNU General Public License v3.0 5 votes vote down vote up
private void fixLimit(MySqlSelectQueryBlock mysqlSelectQuery, RouteResultsetNode node) {
	if(!getCurentDbType().equalsIgnoreCase("mysql")) {
		MySqlSelectQueryBlock.Limit  _limit = mysqlSelectQuery.getLimit();
		if (_limit != null) {
			SQLIntegerExpr offset = (SQLIntegerExpr) _limit.getOffset();
			SQLIntegerExpr count = (SQLIntegerExpr) _limit.getRowCount();
			if (offset != null && count != null) {
				String nativeSql = PageSQLUtil
						.convertLimitToNativePageSql(getCurentDbType(), node.getStatement(),
								offset.getNumber().intValue(), count.getNumber().intValue());
				node.setStatement(nativeSql);
			}
		}
	}
}
 
Example #25
Source File: BatchInsertSequence.java    From Mycat2 with GNU General Public License v3.0 4 votes vote down vote up
@Override
public void route(SystemConfig sysConfig, SchemaConfig schema, int sqlType,
		String realSQL, String charset, ServerConnection sc,
		LayerCachePool cachePool) {
	int rs = ServerParse.parse(realSQL);
	this.sqltype = rs & 0xff;
	this.sysConfig=sysConfig; 
	this.schema=schema;
	this.charset=charset; 
	this.sc=sc;	
	this.cachePool=cachePool;	
	
	try {
		MySqlStatementParser parser = new MySqlStatementParser(realSQL);	 
		SQLStatement statement = parser.parseStatement();
		MySqlInsertStatement insert = (MySqlInsertStatement)statement;
		if(insert.getValuesList()!=null){
			String tableName = StringUtil.getTableName(realSQL).toUpperCase();
			TableConfig tableConfig = schema.getTables().get(tableName);
			String primaryKey = tableConfig.getPrimaryKey();//获得表的主键字段
			
			SQLIdentifierExpr sqlIdentifierExpr = new SQLIdentifierExpr();
			sqlIdentifierExpr.setName(primaryKey);
			insert.getColumns().add(sqlIdentifierExpr);
			
			if(sequenceHandler == null){
				int seqHandlerType = MycatServer.getInstance().getConfig().getSystem().getSequenceHandlerType();
				switch(seqHandlerType){
					case SystemConfig.SEQUENCEHANDLER_MYSQLDB:
						sequenceHandler = IncrSequenceMySQLHandler.getInstance();
						break;
					case SystemConfig.SEQUENCEHANDLER_LOCALFILE:
						sequenceHandler = IncrSequencePropHandler.getInstance();
						break;
					case SystemConfig.SEQUENCEHANDLER_LOCAL_TIME:
						sequenceHandler = IncrSequenceTimeHandler.getInstance();
						break;
					case SystemConfig.SEQUENCEHANDLER_ZK_DISTRIBUTED:
						sequenceHandler = DistributedSequenceHandler.getInstance(MycatServer.getInstance().getConfig().getSystem());
						break;
					case SystemConfig.SEQUENCEHANDLER_ZK_GLOBAL_INCREMENT:
						sequenceHandler = IncrSequenceZKHandler.getInstance();
						break;
					default:
						throw new java.lang.IllegalArgumentException("Invalid sequnce handler type "+seqHandlerType);
				}
			}
			
			for(ValuesClause vc : insert.getValuesList()){
				SQLIntegerExpr sqlIntegerExpr = new SQLIntegerExpr();
				long value = sequenceHandler.nextId(tableName.toUpperCase());
				sqlIntegerExpr.setNumber(value);//插入生成的sequence值
				vc.addValue(sqlIntegerExpr);
			}
			
			String insertSql = insert.toString();
			this.executeSql = insertSql;
		}
		
	} catch (Exception e) {
		LOGGER.error("BatchInsertSequence.route(......)",e);
	}
}
 
Example #26
Source File: ItemInt.java    From dble with GNU General Public License v2.0 4 votes vote down vote up
@Override
public SQLExpr toExpression() {
    return new SQLIntegerExpr(value);
}
 
Example #27
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 #28
Source File: JoinParser.java    From Mycat2 with GNU General Public License v3.0 4 votes vote down vote up
private int getSQLExprToInt(SQLExpr expr){
	if (expr instanceof SQLIntegerExpr){
		return ((SQLIntegerExpr)expr).getNumber().intValue();
	}
	return 0;		
}