org.apache.calcite.sql.SqlBinaryOperator Java Examples

The following examples show how to use org.apache.calcite.sql.SqlBinaryOperator. 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: MysqlSideFunction.java    From alchemy with Apache License 2.0 6 votes vote down vote up
private List<SqlBasicCall> createConditionNodes(List<String> conditions, Alias alias) {
    SqlBinaryOperator equal = new SqlBinaryOperator("=", SqlKind.EQUALS, 30, true, ReturnTypes.BOOLEAN_NULLABLE,
        InferTypes.FIRST_KNOWN, OperandTypes.COMPARABLE_UNORDERED_COMPARABLE_UNORDERED);
    List<SqlBasicCall> nodes = new ArrayList<>(conditions.size());
    int num = 0;
    for (String condition : conditions) {
        List<String> fields = new ArrayList<>(2);
        fields.add(alias.getAlias());
        fields.add(condition);
        SqlIdentifier leftIdentifier = new SqlIdentifier(fields, new SqlParserPos(0, 0));
        SqlDynamicParam sqlDynamicParam = new SqlDynamicParam(num++, new SqlParserPos(0, 0));
        SqlNode[] sqlNodes = new SqlNode[2];
        sqlNodes[0] = leftIdentifier;
        sqlNodes[1] = sqlDynamicParam;
        SqlBasicCall andEqual = new SqlBasicCall(equal, sqlNodes, new SqlParserPos(0, 0));
        nodes.add(andEqual);
    }
    return nodes;
}
 
Example #2
Source File: JoinFilterCanonicalizationRule.java    From dremio-oss with Apache License 2.0 6 votes vote down vote up
/**
 * Build a join condition based on the left/right keys
 *
 * @param leftRowType
 * @param rightRowType
 * @param leftKeys
 * @param rightKeys
 * @param filterNulls
 * @param builder
 * @return a conjunction of equi-join conditions
 */
static RexNode buildJoinCondition(RexBuilder builder, RelDataType leftRowType, RelDataType rightRowType, List<Integer> leftKeys, List<Integer> rightKeys, List<Boolean> filterNulls) {
  final List<RexNode> equijoinList = Lists.newArrayList();
  final int numLeftFields = leftRowType.getFieldCount();
  final List<RelDataTypeField> leftTypes = leftRowType.getFieldList();
  final List<RelDataTypeField> rightTypes = rightRowType.getFieldList();

  for (int i = 0; i < leftKeys.size(); i++) {
    int leftKeyOrdinal = leftKeys.get(i);
    int rightKeyOrdinal = rightKeys.get(i);

    SqlBinaryOperator operator = filterNulls.get(i) ? SqlStdOperatorTable.EQUALS : SqlStdOperatorTable.IS_NOT_DISTINCT_FROM;
    RexNode leftInput = builder.makeInputRef(leftTypes.get(leftKeyOrdinal).getType(), leftKeyOrdinal);
    RexNode rightInput = builder.makeInputRef(rightTypes.get(rightKeyOrdinal).getType(), rightKeyOrdinal + numLeftFields);
    equijoinList.add(builder.makeCall(operator, leftInput, rightInput));
  }

  return RexUtil.composeConjunction(builder, equijoinList, false);
}
 
Example #3
Source File: BinaryOperatorTable.java    From streamline with Apache License 2.0 6 votes vote down vote up
private static ImmutableMap<SqlBinaryOperator, Operator> buildTable() {
    return ImmutableMap.<SqlBinaryOperator, Operator>builder()
            .put(SqlStdOperatorTable.GREATER_THAN, Operator.GREATER_THAN)
            .put(SqlStdOperatorTable.LESS_THAN, Operator.LESS_THAN)
            .put(SqlStdOperatorTable.GREATER_THAN_OR_EQUAL, Operator.GREATER_THAN_EQUALS_TO)
            .put(SqlStdOperatorTable.LESS_THAN_OR_EQUAL, Operator.LESS_THAN_EQUALS_TO)
            .put(SqlStdOperatorTable.EQUALS, Operator.EQUALS)
            .put(SqlStdOperatorTable.NOT_EQUALS, Operator.NOT_EQUAL)
            .put(SqlStdOperatorTable.AND, Operator.AND)
            .put(SqlStdOperatorTable.OR, Operator.OR)
            .put(SqlStdOperatorTable.MULTIPLY, Operator.MULTIPLY)
            .put(SqlStdOperatorTable.DIVIDE, Operator.DIVIDE)
            .put(SqlStdOperatorTable.PLUS, Operator.PLUS)
            .put(SqlStdOperatorTable.MINUS, Operator.MINUS)
            .build();
}
 
Example #4
Source File: SqlParserUtil.java    From Bats with Apache License 2.0 5 votes vote down vote up
@Override public PrecedenceClimbingParser parser(int start,
    Predicate<PrecedenceClimbingParser.Token> predicate) {
  final PrecedenceClimbingParser.Builder builder =
      new PrecedenceClimbingParser.Builder();
  for (Object o : Util.skip(list, start)) {
    if (o instanceof ToTreeListItem) {
      final ToTreeListItem item = (ToTreeListItem) o;
      final SqlOperator op = item.getOperator();
      if (op instanceof SqlPrefixOperator) {
        builder.prefix(item, op.getLeftPrec());
      } else if (op instanceof SqlPostfixOperator) {
        builder.postfix(item, op.getRightPrec());
      } else if (op instanceof SqlBinaryOperator) {
        builder.infix(item, op.getLeftPrec(),
            op.getLeftPrec() < op.getRightPrec());
      } else if (op instanceof SqlSpecialOperator) {
        builder.special(item, op.getLeftPrec(), op.getRightPrec(),
            (parser, op2) -> {
              final List<PrecedenceClimbingParser.Token> tokens =
                  parser.all();
              final SqlSpecialOperator op1 =
                  (SqlSpecialOperator) ((ToTreeListItem) op2.o).op;
              SqlSpecialOperator.ReduceResult r =
                  op1.reduceExpr(tokens.indexOf(op2),
                      new TokenSequenceImpl(parser));
              return new PrecedenceClimbingParser.Result(
                  tokens.get(r.startOrdinal),
                  tokens.get(r.endOrdinal - 1),
                  parser.atom(r.node));
            });
      } else {
        throw new AssertionError();
      }
    } else {
      builder.atom(o);
    }
  }
  return builder.build();
}
 
Example #5
Source File: FindPartitionConditions.java    From Bats with Apache License 2.0 5 votes vote down vote up
private void popOpStackAndBuildFilter() {
  // Parsing a special expression; handled holistically by the parent
  if (holisticExpression > 0) {
    return;
  }
  OpState currentOp = opStack.pop();
  int size = currentOp.getChildren().size();
  RexNode newFilter = null;
  if (size >= 1) {
    if (size == 1 && currentOp.getOp() instanceof SqlBinaryOperator) {
      /* The only operator for which we allow partial pushes is AND.
       * For all other operators we clear the children if one of the
       * children is a no push.
       */
      if (currentOp.getOp().getKind() == SqlKind.AND) {
        newFilter = currentOp.getChildren().get(0);
        for (OpState opState : opStack) {
          if (opState.getOp().getKind() == SqlKind.NOT) {
            //AND under NOT should not get pushed
            newFilter = null;
          }
        }

      }
    } else {
      newFilter = builder.makeCall(currentOp.getOp(), currentOp.getChildren());
    }
  }

  if (newFilter != null) {
    // add this new filter to my parent boolean operator's children
    if (!opStack.isEmpty()) {
      OpState parentOp = opStack.peek();
      parentOp.addChild(newFilter);
    } else {
      resultCondition = newFilter;
    }
  }
}
 
Example #6
Source File: MysqlSideFunction.java    From alchemy with Apache License 2.0 5 votes vote down vote up
private String modifySql(SideTable sideTable) throws SqlParseException {
    SqlParser.Config config = SqlParser.configBuilder().setLex(Lex.MYSQL).build();
    SqlParser sqlParser = SqlParser.create(sideTable.getSql(), config);
    SqlNode sqlNode = sqlParser.parseStmt();
    if (SqlKind.SELECT != sqlNode.getKind()) {
        throw new UnsupportedOperationException(
            "MysqlAsyncReqRow only support query sql, sql:" + sideTable.getSql());
    }
    SqlSelect sqlSelect = (SqlSelect)sqlNode;
    SqlNode whereNode = sqlSelect.getWhere();
    SqlBinaryOperator and = new SqlBinaryOperator("AND", SqlKind.AND, 24, true,
        ReturnTypes.BOOLEAN_NULLABLE_OPTIMIZED, InferTypes.BOOLEAN, OperandTypes.BOOLEAN_BOOLEAN);
    List<SqlBasicCall> conditionNodes = createConditionNodes(sideTable.getConditions(), sideTable.getSideAlias());
    List<SqlNode> nodes = new ArrayList<>();
    nodes.addAll(conditionNodes);
    if (whereNode != null) {
        nodes.add(whereNode);
    } else {
        SqlBinaryOperator equal = new SqlBinaryOperator("=", SqlKind.EQUALS, 30, true, ReturnTypes.BOOLEAN_NULLABLE,
            InferTypes.FIRST_KNOWN, OperandTypes.COMPARABLE_UNORDERED_COMPARABLE_UNORDERED);
        SqlBasicCall andEqual
            = new SqlBasicCall(equal, SideParser.createEqualNodes(SqlKind.AND), new SqlParserPos(0, 0));
        nodes.add(andEqual);
    }
    SqlBasicCall sqlBasicCall
        = new SqlBasicCall(and, nodes.toArray(new SqlNode[nodes.size()]), new SqlParserPos(0, 0));
    sqlSelect.setWhere(sqlBasicCall);
    return sqlSelect.toString();
}
 
Example #7
Source File: FindPartitionConditions.java    From dremio-oss with Apache License 2.0 5 votes vote down vote up
private void popOpStackAndBuildFilter() {
  // Parsing a special expression; handled holistically by the parent
  if (holisticExpression > 0) {
    return;
  }
  OpState currentOp = opStack.pop();
  int size = currentOp.getChildren().size();
  RexNode newFilter = null;
  if (size >= 1) {
    if (size == 1 && currentOp.getOp() instanceof SqlBinaryOperator) {
      /* The only operator for which we allow partial pushes is AND.
       * For all other operators we clear the children if one of the
       * children is a no push.
       */
      newFilter = currentOp.getChildren().get(0);
    } else {
      newFilter = builder.makeCall(currentOp.getOp(), currentOp.getChildren());
    }
  }

  if (newFilter != null) {
    // add this new filter to my parent boolean operator's children
    if (!opStack.isEmpty()) {
      OpState parentOp = opStack.peek();
      parentOp.addChild(newFilter);
    } else {
      resultCondition = newFilter;
    }
  }
}
 
Example #8
Source File: BinaryOperatorTable.java    From streamline with Apache License 2.0 5 votes vote down vote up
public static Operator getOperator(SqlBinaryOperator sqlBinaryOperator) {
    Operator operator = operatorTable.get(sqlBinaryOperator);
    if (operator == null) {
        throw new UnsupportedOperationException("Operator " + sqlBinaryOperator.getName() + " is not supported");
    }
    return operator;
}
 
Example #9
Source File: ExpressionGenerator.java    From streamline with Apache License 2.0 5 votes vote down vote up
@Override
public Expression visit(SqlCall call) {
    SqlOperator sqlOperator = call.getOperator();
    if (sqlOperator instanceof SqlBinaryOperator) {
        return visitBinaryOperator((SqlBinaryOperator) sqlOperator, call.getOperandList().get(0),
                call.getOperandList().get(1));
    } else if (sqlOperator instanceof SqlSpecialOperator) {
        return visitSqlSpecialOperator((SqlSpecialOperator) sqlOperator, call.getOperandList());
    } else if (sqlOperator instanceof SqlFunction) {
        SqlFunction sqlFunction = (SqlFunction) sqlOperator;
        if (sqlFunction instanceof SqlAggFunction) {
            return visitAggregateFunction(sqlFunction.getName(), call.getOperandList());
        } else if (sqlFunction instanceof SqlUnresolvedFunction) {
            String udfName = sqlFunction.getName().toUpperCase();
            if (catalogUdfs.containsKey(udfName)) {
                Udf udfInfo = catalogUdfs.get(udfName);
                if (udfInfo.isAggregate()) {
                    return visitUserDefinedAggregateFunction(udfInfo, call.getOperandList());
                } else {
                    return visitUserDefinedFunction(udfInfo, call.getOperandList());
                }
            } else {
                throw new UnsupportedOperationException("Unknown built-in or User defined function '" + udfName + "'");
            }
        } else {
            return visitFunction(sqlFunction.getName(), call.getOperandList());
        }
    } else {
        throw new UnsupportedOperationException("Operator " + sqlOperator.getName() + " is not supported");
    }
}
 
Example #10
Source File: SplunkPushDownRule.java    From calcite with Apache License 2.0 5 votes vote down vote up
private boolean getFilter(SqlOperator op, List<RexNode> operands,
    StringBuilder s, List<String> fieldNames) {
  if (!valid(op.getKind())) {
    return false;
  }

  boolean like = false;
  switch (op.getKind()) {
  case NOT:
    // NOT op pre-pended
    s = s.append(" NOT ");
    break;
  case CAST:
    return asd(false, operands, s, fieldNames, 0);
  case LIKE:
    like = true;
    break;
  }

  for (int i = 0; i < operands.size(); i++) {
    if (!asd(like, operands, s, fieldNames, i)) {
      return false;
    }
    if (op instanceof SqlBinaryOperator && i == 0) {
      s.append(" ").append(op).append(" ");
    }
  }
  return true;
}
 
Example #11
Source File: SqlParserUtil.java    From calcite with Apache License 2.0 5 votes vote down vote up
@Override public PrecedenceClimbingParser parser(int start,
    Predicate<PrecedenceClimbingParser.Token> predicate) {
  final PrecedenceClimbingParser.Builder builder =
      new PrecedenceClimbingParser.Builder();
  for (Object o : Util.skip(list, start)) {
    if (o instanceof ToTreeListItem) {
      final ToTreeListItem item = (ToTreeListItem) o;
      final SqlOperator op = item.getOperator();
      if (op instanceof SqlPrefixOperator) {
        builder.prefix(item, op.getLeftPrec());
      } else if (op instanceof SqlPostfixOperator) {
        builder.postfix(item, op.getRightPrec());
      } else if (op instanceof SqlBinaryOperator) {
        builder.infix(item, op.getLeftPrec(),
            op.getLeftPrec() < op.getRightPrec());
      } else if (op instanceof SqlSpecialOperator) {
        builder.special(item, op.getLeftPrec(), op.getRightPrec(),
            (parser, op2) -> {
              final List<PrecedenceClimbingParser.Token> tokens =
                  parser.all();
              final SqlSpecialOperator op1 =
                  (SqlSpecialOperator) ((ToTreeListItem) op2.o).op;
              SqlSpecialOperator.ReduceResult r =
                  op1.reduceExpr(tokens.indexOf(op2),
                      new TokenSequenceImpl(parser));
              return new PrecedenceClimbingParser.Result(
                  tokens.get(r.startOrdinal),
                  tokens.get(r.endOrdinal - 1),
                  parser.atom(r.node));
            });
      } else {
        throw new AssertionError();
      }
    } else {
      builder.atom(o);
    }
  }
  return builder.build();
}
 
Example #12
Source File: ExpressionGenerator.java    From streamline with Apache License 2.0 4 votes vote down vote up
private Expression visitBinaryOperator(SqlBinaryOperator binaryOperator, SqlNode left, SqlNode right) {
    Operator operator = BinaryOperatorTable.getOperator(binaryOperator);
    return new BinaryExpression(operator, left.accept(this), right.accept(this));
}
 
Example #13
Source File: CalcitePrepareImpl.java    From calcite with Apache License 2.0 4 votes vote down vote up
private RexNode binary(Expression expression, SqlBinaryOperator op) {
  BinaryExpression call = (BinaryExpression) expression;
  return rexBuilder.makeCall(type(call), op,
      toRex(ImmutableList.of(call.expression0, call.expression1)));
}
 
Example #14
Source File: RexImpTable.java    From calcite with Apache License 2.0 4 votes vote down vote up
@Override Expression implementSafe(
    final RexToLixTranslator translator,
    final RexCall call,
    final List<Expression> argValueList) {
  // neither nullable:
  //   return x OP y
  // x nullable
  //   null_returns_null
  //     return x == null ? null : x OP y
  //   ignore_null
  //     return x == null ? null : y
  // x, y both nullable
  //   null_returns_null
  //     return x == null || y == null ? null : x OP y
  //   ignore_null
  //     return x == null ? y : y == null ? x : x OP y
  if (backupMethodName != null) {
    // If one or both operands have ANY type, use the late-binding backup
    // method.
    if (anyAnyOperands(call)) {
      return callBackupMethodAnyType(translator, call, argValueList);
    }

    final Type type0 = argValueList.get(0).getType();
    final Type type1 = argValueList.get(1).getType();
    final SqlBinaryOperator op = (SqlBinaryOperator) call.getOperator();
    final RelDataType relDataType0 = call.getOperands().get(0).getType();
    final Expression fieldComparator = generateCollatorExpression(relDataType0.getCollation());
    if (fieldComparator != null) {
      argValueList.add(fieldComparator);
    }
    final Primitive primitive = Primitive.ofBoxOr(type0);
    if (primitive == null
        || type1 == BigDecimal.class
        || COMPARISON_OPERATORS.contains(op)
        && !COMP_OP_TYPES.contains(primitive)) {
      return Expressions.call(SqlFunctions.class, backupMethodName,
          argValueList);
    }
    // When checking equals or not equals on two primitive boxing classes
    // (i.e. Long x, Long y), we should fall back to call `SqlFunctions.eq(x, y)`
    // or `SqlFunctions.ne(x, y)`, rather than `x == y`
    final Primitive boxPrimitive0 = Primitive.ofBox(type0);
    final Primitive boxPrimitive1 = Primitive.ofBox(type1);
    if (EQUALS_OPERATORS.contains(op)
        && boxPrimitive0 != null && boxPrimitive1 != null) {
      return Expressions.call(SqlFunctions.class, backupMethodName,
          argValueList);
    }
  }
  return Expressions.makeBinary(expressionType,
      argValueList.get(0), argValueList.get(1));
}