Repository navigation
Fix root alias registration and nested alias path resolution in subqueries - #16821
borinquenkid wants to merge 21 commits into
Conversation
…eries - Register root alias in JpaQueryContext during createQuery() and populateSubquery() in JpaCriteriaQueryCreator so correlated subqueries can resolve outer root aliases - Walk nested PropertyExpression chains to the root VariableExpression via aliasRootName() in DetachedCriteriaTransformer when rewriting alias property comparisons - Preserve alias in AbstractDetachedCriteria.clone() and read effective.alias in DetachedCriteria.withPopulatedQuery() for derived and whereLazy queries - Add unit and subquery alias specifications Fixes #16813
a729094 to
79a7bdb
Compare
…root-alias-nested-paths-8.0.x
…subquery-root-alias-nested-paths-8.0.x
…subquery-root-alias-nested-paths-8.0.x
…subquery-root-alias-nested-paths-8.0.x
…in property comparisons, as Hibernate 5 does id == t.club in a correlated subquery worked on H5 and failed on H7 with 'Cannot compare Long with ScenarioOwner'. The H7 spec had been rewritten to t.club.id, which hid the difference. Claude-Session: https://claude.ai/code/session_01Dmki4SQGwRSj8pRJ5KCWyX
|
Added integration scenarios for correlated subqueries ( Two things for the team:
|
…subquery-root-alias-nested-paths-8.0.x
Claude-Session: https://claude.ai/code/session_01Dmki4RzWwreEC2GkkyFnvL # Conflicts: # grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/query/FunctionCallingCriterionHandler.java # grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/query/PropertyCriterionHandler.java # grails-datastore-core/src/main/groovy/org/grails/datastore/mapping/query/jpa/JpaQueryBuilder.java
…repair, so it is no longer pending Claude-Session: https://claude.ai/code/session_01Dmki4RzWwreEC2GkkyFnvL
|
The run on 6a8e77d is cancelled: it would have failed on the Hibernate 7 |
jamesfredley
left a comment
There was a problem hiding this comment.
Requested changes. Two associations whose identifiers hold an association to unrelated classes are still compared as entities.
| List<Predicate> parts = new ArrayList<>(); | ||
| for (int i = 0; i < leftParts.size(); i++) { | ||
| parts.add(negate ? criteriaBuilder.notEqual(leftParts.get(i), rightParts.get(i)) : | ||
| criteriaBuilder.equal(leftParts.get(i), rightParts.get(i))); |
There was a problem hiding this comment.
Left and Right both use a composite identifier whose first part is an association to a different class. eqProperty('left', 'right') should compare the identifier columns. It throws, because those association parts are compared as entities. Compare those parts by their identifiers too.
matrei
left a comment
There was a problem hiding this comment.
Reviewed at 8142212 (base fix/datastore-wherelazy-thread-safe-8.0.x, #16820's head branch, at ef5bdda). CI ran on this head and passed: that is the one run of the whole stack asked for on #16816 and #16820.
GitHub shows 268 changed files because this branch has #16816's current head, with today's 8.0.x, and #16820's branch does not. Measured against #16820 merged with #16816's head, this PR changes 11 files: JpaCriteriaQueryCreator, PredicateGenerator, PropertyComparisonCriterionHandler, DetachedCriteriaTransformer, FunctionComparison (item 2) and six specs. Merging #16816's head into #16820's branch would bring the diff here down to them.
What I ran locally:
- The new specs on #16820 merged with #16816's head (the conflicts resolved as in e4e3278): all six
SubqueryAliasSpecfeatures, all fiveSiblingAssociationPropertyComparisonSpecfeatures and the two nested-path features ofWhereQueryPropertyAliasSpecfail there, so they guard the change. - The same Hibernate 7 specs on today's 8.0.x (9fc7dd3). In "Test subquery comparing an id with an association of the root alias",
id == t.club && name == "Manchester United"returns both teams, so the comparison is dropped. Thet.club.idfeatures throwMissingPropertyException: No such property: club for class: Team. The five sibling features throwSemanticException: Cannot compare left expression of type .... - 7.0.x with Hibernate 5 (item 1).
- A throwaway spec for comparing two associations to unrelated classes, on this head, on 8.0.x and on Hibernate 5 (item 3).
Needs a fix
-
Branch: the nested alias path fix belongs on 7.0.x as well.
DetachedCriteriaTransformeris ingrails-datamapping-core, which Hibernate 5 shares, and 7.0.x has the same check. There, on Hibernate 5,exists(Club.where { id == t.club.id && name == "Manchester United" }.property('name'))insideTeam.where { def t = Team ... }throwsMissingPropertyException: No such property: club for class: grails.gorm.tests.Team: the transform leavest.club.idas a Groovy expression on the class. With this PR's change to the transform applied to 7.0.x, the query returns the right team.grails-datamapping-corestill passes, andgrails-data-hibernate5-corehas no new failures. A call that throws is a bug that goes to the oldest branch that has it, by the rule in the dev@ thread. A small PR against 7.0.x, with the change to the transform, the two nested-path features ofWhereQueryPropertyAliasSpecand a Hibernate 5 feature (the last feature of your Hibernate 5SubqueryAliasScenarioSpecis one), would bring the fix to Hibernate 5 applications on 7.x once merged up. This PR keeps the Hibernate 7 parts. The root alias registration is needed on Hibernate 7 only: on 7.0.x, Hibernate 5 already correlatesid == t.club. -
The merge commit e4e3278 adds code that is in neither parent. Resolving the conflict with #16816, it adds two changes that neither #16816 nor #16820 has:
FunctionComparisonnow leaves null out of the list of aninon a function, andFunctionCallingCriterionHandlerreturns a disjunction for an empty list. That is #16818's null filtering for a function's list, moved out of #16818's handler and intoFunctionComparison.JpaQueryBuilderuses that class too, so the change also reaches the bulk statements of Hibernate 5 and Hibernate 7. It belongs in #16816, where #16818 now is: theFunctionCallingCriterionHandlerconflict was resolved there by keeping #16816's version, without the filter. James's open point on #16816 also applies to it:!(qty in [1, null])should match no rows, as SQLNOT INwith a null does, and leaving the null out matches the row with 2. At this head,!(upper(name) in ['A', null])matches the row whose name isb, just as!(name in ['a', null])does. Whatever #16816 decides for a plainin, a function's list should follow it there, in a commit that gets reviewed. The merge here should take #16816's version of both files. -
Two associations to unrelated classes: the parts of a composite id are paired by name, and an association part still throws.
identifierPartssorts the properties of a composite id by name, andcompareIdentifierspairs the two lists in that order. When the two ids have different property names, the parts are paired wrong without an error. Withid composite: ['country', 'city']on one side andid composite: ['nation', 'town']on the other,eqProperty('left', 'right')comparescitywithnationandcountrywithtown. (SE, Lund) against (SE, Lund) does not match, and (SE, Lund) against (Lund, SE) does. Hibernate 5 pairs the columns in the declared order and returns the first. James's point from today is a second gap in the same code: when a part of the composite id is an association, and the two sides' associations go to unrelated classes, it still throwsSemanticException: Cannot compare left expression of type 'OwnerA' with right expression of type 'OwnerB'. Hibernate 5 compares the foreign key columns there and returns the row.#16813 does not need this comparison.
id == t.clubandeqProperty('plainLeft', 'id')go throughidentifierIfCompared, which compares an association with a value that is not an entity. Two associations to unrelated classes throw on 8.0.x today, so nothing is lost if they wait. I'd takeunrelatedEntities,compareIdentifiersand their features out of this PR and into one of their own. That PR would pair the parts in the declared order (GORM's composite identity keeps it; the JPA metamodel does not) and compare an association part by its identifier, so this PR no longer waits on them. Keep the!isEntityValued(other)guard from 8052e93, so that two associations are compared as entities, as on 8.0.x. If the comparison stays here instead, both gaps need fixing before this lands. In that case, also note that fornePropertythis head is true when any part differs, which is what the call asks for, while Hibernate 5 ANDs the column comparisons and is true only when every part differs. The Javadoc's "This is what Hibernate 5 does" would need to say which one this does. -
Description. Please rewrite it to match this head:
- It says the PR keeps the alias across
clone()andwithPopulatedQuery. That is in #16820 now (clone()copies the alias there), and this PR does not touchAbstractDetachedCriteria. - It leaves out four things: an association compared with a value that is not an entity (
id == t.club,eqProperty('club', 'id')) is now compared by its identifier; two associations to unrelated classes are compared by their identifiers (if that stays); #16921, squash-merged into this branch, drops thePredicateGeneratorregistrations; and the example-app scenario specs on Hibernate 5 and 7. - What changes for applications on 8.0.x, as the rule in the dev@ thread asks. A subquery that compares with an association of the enclosing query's root alias (
id == t.club) was dropped on 8.0.x, so the outer query returned rows it should not have. It now restricts them, as on Grails 7. That old result contradicts the query, so there is nothing to keep it for, but it changes results, so it needs a line in the upgrade notes.t.club.id, and an association compared with an identifier, threw and now run.
- It says the PR keeps the alias across
Note
PredicateGeneratorHandlerRegistrySpec(from #16921) reads the privateBUILTIN_HANDLERSmap and calls the privatefindHandlerby reflection, where the repository's rule is to test through public APIs. Its "is registered only when its handler differs from its ancestor" feature pins how the map is laid out rather than what a query does: registering a subclass with its ancestor's handler would fail it and change no query. The rest of the suite runs every criterion type through queries, so I would drop that feature at least.
Verified as correct
registerRootAliasregisters the alias a criteria declares for its own root, for the query and for each subquery. A subquery's context resolves through its parent, sotin a subquery finds the enclosing root, and a nested subquery's own alias (subClub) is found before its parent's.aliasRootNamefollows the chain to its first element and rewrites the comparison only when that element is a declared alias. A chain that starts at a method call, or at a variable that is not an alias, still becomeseq.- Every criterion class of
Querystill gets the handler it had before the registrations were dropped: the table inPredicateGeneratorHandlerRegistrySpecpasses on the base as well. - Two associations to subclasses of one hierarchy (
eqProperty('dog', 'cat')) still compare as entities, with the same result as on 8.0.x and on Hibernate 5.
…p the registry layout feature The merge of #16816 had added null filtering for a function's in list and a disjunction for an empty one in FunctionComparison and FunctionCallingCriterionHandler. Neither parent has it, so it goes back to #16816's version of both files; a function's list follows whatever #16816 decides for a plain in. PredicateGeneratorHandlerRegistrySpec no longer has the feature that pins how the registration map is laid out, which no query depends on. Claude-Session: https://claude.ai/code/session_01Dmki4RzWwreEC2GkkyFnvL
…ns out of this branch The identifier comparison for eqProperty/neProperty of two associations to unrelated classes pairs the parts of a composite identifier by name and throws for an association part. It follows in its own pull request on this one; this branch keeps the guard that two associations are compared as entities, as on 8.0.x. Claude-Session: https://claude.ai/code/session_01Dmki4RzWwreEC2GkkyFnvL
…ng root alias under 8.0.1 Claude-Session: https://claude.ai/code/session_01Dmki4RzWwreEC2GkkyFnvL
|
Thank you. Pushed and changed:
Item 1, the 7.0.x pull request for the nested alias path, comes next; I'll link it here. |
|
The 7.0.x part (item 1 of your review) is #17060: the transformer change, three features of |
jamesfredley
left a comment
There was a problem hiding this comment.
Requested changes. Two associations whose identifiers hold an association to unrelated classes are still compared as entities.
| otherPropertyPath = right; | ||
|
|
||
| if (c instanceof Query.EqualsProperty) { | ||
| return criteriaBuilder.equal(propertyPath, otherPropertyPath); |
There was a problem hiding this comment.
Left and Right both use a composite identifier whose first part is an association to a different class. eqProperty('leftRef', 'rightRef') should compare the identifier columns. It throws, because those parts are still compared as entities. Compare those parts by their identifiers too.
… in) into fix/h7-subquery-root-alias-nested-paths-8.0.x # Conflicts: # grails-doc/src/en/guide/upgrading/upgrading80x.adoc
|
Merged #16820's branch (fb22058, which carries #16816 with 8.0.x merged in) into this one, so this branch has the null handling of #16816 and the |
|
@jamesfredley the comparison of two associations whose composite identifiers hold an association to unrelated classes is in its own pull request on this one: #17154. |
jdaugherty
left a comment
There was a problem hiding this comment.
@borinquenkid #16863 and #17079, the Hibernate 7 counterparts of the association-sort and requested-join parts on 7.0.x, are now narrowed to what those Hibernate 5 parts do, and the root alias of a detached criteria is outside them. One merged Hibernate 5 part depends on it, though: #17063 keeps the root alias of a detached criteria in the count of a paged list. With Hibernate 7 such criteria fail before the count runs, as #17167 describes:
new DetachedCriteria(Book, 'b').eq('b.title', 'Example').list(max: 2).totalCount
new DetachedCriteria(Book, 'b').list(sort: 'b.title')This PR registers the root alias that a criteria declares in JpaQueryContext, for the query and for each subquery. Could it cover these top-level cases too, at least the restriction and the paged count that #17063 needs, with specs for them? If that is too far from #16813, say so, and #17167 stays the place for it.
… queried class A join type requested for a path was not applied to a sort that named the path through the root alias, so it left out the instances without the association. A path through an association with the same name as the root alias resolved against the root and returned other rows. Part of #17167 Claude-Session: https://claude.ai/code/session_01Dmki4RzWwreEC2GkkyFnvL
… in the join plan The upgrade note says that a property of the same name as the root alias keeps its meaning. Claude-Session: https://claude.ai/code/session_01Dmki4RzWwreEC2GkkyFnvL
|
@jdaugherty Yes, it is covered here now. Both of your calls, the restriction with its paged
Not covered, so #17167 stays open: |
🔎 No tests executed 🔎🏷️ Commit: 91902b5 Learn more about TestLens at testlens.app/docs. |
Fixes #16813
Chained on #16820 (chain: #16816, #16817, #16818, #16820).
no ciuntil the chain reaches 8.0.x.Problem
On Hibernate 7, a subquery that is correlated on the root alias of the enclosing query lost the correlation:
Team.where { def t = Team ... exists(Club.where { id == t.club }...) }and the nested patht.club.ideither dropped the comparison or threw. The outer query then returned rows it should not have.Changes
JpaCriteriaQueryCreatorregisters the root alias a criteria declares for its own root inJpaQueryContext, for the query and for each subquery. Hibernate 5 already correlatesid == t.club, so this is Hibernate 7 only.new DetachedCriteria(Book, 'b').eq('b.title', ...), resolves in restrictions, projections, sorts and thetotalCountof a paged list (part of Hibernate 7: resolve the root alias in detached-criteria sorts and restrictions #17167). A join type requested for a path now applies to a sort that names the path through the alias. When the alias is also the name of a property, that name and a path through it stay the property.updateAllanddeleteAlldo not accept the alias, andcountignores a sort with or without it.DetachedCriteriaTransformerresolves a nested alias path (t.club.id) to its root alias when the chain starts at a declared alias; a chain that starts at a method call or an undeclared variable stayseq. It is ingrails-datamapping-core, which Hibernate 5 shares: the same fix for Hibernate 5 is proposed against 7.0.x in its own pull request.PropertyComparisonCriterionHandlercompares an association with a value that is not an entity (id == t.club,eqProperty('club', 'id')) by its identifier, as Hibernate 5 does. Two associations are compared as entities, as on 8.0.x. Comparing two associations of unrelated classes follows in its own pull request on this one.PredicateGeneratorregistrations that the superclass lookup covers.SubqueryAliasScenarioSpec) run the root alias subqueries end to end.The merge commits of #16816 and #16820 into this branch contain conflict resolutions; the one that had added code in neither parent (null filtering for a function's
inlist) is reverted in the last commits, so the tree has nothing that is in neither of them.What changes for applications on 8.0.x
A subquery that compared with an association of the enclosing root alias (
id == t.club) was dropped on 8.0.x, so the outer query returned rows it should not have. It now restricts them, as on Grails 7. That old result contradicts the query, so there is nothing to keep it for, but it changes results and has a note in the Grails 8.0.1 upgrade section.t.club.idand an association compared with an identifier threw and now run.Tests
DetachedCriteriaRootAliasSpecruns each call with and without the root alias, and the paths whose first name is also the alias. 8 of its rows failed before the last two commits. The Hibernate 7 module (5509 tests) andcodeStylepass on the head.SubqueryAliasSpec,WhereQueryPropertyAliasSpecand the scenario specs; Hibernate 7 core, datamapping-core-test and datastore-core pass with 0 failures at this head.https://claude.ai/code/session_01Dmki4RzWwreEC2GkkyFnvL