1818
1919import org .apache .calcite .linq4j .function .Experimental ;
2020import org .apache .calcite .plan .RelOptCostImpl ;
21+ import org .apache .calcite .plan .RelOptRule ;
2122import org .apache .calcite .plan .RelOptUtil ;
2223import org .apache .calcite .plan .Strong ;
2324import org .apache .calcite .plan .hep .HepPlanner ;
3536import org .apache .calcite .rel .core .SetOp ;
3637import org .apache .calcite .rel .core .Sort ;
3738import org .apache .calcite .rel .rules .CoreRules ;
39+ import org .apache .calcite .rel .rules .FilterProjectTransposeRule ;
3840import org .apache .calcite .rel .type .RelDataType ;
3941import org .apache .calcite .rex .RexCall ;
4042import org .apache .calcite .rex .RexCorrelVariable ;
@@ -196,10 +198,26 @@ private TopDownGeneralDecorrelator createSubDecorrelator() {
196198 * @return Equivalent node without correlation
197199 */
198200 public static RelNode decorrelateQuery (RelNode rel , RelBuilder builder ) {
201+ // Use a custom FILTER_PROJECT_TRANSPOSE that does not push filters through
202+ // projects containing V2M (measure) expressions. Pushing a filter past a
203+ // V2M-carrying project changes the scope of the measure computation and
204+ // produces incorrect aggregate results.
205+ RelOptRule filterProjectTransposeNoV2m =
206+ CoreRules .FILTER_PROJECT_TRANSPOSE .config
207+ .as (FilterProjectTransposeRule .Config .class )
208+ .withOperandSupplier (b0 ->
209+ b0 .operand (Filter .class )
210+ .predicate (f -> !RexUtil .containsCorrelation (f .getCondition ()))
211+ .oneInput (b1 ->
212+ b1 .operand (Project .class )
213+ .predicate (p -> !RexUtil .find (SqlKind .V2M ).inProject (p ))
214+ .anyInputs ()))
215+ .as (FilterProjectTransposeRule .Config .class )
216+ .toRule ();
199217 HepProgram preProgram = HepProgram .builder ()
200218 .addRuleCollection (
201219 ImmutableList .of (
202- CoreRules . FILTER_PROJECT_TRANSPOSE ,
220+ filterProjectTransposeNoV2m ,
203221 CoreRules .FILTER_INTO_JOIN ,
204222 CoreRules .FILTER_CORRELATE ))
205223 .build ();
@@ -226,7 +244,7 @@ public static RelNode decorrelateQuery(RelNode rel, RelBuilder builder) {
226244 HepProgram postProgram = HepProgram .builder ()
227245 .addRuleCollection (
228246 ImmutableList .of (
229- CoreRules . FILTER_PROJECT_TRANSPOSE ,
247+ filterProjectTransposeNoV2m ,
230248 CoreRules .FILTER_INTO_JOIN ,
231249 CoreRules .MARK_TO_SEMI_OR_ANTI_JOIN_RULE ,
232250 CoreRules .PROJECT_MERGE ,
0 commit comments