### Question:
TransformExistsApplyToCorrelatedJoin implements Rule<ApplyNode> { @Override public Result apply(ApplyNode parent, Captures captures, Context context) { if (parent.getSubqueryAssignments().size() != 1) { return Result.empty(); } Expression expression = getOnlyElement(parent.getSubqueryAssignments().getExpressions()); if (!(expression instanceof ExistsPredicate)) { return Result.empty(); } if (parent.getCorrelation().isEmpty()) { return Result.ofPlanNode(rewriteToDefaultAggregation(parent, context)); } Optional<PlanNode> nonDefaultAggregation = rewriteToNonDefaultAggregation(parent, context); return nonDefaultAggregation .map(Result::ofPlanNode) .orElseGet(() -> Result.ofPlanNode(rewriteToDefaultAggregation(parent, context))); } TransformExistsApplyToCorrelatedJoin(Metadata metadata); @Override Pattern<ApplyNode> getPattern(); @Override Result apply(ApplyNode parent, Captures captures, Context context);  }### Answer:
@Test public void testRewrite() { tester().assertThat(new TransformExistsApplyToCorrelatedJoin(tester().getMetadata())) .on(p -> p.apply( Assignments.of(p.symbol("b", BOOLEAN), expression("EXISTS(SELECT TRUE)")), ImmutableList.of(), p.values(), p.values())) .matches(correlatedJoin( ImmutableList.of(), values(ImmutableMap.of()), project( ImmutableMap.of("b", PlanMatchPattern.expression("(\"count_expr\" > CAST(0 AS bigint))")), aggregation(ImmutableMap.of("count_expr", functionCall("count", ImmutableList.of())), values())))); }
@Test public void testRewritesToLimit() { tester().assertThat(new TransformExistsApplyToCorrelatedJoin(tester().getMetadata())) .on(p -> p.apply( Assignments.of(p.symbol("b", BOOLEAN), expression("EXISTS(SELECT TRUE)")), ImmutableList.of(p.symbol("corr")), p.values(p.symbol("corr")), p.project(Assignments.of(), p.filter( expression("corr = column"), p.values(p.symbol("column")))))) .matches( project(ImmutableMap.of("b", PlanMatchPattern.expression("COALESCE(subquerytrue, false)")), correlatedJoin( ImmutableList.of("corr"), values("corr"), project( ImmutableMap.of("subquerytrue", PlanMatchPattern.expression("true")), limit(1, project(ImmutableMap.of(), node(FilterNode.class, values("column")))))))); }