Repository navigation
Sort a criteria query by a property of an association - #17070
jdaugherty wants to merge 24 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.
jamesfredley
left a comment
There was a problem hiding this comment.
Requested changes. A sort through an alias stops at the first property and does not join the rest.
| */ | ||
| private void requestOrder(String propertyName, Function<String, Order> orderFactory) { | ||
| String[] tokens = propertyName.split("\\."); | ||
| if (tokens.length == 1 || datastore == null || aliasMap.containsValue(tokens[0]) || isAssociationIdentifier(tokens)) { |
There was a problem hiding this comment.
The query aliases team as t and sorts by t.club.name. That should join club and sort by its name. It throws, because the path is treated as already resolved once it starts with t. Join the rest of the path.
There was a problem hiding this comment.
Fixed in f2e1cc6. An order starting with an association alias now resolves the remaining path from that association and creates the missing joins. A direct alias property and a foreign-key identifier retain their existing handling.
The regression covers order("t.club.name", "desc") and Query.Order, with and without pagination. The association-sort specs pass in both compatibility-setting modes: 194 cases, 171 passed and 23 skipped. The module codeStyle check passes too.
matrei
left a comment
There was a problem hiding this comment.
Reviewed at e54321e (base 7.0.x): 4a6224d, f2e1cc6 and the merge of #17069's head. The merge drops #17069's addOrderPossiblyNested, which this part replaces. The criteria probes of my review of #17069 return the same here as at #17069, with the setting off and on, so its sort fixes are kept.
I probed order and the sort argument of criteria queries, by a property of an association, a nested path, an alias, a hasOne, inside the criteria of an association, with a requested join type, paged, as a map, and with count, get and projections:
- at this head, at #17069 (48bcf09), on 7.0.x (aee4c04) and at the stack top (16bd465), with the setting off and on;
- with Hibernate 7 on 8.0.x (0518f48) and at #17079 (6de9334).
The failing calls work. With the setting off, they return the rows and the order of Hibernate 7 at #17079, apart from a map of sort properties (point 2) and a totalCount of a sort (below the table):
| 7.0.x and #17069 | This head | #17079 | |
|---|---|---|---|
Team.createCriteria().list { like('name', '%First%'); order('club.name') }, also desc, withCriteria, a projection of name and order('club.name') inside a club { } block |
could not resolve property |
4 teams, by club | 4 |
Player.createCriteria().list { order('team.club.name') }, also order('contract.salary') of a hasOne |
could not resolve property |
6 players | 6 |
Player.createCriteria().list { team { like('name', '%First%'); order('club.name') } }, also order('team.club.name') after the block |
throws | 3 | 3 |
Player.createCriteria().list(max: 2, sort: 'team.club.name') { … } |
could not resolve property: club |
2, totalCount 6 |
2, totalCount 7 |
the same with team { like('name', '%First%') } |
throws, duplicate association path: team on 7.0.x |
2, totalCount 3 |
2, totalCount 4 |
order('club.name') with join('club', JoinType.LEFT) or fetch: [club: JoinType.LEFT] |
could not resolve property |
5, the team without a club first | 5 |
list(sort: ['club.name': 'desc', name: 'asc']) { … }, also ['c.name': 'desc'] with createAlias('club', 'c') |
ClassCastException |
4 | ClassCastException |
order('club.id') reads the foreign key, as before. club { order(Query.Order.desc('name')) } now sorts by the name of the club, as at #17079, where 7.0.x sorted by the name of the team. A totalCount that differs from Hibernate 7 is the count of #16863, which leaves out the join of the sort.
Needs a fix
1. Rows change with the setting off. The description says "no rows change by default". A sort that starts with an alias and goes on to another association was ignored, and now joins that association with an inner join, as a sort does without the setting:
Player.createCriteria().list(sort: 't.club.name') { createAlias('team', 't'); like('name', '%') } |
7.0.x | This head, setting off | Setting on | Hibernate 7 on 8.0.x and #17079 |
|---|---|---|---|---|
| players | 7, unsorted | 6, by club | 7, by club | 6 |
totalCount |
7 | 6 | 7 | 7 |
Hibernate 7 leaves the player out as well, so this needs no setting. But "Results that change", the note and the skill entry should say that such a sort also leaves out the instances without the association, unless grails.gorm.leftJoinAssociationSort is enabled. The note's advice, "Remove the sort to get the results unsorted, as before", keeps the rows as well, and could say so.
sort: 'c.name' with createAlias('club', 'c') keeps its rows, since the alias already joins the club with an inner join.
2. No Hibernate 7 counterpart. #17079 is the counterpart of #17067, #17068, #17069 and #17071. A map of sort properties in a criteria query still throws a ClassCastException with Hibernate 7, on 8.0.x and at #17079. After the merge-up, that call works with Hibernate 5 and fails with Hibernate 7. Hibernate 7 needs the same fix, in #17079 or in a pull request of its own, merged before this one, as for the other parts.
3. New API on 7.0.x, as on #17067 and #17069: the public static GrailsHibernateUtil.getJoinAlias, and the protected AbstractHibernateCriteriaBuilder.getWholeAssociationPath, which every subclass of HibernateCriteriaBuilder inherits. getJoinAlias has one caller, in AbstractHibernateCriteriaBuilder. getWholeAssociationPath is protected because HibernateCriteriaBuilder calls it. The description should say why each is needed on a patch branch.
4. Add run ci, and resolve the conflicts with 7.0.x, as on the other parts. Locally, the tests of grails-data-hibernate5-core pass at this head (1285 tests, 60 skipped). The stack top returns the same rows as this head for all of these queries.
Notes
-
On James's comment,
list(sort: 't.club.name') { createAlias('team', 't') }works at this head, with the rows of point 1. -
Team.createCriteria().count { like('name', '%First%'); order('club.name') }still fails, now withColumn "CLUB_ALIAS1_.NAME" must be in the GROUP BY listinstead ofcould not resolve property. Hibernate 7 returns 5. An order in a criteriacountfails on 7.0.x for any property, as I noted on #17064, so that isn't this part's to fix. -
order('players.name')returns the team with three players three times, as Hibernate 7 on 8.0.x does. #17079 returns each team once, as it does for the other collection joins of a criteria query (point 2 on #17069). -
The description names 4a6224d as the change to review. f2e1cc6 is on top of it.
-
As a fix that changes a result, this needs a second reviewer (#17061).
Description
Part 10 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 #17069. Until that merges, this pull request also shows the commits below it. The change to review is the last commit, 4a6224d.
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
#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.
Results that change
order('author.name')in a criteria query works instead of failing. Anorderthat is passed aQuery.Orderinside the criteria of an association sorts by the property of that association, not by the property of the queried class with the same name. The join is an inner join, or a left join withgrails.gorm.leftJoinAssociationSort.orderout of the criteria of the association.The upgrade guide has a note under Grails 7.0.18, and the upgrade skill has the same entry.
Verification
The association sort and join specs of
grails-data-hibernate5-corepass on this branch, withgrails.gorm.leftJoinAssociationSortoff and on, andcodeStylepasses for the touched modules. The full build was not run locally.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