### Question:
PruneApplySourceColumns implements Rule<ApplyNode> { @Override public Result apply(ApplyNode applyNode, Captures captures, Context context) { Set<Symbol> subqueryAssignmentsSymbols = applyNode.getSubqueryAssignments().getExpressions().stream() .flatMap(expression -> SymbolsExtractor.extractUnique(expression).stream()) .collect(toImmutableSet()); Optional<PlanNode> prunedSubquery = restrictOutputs(context.getIdAllocator(), applyNode.getSubquery(), subqueryAssignmentsSymbols); return prunedSubquery.map(subquery -> applyNode.replaceChildren(ImmutableList.of(applyNode.getInput(), subquery))) .map(Result::ofPlanNode) .orElse(Result.empty()); }  @Override Pattern<ApplyNode> getPattern(); @Override Result apply(ApplyNode applyNode, Captures captures, Context context);  }### Answer:
@Test public void testNotAllSubquerySymbolsReferenced() { tester().assertThat(new PruneApplySourceColumns()) .on(p -> { Symbol a = p.symbol("a"); Symbol subquerySymbol1 = p.symbol("subquery_symbol_1"); Symbol subquerySymbol2 = p.symbol("subquery_symbol_2"); Symbol inResult = p.symbol("in_result"); return p.apply( Assignments.of(inResult, new InPredicate(a.toSymbolReference(), subquerySymbol1.toSymbolReference())), ImmutableList.of(), p.values(a), p.values(subquerySymbol1, subquerySymbol2)); }) .matches( apply( ImmutableList.of(), ImmutableMap.of("in_result", ExpressionMatcher.inPredicate(new SymbolReference("a"), new SymbolReference("subquery_symbol_1"))), values("a"), project( ImmutableMap.of("subquery_symbol_1", PlanMatchPattern.expression("subquery_symbol_1")), values("subquery_symbol_1", "subquery_symbol_2")))); }
@Test public void testAllSubquerySymbolsReferenced() { tester().assertThat(new PruneApplySourceColumns()) .on(p -> { Symbol a = p.symbol("a"); Symbol subquerySymbol1 = p.symbol("subquery_symbol_1"); Symbol subquerySymbol2 = p.symbol("subquery_symbol_2"); Symbol inResult1 = p.symbol("in_result_1"); Symbol inResult2 = p.symbol("in_result_2"); return p.apply( Assignments.of( inResult1, new InPredicate(a.toSymbolReference(), subquerySymbol1.toSymbolReference()), inResult2, new InPredicate(a.toSymbolReference(), subquerySymbol2.toSymbolReference())), ImmutableList.of(), p.values(a), p.values(subquerySymbol1, subquerySymbol2)); }) .doesNotFire(); }
@Test public void testNoSubquerySymbolsReferenced() { tester().assertThat(new PruneApplySourceColumns()) .on(p -> { Symbol a = p.symbol("a"); Symbol subquerySymbol = p.symbol("subquery_symbol"); Symbol inResult = p.symbol("in_result"); return p.apply( Assignments.of(inResult, new InPredicate(a.toSymbolReference(), a.toSymbolReference())), ImmutableList.of(), p.values(a), p.values(subquerySymbol)); }) .matches( apply( ImmutableList.of(), ImmutableMap.of("in_result", ExpressionMatcher.inPredicate(new SymbolReference("a"), new SymbolReference("a"))), values("a"), project( ImmutableMap.of(), values("subquery_symbol")))); }