Skip to content

Reject a sort by an alias that the query does not define - #17074

Merged
jdaugherty merged 3 commits into
apache:9.0.xfrom
jdaugherty:fix/16853-14-reject-undefined-sort-alias
Nov 25, 2026
Merged

jdaugherty merged 3 commits into
apache:9.0.xfrom
jdaugherty:fix/16853-14-reject-undefined-sort-alias

Conversation

@jdaugherty

@jdaugherty jdaugherty commented Nov 19, 2026 •

Copy link
Copy Markdown
Contributor

Description

Part 14 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.

This part makes a call that runs today throw, so under the rule from the thread it goes to the next major, 9.0.x, and not to 7.0.x. The current head is 51ba6e7, merged with the current 9.0.x and independent of the other parts of the split.

With GORM for Hibernate 5, a sort whose path starts with a name that is neither a property of the queried class nor an alias of the query was ignored: the query returned its rows in the same order for asc and desc, without an error. Any other invalid sort property throws IllegalArgumentException: Invalid sort property, and such a sort now does the same, in where queries, detached criteria, dynamic finders, list, the example queries and the sort argument of a criteria query.

A sort that starts with a declared association alias remains supported. Hibernate 5 root-alias behavior is unchanged. Hibernate 7 now reports the same invalid-sort exception across where queries, detached criteria, dynamic finders, criteria orders, static and example queries, and stored sorts used by count or get. Its existing null result for an empty example with a valid sort is unchanged; root-alias support remains a separate follow-up, tracked by #17167 with #17073 and #17063.

Results that change

  • What changes: A sort whose path starts with a name that is neither a property of the queried class nor an alias of the query throws IllegalArgumentException: Invalid sort property. Hibernate 5 ignored the sort; Hibernate 7 ignored it or failed with inconsistent exceptions. Stored sorts are also validated by count and get, even though a count does not order its result.
  • How to get the old result: Remove the sort, or define the alias in the query.
  • Setting: No setting. It is a new exception for a call that runs today, which is why it targets the next major.

The upgrade guide has note 32 in "Upgrading from Grails 8 to Grails 9", covering both Hibernate modules, count/get and optional-filter tables. The upgrade skill has the same entry.

Merge-up

Parts 1 to 13 change the same methods on 7.0.x. When they are merged up into 9.0.x they will conflict with this change in AbstractHibernateQuery, GrailsHibernateQueryUtils and GrailsHibernateUtil. The resolution is the 7.0.x code plus the rejection, which is kept for reference at fix/16853-14-reject-undefined-sort-alias-7.0.x on my fork. That reference is now 38d391d, merged with the reviewed #17073 head eba8ef9. It preserves association-path precedence when a root alias has the same name and keeps Invalid sort property for invalid remaining association paths. It is reference material for the Grails 9 merge-up, not a proposal to land this new rejection on 7.0.x.

Verification

Verification at cb432c0a73d2, a normal merge of 9.0.x that includes the upstream LDAP fix #17144 without changing the undefined-sort implementation: both full Hibernate core suites pass, with 1,317 Hibernate 5 cases (29 skipped) and 4,777 Hibernate 7 cases (20 skipped), and zero failures. The expanded undefined-sort regressions cover count/get, paging, sort maps, example queries and invalid nested paths; positive cases retain declared aliases.

The final aggregate gate passed with 34,001 tests (29,915 unit and 4,086 integration), zero failures, zero errors and 463 skipped. Transient Neo4j port-cleanup and Hibernate 7 redirect failures passed full-module isolated reruns before the aggregate reports were refreshed. Checkstyle, CodeNarc, repository conventions and enabled PMD checks are clean; RAT reports zero unknown licenses and SpotBugs is disabled. The guide build passed. This is the aggregate test/analysis gate, not build --rerun-tasks.

Current-head checks are tracked in CI run 45483620083 and Groovy Snapshot Canary run 45483625983.

The refreshed merge-up reference also passes its full Hibernate 5 suite (1,747 cases, zero failures, 163 skipped), full code style, RAT and guide generation.

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.

@jdaugherty

Copy link
Copy Markdown
Contributor Author

This one is for 9.0.x, not 7.0.x: it makes a call that runs today throw, which the rule from the dev@ thread sends to the next major. Its base is 7.0.x only because it is stacked on #17073. Please review it, but do not merge it here; I'll rebase it onto 9.0.x and change the base once the parts below it have been merged up.

With GORM for Hibernate 5, a sort whose path starts with a name that is
neither a property of the queried class nor an alias of the query was
ignored: the query returned its rows in the same order for asc and desc,
without an error. Any other invalid sort property throws
IllegalArgumentException: Invalid sort property, and such a sort now
does the same, in where queries, detached criteria, dynamic finders,
list, the example queries and the sort argument of a criteria query.

A sort that starts with an alias that the query defines, or with the
alias of the queried class, is left as it is.

Part 14 of the split of apache#16853. It makes a call that runs today throw,
so it goes to the next major and not to 7.0.x.
@jdaugherty
jdaugherty changed the base branch from 7.0.x to 9.0.x November 19, 2026 17:45
@jdaugherty
jdaugherty force-pushed the fix/16853-14-reject-undefined-sort-alias branch from cc8c7a0 to 9d65dad Compare November 19, 2026 17:46
@jdaugherty

Copy link
Copy Markdown
Contributor Author

Done: this pull request now targets 9.0.x and is one commit on 9.0.x (9d65dad). It no longer depends on the other parts of the split, so it can be reviewed and merged on its own. The earlier 7.0.x based version is kept at fix/16853-14-reject-undefined-sort-alias-7.0.x on my fork for the merge-up of parts 1 to 13.

@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 alias the query defined is refused.

PersistentProperty property = entity.getPropertyByName(sortHead);
if (property == null && !sortHead.equals(c.getAlias())) {
// not a property of the entity, so a sort by it, such as by an alias that the query does not define, can only be a mistake
throw new IllegalArgumentException("Invalid sort 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.

The query aliases club as c and sorts by c.name. That sort should run. It is refused, because this check only knows the root alias. Accept an alias the query defined.

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.

Could you provide the public GORM call and fixture for this? I reran UndefinedAliasSortSpec on this PR: all 12 cases pass, including a where query with a declared association alias, a criteria query with createAlias("club", "c") and sort: "c.name", and a detached criteria with a root alias.

The code cited here handles static list and the example/findWhere paths, which create fresh criteria and process the sort before publishing PreQueryEvent. The criteria-builder path already checks the aliases declared by the criteria. I would like to establish an end-user regression before changing this helper. An older alias-sorting omission belongs in the relevant sort PR or a follow-up, rather than expanding this PR beyond rejecting undefined aliases.

@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 9d65dad (base 9.0.x). I probed sorts by an alias that the query doesn't define, by one that it defines, by the alias of the queried class, by an association and by properties that don't exist, in list, where queries, detached criteria, dynamic finders, findAll with an example, the sort argument and order of a criteria query, a map of sorts, a paged list, count and get:

  • with Hibernate 5 at this head and at its parent on 9.0.x (e51343f);
  • with Hibernate 7 on 9.0.x;
  • with Hibernate 5 on the 7.0.x branch kept for the merge-up (cc8c7a0), at the top of the 7.0.x stack (#17073, 16bd465) and on 7.0.x (aee4c04).

The change does what the description says:

Hibernate 5 9.0.x This head
Team.list(sort: 'x.name'), also a where query, a detached criteria, sort('x.name'), a dynamic finder, findAll with an example, the sort argument of a criteria query, a map, order: 'desc' and max: 2 the rows unsorted IllegalArgumentException: Invalid sort property
Team.where { … }.sort('x.name').count(), also get() 7, and the team Invalid sort property
Team.where { def c = club; … }.list(sort: 'c.name'), createCriteria().list(sort: 'c.name') { createAlias('club', 'c') }, new DetachedCriteria(Team, 't').list(sort: 't.name') and Team.list(sort: 'club.name') sorted the same

The other invalid sort properties, sort: 'unknown' and sort: 'club.unknown', already throw Invalid sort property with Hibernate 5 on 9.0.x, so this makes the message the same for all of them. The tests of grails-data-hibernate5-core pass at this head (1294 tests, 29 skipped). It's a call that runs today and now throws, so I agree that it belongs in 9.0.x, with the note.

Needs a fix

1. Resolve the conflicts with 9.0.x. upgrading90x.adoc and the skill conflict with the notes merged into 9.0.x since. The note is "26." here, and 9.0.x has notes up to "31." now, so it becomes "32." when it's rebased.

2. Hibernate 7 on 9.0.x fails for the same sorts, but not with this exception:

Hibernate 7 on 9.0.x
Team.list(sort: 'x.name'), also a map Invalid sort property
a where query, a detached criteria, a dynamic finder, the sort argument of a criteria query, order: 'desc', max: 2 NullPointerException: Cannot invoke "jakarta.persistence.criteria.Expression.getJavaType()"
sort('x.name').list(), sort('x.name').get(), order('x.name') in a criteria query AssertionError
Team.where { … }.sort('x.name').count() 7, the sort ignored
Team.findAll(new Team(), [sort: 'x.name']) null

With this change, Hibernate 5 rejects such a sort cleanly on 9.0.x, while Hibernate 7 fails in five different ways or not at all. The note says "With GORM for Hibernate 5". Hibernate 7 should throw the same exception, in this pull request or one next to it, and the note then covers both. If that's left for later, an issue for it, linked from the note, would keep it in view. A findAll with an example that returns null looks like a bug of its own.

3. The branch for the merge-up is built on an older part 13. fix/16853-14-reject-undefined-sort-alias-7.0.x (cc8c7a0) is on e359719. The 7.0.x stack has moved on since, with 5dc4d34, b3ae39f, 429b6d5, f2e1cc6 and 35242f9 and the merges of today. 35242f9 changes the same lines of AbstractHibernateQuery that this change does, so the resolution on that branch no longer applies as it is. It also returns other rows than the stack top for an alias that is also the name of an association:

new DetachedCriteria(Team, 'club').list(sort: 'club.name') Stack top Branch for the merge-up
7 teams, by the name of the team 5, by the name of the club

That's point 2 of my review of #17073. The branch should be rebuilt on the stack once #17073 is settled.

Notes

  1. On James's comment: the static list, findWhere and the example queries can't define an alias, and a sort by an alias that a where query or a criteria query defines works here (the last row of the first table). I couldn't reproduce a refused sort by a defined alias either, so I agree with your reply.

  2. "Results that change" and the note could name count and get: they reject the sort too, although a count doesn't sort. A count from a sortable table with optional filters, built from the same sort parameter, then throws as well.

  3. At the top of the 7.0.x stack, new DetachedCriteria(Team).list(sort: 'club.unknown') fails with could not resolve property: club_alias0 of: Team, and the same holds for Player with sort: 'team.x.name'. On 7.0.x, the error names unknown of: Club. With this change on 9.0.x, it's Invalid sort property. The resolution of the merge-up should keep the 9.0.x message for it.

@codecov

codecov Bot commented Nov 22, 2026

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 75.00000% with 2 lines in your changes missing coverage. Please review.
✅ Project coverage is 65.6620%. Comparing base (51b004c) to head (51ba6e7).

Files with missing lines Patch % Lines
...ls/orm/hibernate/query/AbstractHibernateQuery.java 75.0000% 0 Missing and 1 partial ⚠️
...orm/hibernate/query/GrailsHibernateQueryUtils.java 75.0000% 0 Missing and 1 partial ⚠️
Additional details and impacted files

Impacted file tree graph

@@                Coverage Diff                 @@
##                9.0.x     #17074        +/-   ##
==================================================
+ Coverage     65.6498%   65.6620%   +0.0121%     
- Complexity      33029      33041        +12     
==================================================
  Files            2446       2446                
  Lines          121420     121428         +8     
  Branches        22528      22533         +5     
==================================================
+ Hits            79712      79732        +20     
+ Misses          31639      31629        -10     
+ Partials        10069      10067         -2     
Files with missing lines Coverage Δ
...ls/orm/hibernate/query/AbstractHibernateQuery.java 47.2906% <75.0000%> (+0.3485%) ⬆️
...orm/hibernate/query/GrailsHibernateQueryUtils.java 44.9761% <75.0000%> (+5.9517%) ⬆️

... and 6 files with indirect coverage changes

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@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 51ba6e7. The points from my first review are fixed:

  1. The pull request merges cleanly with 9.0.x, and the note is 32.

  2. Hibernate 7 throws IllegalArgumentException: Invalid sort property for the same sorts as Hibernate 5:

    • where queries and detached criteria, also with sort(), order: 'desc' and max;
    • dynamic finders, and findAll with an example;
    • the sort argument and order of a criteria query;
    • count and get with a stored sort.

    On 9.0.x these failed with a NullPointerException or an AssertionError, count ignored the sort, and findAll with an example returned null. A sort by an alias that the query defines, c.name with def c = club or with createAlias('club', 'c'), still sorts with both modules. The note covers both.

  3. The branch for the merge-up (38d391d) is merged with #17073 at eba8ef9. With Hibernate 5 it returns what the stack top returns, apart from the new exception, also for new DetachedCriteria(Team, 'club').list(sort: 'club.name'). A sort by club.unknown gets Invalid sort property there, my note 6.

With Hibernate 5, my probes from the first review give the same results here as at 9d65dad. "Results that change" and the note name count, get and the sortable table with optional filters, my note 5.

Smaller points:

  • With Hibernate 5, order('x.name') in a criteria query still fails with could not resolve property: x, as on 9.0.x, where Hibernate 7 now throws Invalid sort property.
  • With Hibernate 7, new DetachedCriteria(Team, 't').list(sort: 't.name') now throws Invalid sort property too, although t is the alias of the query. On 9.0.x it threw a NullPointerException, so nothing that worked fails. The Hibernate 7 counterpart of #17073 has to accept it, which I asked to be tracked on #17073.
  • #17157 adds a note 32 to upgrading90x.adoc as well, so whichever of the two merges second becomes 33.
  • The Groovy Snapshot Canary Build failed on 22 November, compiling an example application of the Spring Security LDAP plugin with the Groovy snapshot of that day. It passes on 9.0.x since, so a rerun should pass.
  • Not for this pull request: with Hibernate 7, Team.findAll(new Team()) returns null, with or without a sort, and find(new Team()) returns null too. An example with a property set works. That's the null the description keeps, and it looks like an issue of its own.

@testlens-app

testlens-app Bot commented Nov 24, 2026

Copy link
Copy Markdown

✅ All tests passed ✅

🏷️ Commit: cb432c0
▶️ Tests: 147316 executed
⚪️ Checks: 98/98 completed


Learn more about TestLens at testlens.app/docs.

@jdaugherty
jdaugherty merged commit 6034270 into apache:9.0.x Nov 25, 2026
99 checks passed
@jdaugherty
jdaugherty deleted the fix/16853-14-reject-undefined-sort-alias branch November 25, 2026 15:30
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

Status: Done

Development

Successfully merging this pull request may close these issues.

3 participants