com.alibaba.druid.sql.ast.SQLExpr Java Examples

The following examples show how to use com.alibaba.druid.sql.ast.SQLExpr. 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: 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 #2
Source File: SqlParserTests.java    From elasticsearch-sql with Apache License 2.0 6 votes vote down vote up
@Test
public void filterAggTestNoAlias() throws SqlParseException {
    String query = "select * from myIndex group by a , filter(  a > 3 AND b='3' )";
    SQLExpr sqlExpr = queryToExpr(query);
    Select select = parser.parseSelect((SQLQueryExpr) sqlExpr);
    List<List<Field>> groupBys = select.getGroupBys();
    Assert.assertEquals(1, groupBys.size());
    Field aAgg = groupBys.get(0).get(0);
    Assert.assertEquals("a", aAgg.getName());
    Field field = groupBys.get(0).get(1);
    Assert.assertTrue("filter field should be method field", field instanceof MethodField);
    MethodField filterAgg = (MethodField) field;
    Assert.assertEquals("filter", filterAgg.getName());
    Map<String, Object> params = filterAgg.getParamsAsMap();
    Assert.assertEquals(2, params.size());
    Object alias = params.get("alias");
    Assert.assertEquals("filter(a > 3 AND b = '3')@FILTER", alias);

    Assert.assertTrue(params.get("where") instanceof Where);
    Where where = (Where) params.get("where");
    Assert.assertEquals(2, where.getWheres().size());
}
 
Example #3
Source File: SqlParserTests.java    From elasticsearch-sql with Apache License 2.0 6 votes vote down vote up
@Test
public void explicitScriptOnAggregation() throws SqlParseException {
    String query = "SELECT avg( script('add','doc[\\'field1\\'].value + doc[\\'field2\\'].value') ) FROM index/type";
    SQLExpr sqlExpr = queryToExpr(query);
    Select select = parser.parseSelect((SQLQueryExpr) sqlExpr);
    List<Field> fields = select.getFields();
    Assert.assertEquals(1, fields.size());
    Field field = fields.get(0);
    Assert.assertTrue(field instanceof MethodField);
    MethodField avgMethodField = (MethodField) field;
    Assert.assertEquals("avg", avgMethodField.getName().toLowerCase());
    Assert.assertEquals(1, avgMethodField.getParams().size());
    MethodField scriptMethod = (MethodField) avgMethodField.getParams().get(0).value;
    Assert.assertEquals("script", scriptMethod.getName().toLowerCase());
    Assert.assertEquals(2, scriptMethod.getParams().size());
    Assert.assertEquals("doc['field1'].value + doc['field2'].value", scriptMethod.getParams().get(1).toString());
}
 
Example #4
Source File: SetHandler.java    From dble with GNU General Public License v2.0 6 votes vote down vote up
private static boolean handleCharsetClientInMultiStmt(ServerConnection c, List<Pair<KeyType, Pair<String, String>>> contextTask, SQLExpr valueExpr) {
    String charsetClient = SetInnerHandler.parseStringValue(valueExpr);
    if (charsetClient.equalsIgnoreCase("null")) {
        c.writeErrMessage(ErrorCode.ER_WRONG_VALUE_FOR_VAR, "Variable 'character_set_client' can't be set to the value of 'NULL'");
        return false;
    } else if (checkCharset(charsetClient)) {
        if (!CharsetUtil.checkCharsetClient(charsetClient)) {
            c.writeErrMessage(ErrorCode.ER_WRONG_VALUE_FOR_VAR, "Variable 'character_set_client' can't be set to the value of '" + charsetClient + "'");
            return false;
        } else {
            contextTask.add(new Pair<>(KeyType.CHARACTER_SET_CLIENT, new Pair<String, String>(charsetClient, null)));
            return true;
        }
    } else {
        c.writeErrMessage(ErrorCode.ER_UNKNOWN_CHARACTER_SET, "Unknown character set '" + charsetClient + "'");
        return false;
    }
}
 
Example #5
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 #6
Source File: ShardColumnValueUtil.java    From Zebra with Apache License 2.0 6 votes vote down vote up
private static void parseValueList(Set<Object> evalSet, List<Object> params, List<SQLExpr> columns,
      List<SQLInsertStatement.ValuesClause> valuesList, String column) {
	SQLInsertStatement.ValuesClause values = valuesList.get(0);
	for (int i = 0; i < columns.size(); i++) {
		SQLName columnObj = (SQLName) columns.get(i);
		if (evalColumn(columnObj.getSimpleName(), column)) {
			SQLExpr sqlExpr = values.getValues().get(i);
			if (sqlExpr instanceof SQLVariantRefExpr) {
				SQLVariantRefExpr ref = (SQLVariantRefExpr) sqlExpr;
				evalSet.add(params.get(ref.getIndex()));
			} else if (sqlExpr instanceof SQLValuableExpr) {
				evalSet.add(((SQLValuableExpr) sqlExpr).getValue());
			}
			break;
		}
	}
}
 
Example #7
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 #8
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 #9
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 #10
Source File: ItemFuncTrim.java    From dble with GNU General Public License v2.0 6 votes vote down vote up
@Override
public SQLExpr toExpression() {
    SQLMethodInvokeExpr method = new SQLMethodInvokeExpr();
    if (mTrimMode == TrimTypeEnum.LTRIM) {
        method.setMethodName("LTRIM");
        method.addParameter(args.get(0).toExpression());

    } else if (mTrimMode == TrimTypeEnum.RTRIM) {
        method.setMethodName("RTRIM");
        method.addParameter(args.get(0).toExpression());

    } else {
        method.setMethodName("TRIM");
        method.addParameter(args.get(0).toExpression());
        if (this.getArgCount() > 1) {
            method.setFrom(args.get(1).toExpression());
        }
        if (mTrimMode != TrimTypeEnum.DEFAULT) {
            method.setTrimOption(mTrimMode.toString());
        }
    }
    return method;
}
 
Example #11
Source File: SqlParserTests.java    From elasticsearch-sql with Apache License 2.0 6 votes vote down vote up
@Test
public void castToDoubleThenDivideTest() throws Exception {
    String query = "select cast(age as double)/2 from "+ TEST_INDEX_ACCOUNT + "/account limit 10";
    SQLExpr sqlExpr = queryToExpr(query);
    Select select = parser.parseSelect((SQLQueryExpr) sqlExpr);
    Field castField = select.getFields().get(0);
    Assert.assertTrue(castField instanceof MethodField);

    MethodField methodField = (MethodField) castField;
    Assert.assertEquals("script",castField.getName());

    String alias = (String) methodField.getParams().get(0).value;
    String scriptCode = (String) methodField.getParams().get(1).value;
    Assert.assertTrue(scriptCode.contains("doc['age'].value"));
    Assert.assertTrue(scriptCode.contains("Double.parseDouble(doc['age'].value.toString()).doubleValue()"));
    Assert.assertTrue(scriptCode.contains("/ 2"));
}
 
Example #12
Source File: SequoiaSQLParser.java    From Mycat2 with GNU General Public License v3.0 6 votes vote down vote up
private int UpData(SQLUpdateStatement state) {
	SQLTableSource table=state.getTableSource();
	DBCollection coll =this._db.getCollection(table.toString());
	
	SQLExpr expr=state.getWhere();
	BSONObject query = parserWhere(expr);
	
	BasicBSONObject set = new BasicBSONObject();
	for(SQLUpdateSetItem col : state.getItems()){
		set.put(getFieldName2(col.getColumn()), getExpValue(col.getValue()));	
	}
	BSONObject mod = new BasicBSONObject("$set", set);
	//coll.updateMulti(query, mod);
	coll.update(query, mod, null);
	//System.out.println("changs count:"+coll.getStats().size());
	return 1;		
}
 
Example #13
Source File: SetHandler.java    From dble with GNU General Public License v2.0 6 votes vote down vote up
private static boolean handleSingleCharsetClient(ServerConnection c, SQLExpr valueExpr) {
    String charsetClient = SetInnerHandler.parseStringValue(valueExpr);
    if (charsetClient.equalsIgnoreCase("null")) {
        c.writeErrMessage(ErrorCode.ER_WRONG_VALUE_FOR_VAR, "Variable 'character_set_client' can't be set to the value of 'NULL'");
        return false;
    }
    if (checkCharset(charsetClient)) {
        if (!CharsetUtil.checkCharsetClient(charsetClient)) {
            c.writeErrMessage(ErrorCode.ER_WRONG_VALUE_FOR_VAR, "Variable 'character_set_client' can't be set to the value of '" + charsetClient + "'");
            return false;
        } else {
            c.setCharacterClient(charsetClient);
            boolean multiStatementFlag = c.getSession2().getIsMultiStatement().get();
            c.write(c.writeToBuffer(c.getSession2().getOkByteArray(), c.allocate()));
            c.getSession2().multiStatementNextSql(multiStatementFlag);
            return true;
        }
    } else {
        c.writeErrMessage(ErrorCode.ER_UNKNOWN_CHARACTER_SET, "Unknown character set '" + charsetClient + "'");
        return false;
    }
}
 
Example #14
Source File: SequoiaSQLParser.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().intValue();
	}
	if (expr instanceof SQLNumberExpr){
		return ((SQLNumberExpr)expr).getNumber().doubleValue();
	}		
	if (expr instanceof SQLCharExpr){
		String va=((SQLCharExpr)expr).toString();
		return remove(va,'\'');
	}
	if (expr instanceof SQLBooleanExpr){			
		return ((SQLBooleanExpr)expr).getValue();
	}			
	if (expr instanceof SQLNullExpr){
		return null;
	}
    if (expr instanceof SQLVariantRefExpr) {
       return this._params.get(this._pos++);
    }		
	return expr;
	
}
 
Example #15
Source File: DruidReplaceParser.java    From dble with GNU General Public License v2.0 6 votes vote down vote up
/**
 * insert single record
 *
 * @param schemaInfo       SchemaInfo
 * @param rrs              RouteResultset
 * @param partitionColumn  partitionColumn
 * @param replaceStatement SQLReplaceStatement
 * @throws SQLNonTransientException if not find a valid data node
 */
private void parserSingleInsert(SchemaInfo schemaInfo, RouteResultset rrs, String partitionColumn,
                                SQLReplaceStatement replaceStatement) throws SQLNonTransientException {
    int shardingColIndex = tryGetShardingColIndex(schemaInfo, replaceStatement, partitionColumn);
    SQLExpr valueExpr = replaceStatement.getValuesList().get(0).getValues().get(shardingColIndex);
    String shardingValue = shardingValueToSting(valueExpr);
    TableConfig tableConfig = schemaInfo.getSchemaConfig().getTables().get(schemaInfo.getTable());
    AbstractPartitionAlgorithm algorithm = tableConfig.getRule().getRuleAlgorithm();
    Integer nodeIndex = algorithm.calculate(shardingValue);
    if (nodeIndex == null) {
        String msg = "can't find any valid data node :" + schemaInfo.getTable() + " -> " + partitionColumn + " -> " + shardingValue;
        LOGGER.info(msg);
        throw new SQLNonTransientException(msg);
    }
    RouteResultsetNode[] nodes = new RouteResultsetNode[1];
    nodes[0] = new RouteResultsetNode(tableConfig.getDataNodes().get(nodeIndex),
            rrs.getSqlType(), RouterUtil.removeSchema(statementToString(replaceStatement), schemaInfo.getSchema()));

    rrs.setNodes(nodes);
    rrs.setFinishedRoute(true);
}
 
Example #16
Source File: SelectHandler.java    From dble with GNU General Public License v2.0 6 votes vote down vote up
private static boolean isSupportSelect(String stmt) {
    SQLStatementParser parser = new MySqlStatementParser(stmt);
    SQLStatement statement = parser.parseStatement();
    if (!(statement instanceof SQLSelectStatement)) {
        return false;
    }

    SQLSelectQuery sqlSelectQuery = ((SQLSelectStatement) statement).getSelect().getQuery();
    if (!(sqlSelectQuery instanceof MySqlSelectQueryBlock)) {
        return false;
    }
    MySqlSelectQueryBlock selectQueryBlock = (MySqlSelectQueryBlock) sqlSelectQuery;
    SQLTableSource mysqlFrom = selectQueryBlock.getFrom();
    if (mysqlFrom != null) {
        return false;
    }
    for (SQLSelectItem item : selectQueryBlock.getSelectList()) {
        SQLExpr selectItem = item.getExpr();
        if (!isVariantRef(selectItem)) {
            return false;
        }
    }
    return true;
}
 
Example #17
Source File: SqlParserTests.java    From elasticsearch-sql with Apache License 2.0 6 votes vote down vote up
@Test
public void filterAggTestWithAlias() throws SqlParseException {
    String query = "select * from myIndex group by a , filter(myFilter, a > 3 AND b='3' )";
    SQLExpr sqlExpr = queryToExpr(query);
    Select select = parser.parseSelect((SQLQueryExpr) sqlExpr);
    List<List<Field>> groupBys = select.getGroupBys();
    Assert.assertEquals(1, groupBys.size());
    Field aAgg = groupBys.get(0).get(0);
    Assert.assertEquals("a", aAgg.getName());
    Field field = groupBys.get(0).get(1);
    Assert.assertTrue("filter field should be method field", field instanceof MethodField);
    MethodField filterAgg = (MethodField) field;
    Assert.assertEquals("filter", filterAgg.getName());
    Map<String, Object> params = filterAgg.getParamsAsMap();
    Assert.assertEquals(2, params.size());
    Object alias = params.get("alias");
    Assert.assertEquals("myFilter@FILTER", alias);

    Assert.assertTrue(params.get("where") instanceof Where);
    Where where = (Where) params.get("where");
    Assert.assertEquals(2, where.getWheres().size());
}
 
Example #18
Source File: SqlParserTests.java    From elasticsearch-sql with Apache License 2.0 6 votes vote down vote up
@Test
public void castToLongTest() throws Exception {
    String query = "select cast(insert_time as long) from "+ TEST_INDEX_ACCOUNT + " limit 10";
    SQLExpr sqlExpr = queryToExpr(query);
    Select select = parser.parseSelect((SQLQueryExpr) sqlExpr);
    Field castField = select.getFields().get(0);
    Assert.assertTrue(castField instanceof MethodField);

    MethodField methodField = (MethodField) castField;
    Assert.assertEquals("script",castField.getName());

    String alias = (String) methodField.getParams().get(0).value;
    String scriptCode = (String) methodField.getParams().get(1).value;
    Assert.assertEquals("cast_insert_time",alias);
    Assert.assertTrue(scriptCode.contains("doc['insert_time'].value"));
    Assert.assertTrue(scriptCode.contains("Double.parseDouble(doc['insert_time'].value.toString()).longValue()"));
}
 
Example #19
Source File: MysqlMethodInvocationHandler.java    From Mycat2 with GNU General Public License v3.0 6 votes vote down vote up
private SQLExpr doInvoke(SQLMethodInvokeExpr expr) throws SQLNonTransientException {
    String methodName = expr.getMethodName().toUpperCase();
    switch (methodName) {
        case "NOW":
        case "SYSDATE":
        case "CURRENT_TIMESTAMP":
            return invokeNow();
        case "ADDDATE":
        case "DATE_ADD":
            return invokeAddDate(expr, false);
        case "SUBDATE":
        case "DATE_SUB":
            return invokeAddDate(expr, true);
    }
    return null;
}
 
Example #20
Source File: DruidInsertParser.java    From dble with GNU General Public License v2.0 6 votes vote down vote up
private void genDuplicate(StringBuilder sb, List<SQLExpr> dku) throws SQLNonTransientException {
    sb.append(" on duplicate key update ");
    for (int i = 0; i < dku.size(); i++) {
        SQLExpr exp = dku.get(i);
        if (!(exp instanceof SQLBinaryOpExpr)) {
            String msg = "not supported! on duplicate key update exp is " + exp.getClass();
            LOGGER.info(msg);
            throw new SQLNonTransientException(msg);
        }
        SQLBinaryOpExpr binaryOpExpr = (SQLBinaryOpExpr) exp;
        sb.append(binaryOpExpr.toString());
        if (i < dku.size() - 1) {
            sb.append(",");
        }
    }
}
 
Example #21
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 #22
Source File: ExpressionUtil.java    From dble with GNU General Public License v2.0 5 votes vote down vote up
private static boolean isLogicalExpression(SQLExpr expr) { //XOR?
    if (!(expr instanceof SQLBinaryOpExpr)) {
        return false;
    }
    SQLBinaryOpExpr binOpExpr = (SQLBinaryOpExpr) expr;
    return binOpExpr.getOperator() == SQLBinaryOperator.BooleanAnd || binOpExpr.getOperator() == SQLBinaryOperator.BooleanOr;
}
 
Example #23
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 #24
Source File: ItemDateTypeCast.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("DATE");
    cast.setDataType(dataType);
    return cast;
}
 
Example #25
Source File: InsertParser.java    From dts with Apache License 2.0 5 votes vote down vote up
@Override
public TableDataInfo getPresentValue(List<Object> sqlParamsList, MySqlInsertStatement parseSqlStatement,
    StatementAdapter statementAdapter, TableMetaInfo tableMetaInfo) throws SQLException {
    TableDataInfo txcTable = new TableDataInfo();
    txcTable.setTableName(parseSqlStatement.getTableName().getSimpleName());
    List<TxcLine> line = txcTable.getLine();
    List<SQLInsertStatement.ValuesClause> valuesList = parseSqlStatement.getValuesList();
    List<SQLExpr> columns = parseSqlStatement.getColumns();
    for (SQLInsertStatement.ValuesClause valuesClause : valuesList) {
        List<SQLExpr> values = valuesClause.getValues();
        TxcLine txcLine = new TxcLine();
        for (int i = 0; i < columns.size(); i++) {
            TxcField txcField = new TxcField();
            String columnName = SQLUtils.toSQLString(columns.get(i)).replace("\'", "").replace("`", "").trim();
            txcField.setName(columnName);
            if (sqlParamsList != null && !sqlParamsList.isEmpty()) {
                if (columnName.equalsIgnoreCase(tableMetaInfo.getAutoIncrementPrimaryKey())) {
                    sqlParamsList.add(i, getAutoIncrementPrimaryKeyValue(statementAdapter.getStatement()));
                }
                txcField.setValue(sqlParamsList.get(i));
            } else {
                txcField.setValue(SQLUtils.toSQLString(values.get(i)));
            }
            txcField.setJdkValue(SerializeUtils.serialize(txcField.getValue()));
            txcLine.getFields().add(txcField);
        }
        line.add(txcLine);
    }
    return txcTable;
}
 
Example #26
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 #27
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 #28
Source File: ItemSumXor.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());
    for (Item arg : args) {
        method.addParameter(arg.toExpression());
    }
    return method;
}
 
Example #29
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 #30
Source File: SetHandler.java    From dble with GNU General Public License v2.0 5 votes vote down vote up
private static boolean handleSingleCharsetResults(ServerConnection c, SQLExpr valueExpr) {
    String charsetResult = SetInnerHandler.parseStringValue(valueExpr);
    if (charsetResult.equalsIgnoreCase("NULL") || checkCharset(charsetResult)) {
        c.setCharacterResults(charsetResult);
        boolean multiStatementFlag = c.getSession2().getIsMultiStatement().get();
        c.write(c.writeToBuffer(c.getSession2().getOkByteArray(), c.allocate()));
        c.getSession2().multiStatementNextSql(multiStatementFlag);
        return true;
    } else {
        c.writeErrMessage(ErrorCode.ER_UNKNOWN_CHARACTER_SET, "Unknown character set '" + charsetResult + "'");
        return false;
    }
}