@Override public void onMatch(RelOptRuleCall call) { final LimitPrel limit = (LimitPrel) call.rel(0); final ExchangePrel exchangePrel = (ExchangePrel) call.rel(1); RelNode child = exchangePrel.getInput(); final int offset = limit.getOffset() != null ? Math.max(0, RexLiteral.intValue(limit.getOffset())) : 0; final int fetch = Math.max(0, RexLiteral.intValue(limit.getFetch())); // child Limit uses conservative approach: use offset 0 and fetch = parent limit offset + parent limit fetch. final RexNode childFetch = limit.getCluster().getRexBuilder().makeExactLiteral(BigDecimal.valueOf(offset + fetch)); final RelNode limitUnderExchange = new LimitPrel(child.getCluster(), child.getTraitSet(), child, null, childFetch); final RelNode newExch = exchangePrel.copy(exchangePrel.getTraitSet(), ImmutableList.of(limitUnderExchange)); final RelNode limitAboveExchange = new LimitPrel(limit.getCluster(), limit.getTraitSet(), newExch, limit.getOffset(), limit.getFetch(), true); call.transformTo(limitAboveExchange); }
@Override public void onMatch(RelOptRuleCall call) { final LimitPrel limit = call.rel(0); final SingleMergeExchangePrel smex = call.rel(1); final SortPrel sort = call.rel(2); // First offset to include into results (inclusive). Null implies it is starting from offset 0 int offset = limit.getOffset() != null ? Math.max(0, RexLiteral.intValue(limit.getOffset())) : 0; int fetch = Math.max(0, RexLiteral.intValue(limit.getFetch())); final TopNPrel topN = new TopNPrel(limit.getCluster(), sort.getTraitSet(), sort.getInput(), offset + fetch, sort.getCollation()); final LimitPrel newLimit = new LimitPrel(limit.getCluster(), limit.getTraitSet(), new SingleMergeExchangePrel(smex.getCluster(), smex.getTraitSet(), topN, sort.getCollation()), limit.getOffset(), limit.getFetch()); call.transformTo(newLimit); }