Paul King created OPENJPA-3091:
----------------------------------

             Summary: JPQL set operations (UNION/INTERSECT/EXCEPT) lose their 
projection: typed queries fail, results come back as Object[], and re-running a 
query returns wrong results
                 Key: OPENJPA-3091
                 URL: https://issues.apache.org/jira/browse/OPENJPA-3091
             Project: OpenJPA
          Issue Type: Bug
          Components: jpa, kernel
    Affects Versions: 4.2.0
         Environment: OpenJPA 4.2.0, JDK 17.0.20, H2 2.5.252, entities enhanced 
at build time
            Reporter: Paul King


h3. Description

Jakarta Persistence 3.2 set operations in JPQL return the right rows, but their 
projection information is lost:

# *Typed queries fail.* {{em.createQuery("select a.name from Author a union 
select g.label from Gadget g", String.class).getResultList()}} throws:
{noformat}
<openjpa-4.2.0-r977f0cb nonfatal user error> 
org.apache.openjpa.persistence.ArgumentException: There is no conversion 
between query projection type "class repro.Author" and result type "class 
java.lang.String".
{noformat}
OpenJPA takes the projection type to be the root entity of the first operand, 
not the selected {{String}} path.
# *Untyped queries return the wrong shape.* The same query via 
{{em.createQuery(q).getResultList()}} returns each single-column row as an 
{{Object[]}} of length 1. The equivalent query without a set operation returns 
plain {{String}} values.
# *Running the same query again returns wrong results.* The second execution of 
a set-operation query goes through the prepared-SQL cache 
({{openjpa.jdbc.QuerySQLCache}}, on by default) and is treated as a query for 
instances of the first operand's entity. For example, {{select a.id, a.name 
from Author a union select g.id, g.label from Gadget g}} returns {{[1, Dierk], 
[1, widget]}} the first time and a single {{Author}} the second time. With 
{{QuerySQLCache=false}} both runs are correct.

This affects {{UNION}}, {{UNION ALL}}, {{INTERSECT}} and {{EXCEPT}}, whether 
the operands select from the same entity or from different ones.

h3. Steps to reproduce

Both entities are enhanced at build time with {{PCEnhancer}} before running.

{code:java|title=Author.java}
package repro;

import jakarta.persistence.*;

@Entity
public class Author {
    @Id @GeneratedValue
    private Long id;
    private String name;

    protected Author() { }
    public Author(String name) { this.name = name; }

    public Long getId() { return id; }
    public String getName() { return name; }
}
{code}

{code:java|title=Gadget.java}
package repro;

import jakarta.persistence.*;

@Entity
public class Gadget {
    @Id @GeneratedValue
    private Long id;
    private String label;

    protected Gadget() { }
    public Gadget(String label) { this.label = label; }

    public Long getId() { return id; }
    public String getLabel() { return label; }
}
{code}

{code:java|title=Repro.java}
package repro;

import jakarta.persistence.*;

final class Repro {
    private Repro() { }

    static EntityManagerFactory emf() {
        return new PersistenceConfiguration("repro")
            .provider("org.apache.openjpa.persistence.PersistenceProviderImpl")
            .managedClass(Author.class)
            .managedClass(Gadget.class)
            .property(PersistenceConfiguration.JDBC_DRIVER, "org.h2.Driver")
            .property(PersistenceConfiguration.JDBC_URL, 
"jdbc:h2:mem:repro;DB_CLOSE_DELAY=-1")
            .property("openjpa.jdbc.SynchronizeMappings", 
"buildSchema(ForeignKeys=true)")
            .property("openjpa.RuntimeUnenhancedClasses", "unsupported")
            .property("openjpa.Log", "DefaultLevel=WARN")
            .createEntityManagerFactory();
    }
}
{code}

{code:java|title=SetOperationRepro.java}
package repro;

import jakarta.persistence.*;
import java.util.Arrays;
import java.util.List;

public class SetOperationRepro {
    public static void main(String[] args) {
        try (EntityManagerFactory emf = Repro.emf()) {
            emf.runInTransaction(em -> {
                em.persist(new Author("Dierk"));
                em.persist(new Gadget("widget"));
            });
            String[] queries = {
                "select a.name from Author a union select g.label from Gadget 
g",
                "select a.name from Author a union all select a.name from 
Author a",
                "select a.name from Author a intersect select a.name from 
Author a",
                "select a.name from Author a except select g.label from Gadget 
g",
                "select a.name from Author a" // no set operation, for 
comparison
            };
            // the same multi-column set-operation query, run twice
            String twice = "select a.id, a.name from Author a union select 
g.id, g.label from Gadget g";
            try (EntityManager em = emf.createEntityManager()) {
                System.out.println(twice);
                System.out.println("  1st run: " + 
describe(em.createQuery(twice).getResultList()));
                System.out.println("  2nd run: " + 
describe(em.createQuery(twice).getResultList()));
            }
            try (EntityManager em = emf.createEntityManager()) {
                for (String q : queries) {
                    System.out.println(q);
                    try {
                        List<?> untyped = em.createQuery(q).getResultList();
                        System.out.println("  untyped: " + describe(untyped));
                    } catch (RuntimeException e) {
                        System.out.println("  untyped failed: " + e);
                    }
                    try {
                        List<String> typed = em.createQuery(q, 
String.class).getResultList();
                        System.out.println("  typed:   " + describe(typed));
                    } catch (RuntimeException e) {
                        System.out.println("  typed failed: " + e);
                    }
                }
            }
        }
    }

    private static String describe(List<?> rows) {
        StringBuilder sb = new StringBuilder("[");
        for (Object row : rows) {
            if (sb.length() > 1) sb.append(", ");
            sb.append(row instanceof Object[] arr
                ? "Object[]" + Arrays.toString(arr)
                : row.getClass().getSimpleName() + "(" + row + ")");
        }
        return sb.append(']').toString();
    }
}
{code}

h3. Actual output

{noformat}
select a.id, a.name from Author a union select g.id, g.label from Gadget g
  1st run: [Object[][1, Dierk], Object[][1, widget]]
  2nd run: [Author(repro.Author@...)]
select a.name from Author a union select g.label from Gadget g
  untyped: [Object[][Dierk], Object[][widget]]
  typed failed: <openjpa-4.2.0-r977f0cb nonfatal user error> 
org.apache.openjpa.persistence.ArgumentException: There is no conversion 
between query projection type "class repro.Author" and result type "class 
java.lang.String".
select a.name from Author a union all select a.name from Author a
  untyped: [Object[][Dierk], Object[][Dierk]]
  typed failed: ... There is no conversion between query projection type "class 
repro.Author" and result type "class java.lang.String".
select a.name from Author a intersect select a.name from Author a
  untyped: [Object[][Dierk]]
  typed failed: ... There is no conversion between query projection type "class 
repro.Author" and result type "class java.lang.String".
select a.name from Author a except select g.label from Gadget g
  untyped: [Object[][Dierk]]
  typed failed: ... There is no conversion between query projection type "class 
repro.Author" and result type "class java.lang.String".
select a.name from Author a
  untyped: [String(Dierk)]
  typed:   [String(Dierk)]
{noformat}

h3. Expected output

The multi-column query returns the same two {{Object[]}} rows on both runs. 
Each single-column query behaves like the plain query at the end: untyped and 
typed both return {{String}} values, for example {{[String(Dierk), 
String(widget)]}} for the first one.

h3. Analysis

{{JPQLExpressionBuilder.evalSetOperatorExpressions()}} builds a compound 
{{QueryExpressions}} that only fills in {{setOperationType}} and 
{{setOperands}}. Its {{projections}}, {{projectionAliases}} and 
{{projectionClauses}} keep their empty defaults. Everything that inspects the 
compound therefore sees a query for candidate instances:

* In {{QueryImpl.getResultPacker()}}, {{aliases.length == 0}} is read as "the 
candidate is the result", so it builds {{new ResultPacker(_class, getAlias(), 
resultClass)}} with the candidate entity class. That causes the "no conversion 
between query projection type ... Author" error.
* In {{QueryImpl.toResult()}}, the single-projection unwrapping 
({{aliases.length == 1}}) never applies, so the {{Object[]}} rows from 
{{ProjectionResultObjectProvider}} are passed through unchanged.
* On re-execution, {{PreparedSQLStoreQuery}} picks its result provider from 
{{getQueryExpressions()[0]}}, the compound. With no projections it takes the 
{{PreparedResultObjectProvider}} (candidate instance) branch and turns the rows 
into {{Author}} instances. Even with projections it couldn't use the projection 
branch, because the compound's {{state}} is never set 
({{executeSetOperatorQuery()}} only sets it on the operands). The test 
{{TestEJBQLFunction.setOperatorRange()}} already works around this: its comment 
says re-executing the same set-operation string "is broken by the prepared 
query SQL cache - an unrelated, pre-existing defect". I found no JIRA issue for 
that.

{{JDBCStoreQuery.executeSetOperatorQuery()}} itself is fine: the generated SQL 
is correct, and it already builds its {{ProjectionResultObjectProvider}} from 
the first operand.

h3. Suggested fix

The patch below fixes all three symptoms. It applies cleanly to master 
(2e70610).

# Give the compound expression the projection metadata of its first (leftmost) 
operand.
# Set the compound's {{distinct}} to {{DISTINCT_FALSE}}. Its default, 
{{DISTINCT_AUTO}}, would otherwise turn on in-memory duplicate removal once it 
has projections, so {{UNION ALL}} would lose duplicate rows. Duplicates are the 
SQL set operator's job.
# Make {{QueryExpressions.isAggregate()}} return {{false}} for a set operation. 
Otherwise copying an aggregate projection ({{select count(a) ... union all 
select count(g) ...}}) makes {{toResult()}} collapse the result to a single 
value.
# Exclude set-operation queries from the prepared-SQL cache, the same way 
{{IN}} expressions and other cases are excluded. (An alternative is to set the 
compound's {{state}} in {{executeSetOperatorQuery()}} and make sure the 
in-memory range from OPENJPA-2964 is still applied on the cached path. 
Excluding them is the smaller change.)

{code:diff}
--- 
a/openjpa-kernel/src/main/java/org/apache/openjpa/kernel/jpql/JPQLExpressionBuilder.java
+++ 
b/openjpa-kernel/src/main/java/org/apache/openjpa/kernel/jpql/JPQLExpressionBuilder.java
@@ -371,6 +371,20 @@
             evalOperand(left),
             evalOperand(right)
         };
+
+        // The result of a set operation has the shape of its first operand.
+        // Without this, the compound looks like a candidate-instance query:
+        // typed queries get the wrong projection type and single-column
+        // results are not unwrapped from Object[].
+        QueryExpressions first = exps.setOperands[0];
+        while (first.setOperationType != QueryExpressions.SET_OP_NONE)
+            first = first.setOperands[0];
+        exps.projections = first.projections;
+        exps.projectionAliases = first.projectionAliases;
+        exps.projectionClauses = first.projectionClauses;
+        // duplicates are handled by the SQL set operator (UNION vs UNION ALL),
+        // not by in-memory distinct processing
+        exps.distinct = QueryExpressions.DISTINCT_FALSE;
 
         if (parameterTypes != null)
             exps.parameterTypes = parameterTypes;
--- 
a/openjpa-kernel/src/main/java/org/apache/openjpa/kernel/exps/QueryExpressions.java
+++ 
b/openjpa-kernel/src/main/java/org/apache/openjpa/kernel/exps/QueryExpressions.java
@@ -109,7 +109,7 @@
      * Whether this is an aggregate results.
      */
     public boolean isAggregate() {
-        if (projections.length == 0)
+        if (projections.length == 0 || setOperationType != SET_OP_NONE)
             return false;
         if (_aggregate == null)
             _aggregate = (AggregateExpressionVisitor.isAggregate(projections))
--- 
a/openjpa-jdbc/src/main/java/org/apache/openjpa/jdbc/kernel/PreparedQueryImpl.java
+++ 
b/openjpa-jdbc/src/main/java/org/apache/openjpa/jdbc/kernel/PreparedQueryImpl.java
@@ -235,6 +235,8 @@
             return new Object[]{null, _loc.get("exclude-not-executor", _id)};
         _exps = ((StoreQuery.Executor)executor).getQueryExpressions();
         for (QueryExpressions exp : _exps) {
+            if (exp.setOperationType != QueryExpressions.SET_OP_NONE)
+                return new Object[]{null, _loc.get("exclude-set-operation", 
_id)};
             if (exp.hasInExpression)
                 return new Object[]{null, _loc.get("exclude-in-expression", 
_id)};
             if (isUsingExternalizedParameter(exp)) {
--- 
a/openjpa-jdbc/src/main/resources/org/apache/openjpa/jdbc/kernel/localizer.properties
+++ 
b/openjpa-jdbc/src/main/resources/org/apache/openjpa/jdbc/kernel/localizer.properties
@@ -167,6 +167,8 @@
     data store.
 exclude-externalized-param: Query "{0}" is not cached because some 
parameterized \
     field values are externalized.
+exclude-set-operation: Query "{0}" is not cached because it uses a set 
operation \
+       (UNION, INTERSECT or EXCEPT).
 exclude-in-expression: Query "{0}" is not cached because it uses IN expression 
with \
        variable-length parameter.
 exclude-untyped-math-param: Query "{0}" is not cached because it uses a \
{code}

I tested it by putting the patched classes ahead of the 4.2.0 jars, with 
build-time enhanced entities and with {{RuntimeUnenhancedClasses=supported}}. 
With the patch, the repro above prints the expected output, and these all 
return correct results both untyped and typed: {{UNION}}, {{UNION ALL}}, 
{{INTERSECT}}, {{EXCEPT}}, a chained {{UNION ... EXCEPT}}, {{count()}} 
operands, two-column projections, entity-valued unions, {{setMaxResults}}, and 
re-running the same query.

I also built master (2e70610) with and without the patch and ran the related 
upstream tests on the default test database: TestEJBQLFunction, 
TestInMemoryScalarExpressions, TestPreparedQueryCache, 
TestPreparedQueryCacheExclusion, both TestQuerySQLCache classes, 
TestNamedCriteriaQueryWithSQLCache, TestEntityManagerFactoryTransactions, 
TestEntityManagerFactoryTCK and TestPersistenceUnitUtil. All 212 tests pass in 
both runs (2 skipped in both).

The existing set-operation tests in {{TestEJBQLFunction}} accept either result 
shape ("Results may be scalar Strings or Object[] arrays"). They could be 
tightened to expect scalars, and {{setOperatorRange()}} would no longer need a 
different JPQL string for each execution.

h3. Related

* OPENJPA-2964 (range ignored on set operations, fixed by PR #172) and 
OPENJPA-2956 (set operations rejected in memory, PR #178) cover other parts of 
the set-operation support. Neither deals with the projection or result type.
* No existing issue found for this problem (searched JIRA for 
union/intersect/except/"set operation"/"query projection type", all JIRA issues 
created since 2026-07-01, and GitHub PRs as of 2026-11-20).




--
This message was sent by Atlassian Jira
(v10.3.26#10030026)

Reply via email to