org.apache.calcite.rex.RexOver Java Examples

The following examples show how to use org.apache.calcite.rex.RexOver. 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: LogicalWindow.java    From Bats with Apache License 2.0 6 votes vote down vote up
private static void addWindows(Multimap<WindowKey, RexOver> windowMap, RexOver over, final int inputFieldCount) {
    final RexWindow aggWindow = over.getWindow();

    // Look up or create a window.
    RelCollation orderKeys = getCollation(Lists.newArrayList(Util.filter(aggWindow.orderKeys, rexFieldCollation ->
    // If ORDER BY references constant (i.e. RexInputRef),
    // then we can ignore such ORDER BY key.
    rexFieldCollation.left instanceof RexLocalRef)));
    ImmutableBitSet groupSet = ImmutableBitSet.of(getProjectOrdinals(aggWindow.partitionKeys));
    final int groupLength = groupSet.length();
    if (inputFieldCount < groupLength) {
        // If PARTITION BY references constant, we can ignore such partition key.
        // All the inputs after inputFieldCount are literals, thus we can clear.
        groupSet = groupSet.except(ImmutableBitSet.range(inputFieldCount, groupLength));
    }

    WindowKey windowKey = new WindowKey(groupSet, orderKeys, aggWindow.isRows(), aggWindow.getLowerBound(),
            aggWindow.getUpperBound());
    windowMap.put(windowKey, over);
}
 
Example #2
Source File: SubQueryDecorrelator.java    From flink with Apache License 2.0 6 votes vote down vote up
@Override
public RelNode visit(LogicalProject project) {
	hasOverNode = RexOver.containsOver(project.getProjects(), null);
	final boolean hasSubQuery = RexUtil.SubQueryFinder.find(project.getProjects()) != null;
	try {
		if (!corNodeStack.isEmpty()) {
			mapSubQueryNodeToCorSet.put(project, corNodeStack.peek().getVariablesSet());
		}
		if (hasSubQuery) {
			corNodeStack.push(project);
		}
		checkCorCondition(project);
		for (RexNode node : project.getProjects()) {
			node.accept(rexVisitor(project));
		}
	} finally {
		if (hasSubQuery) {
			corNodeStack.pop();
		}
	}
	return super.visit(project);
}
 
Example #3
Source File: DremioRelToSqlConverter.java    From dremio-oss with Apache License 2.0 6 votes vote down vote up
@Override
public SqlImplementor.Result visit(Window e) {
  SqlImplementor.Result x = visitChild(0, e.getInput());
  SqlImplementor.Builder builder = x.builder(e);
  RelNode input = e.getInput();
  List<RexOver> rexOvers = WindowUtil.getOver(e);

  final List<SqlNode> selectList = new ArrayList<>();
  final Set<String> fields = ImmutableSet.copyOf(e.getRowType().getFieldNames());
  for (RelDataTypeField field : input.getRowType().getFieldList()) {
    if (fields.contains(field.getName())) {
      addSelect(selectList, builder.context.field(field.getIndex()), e.getRowType());
    }
  }

  for (RexOver rexOver : rexOvers) {
    addSelect(selectList, builder.context.toSql(null, rexOver), e.getRowType());
  }
  builder.setSelect(new SqlNodeList(selectList, POS));
  return builder.result();
}
 
Example #4
Source File: SubQueryDecorrelator.java    From flink with Apache License 2.0 6 votes vote down vote up
@Override
public RelNode visit(LogicalProject project) {
	hasOverNode = RexOver.containsOver(project.getProjects(), null);
	final boolean hasSubQuery = RexUtil.SubQueryFinder.find(project.getProjects()) != null;
	try {
		if (!corNodeStack.isEmpty()) {
			mapSubQueryNodeToCorSet.put(project, corNodeStack.peek().getVariablesSet());
		}
		if (hasSubQuery) {
			corNodeStack.push(project);
		}
		checkCorCondition(project);
		for (RexNode node : project.getProjects()) {
			node.accept(rexVisitor(project));
		}
	} finally {
		if (hasSubQuery) {
			corNodeStack.pop();
		}
	}
	return super.visit(project);
}
 
Example #5
Source File: RelOptUtil.java    From calcite with Apache License 2.0 6 votes vote down vote up
/** As {@link #pushPastProject}, but returns null if the resulting expressions
 * are significantly more complex.
 *
 * @param bloat Maximum allowable increase in complexity */
public static @Nullable List<RexNode> pushPastProjectUnlessBloat(
    List<? extends RexNode> nodes, Project project, int bloat) {
  if (bloat < 0) {
    // If bloat is negative never merge.
    return null;
  }
  if (RexOver.containsOver(nodes, null)
      && RexOver.containsOver(project.getProjects(), null)) {
    // Is it valid relational algebra to apply windowed function to a windowed
    // function? Possibly. But it's invalid SQL, so don't go there.
    return null;
  }
  final List<RexNode> list = pushPastProject(nodes, project);
  final int bottomCount = RexUtil.nodeCount(project.getProjects());
  final int topCount = RexUtil.nodeCount(nodes);
  final int mergedCount = RexUtil.nodeCount(list);
  if (mergedCount > bottomCount + topCount + bloat) {
    // The merged expression is more complex than the input expressions.
    // Do not merge.
    return null;
  }
  return list;
}
 
Example #6
Source File: OLAPProjectRel.java    From kylin-on-parquet-v2 with Apache License 2.0 5 votes vote down vote up
/**
 * Since the project under aggregate maybe reduce expressions by {@link org.apache.kylin.query.optrule.AggregateProjectReduceRule},
 * consider the count of expressions into cost, the reduced project will be used.
 *
 * Made RexOver much more expensive so we can transform into {@link org.apache.kylin.query.relnode.OLAPWindowRel}
 * by rules in {@link org.apache.calcite.rel.rules.ProjectToWindowRule}
 */
@Override
public RelOptCost computeSelfCost(RelOptPlanner planner, RelMetadataQuery mq) {
    boolean hasRexOver = RexOver.containsOver(getProjects(), null);
    RelOptCost relOptCost = super.computeSelfCost(planner, mq).multiplyBy(.05)
            .multiplyBy(getProjects().size() * (double) (hasRexOver ? 50 : 1))
            .plus(planner.getCostFactory().makeCost(0.1 * caseCount, 0, 0));
    return planner.getCostFactory().makeCost(relOptCost.getRows(), 0, 0);
}
 
Example #7
Source File: ProjectToWindowRule.java    From Bats with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a CalcToWindowRule.
 *
 * @param relBuilderFactory Builder for relational expressions
 */
public CalcToWindowRule(RelBuilderFactory relBuilderFactory) {
  super(
      operandJ(Calc.class, null,
          calc -> RexOver.containsOver(calc.getProgram()), any()),
      relBuilderFactory, "ProjectToWindowRule");
}
 
Example #8
Source File: ProjectToWindowRule.java    From Bats with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a ProjectToWindowRule.
 *
 * @param relBuilderFactory Builder for relational expressions
 */
public ProjectToLogicalProjectAndWindowRule(
    RelBuilderFactory relBuilderFactory) {
  super(
      operandJ(Project.class, null,
          project -> RexOver.containsOver(project.getProjects(), null),
          any()),
      relBuilderFactory, "ProjectToWindowRule:project");
}
 
Example #9
Source File: FilterProjectTransposeRule.java    From Bats with Apache License 2.0 5 votes vote down vote up
public void onMatch(RelOptRuleCall call) {
  final Filter filter = call.rel(0);
  final Project project = call.rel(1);

  if (RexOver.containsOver(project.getProjects(), null)) {
    // In general a filter cannot be pushed below a windowing calculation.
    // Applying the filter before the aggregation function changes
    // the results of the windowing invocation.
    //
    // When the filter is on the PARTITION BY expression of the OVER clause
    // it can be pushed down. For now we don't support this.
    return;
  }
  // convert the filter to one that references the child of the project
  RexNode newCondition =
      RelOptUtil.pushPastProject(filter.getCondition(), project);

  final RelBuilder relBuilder = call.builder();
  RelNode newFilterRel;
  if (copyFilter) {
    newFilterRel = filter.copy(filter.getTraitSet(), project.getInput(),
        simplifyFilterCondition(newCondition, call));
  } else {
    newFilterRel =
        relBuilder.push(project.getInput()).filter(newCondition).build();
  }

  RelNode newProjRel =
      copyProject
          ? project.copy(project.getTraitSet(), newFilterRel,
              project.getProjects(), project.getRowType())
          : relBuilder.push(newFilterRel)
              .project(project.getProjects(), project.getRowType().getFieldNames())
              .build();

  call.transformTo(newProjRel);
}
 
Example #10
Source File: SqlImplementor.java    From Bats with Apache License 2.0 5 votes vote down vote up
private SqlCall toSql(RexProgram program, RexOver rexOver) {
    final RexWindow rexWindow = rexOver.getWindow();
    final SqlNodeList partitionList = new SqlNodeList(toSql(program, rexWindow.partitionKeys), POS);

    ImmutableList.Builder<SqlNode> orderNodes = ImmutableList.builder();
    if (rexWindow.orderKeys != null) {
        for (RexFieldCollation rfc : rexWindow.orderKeys) {
            orderNodes.add(toSql(program, rfc));
        }
    }
    final SqlNodeList orderList = new SqlNodeList(orderNodes.build(), POS);

    final SqlLiteral isRows = SqlLiteral.createBoolean(rexWindow.isRows(), POS);

    // null defaults to true.
    // During parsing the allowPartial == false (e.g. disallow partial)
    // is expand into CASE expression and is handled as a such.
    // Not sure if we can collapse this CASE expression back into
    // "disallow partial" and set the allowPartial = false.
    final SqlLiteral allowPartial = null;

    SqlAggFunction sqlAggregateFunction = rexOver.getAggOperator();

    SqlNode lowerBound = null;
    SqlNode upperBound = null;

    if (sqlAggregateFunction.allowsFraming()) {
        lowerBound = createSqlWindowBound(rexWindow.getLowerBound());
        upperBound = createSqlWindowBound(rexWindow.getUpperBound());
    }

    final SqlWindow sqlWindow = SqlWindow.create(null, null, partitionList, orderList, isRows, lowerBound,
            upperBound, allowPartial, POS);

    final List<SqlNode> nodeList = toSql(program, rexOver.getOperands());
    return createOverCall(sqlAggregateFunction, nodeList, sqlWindow);
}
 
Example #11
Source File: SqlImplementor.java    From calcite with Apache License 2.0 5 votes vote down vote up
private SqlCall toSql(RexProgram program, RexOver rexOver) {
  final RexWindow rexWindow = rexOver.getWindow();
  final SqlNodeList partitionList = new SqlNodeList(
      toSql(program, rexWindow.partitionKeys), POS);

  List<SqlNode> orderNodes = Expressions.list();
  if (rexWindow.orderKeys != null) {
    for (RexFieldCollation rfc : rexWindow.orderKeys) {
      addOrderItem(orderNodes, program, rfc);
    }
  }
  final SqlNodeList orderList =
      new SqlNodeList(orderNodes, POS);

  final SqlLiteral isRows =
      SqlLiteral.createBoolean(rexWindow.isRows(), POS);

  // null defaults to true.
  // During parsing the allowPartial == false (e.g. disallow partial)
  // is expand into CASE expression and is handled as a such.
  // Not sure if we can collapse this CASE expression back into
  // "disallow partial" and set the allowPartial = false.
  final SqlLiteral allowPartial = null;

  SqlAggFunction sqlAggregateFunction = rexOver.getAggOperator();

  SqlNode lowerBound = null;
  SqlNode upperBound = null;

  if (sqlAggregateFunction.allowsFraming()) {
    lowerBound = createSqlWindowBound(rexWindow.getLowerBound());
    upperBound = createSqlWindowBound(rexWindow.getUpperBound());
  }

  final SqlWindow sqlWindow = SqlWindow.create(null, null, partitionList,
      orderList, isRows, lowerBound, upperBound, allowPartial, POS);

  final List<SqlNode> nodeList = toSql(program, rexOver.getOperands());
  return createOverCall(sqlAggregateFunction, nodeList, sqlWindow);
}
 
Example #12
Source File: OverUtils.java    From dremio-oss with Apache License 2.0 5 votes vote down vote up
public static boolean hasDefaultFrame(RexOver over) {
  return hasDefaultFrame(
    over.getAggOperator(),
    over.getWindow().isRows(),
    over.getWindow().getLowerBound(),
    over.getWindow().getUpperBound(),
    over.getWindow().orderKeys.size());
}
 
Example #13
Source File: FilterProjectNLJRule.java    From dremio-oss with Apache License 2.0 5 votes vote down vote up
@Override
public boolean matches(RelOptRuleCall call) {
  FilterPrel filter = call.rel(0);
  ProjectPrel project = call.rel(1);
  if (RexOver.containsOver(project.getProjects(), null) ||
      RexUtil.containsCorrelation(filter.getCondition())) {
    return false;
  }

  NestedLoopJoinPrel join = call.rel(2);
  return join.getJoinType() == JoinRelType.INNER &&
      PrelUtil.getPlannerSettings(call.getPlanner()).getOptions().getOption(NestedLoopJoinPrel.VECTORIZED);
}
 
Example #14
Source File: SqlImplementor.java    From dremio-oss with Apache License 2.0 5 votes vote down vote up
protected SqlCall toSql(RexProgram program, RexOver rexOver) {
  final RexWindow rexWindow = rexOver.getWindow();
  final SqlNodeList partitionList = new SqlNodeList(
    toSql(program, rexWindow.partitionKeys), POS);

  ImmutableList.Builder<SqlNode> orderNodes = ImmutableList.builder();
  if (rexWindow.orderKeys != null) {
    for (RexFieldCollation rfc : rexWindow.orderKeys) {
      orderNodes.add(toSql(program, rfc));
    }
  }
  final SqlNodeList orderList =
    new SqlNodeList(orderNodes.build(), POS);

  final SqlLiteral isRows =
    SqlLiteral.createBoolean(rexWindow.isRows(), POS);

  final SqlNode lowerBound =
    createSqlWindowBound(rexWindow.getLowerBound());
  final SqlNode upperBound =
    createSqlWindowBound(rexWindow.getUpperBound());

  // null defaults to true.
  // During parsing the allowPartial == false (e.g. disallow partial)
  // is expand into CASE expression and is handled as a such.
  // Not sure if we can collapse this CASE expression back into
  // "disallow partial" and set the allowPartial = false.
  final SqlLiteral allowPartial = null;

  final SqlWindow sqlWindow = SqlWindow.create(null, null, partitionList,
    orderList, isRows, lowerBound, upperBound, allowPartial, POS);

  final List<SqlNode> nodeList = toSql(program, rexOver.getOperands());
  final SqlCall aggFunctionCall =
    rexOver.getAggOperator().createCall(POS, nodeList);

  return SqlStdOperatorTable.OVER.createCall(POS, aggFunctionCall,
    sqlWindow);
}
 
Example #15
Source File: OLAPProjectRel.java    From kylin with Apache License 2.0 5 votes vote down vote up
/**
 * Since the project under aggregate maybe reduce expressions by {@link org.apache.kylin.query.optrule.AggregateProjectReduceRule},
 * consider the count of expressions into cost, the reduced project will be used.
 *
 * Made RexOver much more expensive so we can transform into {@link org.apache.kylin.query.relnode.OLAPWindowRel}
 * by rules in {@link org.apache.calcite.rel.rules.ProjectToWindowRule}
 */
@Override
public RelOptCost computeSelfCost(RelOptPlanner planner, RelMetadataQuery mq) {
    boolean hasRexOver = RexOver.containsOver(getProjects(), null);
    RelOptCost relOptCost = super.computeSelfCost(planner, mq).multiplyBy(.05)
            .multiplyBy(getProjects().size() * (double) (hasRexOver ? 50 : 1))
            .plus(planner.getCostFactory().makeCost(0.1 * caseCount, 0, 0));
    return planner.getCostFactory().makeCost(relOptCost.getRows(), 0, 0);
}
 
Example #16
Source File: JdbcRules.java    From calcite with Apache License 2.0 5 votes vote down vote up
/** Creates a JdbcProjectRule. */
public JdbcProjectRule(final JdbcConvention out,
    RelBuilderFactory relBuilderFactory) {
  super(Project.class, (Predicate<Project>) project ->
          (out.dialect.supportsWindowFunctions()
              || !RexOver.containsOver(project.getProjects(), null))
              && !userDefinedFunctionInProject(project),
      Convention.NONE, out, relBuilderFactory, "JdbcProjectRule");
}
 
Example #17
Source File: LogicalWindow.java    From calcite with Apache License 2.0 5 votes vote down vote up
private static void addWindows(
    Multimap<WindowKey, RexOver> windowMap,
    RexOver over, final int inputFieldCount) {
  final RexWindow aggWindow = over.getWindow();

  // Look up or create a window.
  RelCollation orderKeys = getCollation(
      Lists.newArrayList(
          Util.filter(aggWindow.orderKeys,
              rexFieldCollation ->
                  // If ORDER BY references constant (i.e. RexInputRef),
                  // then we can ignore such ORDER BY key.
                  rexFieldCollation.left instanceof RexLocalRef)));
  ImmutableBitSet groupSet =
      ImmutableBitSet.of(getProjectOrdinals(aggWindow.partitionKeys));
  final int groupLength = groupSet.length();
  if (inputFieldCount < groupLength) {
    // If PARTITION BY references constant, we can ignore such partition key.
    // All the inputs after inputFieldCount are literals, thus we can clear.
    groupSet =
        groupSet.except(ImmutableBitSet.range(inputFieldCount, groupLength));
  }

  WindowKey windowKey =
      new WindowKey(
          groupSet, orderKeys, aggWindow.isRows(),
          aggWindow.getLowerBound(), aggWindow.getUpperBound());
  windowMap.put(windowKey, over);
}
 
Example #18
Source File: SortProjectTransposeRule.java    From calcite with Apache License 2.0 5 votes vote down vote up
/** Creates a SortProjectTransposeRule. */
public SortProjectTransposeRule(
    Class<? extends Sort> sortClass,
    Class<? extends Project> projectClass,
    RelBuilderFactory relBuilderFactory, String description) {
  this(
      operand(sortClass,
          operandJ(projectClass, null,
              p -> !RexOver.containsOver(p.getProjects(), null),
              any())),
      relBuilderFactory, description);
}
 
Example #19
Source File: ProjectToWindowRule.java    From calcite with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a CalcToWindowRule.
 *
 * @param relBuilderFactory Builder for relational expressions
 */
public CalcToWindowRule(RelBuilderFactory relBuilderFactory) {
  super(
      operandJ(Calc.class, null,
          calc -> RexOver.containsOver(calc.getProgram()), any()),
      relBuilderFactory, "ProjectToWindowRule");
}
 
Example #20
Source File: ProjectToWindowRule.java    From calcite with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a ProjectToWindowRule.
 *
 * @param relBuilderFactory Builder for relational expressions
 */
public ProjectToLogicalProjectAndWindowRule(
    RelBuilderFactory relBuilderFactory) {
  super(
      operandJ(Project.class, null,
          project -> RexOver.containsOver(project.getProjects(), null),
          any()),
      relBuilderFactory, "ProjectToWindowRule:project");
}
 
Example #21
Source File: ProjectCalcMergeRule.java    From calcite with Apache License 2.0 4 votes vote down vote up
public void onMatch(RelOptRuleCall call) {
  final LogicalProject project = call.rel(0);
  final LogicalCalc calc = call.rel(1);

  // Don't merge a project which contains windowed aggregates onto a
  // calc. That would effectively be pushing a windowed aggregate down
  // through a filter. Transform the project into an identical calc,
  // which we'll have chance to merge later, after the over is
  // expanded.
  final RelOptCluster cluster = project.getCluster();
  RexProgram program =
      RexProgram.create(
          calc.getRowType(),
          project.getProjects(),
          null,
          project.getRowType(),
          cluster.getRexBuilder());
  if (RexOver.containsOver(program)) {
    LogicalCalc projectAsCalc = LogicalCalc.create(calc, program);
    call.transformTo(projectAsCalc);
    return;
  }

  // Create a program containing the project node's expressions.
  final RexBuilder rexBuilder = cluster.getRexBuilder();
  final RexProgramBuilder progBuilder =
      new RexProgramBuilder(
          calc.getRowType(),
          rexBuilder);
  for (Pair<RexNode, String> field : project.getNamedProjects()) {
    progBuilder.addProject(field.left, field.right);
  }
  RexProgram topProgram = progBuilder.getProgram();
  RexProgram bottomProgram = calc.getProgram();

  // Merge the programs together.
  RexProgram mergedProgram =
      RexProgramBuilder.mergePrograms(
          topProgram,
          bottomProgram,
          rexBuilder);
  final LogicalCalc newCalc =
      LogicalCalc.create(calc.getInput(), mergedProgram);
  call.transformTo(newCalc);
}
 
Example #22
Source File: ORCSearchArgumentGenerator.java    From dremio-oss with Apache License 2.0 4 votes vote down vote up
@Override
public Object visitOver(RexOver over) {
  throw new IllegalArgumentException("this shouldn't be part of the input expression: " + over);
}
 
Example #23
Source File: ORCFindRelevantFilters.java    From dremio-oss with Apache License 2.0 4 votes vote down vote up
@Override
public RexNode visitOver(RexOver over) {
  return null;
}
 
Example #24
Source File: DremioRelToSqlConverter.java    From dremio-oss with Apache License 2.0 4 votes vote down vote up
@Override
public SqlCall toSql(RexProgram program, RexOver rexOver) {
  final RexWindow rexWindow = rexOver.getWindow();
  final SqlNodeList partitionList = new SqlNodeList(
    toSql(program, rexWindow.partitionKeys), POS);

  ImmutableList.Builder<SqlNode> orderNodes = ImmutableList.builder();
  if (rexWindow.orderKeys != null) {
    for (RexFieldCollation rfc : rexWindow.orderKeys) {
      // Omit ORDER BY <ordinal> clauses, which are parsed by Calcite but not actually
      // used for sorting.
      if (!(rfc.getKey() instanceof RexLiteral)) {
        if (rfc.getNullDirection() != dialect.defaultNullDirection(rfc.getDirection())) {
          // Get the SQL Node for the column being sorted on only.
          final SqlNode orderingColumnNode = toSql(program, rfc.left);

          final SqlNode emulatedNullDirNode = dialect.emulateNullDirection(orderingColumnNode,
            rfc.getNullDirection() == RelFieldCollation.NullDirection.FIRST, rfc.getDirection().isDescending());
          if (emulatedNullDirNode != null) {
            // Dialect requires emulating null direction.
            // Put the emulation in the order list first, then the ordering on the column only.
            orderNodes.add(emulatedNullDirNode);
            orderNodes.add(orderingColumnNode);
          } else {
            // Dialect implements NULLS FIRST and NULLS LAST clauses. These will get
            // unparsed as part of the RexFieldCollation.
            orderNodes.add(toSql(program, rfc));
          }
        } else {
          orderNodes.add(toSql(program, rfc));
        }
      }
    }
  }

  final SqlNodeList orderList =
    new SqlNodeList(orderNodes.build(), POS);

  final SqlLiteral isRows =
    SqlLiteral.createBoolean(rexWindow.isRows(), POS);

  final SqlNode lowerBound;
  final SqlNode upperBound;

  // Remove unnecessary Window Frames. When Calcite parses an OVER clause with no frame,
  final boolean hasUnnecessaryFrame = getDialect().removeDefaultWindowFrame(rexOver)
    && OverUtils.hasDefaultFrame(rexOver);

  if (hasUnnecessaryFrame) {
    lowerBound = null;
    upperBound = null;
  } else {
    lowerBound = createSqlWindowBound(rexWindow.getLowerBound());
    upperBound = createSqlWindowBound(rexWindow.getUpperBound());
  }

  // null defaults to true.
  // During parsing the allowPartial == false (e.g. disallow partial)
  // is expand into CASE expression and is handled as a such.
  // Not sure if we can collapse this CASE expression back into
  // "disallow partial" and set the allowPartial = false.
  final SqlLiteral allowPartial = null;

  final SqlWindow sqlWindow = getDremioRelToSqlConverter().adjustWindowForSource(
    this, rexOver.getAggOperator(), SqlWindow.create(
      null, null, partitionList,
      orderList, isRows, lowerBound, upperBound, allowPartial, POS));

  final List<SqlNode> nodeList = toSql(program, rexOver.getOperands());

  // Create the call for the aggregate in the window function.
  // If it happens to be a SUM0 call, we need to swap that with our own version which sets
  // the name to just SUM, rather than $SUM0, so that it can be translated to SQL compatible
  // with RDBMSes.
  final SqlAggFunction operator = rexOver.getAggOperator() != SqlStdOperatorTable.SUM0 ?
    rexOver.getAggOperator() : SUM0_FUNCTION;

  final SqlCall aggFunctionCall = operator.createCall(POS, nodeList);

  return SqlStdOperatorTable.OVER.createCall(POS, aggFunctionCall,
    sqlWindow);
}
 
Example #25
Source File: PredicateAnalyzer.java    From dremio-oss with Apache License 2.0 4 votes vote down vote up
@Override
public Expression visitOver(RexOver over) {
  return super.visitOver(over);
}
 
Example #26
Source File: KylinSortProjectTransposeRule.java    From kylin with Apache License 2.0 4 votes vote down vote up
private static boolean noWindowFunc(Project project) {
    return !RexOver.containsOver(project.getProjects(), null);
}
 
Example #27
Source File: RelOptUtil.java    From Bats with Apache License 2.0 4 votes vote down vote up
/** Predicate for whether a {@link Project} contains multisets or windowed
 * aggregates. */
public static boolean containsMultisetOrWindowedAgg(Project project) {
    return !(B && RexMultisetUtil.containsMultiset(project.getProjects(), true)
            || RexOver.containsOver(project.getProjects(), null));
}
 
Example #28
Source File: RelJson.java    From calcite with Apache License 2.0 4 votes vote down vote up
private Object toJson(RexNode node) {
  final Map<String, Object> map;
  switch (node.getKind()) {
  case FIELD_ACCESS:
    map = jsonBuilder.map();
    final RexFieldAccess fieldAccess = (RexFieldAccess) node;
    map.put("field", fieldAccess.getField().getName());
    map.put("expr", toJson(fieldAccess.getReferenceExpr()));
    return map;
  case LITERAL:
    final RexLiteral literal = (RexLiteral) node;
    final Object value = literal.getValue3();
    map = jsonBuilder.map();
    map.put("literal", RelEnumTypes.fromEnum(value));
    map.put("type", toJson(node.getType()));
    return map;
  case INPUT_REF:
    map = jsonBuilder.map();
    map.put("input", ((RexSlot) node).getIndex());
    map.put("name", ((RexSlot) node).getName());
    return map;
  case LOCAL_REF:
    map = jsonBuilder.map();
    map.put("input", ((RexSlot) node).getIndex());
    map.put("name", ((RexSlot) node).getName());
    map.put("type", toJson(node.getType()));
    return map;
  case CORREL_VARIABLE:
    map = jsonBuilder.map();
    map.put("correl", ((RexCorrelVariable) node).getName());
    map.put("type", toJson(node.getType()));
    return map;
  default:
    if (node instanceof RexCall) {
      final RexCall call = (RexCall) node;
      map = jsonBuilder.map();
      map.put("op", toJson(call.getOperator()));
      final List<Object> list = jsonBuilder.list();
      for (RexNode operand : call.getOperands()) {
        list.add(toJson(operand));
      }
      map.put("operands", list);
      switch (node.getKind()) {
      case CAST:
        map.put("type", toJson(node.getType()));
      }
      if (call.getOperator() instanceof SqlFunction) {
        if (((SqlFunction) call.getOperator()).getFunctionType().isUserDefined()) {
          SqlOperator op = call.getOperator();
          map.put("class", op.getClass().getName());
          map.put("type", toJson(node.getType()));
          map.put("deterministic", op.isDeterministic());
          map.put("dynamic", op.isDynamicFunction());
        }
      }
      if (call instanceof RexOver) {
        RexOver over = (RexOver) call;
        map.put("distinct", over.isDistinct());
        map.put("type", toJson(node.getType()));
        map.put("window", toJson(over.getWindow()));
      }
      return map;
    }
    throw new UnsupportedOperationException("unknown rex " + node);
  }
}
 
Example #29
Source File: RelOptUtil.java    From Bats with Apache License 2.0 4 votes vote down vote up
/** Predicate for whether a {@link Filter} contains multisets or windowed
 * aggregates. */
public static boolean containsMultisetOrWindowedAgg(Filter filter) {
    return !(B && RexMultisetUtil.containsMultiset(filter.getCondition(), true)
            || RexOver.containsOver(filter.getCondition()));
}
 
Example #30
Source File: RexFactoryImpl.java    From Bats with Apache License 2.0 4 votes vote down vote up
@Override
public RexOver makeOver(RelDataType type, SqlAggFunction op, List<RexNode> operands, RexWindow window,
        boolean distinct) {
    return new RexOverImpl(type, op, operands, window, distinct);
}