Repository navigation
Sort by and join a collection without changing what a query fetches - #17072
jdaugherty wants to merge 56 commits into
Conversation
Sorting a where query by a property of an association, such as sort: 'club.name', failed with a QueryException when the query also had criteria on that association. The criteria join the association under a generated alias, and the order was added with the association path, which Hibernate cannot resolve. The order now uses the alias of the join.
A sort by a path through more than one association, such as owner.employer.name, is still not supported.
This reverts commit b494caa.
A sort by a path that crosses more than one association, such as team.club.name, failed with a QueryException whether or not the where query joined the nested association, because order() split the path at its first dot only. The sort property is now qualified with the alias of the last association on its path: an association the query has already joined is reused, and one it has not joined yet is joined for the sort and registered like any other join. A sort by two properties of the same association no longer fails with "duplicate association path" either, since the sort join is registered instead of created anew for every order.
Since order() walks the whole sort path, a sort by the identifier of an association that follows another one on the path, such as team.club.id, joined that last association too. The join is an inner join unless fetch requests another type, so the sort left out the rows where the association is null. Before, only the first association was joined and Hibernate read club.id from the foreign key of team, which kept them. The identifier is sorted by the foreign key again when the entity before the association holds it. An association without such a foreign key, a hasOne or the inverse side of a one-to-one, is still joined, and so is the first association of a path, as it always has been. The spec also covers the join type of a sort join: an inner join by default, and a left join when fetch requests one. Team.club is nullable in the fixture for these cases. The docs describe the inner join, how to request a left join, and the identifier of a nested association.
list with a map of sort properties, such as Team.list(sort: ['club.name': 'asc', name: 'desc']), sorted by the last entry only, because each entry replaced the orders of the query. The same held for a default sort that the mapping declares for more than one property. Every entry is now applied, in the order of the map. An association is joined once for all the sort properties that use it. list joined it once for each, and find and findAll with an example, findWhere and findAllWhere failed with "duplicate association path". Part 2 of the split of apache#16853.
A paged query of a detached criteria that has an alias for the queried
class, and criteria that use it, failed when totalCount was read:
new DetachedCriteria(Team, 't').eq('t.name', 'Arsenal').list(max: 2).totalCount
The count runs on a copy of the criteria, and the copy was created
without the alias, so Hibernate could not resolve t.name. The copy now
has the alias of the original.
Part 3 of the split of apache#16853.
count on a where query or a detached criteria that has a sort, such as
Team.where { ... }.sort('name').count(), kept the order by in the query
that counts the rows, which H2 rejects with "must be in the GROUP BY
list". A query that only counts its rows now has no orders.
The join that a sort by a property of an association makes is kept, so
the count is that of the rows which list returns for the same query.
Part 4 of the split of apache#16853.
… by it A sort by a property of an association joins the association with an inner join, so it leaves out the instances whose association is null: Team.list(sort: 'club.name') does not return the teams without a club, and count and the totalCount of a paged list do not count them. The new grails.gorm.leftJoinAssociationSort setting makes an association that is joined only for a sort a left join, in where queries, detached criteria, dynamic finders, list, find and findAll with an example, findWhere, findAllWhere and a criteria query that is passed pagination arguments. It is disabled by default, so the results of existing applications do not change in a patch release. Grails 8.1 enables it by default. With the setting, a sort by a nested identifier, such as team.club.id, goes through the left join. Without it, it is still read from the foreign key. A sort by a property of a collection keeps its inner join: Hibernate fetches a collection through a left join, which is handled separately. Part 5 of the split of apache#16853.
Team.where { ... }.join('club', JoinType.INNER) lists and counts the
teams with a club, but deleteAll and updateAll on it ignored the join
type and deleted or updated the teams without a club as well. They now
modify the instances that list returns.
An update or a delete cannot join, so each requested join becomes a
restriction: a subquery that selects from the entity of the first
association on the path and joins the rest of it. deleteAll selects the
identifiers first when the path starts with a collection that has a
join table, because Hibernate deletes the join rows before the
instances with the same restriction. A one-to-one whose foreign key the
other class has is matched through the property that refers back.
MySQL, and MariaDB before 10.3, do not allow an update or a delete to
select from the table that it modifies. For a join that leads back to
the queried class, these dialects get an UnsupportedOperationException
that says to restrict the query with criteria instead.
Part 8 of the split of apache#16853.
The criteria builder accepted a join type and never used it.
join('club', JoinType.INNER) has had the body of the one-argument join
since it was added, so it set a fetch mode, and a JoinType in the fetch
argument of list matched no fetch mode, so the association was not
fetched at all.
Both now join and fetch the association with the requested type, with
the rules of a where query: a path through a collection restricts the
query with a subquery, and the associations on the path are fetched.
The join types are applied once the criteria are built, so an
association that the criteria have a block for, or join through an
alias, keeps that join. A fetch mode requested afterwards, with join,
select, fetchMode or the fetch argument, replaces the join type.
The sort argument of the list of a criteria query uses a join that the
criteria already have for the association, such as the one of a join
type that the fetch argument requests for it. It joined the association
a second time, which failed with "duplicate association path".
Part 9 of the split of apache#16853.
order('club.name') in a criteria query failed with "could not resolve
property", and with a Query.Order it sorted by a property of the
queried class. A criteria query that is passed pagination arguments
and a sort by a path through more than one association failed when
totalCount was read, or with "duplicate association path" when the
criteria used the first association, and a map of sort properties
failed with a ClassCastException.
order now resolves an association path, also inside the criteria of an
association, and joins with a left join an association that the
criteria do not join. The orders are added once the criteria are
built, so an order uses the join and the join type that the criteria
or the fetch argument request, whichever comes first. An order by the
identifier of an association reads the foreign key, as before. The
sort argument reuses a join that the criteria have for a path, also
one made through an alias, and creates any other from the root
criteria, which is how the count recreates it.
The sort argument can also start with an alias that the criteria give
an association, as sort: 'c.name' with createAlias('club', 'c'), also
as an entry of a map of sort properties and followed by a further
association. Such a sort was dropped, which review 5868034911 of
apache#16853 reported for the map.
The join that an order makes is a left join only with the
grails.gorm.leftJoinAssociationSort setting. Without it the association
is joined with an inner join, as it is for the other sorts.
Part 10 of the split of apache#16853.
A where query, a detached criteria and a dynamic finder joined an association as soon as criteria, a projection or a sort needed it. The rest of the query can still change after that: criteria passed to list are added later, and the fetch argument of list, which can request a join type, is read last. The result depended on the order in which the query was put together: - a join type in the fetch argument of list was not used for the join that the criteria or a projection had already made; - a sort stored on the query with sort() was joined before a join type requested in list was known, and criteria passed to list could not join the same association through an alias; - a join type was looked up by the name of the association, so a type requested for club was used for team.club, and one requested for team.club was not; - criteria on a nested association used twice failed with "duplicate association path". Criteria, projections and orders only need the alias of a join. A join is now registered under its path from the root entity and its alias, and made when the query is executed, or when a subquery is handed to the query that embeds it, with the join type that the query requests for that path. A listener of the query events that adds criteria on an association to find and findAll with an example, findWhere or findAllWhere gets its joins made after the event. Part 6 of the split of apache#16853.
A where query, a detached criteria or a dynamic finder can request a
join type for an association, with fetch: [club: JoinType.INNER] or
join('club', JoinType.INNER). The type was only used when criteria or
a sort joined the association. Otherwise the association was fetched
with the outer join of its fetch mode, so
Team.where { ... }.list(fetch: [club: JoinType.INNER]) returned the
teams without a club, and the same query sorted by club.name did not.
A requested join type other than LEFT is now applied when the query is
executed, to list, get, find, count, the totalCount of a paged list, a
subquery and a query with a projection:
- INNER and RIGHT on an association to a single instance join and
fetch it; a right join is a right join, not an outer fetch;
- a path that ends in a collection or passes through one restricts the
query with a correlated subquery, so that the collection stays
fetched with all of its elements, each instance is counted once, and
the filters of the session, such as the tenant filter, apply;
- every association on a requested path is joined and fetched;
- a collection of a basic type is handled like any other collection;
- a fetch mode requested afterwards replaces the join type, on the
query and on the detached criteria, while the join that criteria on
the association make keeps it.
Part 7 of the split of apache#16853.
list, findWhere, findAllWhere, and find and findAll with an example ignored a JoinType in their fetch argument: they returned the instances without the association, and list did not fetch it. They now apply it, before a sort by the association, which uses that join. list fetches with the requested type, returns each instance once when it fetches a collection, and applies RIGHT like INNER, since Hibernate does not support right joins in the criteria queries that list runs. 'join' and 'eager' in the fetch argument of list fetch the association with a left join and return every instance, as a where query and a dynamic finder do. list joined it with an inner join without fetching it, so it left out the instances whose association is null or whose collection is empty. The totalCount of a paged list counts each instance once when the list fetches a collection, and keeps a sort join that hangs under a fetch. Part 11 of the split of apache#16853.
A sort by a property of a collection joined the collection with an inner join. It left out the instances whose collection is empty, and took the place of a fetch that the query requested for the collection. Criteria on a collection with a requested left join initialized the collection with only the elements that the criteria matched. - A sort joins a collection with a left join and does not fetch it through that join, unless the query asks for the collection to be fetched, with or without the sort. - A left join of a collection that criteria use does not fetch the collection. When the query also fetches another collection, that one is loaded once the query has run, because Hibernate would read it from the columns of the join of the criteria. - A sort by a collection next to a fetch of another collection repeats rows, and a bag cannot tell a repeated row from a repeated element, which is why Hibernate does not fetch two bags in one query. When either collection is a bag, the query throws an UnsupportedOperationException that names both, where it returned the bag with repeated elements. A query that projects values loads no collection and is not affected. A fetch that a mapping declares counts as fetched only where Hibernate joins it: not at or beyond hibernate.max_fetch_depth joins from the queried class, where Hibernate loads it with a query of its own (review 5868034911 of apache#16853). This applies with the grails.gorm.leftJoinAssociationSort setting. Without it a sort still joins a collection with an inner join, which leaves out the instances whose collection is empty. Part 12 of the split of apache#16853.
jamesfredley
left a comment
There was a problem hiding this comment.
Requested changes. A sort by a collection still drops a row that has no child.
| } | ||
| } | ||
| if (!leftJoin) { | ||
| return from.join(associationName, JoinType.INNER); |
There was a problem hiding this comment.
Team.list() returns a team with no players. Team.list(sort: 'players.name') does not. The sort joins the collection as an inner join. Keep the team that has no players.
There was a problem hiding this comment.
Keeping the inner join with grails.gorm.leftJoinAssociationSort disabled is intentional. The dev@ agreement keeps the old result by default on 7.0.x, 7.1.x, 7.2.x and 8.0.x, enables the setting by default in 8.1, and removes it in 9.0: https://lists.apache.org/thread/btc50c855byrw1zb6rqslyk3dlc546mm.
This part extends the opt-in sort behavior to collections while preserving their fetch behavior. Making Team.list(sort: "players.name") keep an empty collection unconditionally would change the default we agreed to preserve. If the team is dropped with leftJoinAssociationSort: true, please provide that reproducer; that would be an in-scope bug in this part.
Document stored sorts using the requested fetch join type and repair the rendered list. Remove the one-caller association helper and unrelated import churn while merging the reviewed parent.
Load collections on paged requested-join paths separately, preserving complete contents. Retain each unmatched right-join row while deduplicating real entities. Exercise these results and cloned fetch replacements through public queries, and clarify the data-service limitation and changed results.
Select matching identifiers before bulk operations whose subqueries request joins. Correlate bidirectional collections through the owning property so tenant-filter parameters stay bound. Cover updates and deletes through nested criteria and tenant-scoped collection updates.
Reuse an existing alias with the requested join type regardless of declaration order. Keep paged collection fetches separate from limited SQL rows and document unpaged collection duplicates. Restore only the private join-lookup helpers needed by the criteria path.
Name the inner join added by a formerly ignored alias-prefixed sort and how to retain the old rows. Merge the reviewed criteria-join fixes and keep the existing join lookup private.
Name in-memory pagination for collection fetches, the rows retained by sorting a left-fetched association, and the Hibernate 5 right-join limitation. Carry the reviewed parent and align fetch regressions with separately loaded paged criteria collections.
Allow an unfetched sorted bag beside a fetched set of another element type. Keep same-element legacy fetch handling, and protect a static-list fetched bag with either compatibility setting. Make utility-only fetch checks private and document secondary collection loading costs.
matrei
left a comment
There was a problem hiding this comment.
Reviewed again at 7a9c98e. Points 1, 3, 4 and 5 of my first review are fixed, and point 2 is below:
- With the setting on, a sort by a bag next to a fetched set of another class works again:
Team.list(sort: 'members.name', fetch: [trophies: 'join']), the where query withjoin('trophies'), and the criteria query withorder('members.name')return every team with the trophies complete. The compatibility page names the exception that the setting can bring. - The note says that the other collections are then loaded with a query for each instance.
- Two of the helpers are private now, and the description says why the others are shared.
- The pull request merges cleanly with 7.0.x and has
run ci, and CI passed with the tests.
Apart from these, my probes from the first review give the same results here as at f56d69e, with the setting off and on. #17079 (1cba001) now holds both members in the case of my note 8. The tests of grails-data-hibernate5-core pass here (1693 tests, 168 skipped), and the guide builds.
Needs a fix
With the setting off, a list that fetches a bag and sorts by another collection now throws on 7.0.x. It fixes the bag of point 2 by throwing the exception of the setting without it too:
| Setting off | 7.0.x | #17071 | This head | #17079 |
|---|---|---|---|---|
Team.list(sort: 'trophies.title', fetch: [members: 'join']), also 'eager' |
4 rows, the bag complete | 2 teams, the bag holds 4 members for 2 | throws | 2 teams, the bag complete |
the same with JoinType.LEFT |
3 rows, the bag complete | 2 teams, 4 members for 2 | throws | 2 teams, complete |
the same with max: 2 |
2 rows | 2 teams, 4 members for 2 | throws | 1 team, complete |
On 7.0.x these calls returned rows, because 'join' and 'eager' in list didn't fetch the bag and a join type was ignored. So on a patch branch, a call that works now fails, with the setting off, while Hibernate 7 returns the right rows. In my first review I offered the check as one way out. Seeing the result, I'd take the other one: don't fetch the bag in the query, and load it after the query, as this part already does for the other collections when criteria use a left join of a collection. The bag is then complete, the calls keep working, and list returns what #17079 returns.
The same would also answer the queries that still throw with the setting on. These are the where query, findAllByNameLike, findAllWhere, findAll with an example and the criteria query, each with fetch: [members: 'join'] and sort: 'trophies.title', and a mapping with members fetch: 'join' sorted by trophies.title. #17079 answers each of them with the bag complete, and as the setting becomes the default in 8.1, they'd throw for every application that upgrades. With the setting off, those queries hold 4 members for 2, as on 7.0.x, and loading the bag after the query would fix that too.
Smaller point
- The description still names 44c3a4a as the change to review. f56d69e and 7a9c98e are part of it too.
As a fix that changes a result, this needs a second approval under #17061.
Merge the reviewed parent fixes and defer collection fetches that would multiply bag elements. Keep requested left joins, complete fetched collections, sort-map joins and distinct static-list results in both compatibility modes.
jamesfredley
left a comment
There was a problem hiding this comment.
Requested changes. A sort that starts with the alias of the queried class is still ignored.
| PersistentProperty persistentProperty = entity.getPropertyByName(sortHead); | ||
| if (!(persistentProperty instanceof Association)) { | ||
| // neither an alias of this query nor an association, so there is nothing to sort by: the sort is ignored | ||
| return; |
There was a problem hiding this comment.
A criteria for Team whose alias is t, sorted by t.club.name, should sort by the club name. It does not, and a team with no club can be included. This does not treat t as the root alias. Sort by the club name.
There was a problem hiding this comment.
Resolving t as the root alias in t.club.name is the change in #17073, implemented and tested at 318b59bc3f5b. Its public-API regressions cover root-alias-prefixed association sorts, including stored and argument sorts in both compatibility modes. #17072 remains focused on collection sorting and fetch contents.
Merge the corrected requested-join parent and preserve implied left collection joins when an example or where-map query sorts a nested fetch path. Retain explicit intermediate join types, path boundaries, complete collections and static-list controls in both compatibility modes.
Merge the corrected requested-join and example-query parent while retaining deferred bag loading and opt-in collection sorts. Keep explicit intermediate joins and pagination safeguards, and align inherited replacement-fetch controls with both compatibility modes.
jamesfredley
left a comment
There was a problem hiding this comment.
Requested changes. A sort that starts with the alias of the queried class is still ignored.
| PersistentProperty persistentProperty = entity.getPropertyByName(sortHead); | ||
| if (!(persistentProperty instanceof Association)) { | ||
| // neither an alias of this query nor an association, so there is nothing to sort by: the sort is ignored | ||
| return; |
There was a problem hiding this comment.
A criteria for Team whose alias is t, sorted by t.name descending, should return the teams in that order. It does not order them. This does not treat t as the root alias. Sort by the name.
✅ All tests passed ✅🏷️ Commit: 1d11c9c Learn more about TestLens at testlens.app/docs. |
Description
Part 12 of the split of #16853, as agreed there and in the dev@ thread Fixes that change results on patch and minor branches. Relates to #15589.
Stacked on #17071. Until that merges, this pull request also shows the commits below it. Review the changes introduced by this part, including its review fixes, relative to #17071.
A sort by a property of a collection joined the collection with an
inner join. It left out the instances whose collection is empty, and
took the place of a fetch that the query requested for the collection.
Criteria on a collection with a requested left join initialized the
collection with only the elements that the criteria matched.
through that join, unless the query asks for the collection to be
fetched, with or without the sort.
collection. When the query also fetches another collection, that one
is loaded once the query has run, because Hibernate would read it
from the columns of the join of the criteria.
that would repeat bag elements are deferred until after the main query,
and the complete collections are initialized before results are
returned. This applies with either compatibility setting. A query
that projects values loads no collection and is not affected.
A fetch that a mapping declares counts as fetched only where Hibernate
joins it: not at or beyond hibernate.max_fetch_depth joins from the
queried class, where Hibernate loads it with a query of its own
(review 5868034911 of #16853).
With the grails.gorm.leftJoinAssociationSort setting, joins introduced
only for sorting are left joins. Without it they remain inner joins and
can leave out instances whose collection is empty. Deferring fetches that
would multiply bag elements applies in both modes.
Results that change
The utility-only isFetchRequested and fetchesAnotherCollection methods are now private. The remaining cross-package helpers are shared by the query, criteria-builder and static-list implementations so they apply the same fetch rules.
Verification
At 1d11c9c, including the reviewed #17071 parent, the full Hibernate 5 core suite has 2,152 cases: 1,984 passed, 168 skipped and zero failures. The inherited nested-LEFT controls pass alongside complete deferred bag fetches in both compatibility modes, static-list distinct results and sort maps through deferred fetches. Root codeStyle, RAT (zero unknown licenses), dependency-version validation and the guide build passed.
Contributor Checklist
Please review the following checklist before submitting your pull request. Pull requests that do not meet these requirements may be closed without review.
Issue and Scope
7.0.x): Bug fixes only. No new features or API changes.7.1.x): New features are welcome, but breaking existing APIs must be avoided.8.0.x): Reserved for major changes. Breaking API changes are permitted.Code Quality
./gradlew build --rerun-tasks../gradlew codeStyleand resolved any violations. See Code Style for details.Licensing and Attribution
Documentation