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

The following examples show how to use com.alibaba.druid.sql.ast.SQLExpr. 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
Source Project: dble   Source File: ItemFuncTrim.java    License: 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 2
Source Project: elasticsearch-sql   Source File: SqlParserTests.java    License: 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 Project: elasticsearch-sql   Source File: SqlParserTests.java    License: 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 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 5
Source Project: Zebra   Source File: ShardColumnValueUtil.java    License: 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 6
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 7
Source Project: dble   Source File: ItemFuncGroupConcat.java    License: 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 8
Source Project: Mycat2   Source File: SequoiaSQLParser.java    License: 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 9
Source Project: dble   Source File: SetHandler.java    License: 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 10
Source Project: Mycat2   Source File: SequoiaSQLParser.java    License: 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 11
Source Project: elasticsearch-sql   Source File: SqlParserTests.java    License: 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("[email protected]", alias);

    Assert.assertTrue(params.get("where") instanceof Where);
    Where where = (Where) params.get("where");
    Assert.assertEquals(2, where.getWheres().size());
}
 
Example 12
Source Project: elasticsearch-sql   Source File: SqlParserTests.java    License: 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 13
Source Project: dble   Source File: DruidInsertParser.java    License: 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 14
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 15
Source Project: dble   Source File: SelectHandler.java    License: 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 16
Source Project: dble   Source File: DruidReplaceParser.java    License: 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 17
Source Project: elasticsearch-sql   Source File: SqlParserTests.java    License: 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 18
Source Project: elasticsearch-sql   Source File: ElasticSqlExprParser.java    License: 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 19
Source Project: dble   Source File: SetHandler.java    License: 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 20
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 21
Source Project: dts   Source File: InsertParser.java    License: 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 22
Source Project: dble   Source File: ItemDecimalTypeCast.java    License: 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 23
Source Project: Mycat2   Source File: ExplainHandler.java    License: GNU General Public License v3.0 5 votes vote down vote up
private static boolean isMycatSeq(String stmt, SchemaConfig schema)
  {
      if(pattern.matcher(stmt).find()) {
	return true;
}
      SQLStatementParser parser =new MySqlStatementParser(stmt);
      MySqlInsertStatement statement = (MySqlInsertStatement) parser.parseStatement();
      String tableName=   statement.getTableName().getSimpleName();
      TableConfig tableConfig= schema.getTables().get(tableName.toUpperCase());
      if(tableConfig==null) {
	return false;
}
      if(tableConfig.isAutoIncrement())
      {
          boolean isHasIdInSql=false;
          String primaryKey = tableConfig.getPrimaryKey();
          List<SQLExpr> columns = statement.getColumns();
          for (SQLExpr column : columns)
          {
              String columnName = column.toString();
              if(primaryKey.equalsIgnoreCase(columnName))
              {
                  isHasIdInSql = true;
                  break;
              }
          }
          if(!isHasIdInSql) {
		return true;
	}
      }


      return false;
  }
 
Example 24
Source Project: dble   Source File: SetInnerHandler.java    License: GNU General Public License v2.0 5 votes vote down vote up
public static boolean handleSingleAutocommit(String stmt, ServerConnection c, SQLExpr valueExpr) {
    List<Pair<SetHandler.KeyType, Pair<String, String>>> innerSetTask = new ArrayList<>();
    if (preHandleAutocommit(c, valueExpr, innerSetTask)) {
        String key = innerSetTask.get(0).getValue().getKey();
        if (!execSetAutoCommit(stmt, c, Boolean.valueOf(key))) {
            boolean multiStatementFlag = c.getSession2().getIsMultiStatement().get();
            c.write(c.writeToBuffer(c.getSession2().getOkByteArray(), c.allocate()));
            c.getSession2().multiStatementNextSql(multiStatementFlag);
        }
        return true;
    }
    return false;
}
 
Example 25
Source Project: dble   Source File: ItemSumAvg.java    License: GNU General Public License v2.0 5 votes vote down vote up
@Override
public SQLExpr toExpression() {
    Item arg0 = args.get(0);
    SQLAggregateExpr aggregate = new SQLAggregateExpr(funcName());
    aggregate.addArgument(arg0.toExpression());
    if (hasWithDistinct()) {
        aggregate.setOption(SQLAggregateOption.DISTINCT);
    }
    return aggregate;
}
 
Example 26
Source Project: Mycat2   Source File: SequoiaSQLParser.java    License: GNU General Public License v3.0 5 votes vote down vote up
private int DeleteDate(SQLDeleteStatement state) {
	SQLTableSource table=state.getTableSource();
	DBCollection coll =this._db.getCollection(table.toString());
	
	SQLExpr expr=state.getWhere();
	if (expr==null) {
		throw new RuntimeException("not where of sql");
	}
	BSONObject query = parserWhere(expr);
	
	//coll.remove(query);
	coll.delete(query);
	return 1;
	
}
 
Example 27
Source Project: elasticsearch-sql   Source File: SqlParser.java    License: Apache License 2.0 5 votes vote down vote up
private ScriptSortBuilder.ScriptSortType judgeIsStringSort(SQLExpr expr) {
    if (expr instanceof SQLCaseExpr) {
        List<SQLCaseExpr.Item> itemList = ((SQLCaseExpr) expr).getItems();
        for (SQLCaseExpr.Item item : itemList) {
            if (item.getValueExpr() instanceof SQLCharExpr) {
                return ScriptSortBuilder.ScriptSortType.STRING;
            }
        }
    }
    return ScriptSortBuilder.ScriptSortType.NUMBER;
}
 
Example 28
Source Project: dble   Source File: SetHandler.java    License: GNU General Public License v2.0 5 votes vote down vote up
private static boolean checkValue(SQLExpr valueExpr, KeyType keyType) {
    if (keyType == KeyType.USER_VARIABLES) {
        return !(valueExpr instanceof SQLQueryExpr);
    }
    return (valueExpr instanceof MySqlCharExpr) || (valueExpr instanceof SQLCharExpr) ||
            (valueExpr instanceof SQLIdentifierExpr) || (valueExpr instanceof SQLIntegerExpr) ||
            (valueExpr instanceof SQLNumberExpr) || (valueExpr instanceof SQLBooleanExpr) ||
            (valueExpr instanceof SQLDefaultExpr) || (valueExpr instanceof SQLNullExpr);
}
 
Example 29
Source Project: Mycat2   Source File: SequoiaSQLParser.java    License: GNU General Public License v3.0 5 votes vote down vote up
@SuppressWarnings("unused")
private void opSQLExpr(SQLBinaryOpExpr expr,BasicBSONObject o) {
	   SQLExpr exprL=expr.getLeft();
	   if (!(exprL instanceof SQLBinaryOpExpr))
	   {
		  if (expr.getOperator().getName().equals("=")) {  
	        o.put(exprL.toString(), getExpValue(expr.getRight()));
		  }
		  else {
			  //BasicBSONObject xo = new BasicBSONObject();
			  String op="";
			  if (expr.getOperator().getName().equals("<")) {
				  op="$lt";
			  }
			  if (expr.getOperator().getName().equals("<=")) {
				  op = "$lte";
			  }
			  if (expr.getOperator().getName().equals(">")) {
				  op = "$gt";
			  }
			  if (expr.getOperator().getName().equals(">=")) {
				  op = "$gte";
			  }
			  if (expr.getOperator().getName().equals("!=")) {
				  op = "$ne";
			  }
			  if (expr.getOperator().getName().equals("<>")) {
				  op = "$ne";
			  }
			  //xo.put(op, getExpValue(expr.getRight()));
			 // o.put(exprL.toString(),xo);
			  parserDBObject(o,exprL.toString(),op, getExpValue(expr.getRight()));
		  }
	   }		
}
 
Example 30
Source Project: elasticsearch-sql   Source File: SqlParserTests.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void indexWithSemiColons() throws SqlParseException {
    String query = "select * from some;index";
    SQLExpr sqlExpr = queryToExpr(query);
    Select select = parser.parseSelect((SQLQueryExpr) sqlExpr);
    Assert.assertEquals(1, select.getFrom().size());
    Assert.assertEquals("some;index", select.getFrom().get(0).getIndex());
}