Skip to content

Sort list by every sort property, and join an association once - #17062

Merged
jdaugherty merged 4 commits into
apache:7.0.xfrom
jdaugherty:fix/16853-02-sort-every-property
Nov 25, 2026
Merged

jdaugherty merged 4 commits into
apache:7.0.xfrom
jdaugherty:fix/16853-02-sort-every-property

Conversation

@jdaugherty

@jdaugherty jdaugherty commented Nov 19, 2026 •

Copy link
Copy Markdown
Contributor

Description

Part 2 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 #16853. Until that merges, this pull request also shows the commits below it. The original change is 279520e; fdc3ec9 merges 7.0.x and addresses the review feedback.

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".

Results that change

  • What changes: The order of the results of list with a Map of sort properties, or with a default sort on more than one property: every entry is applied, not only the last. The rows selected by max and offset can change. Sorting by two properties of the same collection also returns fewer duplicate rows: an instance with three elements occurs three times, rather than nine times from two joins.
  • How to get the old result: Pass one sort property.
  • Setting: No setting. The call asks for every sort property, and repeated joins of one collection were unintended.

The upgrade guide has a note under Grails 7.0.18, and the upgrade skill has the same entry.

The separate static-list/criteria behavior for a nested association identifier, raised in review, is tracked by #17160; it is outside this sort-map and join-reuse change.

Verification

At 2020942 the full Hibernate 5 core suite passes (777 cases, zero failures, 28 skipped), including the pagination regression with explicit expected page names. The full codeStyle check, RAT and the guide build pass on the merged branch. Join lookup is private to its only caller.

The focused regression features cover every sort-map entry before paging, every mapped default sort property, reuse of an association join for list and query-by-example, collection duplicate counts, two nested paths through one association, and findWhere/findAllWhere with two association sorts.

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.

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.

@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 an association's identifier drops a row whose association is empty.

private boolean isForeignKeyIdentifier(PersistentEntity owner, Association association, String property) {
PersistentEntity associatedEntity = association.getAssociatedEntity();
PersistentProperty identity = associatedEntity != null ? associatedEntity.getIdentity() : null;
if (session == null || identity == null || !identity.getName().equals(property)) {

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 stay when the list sorts by team.club.id. The player is dropped, because the sort joins club instead of using the foreign key. Sort by the foreign key, and keep the player.

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.

This part only changes the sort-map handling and join reuse in GrailsHibernateQueryUtils and GrailsHibernateUtil; AbstractHibernateQuery is unchanged from part 1. Part 1 already reads a nested association identifier through its foreign key for where queries and detached criteria, and those regression cases pass.

If the reproducer is Player.list(sort: "team.club.id"), that is the separate static-list path, which already joins the final association before this part. Please open a follow-up issue for that case rather than extending the sort-map PR. If this is a where query or detached criteria, could you post the public GORM call and fixture that fail? That would let us target the finding to the part that introduces it.

@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 279520e (base 7.0.x), the last commit; the five below it are #16853. I ran this pull request's seven specs at the head and with part 1's main sources (e210655). Part 1 changes only AbstractHibernateQuery, so for list those are 7.0.x's. 7 of the 91 tests fail there and pass here; the other 84 pass on both.

The change is right, and it belongs on 7.0.x without a setting: a sort entry that is dropped, and a row repeated for each pair of elements, both contradict the call. Two things before it can land.

Needs a fix

1. Rows change, and the description and the note say they don't.

  • Team.list(sort: ['players.name': 'asc', 'players.id': 'asc']) returns a team with three players 9 times on 7.0.x, once for each pair that the two joins of players make. This head returns it 3 times. That's the test "list sorted by two properties of a collection returns a team once for each of its players".
  • With max or offset, the rows on a page change once every entry sorts. #17061 counts that as a result change too.

Please put both in "Results that change", in the 7.0.18 note and in the skill entry. "No setting" still holds.

2. Add run ci. On 7.0.x the tests run only on request, so no part of the stack has run its tests in CI: the test jobs of this pull request were skipped. The description says the full build wasn't run locally either. The same goes for parts 3 to 13.

Notes

  1. GrailsHibernateUtil.findJoinCriteria is a new public method on a patch line. Its only caller, here and at the top of the stack (#17073), is GrailsHibernateQueryUtils. As a private method there, with its three helpers, it adds no API that later lines have to keep.

  2. The 84 tests that pass without this commit pin the behavior that the later parts build on. None of the 58 feature methods changes up to #17073, so they work as guards. A reviewer of this part still has to find the 7 that it fixes, so a line in the description naming them would help:

    • list sorted by a map sorts by every entry of the map
    • list sorts by every property of the default sort of the mapping
    • #api sorted by two properties of an association joins the association once, for list and findAll by example
    • list sorted by two properties of a collection returns a team once for each of its players
    • findAll by example can be sorted by two paths through the same association
    • findAllWhere and findWhere can be sorted by two properties of an association
  3. On James's comment: Player.list(sort: 'team.club.id') does drop a player whose team has no club, but this commit doesn't change that. With one such player and one in a team with a club:

sort: 'team.club.id' 7.0.x Part 1 This head #17073, setting off #17073, setting on
Player.list(sort:), createCriteria().list(sort:) { } dropped dropped dropped dropped kept
createCriteria().list { order('team.club.id') } throws throws throws dropped kept
findAllByNameLike('%', [sort:]), where { name ==~ '%' }.list(sort:), DetachedCriteria.sort() kept kept kept kept kept
where { team.name ==~ '%' }.list(sort:) throws kept kept kept kept

So with the setting off, list and criteria queries drop a row that a dynamic finder and a where query keep for the same sort, and they already did on 7.0.x. That's the case where another API returns something else for the same request, so I'd fix it on 7.0.x without the setting: sort list and criteria queries by the foreign key of a nested association id, as part 1 does for where queries. That belongs in a part of its own, though, not in this one.

Verified as correct

  • Hibernate 7 on 8.0.x (0518f48) already sorts list by every entry of a sort map, and findAllWhere with two sorts through club works there. The merge-up brings Hibernate 5 to the same result. (Hibernate 7 rejects a sort by a property of a collection with a PathException, which is part 12's subject.)
  • The note sits under === Grails 7.0.18, without a number, and the skill has the same entry.

Keep join lookup private to its only caller. Document changed page contents and collection duplicates, and cover sorting before pagination. Preserve both sets of upgrade notes when merging the release branch.
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 fdc3ec9. Both points from my first review are fixed:

  • "Results that change", the 7.0.18 note and the skill entry now name both changes: the rows on a page, and a team with three players returned 3 times instead of 9.
  • The pull request has run ci, and CI passed with the tests.

findJoinCriteria is now private in GrailsHibernateQueryUtils, so this part adds no API.

With part 1's main sources, the same 7 features of AssociationSortSpec fail as before, and all 29 pass at this head.

One optional point: the new paging assertion compares the page with the unpaged list of the same call, so it holds without this change too. With part 1's sources, the list is MU First Team, Chelsea First Team, Arsenal Second Team, Arsenal First Team, and the page is Chelsea First Team, Arsenal Second Team, which is results[1..2]. The feature still fails there, on the assertion above it. To make the page assertion pin the page itself, compare it with the names:

Team.list(sort: ['club.name': 'asc', name: 'desc'], max: 2, offset: 1)*.name == ['Arsenal First Team', 'Chelsea First Team']

Since this part changes results, it needs a second approval under the rule of #17061.

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

Dismissed automatically: the pull request changed after this approval, from fdc3ec9 to 2020942.

@testlens-app

This comment has been minimized.

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 2020942, which takes my optional point: the page assertion now names the page, ['Arsenal First Team', 'Chelsea First Team']. With part 1's sources the page is Chelsea First Team, Arsenal Second Team, so this assertion no longer holds without the change either. AssociationSortSpec passes at this head, and CI passed with the tests.

As before, this part changes results, so it needs a second approval under #17061.

@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 left join the call asked for is undone by a sort, so a team with no club is left out of the page.

for (Object o : fetch.keySet()) {
String associationName = (String) o;

final FetchMode fetchMode = getFetchMode(fetch.get(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.

Team.list(sort: ['club.name': 'asc', name: 'desc'], fetch: [club: JoinType.LEFT], max: 2) should include Unattached First Team. The page has only the team that has a club. The left join is not made, and the sort joins club as an inner join. Keep the left join.

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.

This is pre-existing static-list fetch behavior and is outside the scope of this PR. At this head, the fetch parser does not recognize JoinType.LEFT, so the sort creates an inner join. This part applies every sort-map entry and reuses association joins; it does not add support for typed fetch requests.

Applying the requested join type before sorting belongs to #17071, which handles static list and the example-query APIs. The LEFT-fetch/sort regression there passes in both compatibility modes. Keeping that implementation in #17071 preserves the agreed split; #17062 retains its explicit sort-map paging regression.

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

Dismissed automatically: the pull request changed after this approval, from 2020942 to d456e11.

@jdaugherty
jdaugherty merged commit 05bd904 into apache:7.0.x Nov 25, 2026
12 checks passed
@borinquenkid

Copy link
Copy Markdown
Member

#17052 repeats the map sort and the join-once of this pull request. It is a draft that waits for this one, and those parts go when this one merges. What stays in it is the composite id sort, empty in lists, the hasMany default sort and the map sort of a criteria builder, which this pull request does not change.

borinquenkid added a commit that referenced this pull request Nov 26, 2026
The sort-map and join-once work of #17062-#17066 replaces this branch's
own: the sort of a where query, the paged list and the JPA path now use
7.0.x's joins. Kept from this branch: the criteria-builder map sort, the
direction of a map entry that is not a String, the composite id sort,
the empty in list and the hasMany sort error. The upgrade note keeps
only those.

Claude-Session: https://claude.ai/code/session_01Dmki4RzWwreEC2GkkyFnvL
jdaugherty added a commit that referenced this pull request Nov 27, 2026
…hrough

The total of a paged list sorted by a property of a collection, and count
on a where query with such a sort, counted each instance once. max and
offset page through the rows of the join, one for each element, so with
that total the last rows were on a page that the total did not reach.

They count the rows of the join again, as GORM for Hibernate 5 does on
7.0.x (#17062).
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.
jdaugherty added a commit that referenced this pull request Nov 27, 2026
…o work

The merge-up of 7.2.x brought the Hibernate 5 fixes that join an association
once for every restriction of a where query (#17062, #17066), so "a where query
joins an association path once" of QueryEntryPointScenariosSpec passes and is
no longer pending (#16905). It failed the Hibernate 5 functional tests of
58da559 with PendingFeatureSuccessfulError.
@jdaugherty
jdaugherty deleted the fix/16853-02-sort-every-property branch December 3, 2026 12:10
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.

4 participants