Repository navigation
Count a where query that has a sort - #17064
Conversation
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.
jamesfredley
left a comment
There was a problem hiding this comment.
Requested changes. A count of a sorted query throws when a listener adds an order.
| criteria.setProjection(hibernateProjectionList.getHibernateProjectionList()); | ||
| } | ||
| criteria.setResultTransformer(CriteriaSpecification.DISTINCT_ROOT_ENTITY); | ||
| removeOrdersOfRowCount(); |
There was a problem hiding this comment.
A listener adds an order by name before a count of a sorted query. The count should return the number of matching rows. It throws, because the original sort is cleared and the listener's order is left on the count. Do not leave an order on the count.
There was a problem hiding this comment.
Fixed in 5dc4d34. Orders are removed after PreQueryEvent listeners have run, immediately before the count executes. Their joins remain, so a listener that orders through an association still restricts the count in the same way as the list. A query selecting only a count() projection is covered too.
The four new public-API cases failed before the fix. All 34 cases of the listener and association-sort specs pass with the fix, as does the module codeStyle check. The upgrade note and upgrade skill have the same clarification.
matrei
left a comment
There was a problem hiding this comment.
Reviewed at 5dc4d34 (base 7.0.x), the last two commits. I probed counts with a sort on 7.0.x (aee4c04), at part 3 (62bf8ed), at eb84a32 and here. The data is three matching teams: two with a club and players, one with neither.
The fix is right. Every count with a sort throws on 7.0.x and at part 3 with Column "…" must be in the GROUP BY list. Here it returns what the list of the same query returns:
Team.where { name ==~ '%First%' } with |
7.0.x and part 3 | This head | list() |
|---|---|---|---|
.sort('name').count(), countByNameLike('%First%', [sort: 'name']), and if (query.sort('name')) |
throws | 3 | 3 |
.sort('club.name').count(), .count(sort: 'club.name'), a detached criteria, and countByNameLike('%First%', [sort: 'club.name']) |
throws | 2 | 2 |
.join('club', JoinType.LEFT).sort('club.name').count() |
throws | 3 | 3 |
.projections { count() }.sort('club.name').list() |
throws, also at eb84a32 | [2] |
2 |
The count runs the 7.0.x statement without its order by, with the same joins, so a database that accepted the order counts as before. By #17061 that makes this a fix like any other. A grouped projection keeps its orders: projections { groupProperty('name'); count() }.sort('name') returns the same three rows as on 7.0.x.
Needs a fix
1. Parts 5 to 13 are stacked on eb84a32.
- A merge of their head with 5dc4d34 conflicts in
AbstractHibernateQuery.javaandupgrading60x.adoc. - Part 6 (0309713) moves the removal into
applyDeferredJoins, after the listeners, but keeps theisRowCount()condition. - So at the stack top (e359719), the two
count projectionfeatures of 5dc4d34 fail, andprojections { count() }.sort('name').list()still throws.
The rebase has to keep the RowCountProjection check. Squashing 5dc4d34 into eb84a32 would also keep one commit per part, and its message has no body yet.
2. The description and the note. The description names eb84a32 as the change to review.
By #17061, a fix that makes a failing call work needs no "Results that change" section, no note and no skill entry. I'd drop all three, as on #17063. The skill entry says that nothing needs to change, so it gives an upgrade nothing to do.
If you keep the note, its last sentence needs a change, and so does the commit message. With a sort by a property of a collection, count counts the rows of the join, not the instances that list returns:
Team.where { name ==~ '%First%' }.sort('players.name') |
7.0.x | This head |
|---|---|---|
list() |
2 teams | 2 teams |
count() |
throws | 5 |
list(max: 10).totalCount |
5 | 5 |
The number itself is fine:
- The count runs the same statement as that
totalCount. - A criterion on the collection,
where { players.name ==~ '%' }.count(), gives 5 on 7.0.x too.
3. Add run ci, as on #17062 and #17063: the test jobs were skipped. Locally, the tests of grails-data-hibernate5-core pass at the head (778 tests, 23 skipped).
Notes
-
With Hibernate 7 on 8.0.x (0518f48), every count above works, but a count with a sort by an association leaves out the sort's join.
Team.where { … }.sort('club.name').count()is 3 for a list of 2, as is thetotalCountoflist(max: 2, sort: 'club.name'). After the merge-up, Hibernate 5 gives 2 and Hibernate 7 gives 3 for the same call. That's for #16863, which keeps those rows in the list. -
Two counts with a sort still throw with Hibernate 5 and work with Hibernate 7:
- the criteria builder's
Team.createCriteria().count { like('name', '%First%'); order('name') }, which can share its closure withlist; projections { countDistinct('name') }with a sort.
That's not for this pull request. A later fix on 7.0.x would make a failing call work there too.
- the criteria builder's
-
Two style points:
- import
RowCountProjectioninstead of naming it in full; def criteriain the new listener feature can befinal.
- import
Verified as correct
jamesfredley
left a comment
There was a problem hiding this comment.
Requested changes. A sort by a nested identifier drops rows whose association is empty.
| */ | ||
| private boolean isForeignKeyIdentifier(PersistentEntity owner, Association association, String property) { | ||
| PersistentEntity associatedEntity = association.getAssociatedEntity(); | ||
| PersistentProperty identity = associatedEntity != null ? associatedEntity.getIdentity() : null; |
There was a problem hiding this comment.
A player whose team has no club should still be listed when the sort is team.club.id. That player is left out, because this joins club instead of sorting by the foreign key. Keep the player.
Keep the count-projection and listener-order regressions, import RowCountProjection, and remove upgrade entries for calls that previously failed. Counts preserve joined rows rather than promising a distinct entity total.
jamesfredley
left a comment
There was a problem hiding this comment.
Requested changes. A sort by a nested identifier still drops a row whose association is empty.
| return join; | ||
| } | ||
| } | ||
| return from.join(associationName); |
There was a problem hiding this comment.
Player.list(sort: 'team.club.id') should include Unattached Player, whose team has no club. That player is left out, because this joins club instead of sorting by the foreign key. Keep the player.
matrei
left a comment
There was a problem hiding this comment.
Reviewed again at 0f994bd. Every point from my first review is fixed:
- Parts 5 to 13 now have 5dc4d34, and the stack top (#17073, eba8ef9) keeps the
RowCountProjectioncheck. There,projections { count() }.sort('name').list()returns[3]and.sort('club.name')returns[2]; both threw at the old top. - The note and the skill entry are gone. The description says that a sort through a collection counts the joined rows, as
totalCountdoes. - The pull request has
run ci, and CI passed with the tests. RowCountProjectionis imported, and the local in the listener feature isfinal.
My probes give the same results here as at 5dc4d34 in my first review, and the same again at the stack top. PreQueryListenerAssociationCriteriaSpec and WhereQueryWithAssociationSortSpec pass here and at the top.
This change only makes a failing call work, so one approval is enough.
Two optional points about the description:
- It still names only eb84a32 as the change to review. 5dc4d34 is part of it too, and its commit message has no body. Neither matters if the pull request is squashed.
- James's new comment on
Player.list(sort: 'team.club.id')is the one from #17062.listalready dropped that player on 7.0.x, and this part doesn't change that. It's for the follow-up issue you asked for there.
jamesfredley
left a comment
There was a problem hiding this comment.
Requested changes. A sort by a nested identifier still drops a row whose association is empty.
| return join; | ||
| } | ||
| } | ||
| return from.join(associationName); |
There was a problem hiding this comment.
Player.list(sort: 'team.club.id', max: 10) should include Unattached Player, whose team has no club. That player is left out, because this joins club instead of sorting by the foreign key. Keep the player.
This comment has been minimized.
This comment has been minimized.
The sort now matches the Hibernate 5 parts on 7.0.x (#16853, #17062, #17064, #17065 and the approved #17070) and nothing beyond them: - A sort by a property of a collection joins it with an inner join with or without leftJoinAssociationSort, as merged Hibernate 5 does; the left join with the setting is #17072, still under review. - An order in an association block of a criteria query becomes an order by the path through the association when the block ends, and sorts through the join of the block, as with Hibernate 5. AssociationOrder, AssociationOrders and the per-block contexts are removed, and with them the orders by aliases of a block or of the criteria around it. - Orders in the blocks of a detached criteria that the builder did not build, and in the block of an embedded component, are ignored, as with Hibernate 5 and on 8.0.0. Sorts through an embedded component are read as a path, as on 8.0.0, and the fixes for blocks inside an embedded block are removed. - A block order in a distinct, grouped or aggregate query reaches the database, as with Hibernate 5, instead of being rejected beforehand. - grails.gorm.PagedResultList and the TCK DetachedCriteriaSpec are back as on 8.0.x. HibernateQuery.clearOrders() keeps the cleared orders, whose joins a count still makes, as Hibernate 5 keeps the alias that an order joined. - The new methods of ExpressionResolver and JpaQueryContext are package-private.
Description
Part 4 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 #17063. 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 #17063.
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.
This makes a failing sorted count work. The count keeps the joins of the query, including those added by PreQueryEvent listeners, and removes ordering immediately before execution. A collection join counts joined rows, as totalCount does; this is not a distinct-entity count.
The nested-association-identifier finding on static list is tracked separately by #17160; it is not introduced by this sorted-count change.
Verification
At 7f4ae25 the full Hibernate 5 core suite passes (783 cases, zero failures, 28 skipped), including the count-projection and listener regressions. Full codeStyle, RAT and the guide build pass. The merge carries the reviewed parent fixes and resolves the release-branch conflicts.
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