This is an automated email from the ASF dual-hosted git repository.

mihaibudiu pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/calcite.git


The following commit(s) were added to refs/heads/main by this push:
     new 7d72586c79 [CALCITE-7933] Correlated subqueries with lambdas that 
capture columns are incorrectly compiled
7d72586c79 is described below

commit 7d72586c79c2288ee6ddb09f94e11ca8124d6bac
Author: Mihai Budiu <[email protected]>
AuthorDate: Wed Nov 11 17:14:32 2026 -0800

    [CALCITE-7933] Correlated subqueries with lambdas that capture columns are 
incorrectly compiled
    
    This commit contains multiple small changes and fixes related to lambdas:
    
    SqlToRelConverter:
    - Allow a lambda in a sub-query to read a column of the enclosing query.
    - A lambda in an aggregate gave wrong results or an out-of-bounds
      error; now it should work correctly.
    
    CorrelateProjectExtractor:
    - does not move an expression that reads a parameter out of the lambda.
    
    EnumUtils:
    - In the generated Java code the parameters of the generated code are final.
    Before, Janino rejected the generated code.
    
    Validator:
    - Reject lambda which have subquries in the body. This is in line
      with all major SQL dialects which support lambdas.
    - Reject lambdas which invoke an aggregate function, GROUPING, or a
      windowed aggregate.
    - Reject a lambda in the ORDER BY clause which attempts to read
      columns (this used to crash; support can be added later if desired)
    - SqlLambdaScope.isParameter checks the first name of a compound
      identifier, such as r.f0. Before, it failed with an AssertionError.
    
    Signed-off-by: Mihai Budiu <[email protected]>
---
 core/src/main/codegen/templates/Parser.jj          |   3 +-
 .../calcite/adapter/enumerable/EnumUtils.java      |   6 +-
 .../apache/calcite/runtime/CalciteResource.java    |  12 +
 .../calcite/sql/validate/SqlLambdaScope.java       |   5 +-
 .../calcite/sql/validate/SqlValidatorImpl.java     |  55 ++++
 .../calcite/sql2rel/CorrelateProjectExtractor.java |   6 +
 .../apache/calcite/sql2rel/SqlToRelConverter.java  |  23 +-
 .../calcite/runtime/CalciteResource.properties     |   4 +
 .../sql2rel/CorrelateProjectExtractorTest.java     |  51 ++++
 .../apache/calcite/test/SqlToRelConverterTest.java |  16 ++
 .../org/apache/calcite/test/SqlValidatorTest.java  | 170 ++++++++++++
 .../apache/calcite/test/SqlToRelConverterTest.xml  |  20 ++
 core/src/test/resources/sql/lambda.iq              | 288 +++++++++++++++++++++
 .../apache/calcite/sql/parser/SqlParserTest.java   |   8 +
 14 files changed, 653 insertions(+), 14 deletions(-)

diff --git a/core/src/main/codegen/templates/Parser.jj 
b/core/src/main/codegen/templates/Parser.jj
index 97dcd738e5..0055f947cd 100644
--- a/core/src/main/codegen/templates/Parser.jj
+++ b/core/src/main/codegen/templates/Parser.jj
@@ -4800,7 +4800,8 @@ SqlNode LambdaExpression() :
 {
     parameters = SimpleIdentifierOrListOrEmpty()
     <LAMBDA> { s = span(); }
-    expression = Expression(ExprContext.ACCEPT_NON_QUERY)
+    // The validator rejects sub-queries in the body
+    expression = Expression(ExprContext.ACCEPT_SUB_QUERY)
     {
         return new SqlLambda(s.end(this), parameters, expression);
     }
diff --git 
a/core/src/main/java/org/apache/calcite/adapter/enumerable/EnumUtils.java 
b/core/src/main/java/org/apache/calcite/adapter/enumerable/EnumUtils.java
index 3711de36b8..8c4a41345c 100644
--- a/core/src/main/java/org/apache/calcite/adapter/enumerable/EnumUtils.java
+++ b/core/src/main/java/org/apache/calcite/adapter/enumerable/EnumUtils.java
@@ -1014,9 +1014,11 @@ static Expression generatePredicate(
       boolean nullable) {
     final BlockBuilder builder = new BlockBuilder();
     final ParameterExpression left_ =
-        Expressions.parameter(leftPhysType.getJavaRowType(), "left");
+        Expressions.parameter(Modifier.FINAL,
+            leftPhysType.getJavaRowType(), "left");
     final ParameterExpression right_ =
-        Expressions.parameter(rightPhysType.getJavaRowType(), "right");
+        Expressions.parameter(Modifier.FINAL,
+            rightPhysType.getJavaRowType(), "right");
     final RexProgramBuilder program =
         new RexProgramBuilder(
             implementor.getTypeFactory().builder()
diff --git a/core/src/main/java/org/apache/calcite/runtime/CalciteResource.java 
b/core/src/main/java/org/apache/calcite/runtime/CalciteResource.java
index e89a0882be..cd9e834d58 100644
--- a/core/src/main/java/org/apache/calcite/runtime/CalciteResource.java
+++ b/core/src/main/java/org/apache/calcite/runtime/CalciteResource.java
@@ -285,6 +285,18 @@ ExInst<SqlValidatorException> 
paramNotFoundInFunctionDidYouMean(String a0,
   @BaseMessage("Duplicate lambda parameter ''{0}''")
   ExInst<SqlValidatorException> duplicateLambdaParameter(String paramName);
 
+  @BaseMessage("Sub-query is illegal in lambda expression")
+  ExInst<SqlValidatorException> subQueryIllegalInLambda();
+
+  @BaseMessage("Aggregate expression is illegal in lambda expression")
+  ExInst<SqlValidatorException> aggregateIllegalInLambda();
+
+  @BaseMessage("Windowed aggregate expression is illegal in lambda expression")
+  ExInst<SqlValidatorException> windowedAggregateIllegalInLambda();
+
+  @BaseMessage("Lambda expression in ORDER BY clause can read only lambda 
parameters")
+  ExInst<SqlValidatorException> lambdaInOrderByCanReadOnlyParameters();
+
   @BaseMessage("Operand {0} must be a query")
   ExInst<SqlValidatorException> needQueryOp(String a0);
 
diff --git 
a/core/src/main/java/org/apache/calcite/sql/validate/SqlLambdaScope.java 
b/core/src/main/java/org/apache/calcite/sql/validate/SqlLambdaScope.java
index a4ba93d56a..96cb1095ec 100644
--- a/core/src/main/java/org/apache/calcite/sql/validate/SqlLambdaScope.java
+++ b/core/src/main/java/org/apache/calcite/sql/validate/SqlLambdaScope.java
@@ -49,10 +49,11 @@ public SqlLambdaScope(
     lambdaExpr.getParameters().forEach(param -> 
parameterTypes.put(param.toString(), any));
   }
 
-  /** True if the identifier matches one of the parameter names. */
+  /** True if the identifier matches one of the parameter names. In a
+   * compound identifier such as 'x.name', checks the first component. */
   public boolean isParameter(SqlIdentifier id) {
     final SqlNameMatcher nameMatcher = validator.catalogReader.nameMatcher();
-    final String name = id.getSimple();
+    final String name = id.names.get(0);
     return parameterTypes.keySet().stream()
         .anyMatch(paramName -> nameMatcher.matches(paramName, name));
   }
diff --git 
a/core/src/main/java/org/apache/calcite/sql/validate/SqlValidatorImpl.java 
b/core/src/main/java/org/apache/calcite/sql/validate/SqlValidatorImpl.java
index 5161ee8c1e..aa9cfd3d85 100644
--- a/core/src/main/java/org/apache/calcite/sql/validate/SqlValidatorImpl.java
+++ b/core/src/main/java/org/apache/calcite/sql/validate/SqlValidatorImpl.java
@@ -169,6 +169,7 @@
 import java.util.TreeSet;
 import java.util.function.BiFunction;
 import java.util.function.Consumer;
+import java.util.function.Predicate;
 import java.util.function.Supplier;
 import java.util.function.UnaryOperator;
 import java.util.stream.Collectors;
@@ -3425,6 +3426,28 @@ protected void registerQuery(
         true);
   }
 
+  /** Returns the first call in an expression that matches a predicate,
+   * or null; does not look into sub-queries. */
+  private static @Nullable SqlCall findCallOutsideQueries(SqlNode node,
+      Predicate<SqlCall> predicate) {
+    try {
+      node.accept(new SqlBasicVisitor<Void>() {
+        @Override public @Nullable Void visit(SqlCall call) {
+          if (predicate.test(call)) {
+            throw new Util.FoundOne(call);
+          }
+          if (call.isA(SqlKind.QUERY)) {
+            return null;
+          }
+          return super.visit(call);
+        }
+      });
+      return null;
+    } catch (Util.FoundOne e) {
+      return (SqlCall) requireNonNull(e.getNode());
+    }
+  }
+
   /**
    * Registers a query in a parent scope.
    *
@@ -3595,6 +3618,13 @@ private void registerQuery(
           alias,
           lambdaNamespace,
           forceNullable);
+      // Reject sub-queries before they are registered and validated
+      final SqlCall query =
+          findCallOutsideQueries(((SqlLambda) call).getExpression(),
+              c -> c.isA(SqlKind.QUERY));
+      if (query != null) {
+        throw newValidationError(query, RESOURCE.subQueryIllegalInLambda());
+      }
       // Register sub-queries inside the body under lambdaScope, so that
       // nested lambdas can resolve outer lambda parameters.
       registerOperandSubQueries(lambdaScope, call, 1);
@@ -7631,6 +7661,18 @@ public void setOriginal(SqlNode expr, SqlNode original) {
       }
     }
 
+    // A lambda body is evaluated for each element, not for a group of rows
+    final SqlCall agg =
+        findCallOutsideQueries(lambdaExpr.getExpression(),
+            call -> call.getKind() == SqlKind.OVER
+                || call.getOperator().isAggregator());
+    if (agg != null) {
+      throw newValidationError(agg,
+          agg.getKind() == SqlKind.OVER
+              ? RESOURCE.windowedAggregateIllegalInLambda()
+              : RESOURCE.aggregateIllegalInLambda());
+    }
+
     deriveType(scope, lambdaExpr.getExpression());
     RelDataType type = deriveTypeImpl(scope, lambdaExpr);
     setValidatedNodeType(lambdaExpr, type);
@@ -9010,6 +9052,19 @@ private SqlNode nthSelectItem(int ordinal, final 
SqlParserPos pos) {
     }
 
     @Override public SqlNode visit(SqlIdentifier id) {
+      // A lambda can read only parameters; an expanded copy of a lambda
+      // has no scope. A parameter can have the same name as a select item.
+      if (getScope() instanceof SqlLambdaScope) {
+        for (SqlValidatorScope s = getScope(); s instanceof SqlLambdaScope;
+            s = ((SqlLambdaScope) s).getParent()) {
+          if (((SqlLambdaScope) s).isParameter(id)) {
+            return id;
+          }
+        }
+        throw newValidationError(id,
+            RESOURCE.lambdaInOrderByCanReadOnlyParameters());
+      }
+
       // Aliases, e.g. 'select a as x, b from t order by x'.
       if (id.isSimple()
           && config.conformance().isSortByAlias()) {
diff --git 
a/core/src/main/java/org/apache/calcite/sql2rel/CorrelateProjectExtractor.java 
b/core/src/main/java/org/apache/calcite/sql2rel/CorrelateProjectExtractor.java
index a0c4747d2e..edb6efdb25 100644
--- 
a/core/src/main/java/org/apache/calcite/sql2rel/CorrelateProjectExtractor.java
+++ 
b/core/src/main/java/org/apache/calcite/sql2rel/CorrelateProjectExtractor.java
@@ -28,6 +28,7 @@
 import org.apache.calcite.rex.RexCorrelVariable;
 import org.apache.calcite.rex.RexFieldAccess;
 import org.apache.calcite.rex.RexInputRef;
+import org.apache.calcite.rex.RexLambdaRef;
 import org.apache.calcite.rex.RexLocalRef;
 import org.apache.calcite.rex.RexNode;
 import org.apache.calcite.rex.RexOver;
@@ -361,6 +362,11 @@ private SimpleCorrelationDetector(CorrelationId corrId) {
       return Boolean.FALSE;
     }
 
+    @Override public Boolean visitLambdaRef(RexLambdaRef lambdaRef) {
+      // A lambda parameter has a value only inside its lambda
+      return Boolean.FALSE;
+    }
+
     @Override public Boolean visitPatternFieldRef(RexPatternFieldRef fieldRef) 
{
       return Boolean.FALSE;
     }
diff --git 
a/core/src/main/java/org/apache/calcite/sql2rel/SqlToRelConverter.java 
b/core/src/main/java/org/apache/calcite/sql2rel/SqlToRelConverter.java
index 83b2341e4d..649441ed02 100644
--- a/core/src/main/java/org/apache/calcite/sql2rel/SqlToRelConverter.java
+++ b/core/src/main/java/org/apache/calcite/sql2rel/SqlToRelConverter.java
@@ -2587,7 +2587,11 @@ private RexNode convertLambda(Blackboard bb, SqlNode 
node) {
     }
 
     final Blackboard lambdaBb = createBlackboard(scope, nameToNodeMap, false);
-    lambdaBb.setRoot(castNonNull(bb.inputs));
+    lambdaBb.setRoot(castNonNull(bb.inputs), bb.root, false);
+    lambdaBb.inputScope = bb.inputScope;
+    // In an aggregate query, a GROUP BY expression in the lambda reads the
+    // Aggregate result
+    lambdaBb.agg = bb.agg;
     replaceSubQueries(lambdaBb, call.getExpression(), 
RelOptUtil.Logic.TRUE_FALSE_UNKNOWN);
     final RexNode expr = lambdaBb.convertExpression(call.getExpression());
     return rexBuilder.makeLambdaCall(expr, parameters);
@@ -5832,6 +5836,13 @@ protected class Blackboard implements SqlRexContext, 
SqlVisitor<RexNode>,
      * statement.
      */
     public final SqlValidatorScope scope;
+
+    /**
+     * Scope of the query that owns {@link #inputs}. It is {@link #scope},
+     * except in the blackboard of a lambda, which has the inputs of the
+     * blackboard that contains the lambda.
+     */
+    SqlValidatorScope inputScope;
     private final @Nullable Map<String, RexNode> nameToNodeMap;
     public @Nullable RelNode root;
 
@@ -5903,6 +5914,7 @@ protected class Blackboard implements SqlRexContext, 
SqlVisitor<RexNode>,
     protected Blackboard(@Nullable SqlValidatorScope scope,
         @Nullable Map<String, RexNode> nameToNodeMap, boolean top) {
       this.scope = requireNonNull(scope, "scope");
+      this.inputScope = this.scope;
       this.nameToNodeMap = nameToNodeMap;
       this.top = top;
     }
@@ -6150,14 +6162,7 @@ void setRoot(List<RelNode> inputs) {
       // We assume that the order of the from clause items has been
       // preserved.
       final SqlValidatorScope ancestorScope = resolve.scope;
-      boolean isParent = ancestorScope != scope;
-      // When in a lambda scope, external references to tables that are part
-      // of the current blackboard's inputs should be resolved locally, not
-      // as correlation variables. The lambda blackboard inherits inputs from
-      // its parent blackboard.
-      if (isParent && scope instanceof SqlLambdaScope && inputs != null) {
-        isParent = false;
-      }
+      final boolean isParent = ancestorScope != inputScope;
       if ((inputs != null) && !isParent) {
         // For a ListScope, use the row types of the scope's children, not the
         // leaves of the inputs: the leaves can include sub-queries that were
diff --git 
a/core/src/main/resources/org/apache/calcite/runtime/CalciteResource.properties 
b/core/src/main/resources/org/apache/calcite/runtime/CalciteResource.properties
index 09f1053fb8..3a6fe80fd6 100644
--- 
a/core/src/main/resources/org/apache/calcite/runtime/CalciteResource.properties
+++ 
b/core/src/main/resources/org/apache/calcite/runtime/CalciteResource.properties
@@ -416,4 +416,8 @@ DescriptorMustBeIdentifier=The argument of DESCRIPTOR must 
be an identifier
 MeasureAliasDuplicate=Duplicate name ''{0}'' in MATCH_RECOGNIZE MEASURE alias 
list
 LambdaClosureNotAllowed=Lambda closure is not allowed in this conformance: 
reference to ''{0}'' from enclosing scope
 DuplicateLambdaParameter=Duplicate lambda parameter ''{0}''
+SubQueryIllegalInLambda=Sub-query is illegal in lambda expression
+AggregateIllegalInLambda=Aggregate expression is illegal in lambda expression
+WindowedAggregateIllegalInLambda=Windowed aggregate expression is illegal in 
lambda expression
+LambdaInOrderByCanReadOnlyParameters=Lambda expression in ORDER BY clause can 
read only lambda parameters
 # End CalciteResource.properties
diff --git 
a/core/src/test/java/org/apache/calcite/sql2rel/CorrelateProjectExtractorTest.java
 
b/core/src/test/java/org/apache/calcite/sql2rel/CorrelateProjectExtractorTest.java
index da0a17296b..b9ff6273cc 100644
--- 
a/core/src/test/java/org/apache/calcite/sql2rel/CorrelateProjectExtractorTest.java
+++ 
b/core/src/test/java/org/apache/calcite/sql2rel/CorrelateProjectExtractorTest.java
@@ -21,14 +21,19 @@
 import org.apache.calcite.rel.core.JoinRelType;
 import org.apache.calcite.rel.core.RelFactories;
 import org.apache.calcite.rex.RexCorrelVariable;
+import org.apache.calcite.rex.RexLambdaRef;
 import org.apache.calcite.schema.SchemaPlus;
+import org.apache.calcite.sql.fun.SqlLibraryOperators;
 import org.apache.calcite.sql.fun.SqlStdOperatorTable;
 import org.apache.calcite.sql.parser.SqlParser;
+import org.apache.calcite.sql.type.SqlTypeName;
 import org.apache.calcite.test.CalciteAssert;
 import org.apache.calcite.tools.Frameworks;
 import org.apache.calcite.tools.RelBuilder;
 import org.apache.calcite.util.Holder;
 
+import com.google.common.collect.ImmutableList;
+
 import org.checkerframework.checker.nullness.qual.Nullable;
 import org.junit.jupiter.api.Test;
 
@@ -202,4 +207,50 @@ public static Frameworks.ConfigBuilder config() {
         + "      LogicalTableScan(table=[[scott, DEPT]])\n";
     assertThat(after, hasTree(planAfter));
   }
+
+  /** Test case for <a 
href="https://issues.apache.org/jira/browse/CALCITE-7933";>[CALCITE-7933]
+   * Correlated subqueries with lambdas that capture columns are incorrectly
+   * compiled</a>. */
+  @Test void testCorrelationCallInLambdaInFilter() {
+    final RelBuilder builder = RelBuilder.create(config().build());
+    final Holder<@Nullable RexCorrelVariable> v = Holder.empty();
+    final RexLambdaRef e =
+        new RexLambdaRef(0, "E",
+            builder.getTypeFactory().createSqlType(SqlTypeName.INTEGER));
+    RelNode before = builder.scan("EMP")
+        .variable(v::set)
+        .scan("DEPT")
+        .filter(
+            builder.call(SqlLibraryOperators.EXISTS,
+                builder.call(SqlStdOperatorTable.ARRAY_VALUE_CONSTRUCTOR,
+                    builder.field(0)),
+                builder.getRexBuilder().makeLambdaCall(
+                    builder.equals(e,
+                        builder.call(SqlStdOperatorTable.PLUS,
+                            builder.literal(10),
+                            builder.field(v.get(), "DEPTNO"))),
+                    ImmutableList.of(e))))
+        .correlate(JoinRelType.LEFT, v.get().id, builder.field(2, 0, "DEPTNO"))
+        .build();
+
+    final String planBefore = ""
+        + "LogicalCorrelate(correlation=[$cor0], joinType=[left], 
requiredColumns=[{7}])\n"
+        + "  LogicalTableScan(table=[[scott, EMP]])\n"
+        + "  LogicalFilter(condition=[EXISTS(ARRAY($0), (E) -> =(E, +(10, 
$cor0.DEPTNO)))])\n"
+        + "    LogicalTableScan(table=[[scott, DEPT]])\n";
+    assertThat(before, hasTree(planBefore));
+
+    RelNode after = before.accept(new 
CorrelateProjectExtractor(RelFactories.LOGICAL_BUILDER));
+    final String planAfter = ""
+        + "LogicalProject(EMPNO=[$0], ENAME=[$1], JOB=[$2], MGR=[$3], 
HIREDATE=[$4], SAL=[$5], COMM=[$6], DEPTNO=[$7], DEPTNO0=[$9], DNAME=[$10], 
LOC=[$11])\n"
+        + "  LogicalCorrelate(correlation=[$cor0], joinType=[left], 
requiredColumns=[{8}])\n"
+        // The call 10 + $cor0.DEPTNO moves to the left input as $f8
+        + "    LogicalProject(EMPNO=[$0], ENAME=[$1], JOB=[$2], MGR=[$3], 
HIREDATE=[$4], SAL=[$5], COMM=[$6], DEPTNO=[$7], $f8=[+(10, $7)])\n"
+        + "      LogicalTableScan(table=[[scott, EMP]])\n"
+        // The comparison reads the lambda parameter E, so it stays in the
+        // lambda; E has a value only inside the lambda
+        + "    LogicalFilter(condition=[EXISTS(ARRAY($0), (E) -> =(E, 
$cor0.$f8))])\n"
+        + "      LogicalTableScan(table=[[scott, DEPT]])\n";
+    assertThat(after, hasTree(planAfter));
+  }
 }
diff --git 
a/core/src/test/java/org/apache/calcite/test/SqlToRelConverterTest.java 
b/core/src/test/java/org/apache/calcite/test/SqlToRelConverterTest.java
index d34314f709..2f46ffd7c0 100644
--- a/core/src/test/java/org/apache/calcite/test/SqlToRelConverterTest.java
+++ b/core/src/test/java/org/apache/calcite/test/SqlToRelConverterTest.java
@@ -383,6 +383,22 @@ public static void checkActualAndReferenceFiles() {
         .ok();
   }
 
+  /** Test case for <a 
href="https://issues.apache.org/jira/browse/CALCITE-7933";>[CALCITE-7933]
+   * Correlated subqueries with lambdas that capture columns are incorrectly
+   * compiled</a>. */
+  @Test void testLambdaInSubQueryReadsEnclosingColumn() {
+    final String sql = "select t.x,\n"
+        + "  (select count(*) from (values (5, array[1, 5])) as s(y, b)\n"
+        + "   where \"EXISTS\"(s.b, e -> e = t.x)) as c\n"
+        + "from (values (1), (7)) as t(x)";
+    fixture()
+        .withFactory(c ->
+            c.withOperatorTable(t -> 
SqlValidatorTest.operatorTableFor(SqlLibrary.SPARK)))
+        .withSql(sql)
+        .withDecorrelate(false)
+        .ok();
+  }
+
   @Test void testDotLiteralAfterRow() {
     final String sql = "select row(1,2).\"EXPR$1\" from emp";
     sql(sql).ok();
diff --git a/core/src/test/java/org/apache/calcite/test/SqlValidatorTest.java 
b/core/src/test/java/org/apache/calcite/test/SqlValidatorTest.java
index 2cad0239cc..bddf3d4313 100644
--- a/core/src/test/java/org/apache/calcite/test/SqlValidatorTest.java
+++ b/core/src/test/java/org/apache/calcite/test/SqlValidatorTest.java
@@ -9319,6 +9319,176 @@ void 
testOrderByAliasPreservesValidatedExpressions(String query) {
             + "reference to 'X' from enclosing scope");
   }
 
+  /** Test case for
+   * <a 
href="https://issues.apache.org/jira/browse/CALCITE-7933";>[CALCITE-7933]
+   * Correlated subqueries with lambdas that capture columns are incorrectly
+   * compiled</a>. A lambda body is evaluated for each element of an array,
+   * so it cannot contain an aggregate or a windowed aggregate. */
+  @Test void testAggregateInLambda() {
+    final SqlValidatorFixture s = fixture()
+        .withOperatorTable(operatorTableFor(SqlLibrary.SPARK));
+    final String aggError =
+        "Aggregate expression is illegal in lambda expression";
+    s.withSql("select \"EXISTS\"(array[1, 2], e -> e = ^max(deptno)^)\n"
+            + "from emp")
+        .fails(aggError);
+    s.withSql("select deptno,\n"
+            + "  \"EXISTS\"(array[1, 2], e -> e = ^grouping(deptno)^)\n"
+            + "from emp group by deptno")
+        .fails(aggError);
+    s.withSql("select deptno from emp group by deptno\n"
+            + "having \"EXISTS\"(array[1, 2], e -> e = ^count(*)^)")
+        .fails(aggError);
+    // The aggregate is in the inner lambda of a nested lambda
+    s.withSql("select \"EXISTS\"(array[1, 2],\n"
+            + "  e -> \"EXISTS\"(array[3], f -> f = ^min(deptno)^))\n"
+            + "from emp")
+        .fails(aggError);
+    s.withSql("select \"EXISTS\"(array[1, 2],\n"
+            + "  e -> e = ^sum(deptno) over ()^)\n"
+            + "from emp")
+        .fails("Windowed aggregate expression is illegal in lambda 
expression");
+
+    // The lambda is in the argument of an aggregate
+    s.withSql("select max(\"EXISTS\"(array[deptno], e -> e = empno)) from emp")
+        .ok();
+    // In an aggregate query, the parameter is a row, and the lambda reads
+    // one of its fields
+    s.withSql("select deptno,\n"
+            + "  \"EXISTS\"(array[row(1, 2)], r -> r.expr$0 = 1)\n"
+            + "from emp group by deptno")
+        .ok();
+  }
+
+  /** Test case for
+   * <a 
href="https://issues.apache.org/jira/browse/CALCITE-7933";>[CALCITE-7933]
+   * Correlated subqueries with lambdas that capture columns are incorrectly
+   * compiled</a>. A lambda body cannot contain a sub-query. */
+  @Test void testSubQueryInLambda() {
+    final SqlValidatorFixture s = fixture()
+        .withOperatorTable(operatorTableFor(SqlLibrary.SPARK));
+    final String error = "Sub-query is illegal in lambda expression";
+    s.withSql("select \"EXISTS\"(array[1, 2],\n"
+            + "  e -> e = ^(select max(deptno) from dept)^)\n"
+            + "from emp")
+        .fails(error);
+    s.withSql("select \"EXISTS\"(array[1, 2],\n"
+            + "  e -> e in (^select deptno from dept^))\n"
+            + "from emp")
+        .fails(error);
+    s.withSql("select \"EXISTS\"(array[1, 2],\n"
+            + "  e -> e in (^select deptno from dept union select 1^))\n"
+            + "from emp")
+        .fails(error);
+    // The sub-query reads the lambda parameter
+    s.withSql("select \"EXISTS\"(array[1, 2],\n"
+            + "  e -> exists ^(select 1 from dept where deptno = e)^)\n"
+            + "from emp")
+        .fails(error);
+    s.withSql("select \"EXISTS\"(array[1, 2],\n"
+            + "  e -> ^(select count(*) from dept where deptno = e)^ = 2)\n"
+            + "from emp")
+        .fails(error);
+    // The sub-query reads a column of the enclosing query
+    s.withSql("select \"EXISTS\"(array[1, 2],\n"
+            + "  e -> e = ^(select max(deptno) from dept"
+            + " where deptno <= emp.deptno)^)\n"
+            + "from emp")
+        .fails(error);
+    // The sub-query is in the array argument of the inner lambda
+    s.withSql("select \"EXISTS\"(array[1, 2],\n"
+            + "  e -> \"EXISTS\"(array(^select deptno from dept^), f -> f = 
e))\n"
+            + "from emp")
+        .fails(error);
+    s.withSql("select empno from emp\n"
+            + "order by \"EXISTS\"(array[1, 2],"
+            + " e -> e in (^select deptno from dept^))")
+        .fails(error);
+
+    // The sub-query is in the array argument, not in the lambda body
+    s.withSql("select \"EXISTS\"(array(select deptno from dept), e -> e = 
10)\n"
+            + "from emp")
+        .ok();
+    // The lambda is in a sub-query
+    s.withSql("select (select count(*) from dept\n"
+            + "  where \"EXISTS\"(array[deptno], e -> e = emp.deptno))\n"
+            + "from emp")
+        .ok();
+  }
+
+  /** Test case for
+   * <a 
href="https://issues.apache.org/jira/browse/CALCITE-7933";>[CALCITE-7933]
+   * Correlated subqueries with lambdas that capture columns are incorrectly
+   * compiled</a>. A lambda in an ORDER BY item can read only lambda
+   * parameters, but a lambda in a select item that ORDER BY references
+   * can read columns. */
+  @Test void testLambdaInOrderBy() {
+    final SqlValidatorFixture s = fixture()
+        .withOperatorTable(operatorTableFor(SqlLibrary.SPARK));
+    final String error =
+        "Lambda expression in ORDER BY clause can read only lambda parameters";
+    s.withSql("select empno from emp\n"
+            + "order by \"EXISTS\"(array[1, 2], e -> e = ^deptno^)")
+        .fails(error);
+    s.withSql("select empno from emp\n"
+            + "order by \"EXISTS\"(array[1, 2], e -> e = ^emp.deptno^)")
+        .fails(error);
+    // The lambda reads a select item by alias
+    s.withSql("select empno as x from emp\n"
+            + "order by \"EXISTS\"(array[1, 2], e -> e = ^x^)")
+        .fails(error);
+    // The inner lambda reads a column
+    s.withSql("select empno from emp\n"
+            + "order by \"EXISTS\"(array[array[1]],"
+            + " a -> \"EXISTS\"(a, e -> e = ^deptno^))")
+        .fails(error);
+    s.withSql("select deptno from emp group by deptno\n"
+            + "order by \"EXISTS\"(array[1, 2], e -> e = ^deptno^)")
+        .fails(error);
+    s.withSql("select empno from emp union all select deptno from dept\n"
+            + "order by \"EXISTS\"(array[1, 2], e -> e = ^empno^)")
+        .fails(error);
+
+    // The lambda reads only its parameter
+    s.withSql("select empno from emp\n"
+            + "order by \"EXISTS\"(array[1, 2], e -> e = 1) desc")
+        .ok();
+    // The parameter has the same name as a select item
+    s.withSql("select empno as e from emp\n"
+            + "order by \"EXISTS\"(array[1, 2], e -> e = 1)")
+        .ok();
+    // The parameter is a row, and the lambda reads one of its fields
+    s.withSql("select empno from emp\n"
+            + "order by \"EXISTS\"(array[row(1, 2)], r -> r.expr$0 = 1)")
+        .ok();
+    // The inner lambda reads a parameter of the outer lambda
+    s.withSql("select empno from emp\n"
+            + "order by \"EXISTS\"(array[array[1]],"
+            + " a -> \"EXISTS\"(a, e -> e = cardinality(a)))")
+        .ok();
+    // The array argument is a column; the lambda reads only its parameter
+    s.withSql("select empno from emp\n"
+            + "order by \"EXISTS\"(array[deptno], e -> e = 1)")
+        .ok();
+
+    // ORDER BY references a select item by alias, or by ordinal
+    s.withSql("select empno, \"EXISTS\"(array[1, 2], e -> e = deptno) as r\n"
+            + "from emp order by r")
+        .ok();
+    s.withSql("select empno, \"EXISTS\"(array[1, 2], e -> e = deptno) as r\n"
+            + "from emp order by 2")
+        .ok();
+    // The lambda is in a sub-query
+    s.withSql("select empno from emp\n"
+            + "order by (select \"EXISTS\"(array[1, 2], e -> e = emp.deptno))")
+        .ok();
+    // The lambda is in the ORDER BY of a window
+    s.withSql("select empno,\n"
+            + "  row_number() over (order by \"EXISTS\"(array[1, 2], e -> e = 
deptno))\n"
+            + "from emp")
+        .ok();
+  }
+
   /** Test case for
    * <a 
href="https://issues.apache.org/jira/browse/CALCITE-6242";>[CALCITE-6242]
    * Enhance lambda closure parsing</a>.
diff --git 
a/core/src/test/resources/org/apache/calcite/test/SqlToRelConverterTest.xml 
b/core/src/test/resources/org/apache/calcite/test/SqlToRelConverterTest.xml
index a374242839..ba71b11cc6 100644
--- a/core/src/test/resources/org/apache/calcite/test/SqlToRelConverterTest.xml
+++ b/core/src/test/resources/org/apache/calcite/test/SqlToRelConverterTest.xml
@@ -5567,6 +5567,26 @@ from (select ROW(deptno, sal) as r from emp) as t]]>
       <![CDATA[
 LogicalProject(EXPR$0=[EXISTS(ARRAY(1, 2), (X) -> =(X, ROW($7, $5).EXPR$0))])
   LogicalTableScan(table=[[CATALOG, SALES, EMP]])
+]]>
+    </Resource>
+  </TestCase>
+  <TestCase name="testLambdaInSubQueryReadsEnclosingColumn">
+    <Resource name="sql">
+      <![CDATA[select t.x,
+  (select count(*) from (values (5, array[1, 5])) as s(y, b)
+   where "EXISTS"(s.b, e -> e = t.x)) as c
+from (values (1), (7)) as t(x)]]>
+    </Resource>
+    <Resource name="plan">
+      <![CDATA[
+LogicalProject(X=[$0], C=[$1])
+  LogicalCorrelate(correlation=[$cor0], joinType=[left], requiredColumns=[{0}])
+    LogicalValues(tuples=[[{ 1 }, { 7 }]])
+    LogicalAggregate(group=[{}], EXPR$0=[COUNT()])
+      LogicalProject($f0=[0])
+        LogicalFilter(condition=[EXISTS($1, (E) -> =(E, $cor0.X))])
+          LogicalProject(Y=[5], B=[ARRAY(1, 5)])
+            LogicalValues(tuples=[[{ 0 }]])
 ]]>
     </Resource>
   </TestCase>
diff --git a/core/src/test/resources/sql/lambda.iq 
b/core/src/test/resources/sql/lambda.iq
index b51632ca82..693279fe28 100644
--- a/core/src/test/resources/sql/lambda.iq
+++ b/core/src/test/resources/sql/lambda.iq
@@ -271,3 +271,291 @@ from (select ROW(deptno, 1) as r from emp where ename = 
'Jane') as t;
 (1 row)
 
 !ok
+
+# [CALCITE-7933] Correlated subqueries with lambdas that capture columns are
+# incorrectly compiled
+#
+# The results of the tests in this section were validated with Spark 3.5.9
+# and DuckDB 2.0.0. Spark runs each query with array(...) for array[...].
+# In DuckDB, EXISTS(a, e -> p) is spark_exists(list_transform(a, lambda e: p)),
+# where the macro spark_exists has the rule of Spark: TRUE if one element
+# gives TRUE, else NULL if one element gives NULL, else FALSE.
+
+# The lambda in the WHERE clause of a scalar sub-query compares the array
+# elements with t.x of the enclosing query.
+# Result validated with Spark 3.5.9 and DuckDB 2.0.0.
+select (select count(*) from (values (array[1, 2])) as s(b)
+        where "EXISTS"(s.b, e -> e = t.x)) as c
+from (values (1)) as t(x);
++---+
+| C |
++---+
+| 1 |
++---+
+(1 row)
+
+!ok
+
+# Same, but the first column of the sub-query input has the type of t.x.
+# Result validated with Spark 3.5.9 and DuckDB 2.0.0.
+select t.x,
+  (select count(*) from (values (5, array[1, 5]), (6, array[1])) as s(y, b)
+   where "EXISTS"(s.b, e -> e = t.x)) as c
+from (values (1), (7)) as t(x);
++---+---+
+| X | C |
++---+---+
+| 1 | 2 |
+| 7 | 0 |
++---+---+
+(2 rows)
+
+!ok
+
+# The lambda is in the SELECT list of the sub-query.
+# Result validated with Spark 3.5.9 and DuckDB 2.0.0.
+select t.x,
+  (select "EXISTS"(s.b, e -> e = t.x) from (values (array[1, 5])) as s(b)) as c
+from (values (1), (7)) as t(x);
++---+-------+
+| X | C     |
++---+-------+
+| 1 | true  |
+| 7 | false |
++---+-------+
+(2 rows)
+
+!ok
+
+# The lambda references a column of the sub-query (s.y) and a column of the
+# enclosing query (t.x).
+# Result validated with Spark 3.5.9 and DuckDB 2.0.0.
+select t.x,
+  (select count(*) from (values (1, array[1, 5]), (4, array[1])) as s(y, b)
+   where "EXISTS"(s.b, e -> e = t.x + s.y)) as c
+from (values (0), (1)) as t(x);
++---+---+
+| X | C |
++---+---+
+| 0 | 1 |
+| 1 | 0 |
++---+---+
+(2 rows)
+
+!ok
+
+# The inner lambda of a nested lambda references a column of the enclosing
+# query.
+# Result validated with Spark 3.5.9 and DuckDB 2.0.0.
+select t.x,
+  (select count(*) from (values (array[1, 2])) as s(b)
+   where "EXISTS"(s.b, e -> "EXISTS"(array[3], f -> e + f = t.x))) as c
+from (values (4), (6)) as t(x);
++---+---+
+| X | C |
++---+---+
+| 4 | 1 |
+| 6 | 0 |
++---+---+
+(2 rows)
+
+!ok
+
+# The lambda is in a sub-query of a sub-query, and references a column of the
+# outermost query.
+# Result validated with DuckDB 2.0.0. Spark 3.5.9 rejects this query,
+# because it cannot resolve t.x two query levels up.
+select t.x,
+  (select count(*) from (values (10), (20)) as u(z)
+   where exists (select 1 from (values (array[1, 5])) as s(b)
+                 where "EXISTS"(s.b, e -> e = t.x))) as c
+from (values (1), (7)) as t(x);
++---+---+
+| X | C |
++---+---+
+| 1 | 2 |
+| 7 | 0 |
++---+---+
+(2 rows)
+
+!ok
+
+# The lambda is in a correlated EXISTS sub-query in the WHERE clause.
+# Result validated with Spark 3.5.9 and DuckDB 2.0.0.
+select t.x
+from (values (1), (7)) as t(x)
+where exists (select 1 from (values (array[1, 5])) as s(b)
+              where "EXISTS"(s.b, e -> e = t.x));
++---+
+| X |
++---+
+| 1 |
++---+
+(1 row)
+
+!ok
+
+# The lambda in a JOIN ON condition reads a column of the other input.
+# The inputs have more than one row, so the condition is not folded.
+# Result validated with Spark 3.5.9 and DuckDB 2.0.0.
+select *
+from (values (array[1, 2, 3]), (array[4])) as t1(arr)
+inner join (values (1), (4)) as t2(v) on "EXISTS"(arr, x -> x = t2.v);
++-----------+---+
+| ARR       | V |
++-----------+---+
+| [1, 2, 3] | 1 |
+| [4]       | 4 |
++-----------+---+
+(2 rows)
+
+!ok
+
+# The lambda is in the FROM clause, in a LATERAL sub-query, and references a
+# column of the preceding FROM item.
+# Result validated with Spark 3.5.9 and DuckDB 2.0.0.
+select *
+from (values (1), (5)) as b(v),
+  lateral (select "EXISTS"(array[1, 2], e -> e = b.v) as r
+           from (values (0)) as z(z));
++---+-------+
+| V | R     |
++---+-------+
+| 1 | true  |
+| 5 | false |
++---+-------+
+(2 rows)
+
+!ok
+
+# The lambda in the SELECT list of an aggregate query reads a GROUP BY
+# column. K2 is column 1 of the FROM clause, but column 0 of the
+# aggregate result.
+# Result validated with Spark 3.5.9 and DuckDB 2.0.0.
+select k2, k3, "EXISTS"(array[1, 2], e -> e = k2) as r
+from (values (0, 1, 5), (0, 1, 5), (0, 3, 2)) as t(k1, k2, k3)
+group by k2, k3;
++----+----+-------+
+| K2 | K3 | R     |
++----+----+-------+
+|  1 |  5 | true  |
+|  3 |  2 | false |
++----+----+-------+
+(2 rows)
+
+!ok
+
+# The aggregate result has only one column.
+# Result validated with Spark 3.5.9 and DuckDB 2.0.0.
+select k2, "EXISTS"(array[1, 2], e -> e = k2) as r
+from (values (0, 1), (0, 1), (0, 3)) as t(k1, k2)
+group by k2;
++----+-------+
+| K2 | R     |
++----+-------+
+|  1 | true  |
+|  3 | false |
++----+-------+
+(2 rows)
+
+!ok
+
+# The lambda in the HAVING clause reads a GROUP BY column.
+# Result validated with Spark 3.5.9 and DuckDB 2.0.0.
+select k2, count(*) as c
+from (values (0, 1, 5), (0, 1, 5), (0, 3, 2)) as t(k1, k2, k3)
+group by k2, k3
+having "EXISTS"(array[1, 2], e -> e = k3);
++----+---+
+| K2 | C |
++----+---+
+|  3 | 1 |
++----+---+
+(1 row)
+
+!ok
+
+# A nested lambda reads a GROUP BY column.
+# Result validated with Spark 3.5.9 and DuckDB 2.0.0.
+select k2,
+  "EXISTS"(array[array[1], array[4]], a -> "EXISTS"(a, e -> e = k2)) as r
+from (values (0, 1, 5), (0, 3, 2)) as t(k1, k2, k3)
+group by k2, k3;
++----+-------+
+| K2 | R     |
++----+-------+
+|  1 | true  |
+|  3 | false |
++----+-------+
+(2 rows)
+
+!ok
+
+# The lambda reads a GROUP BY expression.
+# Result validated with Spark 3.5.9 and DuckDB 2.0.0.
+select k2 + 1 as p, "EXISTS"(array[2, 3], e -> e = k2 + 1) as r
+from (values (0, 1, 5), (0, 3, 2)) as t(k1, k2, k3)
+group by k2 + 1;
++---+-------+
+| P | R     |
++---+-------+
+| 2 | true  |
+| 4 | false |
++---+-------+
+(2 rows)
+
+!ok
+
+# With ROLLUP, K3 is null in the subtotal rows.
+# Result validated with Spark 3.5.9 and DuckDB 2.0.0.
+select k2, k3, "EXISTS"(array[2], e -> e = k3) as r
+from (values (0, 1, 5), (0, 3, 2)) as t(k1, k2, k3)
+group by rollup(k2, k3);
++----+----+-------+
+| K2 | K3 | R     |
++----+----+-------+
+|  1 |  5 | false |
+|  1 |    |       |
+|  3 |  2 | true  |
+|  3 |    |       |
+|    |    |       |
++----+----+-------+
+(5 rows)
+
+!ok
+
+# A lambda in a sub-query reads a GROUP BY column of the enclosing query.
+# Result validated with DuckDB 2.0.0. Spark 3.5.9 rejects this query,
+# because a correlated scalar sub-query in an aggregate query must be in
+# GROUP BY or in an aggregate function.
+select k2,
+  (select count(*) from (values (array[1, 3]), (array[1])) as s(b)
+   where "EXISTS"(s.b, e -> e = t.k2)) as c
+from (values (0, 1, 5), (0, 1, 5), (0, 3, 2)) as t(k1, k2, k3)
+group by k2, k3;
++----+---+
+| K2 | C |
++----+---+
+|  1 | 2 |
+|  3 | 1 |
++----+---+
+(2 rows)
+
+!ok
+
+# A lambda in ORDER BY can read its parameter, but not a column.
+# The parameter E has the same name as a select item, and E in the
+# lambda is the parameter. The lambda reads the column A only through
+# its array argument.
+# Result validated with Spark 3.5.9 and DuckDB 2.0.0.
+select x as e from (values (1, array[1]), (3, array[2])) as t(x, a)
+order by "EXISTS"(a, e -> e = 2) desc, "EXISTS"(array[1, 2], e -> e = 1);
++---+
+| E |
++---+
+| 3 |
+| 1 |
++---+
+(2 rows)
+
+!ok
diff --git 
a/testkit/src/main/java/org/apache/calcite/sql/parser/SqlParserTest.java 
b/testkit/src/main/java/org/apache/calcite/sql/parser/SqlParserTest.java
index fb406c4f46..bfb5a898dc 100644
--- a/testkit/src/main/java/org/apache/calcite/sql/parser/SqlParserTest.java
+++ b/testkit/src/main/java/org/apache/calcite/sql/parser/SqlParserTest.java
@@ -10504,6 +10504,14 @@ private static Consumer<List<? extends Throwable>> 
checkWarnings(
     sql("select higher_order_func(x -> higher_order_func(y -> x + y, 1), 1) 
from t")
         .ok("SELECT `HIGHER_ORDER_FUNC`(`X` -> `HIGHER_ORDER_FUNC`(`Y` -> (`X` 
+ `Y`), 1), 1)\n"
             + "FROM `T`");
+
+    // The parser accepts a sub-query in any position of a lambda body
+    sql("select higher_order_func(x -> (select 1) = x, 1) from t")
+        .ok("SELECT `HIGHER_ORDER_FUNC`(`X` -> ((SELECT 1) = `X`), 1)\n"
+            + "FROM `T`");
+    sql("select higher_order_func(x -> exists (select 1), 1) from t")
+        .ok("SELECT `HIGHER_ORDER_FUNC`(`X` -> (EXISTS (SELECT 1)), 1)\n"
+            + "FROM `T`");
   }
 
   /**

Reply via email to