Skip to content

Count a where query that has a sort - #17064

Merged
jdaugherty merged 6 commits into
apache:7.0.xfrom
jdaugherty:fix/16853-04-count-with-sort
Nov 25, 2026
Merged

jdaugherty merged 6 commits into
apache:7.0.xfrom
jdaugherty:fix/16853-04-count-with-sort

Conversation

@jdaugherty

@jdaugherty jdaugherty commented Nov 19, 2026 •

Copy link
Copy Markdown
Contributor

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

  • This PR is linked to an existing issue that has been acknowledged or approved by the project team. If no approved issue exists, please give background on why this change is necessary. Tickets are preferred for release change log history.
  • This PR addresses the complete scope of the linked issue. Partial implementations or unfinished work should not be submitted for review.
  • This PR contains a single, focused change. Unrelated changes should be submitted as separate pull requests.
  • This PR targets the correct branch for the type of change:
    • Patch release branches (e.g., 7.0.x): Bug fixes only. No new features or API changes.
    • Minor release branches (e.g., 7.1.x): New features are welcome, but breaking existing APIs must be avoided.
    • Major release branches (e.g., 8.0.x): Reserved for major changes. Breaking API changes are permitted.

Code Quality

  • I have added or updated tests that cover the changes introduced in this PR. All code contributions are expected to include appropriate test coverage.
  • I have verified that all existing tests pass by running ./gradlew build --rerun-tasks.
  • My code follows the project's code style guidelines. I have run ./gradlew codeStyle and resolved any violations. See Code Style for details.
  • This PR does not include mass reformatting, style-only changes, or large-scale refactoring unless it was explicitly approved in the linked issue. Unsolicited reformatting will not be accepted.
  • If generative AI tooling was used in preparing this contribution, a quality model was used to ensure contributions are consistent with the project's quality standards.

Licensing and Attribution

Documentation

  • If this PR introduces user-facing changes, I have included or updated the relevant documentation.
  • If this PR adds a new feature, I have updated the What's New section of the Grails Guide.
  • If this PR introduces breaking changes or changes that require user action during an upgrade, I have updated the Upgrade Notes for the corresponding version in the Grails Guide.
  • The PR description clearly explains what was changed and why.

First-time contributors: Please read our Contributing Guide before submitting.
Pull requests that appear to be auto-generated, incomplete, or unrelated to an approved issue may be
closed to help maintainers focus on reviewed and planned work. We appreciate your understanding.

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 jamesfredley left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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();

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 matrei left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.java and upgrading60x.adoc.
  • Part 6 (0309713) moves the removal into applyDeferredJoins, after the listeners, but keeps the isRowCount() condition.
  • So at the stack top (e359719), the two count projection features of 5dc4d34 fail, and projections { 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

  1. 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 the totalCount of list(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.

  2. 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 with list;
    • 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.

  3. Two style points:

    • import RowCountProjection instead of naming it in full;
    • def criteria in the new listener feature can be final.

Verified as correct

  • The new feature of WhereQueryWithAssociationSortSpec fails at part 3 with a SQLGrammarException and passes here.
  • James's listener case is fixed by 5dc4d34: the four new features of PreQueryListenerAssociationCriteriaSpec fail at eb84a32 and pass here.

@jamesfredley jamesfredley left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 jamesfredley left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Requested changes. A sort by a nested identifier still drops a row whose association is empty.

return join;
}
}
return from.join(associationName);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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
matrei previously approved these changes Nov 23, 2026

@matrei matrei left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 RowCountProjection check. 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 totalCount does.
  • The pull request has run ci, and CI passed with the tests.
  • RowCountProjection is imported, and the local in the listener feature is final.

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. list already 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.

@github-actions
github-actions Bot dismissed matrei’s stale review November 25, 2026 03:17

Dismissed automatically: the pull request changed after this approval, from 0f994bd to 7f4ae25.

matrei
matrei previously approved these changes Nov 25, 2026

@matrei matrei left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reviewed again at 7f4ae25. Since my approval, the only change is the merge of 2020942 from #17062 through #17063: the page assertion in AssociationSortSpec, one line (git diff 0f994bd213 7f4ae25c9f). CI passed with the tests.

@jamesfredley jamesfredley left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Requested changes. A sort by a nested identifier still drops a row whose association is empty.

return join;
}
}
return from.join(associationName);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

@testlens-app

This comment has been minimized.

@github-actions
github-actions Bot dismissed matrei’s stale review November 25, 2026 16:26

Dismissed automatically: the pull request changed after this approval, from 7f4ae25 to 25bdc03.

@jdaugherty
jdaugherty merged commit f28d5ca into apache:7.0.x Nov 25, 2026
12 checks passed
@jdaugherty
jdaugherty deleted the fix/16853-04-count-with-sort branch November 25, 2026 18:29
jdaugherty added a commit that referenced this pull request Nov 27, 2026
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.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

Status: Done

Development

Successfully merging this pull request may close these issues.

3 participants