Repository navigation
Sort by and join a collection without changing what a query fetches - #17072
jdaugherty merged 16 commits into
Conversation
A sort by a property of a collection joined the collection with an inner join. It left out the instances whose collection is empty, and took the place of a fetch that the query requested for the collection. Criteria on a collection with a requested left join initialized the collection with only the elements that the criteria matched. - A sort joins a collection with a left join and does not fetch it through that join, unless the query asks for the collection to be fetched, with or without the sort. - A left join of a collection that criteria use does not fetch the collection. When the query also fetches another collection, that one is loaded once the query has run, because Hibernate would read it from the columns of the join of the criteria. - A sort by a collection next to a fetch of another collection repeats rows, and a bag cannot tell a repeated row from a repeated element, which is why Hibernate does not fetch two bags in one query. When either collection is a bag, the query throws an UnsupportedOperationException that names both, where it returned the bag with repeated elements. A query that projects values loads no collection and is not affected. A fetch that a mapping declares counts as fetched only where Hibernate joins it: not at or beyond hibernate.max_fetch_depth joins from the queried class, where Hibernate loads it with a query of its own (review 5868034911 of apache#16853). This applies with the grails.gorm.leftJoinAssociationSort setting. Without it a sort still joins a collection with an inner join, which leaves out the instances whose collection is empty. Part 12 of the split of apache#16853.
jamesfredley
left a comment
There was a problem hiding this comment.
Requested changes. A sort by a collection still drops a row that has no child.
matrei
left a comment
There was a problem hiding this comment.
Reviewed at f56d69e (base 7.0.x): 44c3a4a and the merge of #17071's head, which merges without a conflict. I probed sorts by a property of a collection, with and without a fetch of that collection or of another one, for a bag (a Collection), a set, and a bag that the mapping fetches with fetch: 'join':
- at this head, at #17071 (b42dc27), 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);
- with a team that has two members and two trophies, one with a member, one with a trophy and one with neither. Members are a bag, trophies a set.
With the setting off, this head returns the instances of #17071 for every query. With the setting on, the changes that the description lists hold:
| Setting on | #17071 | This head |
|---|---|---|
Team.where { … }.sort('members.name').list(), also a projection of name |
2 teams | 4 |
Team.list(sort: 'members.name'), also order('members.name') |
3 rows | 5: the two teams without members kept, and the team with two members twice, as without the setting |
Team.findAllByNameLike('%', [sort: 'members.name', fetch: [members: 'join']]) |
2, members not fetched | 4, members fetched, as at #17079 |
Team.list(sort: 'players.name') with a set and a team without players |
the team left out | kept |
With either setting, Team.where { members { name == 'a' } }.join('members', JoinType.LEFT).list() no longer leaves the team with a fetched bag that holds only a. The bag is now loaded when it's read, with both members. That fixes a wrong collection in the session, so I agree that this one needs no setting.
Needs a fix
1. The bag exception also applies where nothing goes wrong. With the setting on, these now throw UnsupportedOperationException: Cannot sort by a property of [members] … while the query fetches [trophies]:
| Setting on | #17071 | This head | #17079 |
|---|---|---|---|
Team.list(sort: 'members.name', fetch: [trophies: 'join']), also Team.where { … }.join('trophies').list(sort: 'members.name') |
2 teams, trophies fetched complete | throws | 2, trophies complete |
Team.list(sort: 'trophies.title', fetch: [members: 'join']) |
2, the bag holds 4 members for 2 | throws | 2, the bag holds 4 for 2 |
a mapping with members fetch: 'join', and Team.where { … }.sort('trophies.title').list(), also findAllByNameLike |
2, the bag holds 4 for 2 | throws | 2, the bag holds 2 |
The second and third rows are the case that the description explains: a fetched bag can't tell a repeated row of the sort from a repeated element.
In the first row, the bag is the collection that the query sorts by. The collection that it fetches is a set of another class, and #17071 and #17079 return both collections complete. The exception there comes from the rule that a sorted collection is fetched as well when the query fetches another one. The note gives the reason for that rule: Hibernate would fill the fetched collection with the elements of the other one "when both hold elements of the same class". Members and trophies are of different classes, so that reason doesn't apply. Fetching the sorted collection only in that case, and throwing only when a fetched collection is a bag, keeps these queries working.
As the setting becomes the default in 8.1, every such query then throws for an application that upgrades to 8.1. The 8.1 notes have to name the exception as well.
2. With the setting off, a bag that list fetches still holds repeated elements. In Team.list(sort: 'trophies.title', fetch: [members: 'join']), the bag of the team with two members holds 4 members, at #17071 and here. On 7.0.x the list returned the team four times, but it didn't fetch the bag, which then loaded its 2 members. #17071 changed 'join' into a fetch, so this comes from there, and this part fixes it only with the setting on. #17079 holds 4 as well. A mapping with members fetch: 'join' and a where query sorted by trophies.title held 4 on 7.0.x already. list would need the check of point 1 without the setting too, or not fetch a bag next to a sort by another collection.
3. The collections that are loaded after the query are loaded one instance at a time. When criteria use a collection that the query requests JoinType.LEFT for, loadFetchedCollectionsAfterQuery sets every other fetched collection to FetchMode.SELECT. initializeCollections then initializes it for each instance, which is a query per instance and collection. The comment gives the reason as a collection "of the same table" as the joined one. Limiting it to that case would keep the fetch of the others in the query. Otherwise the note should say that such a query loads the other collections with a query for each instance.
4. More public API on 7.0.x, as on the earlier parts. GrailsHibernateUtil gets these new public static methods:
isFetchRequested;- two
checkSortedCollection; keepsSortedCollectionUnfetched;fetchesAnotherCollection;findFetchedCollections;initializeCollections;- two
keepCollectionUnfetched.
5. 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 (1624 tests, 159 skipped). The stack top returns what this head returns for all of these queries.
Notes
-
On James's comment, I agree with your reply. With the setting on,
Team.list(sort: 'players.name')keeps the team without players here. -
With the setting on,
Team.where { … }.sort('members.name').list()returns 4 teams andcount()5. With the setting off, it's 2 and 3. That's the count of a collection sort, which I raised on #17064. -
With Hibernate 7, at #17079,
Team.where { members { name == 'a' } }.join('members', JoinType.LEFT).join('trophies').list()holds 4 members for 2. I'll raise that on #17079. -
As a fix that changes a result, this needs a second reviewer (#17061).
Allow an unfetched sorted bag beside a fetched set of another element type. Keep same-element legacy fetch handling, and protect a static-list fetched bag with either compatibility setting. Make utility-only fetch checks private and document secondary collection loading costs.
matrei
left a comment
There was a problem hiding this comment.
Reviewed again at 7a9c98e. Points 1, 3, 4 and 5 of my first review are fixed, and point 2 is below:
- With the setting on, a sort by a bag next to a fetched set of another class works again:
Team.list(sort: 'members.name', fetch: [trophies: 'join']), the where query withjoin('trophies'), and the criteria query withorder('members.name')return every team with the trophies complete. The compatibility page names the exception that the setting can bring. - The note says that the other collections are then loaded with a query for each instance.
- Two of the helpers are private now, and the description says why the others are shared.
- The pull request merges cleanly with 7.0.x and has
run ci, and CI passed with the tests.
Apart from these, my probes from the first review give the same results here as at f56d69e, with the setting off and on. #17079 (1cba001) now holds both members in the case of my note 8. The tests of grails-data-hibernate5-core pass here (1693 tests, 168 skipped), and the guide builds.
Needs a fix
With the setting off, a list that fetches a bag and sorts by another collection now throws on 7.0.x. It fixes the bag of point 2 by throwing the exception of the setting without it too:
| Setting off | 7.0.x | #17071 | This head | #17079 |
|---|---|---|---|---|
Team.list(sort: 'trophies.title', fetch: [members: 'join']), also 'eager' |
4 rows, the bag complete | 2 teams, the bag holds 4 members for 2 | throws | 2 teams, the bag complete |
the same with JoinType.LEFT |
3 rows, the bag complete | 2 teams, 4 members for 2 | throws | 2 teams, complete |
the same with max: 2 |
2 rows | 2 teams, 4 members for 2 | throws | 1 team, complete |
On 7.0.x these calls returned rows, because 'join' and 'eager' in list didn't fetch the bag and a join type was ignored. So on a patch branch, a call that works now fails, with the setting off, while Hibernate 7 returns the right rows. In my first review I offered the check as one way out. Seeing the result, I'd take the other one: don't fetch the bag in the query, and load it after the query, as this part already does for the other collections when criteria use a left join of a collection. The bag is then complete, the calls keep working, and list returns what #17079 returns.
The same would also answer the queries that still throw with the setting on. These are the where query, findAllByNameLike, findAllWhere, findAll with an example and the criteria query, each with fetch: [members: 'join'] and sort: 'trophies.title', and a mapping with members fetch: 'join' sorted by trophies.title. #17079 answers each of them with the bag complete, and as the setting becomes the default in 8.1, they'd throw for every application that upgrades. With the setting off, those queries hold 4 members for 2, as on 7.0.x, and loading the bag after the query would fix that too.
Smaller point
- The description still names 44c3a4a as the change to review. f56d69e and 7a9c98e are part of it too.
As a fix that changes a result, this needs a second approval under #17061.
Merge the reviewed parent fixes and defer collection fetches that would multiply bag elements. Keep requested left joins, complete fetched collections, sort-map joins and distinct static-list results in both compatibility modes.
jamesfredley
left a comment
There was a problem hiding this comment.
Requested changes. A sort that starts with the alias of the queried class is still ignored.
Merge the corrected requested-join and example-query parent while retaining deferred bag loading and opt-in collection sorts. Keep explicit intermediate joins and pagination safeguards, and align inherited replacement-fetch controls with both compatibility modes.
jamesfredley
left a comment
There was a problem hiding this comment.
Requested changes. A sort that starts with the alias of the queried class is still ignored.
jamesfredley
left a comment
There was a problem hiding this comment.
Requested changes. A sort that starts with the alias of the queried class is still ignored.
matrei
left a comment
There was a problem hiding this comment.
Third round, at 0d72684. Since my second review, 3bc6ea9 no longer throws. A fetch that a sort by a collection would repeat in a bag is now loaded after the query, with the setting off and on. 1d11c9c and 0d72684 merge #17071's heads 97c240e and 5767310. The description says to review the changes relative to #17071, and the branch merges cleanly with 7.0.x at 0c81611.
The point of my second review is fixed, with the setting off and on:
| 7.0.x (0c81611) | 7a9c98e | This head | Hibernate 7 at #17079 (eed6c6e) | |
|---|---|---|---|---|
Setting off: Team.list(sort: 'trophies.title', fetch: [members: 'join']), also with 'eager' and JoinType.LEFT |
3 or 4 rows, the bag not fetched | throws | the 2 teams with trophies, the bag complete | the same |
The same with max: 2 |
2 rows, totalCount 4 |
throws | Full, the bag complete, totalCount 2 |
the same |
Setting on: the where query, findAllByNameLike, findAllWhere, findAll with an example and the criteria query, each with fetch: [members: 'join'] and sort: 'trophies.title', and the where query and the finder of a class whose mapping has members fetch: 'join' |
the teams with trophies, the bag 4 members for 2 | throws | every team, the bag complete | every team, the bag complete |
With the setting off, the same queries now hold the 2 members, where 7.0.x held 4, as Hibernate 7 does. The criteria query and findAll with an example return Full once for each of its trophies, as they return a row for each joined row on 7.0.x. The rows I added this round hold complete bags too, where #17071 held 4 members for 2: find, findByName and the criteria get, and find with an example and findWhere, which held 1 member of 2; a page of 10; a nested bag, as in fetch: ['club.fans': JoinType.LEFT] with sort: 'players.name', in the where query, list and the criteria query; and a sort by one bag next to a fetch of another.
Needs a fix
-
With the setting on, a page sorted by a collection loads that collection with the elements on the page, when the query fetches another collection of the same class. With
class Squad { String name static hasMany = [players: Member, reserves: Member] static mappedBy = [players: 'squad', reserves: 'reserveSquad'] }
S1has the playersp1andp2and the reservesr1andr2,S2has the playerp3, andS3has neither:Setting on 7.0.x #17071 This head #17079 Squad.where { name ==~ '%' }.list(max: 1, offset: 1, sort: 'players.name', fetch: [reserves: 'join']), also withjoin('reserves'), asfindAllByNameLikeandfindAllwith an example, and as the criteria query, with the same arguments or withorder('players.name')andjoin('reserves')S1,playersnot loaded, withp1andp2;orderthrowsS1,playersnot loaded, withp1andp2S1,playersloaded withp1onlyS1,playersnot loaded, withp1andp2;findAllwith an example returnsnull(#17169)The where query with max: 2andorder: 'desc'insteadS2andS1,playersnot loadedthe same S2andS1, theplayersofS1loaded withp2onlyS2andS1,playersnot loadedlist, and the same queries without a page, keepplayerscomplete. With the setting off they're unchanged.When the query fetches another collection of the same class, the sort's left join isn't kept from fetching the collection, so that Hibernate doesn't read
reservesfrom the columns of that join. Hibernate then fetchesplayersthrough it, and on a page the rows hold only some of its elements.keepsSortedCollectionUnfetchedgives that as the reason to keep a sort's join from fetching. The deferral that this head adds can avoid it: on a page, load the other collection after the query, so that the sort's join can be kept from fetching. IndeferSortedCollectionFetches:+ CriteriaImpl.Subcriteria join = findCriteria(root, sorted); + // A left join that Hibernate fetches the sorted collection through would fill it from the rows of the page only. + boolean pagedLeftJoin = join != null && join.getJoinType() == JoinType.LEFT_OUTER_JOIN && !isFetchRequested(root, sorted) && isPaged(root); String fetched; - while ((fetched = findOtherFetchedCollection(root, sorted, true)) != null) { + while ((fetched = findOtherFetchedCollection(root, sorted, true)) != null || + pagedLeftJoin && (fetched = findOtherFetchedCollection(root, sorted, false)) != null) {
with the
joinlookup after the loop removed, andprivate static boolean isPaged(CriteriaImpl root) { Integer maxResults = root.getMaxResults(); Integer firstResult = root.getFirstResult(); return maxResults != null && maxResults < Integer.MAX_VALUE || firstResult != null && firstResult > 0; }
Integer.MAX_VALUEis what the criteria builder sets forlistwith arguments and withoutmax. With this, the rows above keepplayerscomplete and not loaded.reservesis complete too, where 7.0.x and #17071 hold only the reserves on the page. With the setting off, and without a page, no row of my probes changes, apart from which reserve a page that holds one of them has, which varies from one run to the next, and thegrails-data-hibernate5-coretests pass (2395 tests, 163 skipped). The bullet in the note that "a legacy criteria query may also fetch the sorted collection", and the first sentence that I suggest for the guide in point 2, would then add "unless the query is paged". -
The guide on where queries still describes the exception.
whereQueries.adocsays that a query that sorts by a property of one collection and fetches another "throws anUnsupportedOperationExceptionwhen either of them is a bag", that a query which fetches the collection that it sorts by "throws only when both collections are bags", and that "alistsorted by such a collection throws when the collection that it fetches is a bag". None of them throws at this head. For a class with the bagsfoosandbars,where { name ==~ '%' }.list(sort: 'foos.name', fetch: [foos: 'join', bars: 'join'])returns both bags complete, while the same query without the sort throws aMultipleBagFetchException, as on 7.0.x. The sentence "When the query fetches another collection, a collection that it sorts by is fetched as well" holds only for collections of the same class:list(sort: 'members.name', fetch: [trophies: 'join'])leavesmembersunloaded. From "When the query fetches another collection" to "or do not fetch the other one", something like this would describe this head:When a query other than
listalso fetches a collection of the same class as the one that it sorts by, the sorted collection is fetched as well, so that Hibernate does not fill the other collection from the join of the sort. The join of a sort returns a row for each element of the collection, and a bag, a collection declared as aCollection, cannot tell a repeated row from a repeated element. A query that sorts by a property of one collection and fetches a bag, also through an association, as withfetch: ['owner.pets': JoinType.LEFT], or because a mapping declaresfetch: 'join'for it, therefore loads that bag after the query, with a query of its own for each instance. This also holds without the setting.
Smaller points
- The compatibility page now has a paragraph on bags between "This page lists every such setting" and the table. It describes something that happens "with the setting disabled as well as enabled", and the page lists more than one setting. The upgrade note and the guide on where queries already say it, so I'd drop it there.
- In the upgrade note, the paragraph after the list of "A where query uses the join type that it requests for each join of the association", "For a where query whose criteria use a requested left join of a collection, the secondary loading ... applies even when their element types differ", belongs in the bullet that it qualifies. That bullet gives the reason only for collections of the same class. The same holds for the skill.
- The new public
populateArgumentsForCriteria(SessionFactory, ...)takes aSessionFactorythat nothing reads, although its Javadoc says that it tells what the mapping fetches. The same is true offetchArgumentsandquery, whichaddSortArgumentsandaddOrderPossiblyNestedpass togetOrCreateSortJoinwithout using them.getOrCreateSortJoinalso assigns the join to a local only to return it. - The description's "Verification" is for 1d11c9c.
James's three inline comments on a root alias t hold, but not because of this part. With new DetachedCriteria(Team, 't'), sort('t.name', 'desc'), list(sort: 't.name', order: 'desc'), also with max: 1, and sort('t.club.name') return the teams in the order they were saved, on 7.0.x and at this head alike. #17073 (0e290fd) sorts them, with the setting off and on, as jdaugherty replied to the first comment.
What I ran
- My probes of the first two rounds: apart from the rows above, they give the same results as at 7a9c98e, with the setting off and on. A page that ends among equal sort values, such as nulls, can hold other teams from one run to the next.
- New rows: at this head, on 7.0.x at 0c81611, at #17071 (5767310), at #17073 (0e290fd) for the root alias, and with Hibernate 7 at #17079 (eed6c6e).
- The
grails-data-hibernate5-coretests: they pass at this head (2395 tests, 163 skipped), and the guide builds.
CI passed with the tests.
As a fix that changes a result, this needs a second approval under #17061.
jamesfredley
left a comment
There was a problem hiding this comment.
Requested changes. A sort that names the root as this is still ignored.
matrei
left a comment
There was a problem hiding this comment.
Fourth round, at 76d31a7. Since my third review, 76d31a7 has merged #17071's head 89f16e8, which brings in 7.0.x at c1ce8c3, with #17067 and #17068. It also adds CollectionFetchPaginationSpec and a bullet in the note and the skill on the pages of a deferred fetch, which #17185 tracks. The code of this part is the same as at 0d72684. My probes give the same results as there, with the setting off and on, apart from which reserve a page holds and the order of teams with equal sort values, which vary from one run to the next. The grails-data-hibernate5-core tests pass (3002 tests, 163 skipped), and the guide builds. The description's "Verification" is for this head now.
A correction to my third review: it says that the branch merges cleanly with 7.0.x at 0c81611. That held for 0c81611, but before I posted the review, 7.0.x had moved to c1ce8c3, and 0d72684 conflicted with it in fetching.adoc, the note and the skill. This head merges cleanly with 7.0.x at 7165c2d, which has #17069 now as well.
Needs a fix
-
Still open from my third review:
- With the setting on,
Squad.where { name ==~ '%' }.list(max: 1, offset: 1, sort: 'players.name', fetch: [reserves: 'join'])still loads theplayersofS1withp1only, as do the other queries of that point. The patch that I suggested there still applies to this head. whereQueries.adocstill says that such a query "throws anUnsupportedOperationException".
- With the setting on,
-
The total of a static
listwhose fetch is deferred counts other rows than its pages. The new bullet says thatmaxandoffsetthen page through the rows of the sort's join, whiletotalCountcounts the distinct instances, so thattotalCount / maxcan't tell how many pages there are. With the teams of my bag rows (Fullhas two members, a bag, and two trophies;Membershas one member;Trophieshas one trophy;Emptyhas neither):The page totalCountTeam.list(max: 1, offset: n, sort: 'trophies.title', fetch: [members: 'join'])Full,FullandTrophiesfornfrom 0 to 22 The same without the fetch, offset: 1Full3 Team.where { name ==~ '%' }.list(max: 1, offset: 1, sort: 'trophies.title', fetch: [members: 'join']), also the criteria queryFull3 With the setting on, the list with the fetch has a
totalCountof 4, and the list without it 5, which counts the teams without trophies too.Once the fetch is deferred, the query of the list is the one without the fetch. Counting what that one counts, the rows of the sort's join, would make the total match the pages, as it does for the where query, the criteria query and the list without the fetch. In
CollectionFetchPaginationSpecthe total would be 4, for the four one-row pages. A where query sorted by a collection pages and counts those rows too, with both modules, as my comment on #17178 shows, so that would make the staticlistthe same as the other queries. #17185 would then only be about pages of distinct instances, a change for every query sorted by a collection. Hibernate 7 at #17079 (08325a6) counts 4 for the samelistand for the where query, and 3 without the fetch. I raised that on #17079, so both modules could count 3 there.
Smaller points
These from my third review still hold:
- The paragraph on bags on the compatibility page.
- The paragraph after the list in the note, "For a where query whose criteria use a requested left join of a collection, ...", and the same in the skill.
- The unused
SessionFactoryofpopulateArgumentsForCriteria, and the unusedfetchArgumentsandqueryofgetOrCreateSortJoin.
James's comment of 11-26 on this.name holds here, but as on 7.0.x. Team.createCriteria().list(max: 1, sort: 'this.name', order: 'desc') returns the first team that was saved, here and on 7.0.x (7165c2d). At #17073 (33970a6) it returns the last team by name, as jdaugherty replied to the comment on t.name.
What I ran
- My probes of the first three rounds: at this head, at #17071 (89f16e8) and on 7.0.x (7165c2d).
- The page rows of my third review of #17073: at this head.
- James's call: at this head, on 7.0.x and at #17073 (33970a6).
- The
grails-data-hibernate5-coretests and the guide: at this head.
CI passed at this head.
As a fix that changes a result, this needs a second approval under #17061.
…it with the setting With grails.gorm.leftJoinAssociationSort, a sort by a property of an association joins it with a left join, so that the sort keeps the instances whose association is null. A sort by a property of a collection was always joined with an inner join, and left out the instances whose collection is empty. With GORM for Hibernate 5 the setting keeps them as well (#17072), so it now does here. A count joins the collection with the same left join, so the total counts the row of such an instance. A count of a list that fetches a collection counts instances, as before, and needs none of the sort's left joins. Without the setting a sort by a collection is unchanged. With the setting, list and a criteria query return each instance once: Hibernate 7 lists an entity once when the query joins a collection, where GORM for Hibernate 5 returns it once for each element.
…into collection sorting 7.0.x now has apache#17070 and apache#17071, the two parts below this one, and the other changes merged since. No conflicts.
|
@matrei, the points of your fifth review (6096667058) and of your two comments of 11-28 are answered at 51f5ddd. The smaller point of the review, in 632d0fc:
The page of a The static Since your review, the branch also has:
|
matrei
left a comment
There was a problem hiding this comment.
Sixth round, at 51f5ddd. Since my review at 02b0749:
- 632d0fc describes the page of a
'join'fetch of the sorted collection, and names the queries of the bullet on a sorted collection fetched next to another one; - 377917b keeps the join type of a deferred bag fetch for the sort that used it (James's review 6153740585);
- 51f5ddd merges 7.0.x with #17070 and #17071 (ad82e63). It is the merge that git makes by itself, with no conflict resolved by hand.
Following #17274, each point says whether it is a change from 7.0.x that this pull request makes, a defect of the code it adds, or a case that behaves the same on 7.0.x. Nothing is left that I hold my approval for.
Fixed
-
A sort by a fetched bag whose fetch is deferred (James's review 6153740585): a change from 7.0.x that this part made. A squad Full has the regulars A and B and the trophy TA, NoRegulars has the trophy TB, NoTrophies has the regular C, and Empty has neither.
regularsis a bag. With the setting off:Squad.list(sort: ['trophies.title': 'asc', 'regulars.name': 'asc'], fetch: [regulars: JoinType.LEFT])7.0.x (ad82e63) 632d0fc This head also with 'join'or'eager'in place ofJoinType.LEFT, with the two sorts in the other order, with'regulars.name': 'desc', and withmax: 10Full, NoRegulars Full Full, NoRegulars JoinType.INNER, a sort by the bag alone, a where query and a dynamic finder are unchanged. With the setting on, 632d0fc and this head return the same rows. Withmax: 10the total is 3, the rows of the sort's join, as the description says for a static list that loads a fetched bag after the query. The three rows of the new feature fail at 632d0fc with the setting off, and pass there with the setting on. -
The page of a
'join'fetch of the sorted collection (my comment 7240878737): the setting's bullet in the note, the skill andwhereQueries.adocnow says that on a page the fetch fills the sorted collection from the rows of the page, and that leaving out the fetch or requestingJoinType.LEFTkeeps the whole collection. -
The smaller point of my fifth review: the bullet names the where query, the detached criteria, the dynamic finder, the criteria query and the example query in place of "legacy criteria query", and says that it also applies with the setting off when the query requests a left join for the sorted collection.
Not blocking
- The static
listthat fetches a bag next to another collection (my comment 7237848412): #17289 tracks it, as I offered.
What I ran
- The Hibernate 5 tests: they passed in CI at this head. Only the Groovy joint validation build is still running.
AssociationSortSpecandAssociationSortLeftJoinSpecof this head: at 632d0fc, where the three rows of the new feature fail with the setting off.- The probes of my fifth review: at this head, in both modes of the setting. They return the results of 02b0749, except for the order of rows that tie on the sort, and for which element a paged
'join'fetch holds, which depends on the order of the rows, as the note says. - The rows above: on 7.0.x (ad82e63), at 632d0fc and at this head, in both modes of the setting.
jamesfredley
left a comment
There was a problem hiding this comment.
Requested changes. A scroll that sorts one bag and joins another now fails.
borinquenkid
left a comment
There was a problem hiding this comment.
Review at 51f5ddd.
Measured: :grails-data-hibernate5-core:test at this head: 3067 tests, 0 failures, 0 errors, 168 skipped.
One regression, James's last point, confirmed by a probe. With grails.gorm.leftJoinAssociationSort on, a scroll that joins one bag and sorts another bag of the same element type no longer opens. AssociationSortMixedSquad has the bags regulars and substitutes of AssociationSortMixedMember; one squad with two of each:
AssociationSortMixedSquad.createCriteria().scroll {
join('substitutes')
order('regulars.name')
}| 7.0.x (ad82e63) | 51f5ddd | |
|---|---|---|
| setting off | opens, 4 rows | opens, 4 rows |
| setting on | opens, 4 rows | MultipleBagFetchException: cannot simultaneously fetch multiple bags: [...regulars, ...substitutes] |
The cause is in AbstractHibernateCriteriaBuilder, where the join of a sort is created: with the setting on a collection sort is now a left join, and keepsSortedCollectionUnfetched returns false when the query fetches another collection (the same-element-type case of its Javadoc), so the sorted bag is fetched too. list and get defer such fetches after the query (deferSortedCollectionFetches); scroll does not call it, so both bags are fetched in one query. It is a change from 7.0.x that this pull request makes, in code it adds, and only with the setting on.
I did not find a fix that keeps the rest: not fetching the sorted bag in a scroll is what James asks for, but the Javadoc says the fetch is there so that Hibernate does not read the elements of the fetched collection from the columns of the unfetched join. A scroll that sorts a bag and joins another bag of a different element type should be checked as well; I did not run it.
Read, not found wrong: the list and get deferral, initializeCollections and the join type kept for a deferred bag fetch (377917b).
Requesting changes for the scroll case, with a row in AssociationSortLeftJoinSpec for it. matrei approved at this head and the other points are answered.
With grails.gorm.leftJoinAssociationSort, a criteria scroll that joined one bag and sorted by another bag of the same class failed with a MultipleBagFetchException: the sort joins the collection with a left join that is fetched next to the other collection, and only list and get deferred the fetch of the other bag. The scroll now defers the fetches as list and get do, so it returns the rows of the same list with the setting off and on. A deferred collection loads when it is first read.
jdaugherty
left a comment
There was a problem hiding this comment.
@jamesfredley, @borinquenkid, the scroll that joins one bag and sorts by another (reviews of 12-03 at 51f5ddd) is fixed in 6767dce: a criteria scroll now defers the collection fetches as list and get do, so it returns the rows of the same list with the setting off and on. The thread has the rows on 7.0.x, at 51f5ddd and at this head, including a bag next to a set of another class, and the row asked for is in AssociationSortSpec, which AssociationSortLeftJoinSpec runs with the setting on.
jamesfredley
left a comment
There was a problem hiding this comment.
The items this review found have been addressed. A scroll that sorts one bag and joins another runs the query of the list.
✅ All tests passed ✅🏷️ Commit: 6767dce Learn more about TestLens at testlens.app/docs. |
matrei
left a comment
There was a problem hiding this comment.
Seventh round, at 6767dce. Since my review at 51f5ddd, 6767dce runs a criteria scroll with the deferred collection fetches of its list. That answers James's review 6161888053 and borinquenkid's review 6162665815. The push dismissed my approval.
Following #17274, each point says whether it is a change from 7.0.x that this pull request makes, a defect of the code it adds, or a case that behaves the same on 7.0.x. Nothing is left that I hold my approval for.
Fixed
-
A scroll that joins one bag and sorts by another (James's review 6161888053, borinquenkid's review 6162665815): a change from 7.0.x that this pull request made, with the setting on. A squad Full has the regulars RA and RB, the substitutes SA and SB, the reserve VA and the trophies TA and TB. A squad Subs has the substitute SC and the trophy TC, and a squad Empty has none.
regularsandsubstitutesare bags of the same class,reservesis a set of that class, andtrophiesis a set of another class:Squad.createCriteria()7.0.x (ad82e63) 51f5ddd This head scroll { join('substitutes'); order('regulars.name') }, setting onFull four times, the substitutes hold SA MultipleBagFetchExceptionSubs, Empty, Full, Full, the substitutes load when read the same, setting off Full four times, the substitutes hold SA the same Full twice, the substitutes load when read listwith the same criteria, setting off, for comparisonFull four times, the substitutes hold SA, SA, SB, SB Full twice, SA and SB the same With the setting on, the scroll also opens with the two bags swapped, with
JoinType.LEFT, withfetchMode('substitutes', FetchMode.JOIN), withmaxResults(2)orfirstResult(1), and withjoin('regulars')next to the join of the substitutes. 51f5ddd throws for all of them. I ran 18 criteria with the setting off and on. In all 36 cases the scroll here returns the rows of thelistwith the same criteria, or throws where thatlistthrows, for two fetched bags without a sort. They include a sort through an association block or an alias, and a bag next to a set of the same class or of another class. The four rows of the new feature fail at 51f5ddd. -
The scroll with the setting off: a change from 7.0.x, the one this pull request already makes for
list. 51f5ddd scrolled as 7.0.x did, and this head changes that too:- A scroll that fetches a bag and sorts by another collection now returns the rows of the sort's join only, as its
listdoes. Withjoin('substitutes')and a sort by the regulars that is 2 rows in place of 4, and withfirstResult(1)1 in place of 3. - The deferred bag loads all its elements when read. On 7.0.x the scroll leaves the substitutes of Full with SA only.
- A set of the same class, fetched next to a sort by a bag, now loads when read too, with the same elements.
I agree with this change. Without it, a scroll would return other rows than its
list, and the upgrade note and the skill now say that it doesn't. - A scroll that fetches a bag and sorts by another collection now returns the rows of the sort's join only, as its
Not blocking
- A scroll that fetches the collection it sorts by, with the setting on: the result that a collection fetch gives in a criteria scroll on 7.0.x.
scroll { join('regulars'); order('regulars.name') }leaves the regulars of Full with RA only, here and at 51f5ddd. 7.0.x ignores the fetch there, so they load RA and RB when read. A scroll that fetches a collection holds only part of it on 7.0.x as well:scroll { join('substitutes'); order('name') }leaves the substitutes with SA on 7.0.x and here, where thelistholds SA and SB. It is not for this pull request. - The description: its bullet on deferred fetches still says that the complete collections are initialized before the results are returned. A scroll leaves them to load when they are first read. The upgrade note and the skill already say this, and the description could say it too.
What I ran
- The Hibernate 5 tests: CI passed at this head, and
AssociationSortSpecandAssociationSortLeftJoinSpecpass locally. - The new feature of
AssociationSortSpec: at 51f5ddd, where its four rows fail, two inAssociationSortSpecand two inAssociationSortLeftJoinSpec. - The scroll and
listrows above: on 7.0.x (ad82e63), at 51f5ddd and at this head, with the setting off and on. Thelistrows are the same at 51f5ddd and here.
…etches #17073 strips `this` from the sort of a static list through a recursive call of addOrderPossiblyNested for the JPA criteria query, which #17072 had given the path of the association and the join types of the deferred fetches. The two merged without a conflict, and grails-data-hibernate5-core did not compile. The call passes both now.
Carries #17255 (a JPA entity with several @id properties compiles), #17265 (the OAuth2 plugin accepts an intranet authorization url and redirects once on an invalid one), #17072 (a sort by a collection joins it without changing what the query fetches) and #17073 (a sort can start with the alias of the queried class), with 7fa74e0, which makes grails-data-hibernate5-core compile again after #17072 and #17073 merged. - upgrading60x.adoc keeps the 7.1.x side; the changes to the 7.0.18 notes are applied to upgrading70x.adoc, where 7.1.x keeps them.
Carries #17255 (a JPA entity with several @id properties compiles), #17265 (the OAuth2 plugin accepts an intranet authorization url and redirects once on an invalid one), #17072 (a sort by a collection joins it without changing what the query fetches) and #17073 (a sort can start with the alias of the queried class), from 7.0.x, with 7fa74e0, which makes grails-data-hibernate5-core compile again after #17072 and #17073 merged.
Carries #17255 (a JPA entity with several @id properties compiles), #17265 (the OAuth2 plugin accepts an intranet authorization url and redirects once on an invalid one), #17072 (a sort by a collection joins it without changing what the query fetches) and #17073 (a sort can start with the alias of the queried class), from 7.0.x with 7fa74e0, and #17036 (runtime.groovy is only read when application.groovy exists), from 7.2.x. - GrailsHibernateQueryUtils keeps 7.x's populateArgumentsForListQuery and addSortArguments, which defer the fetches a collection sort would multiply, with 8.0.x's validation: an invalid direction is rejected before the sort is read, and every sort property is validated. - HibernateSession imports HashMap and LinkedHashMap. - JpaEntityTransformSpec keeps 8.0.x's features and adds 7.x's. - UndefinedAliasSortSpec and CollectionFetchPaginationSpec register their domain classes with registerDomainClasses, as the other specs on 8.0.x do. - The changes to the 7.0.18 notes are also in the 8.0.1 section of upgrading80x.adoc and in the 8.0.1 part of the upgrade skill, under "GORM for Hibernate 5". Ten rows of UndefinedAliasSortSpec fail on 8.0.x until #17308, in that spec and in RootAliasSortLegacySpec, which runs it with the setting disabled: 20 failures. They sort through a root alias that has the name of a property, as club.club.name for new DetachedCriteria(Team, 'club') and author.author.publisher.name for the alias author, with the sort argument or a sort map. The validation of the sort argument that 8.0.x adds does not know the alias of the criteria and rejects such a key with "Invalid sort property". #17308 makes the validation follow the alias.
Carries, from 7.x: #17255, #17265, #17072, #17073 and #17036, with 7fa74e0, which makes grails-data-hibernate5-core compile after #17072 and #17073; and from 8.0.x: #17295 (nimbus-jose-jwt 10.11), #17076 (with Hibernate 7, deleteAll and updateAll reject max and offset), #16725 and #17296 (the mongodb-developer skill and the scoped agent guides), #17024 (Spock conditions in if blocks and loops are asserted), #16852 and #17029 (setup-gradle 6.4.1 and setup-java 6.3.0), and #17308 (the check of the sort argument reads a key through the alias of a detached criteria that has the name of a property). - AGENTS.md keeps 8.1.x's description of grails-forge and takes 8.0.x's links to the agent guides of build-logic and grails-gradle.
Carries #17255, #17265, #17072, #17073 and #17036 from 7.x, with 7fa74e0, and #17295, #17076, #16725, #17296, #17024, #16852, #17029 and #17308 from 8.0.x. - The sort of Hibernate 5 is the 7.0.x code with the rejection of a sort by an alias that the query does not define, as the merge-up section of #17074 asks, and keeps the declared root alias and this, as #17073 asks of the merge into 9.0.x. AbstractHibernateQuery strips the root alias once, as on 7.0.x, then checks the rest from the queried class or from a declared alias and throws "Invalid sort property" for anything else. Both addOrderPossiblyNested methods of GrailsHibernateQueryUtils handle the root alias and this first and then reject a name that is not a property. GrailsHibernateUtil keeps 9.0.x's rejection. - UndefinedAliasSortSpec has 9.0.x's features for an undefined alias and 7.x's for the root alias, so a sort through an alias with the name of a property sorts, with #17308's check, and an undefined alias is rejected. - dependencies.gradle keeps 9.0.x's pins, with nimbus-jose-jwt 10.11. - The upgrade skill keeps 9.0.x's side, the Grails 9 skill, which has no 8.0.1 part. - The 9.0.x job of benchmark.yml takes setup-java 6.3.0 and setup-gradle 6.4.1, as the other jobs do. - The count features of #17308's SortArgumentValidationSpecs follow 9.0.x, where a count checks its sort as list does (#17074). With Hibernate 5, count(sort: 't.club.unknown') for the alias t is rejected, as club.unknown is; t.unknown still gives the count. With Hibernate 7, which does not sort through the alias of the queried class (#17167), a count rejects such a key, as list and get do.
Brings the merge of 7.2.x with the Hibernate 5 sort and join type changes of apache#17072 and apache#17073, apache#17308, which reads a sort key through the alias of a detached criteria and fixes the Hibernate 5 specs that the sort check rejected, and the test of nested association blocks of apache#16559. This branch changes nothing that they change, apart from the upgrade note and the skill, which merged without a conflict and keep the entries of both sides in their order. apache#17308 leaves a static list with a join type in its fetch argument as it was: it has no alias, and calls the overload without one.
Carries #17255, #17265, #17072, #17073 and #17036 from 7.x, with 7fa74e0, #17295, #17076, #16725, #17296, #17024, #16852, #17029 and #17308 from 8.0.x, and 9.0.x's merge of them, which keeps the rejection of a sort by an alias that the query does not define (#17074) beside the sort through the root alias of 7.0.x.
Description
Part 12 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 #17071, which is on
7.0.xsince ad82e63. This pull request now targets7.0.xand shows only the changes of this part.A sort by a property of a collection joined the collection with an
inner join. It left out the instances whose collection is empty, and
took the place of a fetch that the query requested for the collection.
Criteria on a collection with a requested left join initialized the
collection with only the elements that the criteria matched.
through that join, unless the query asks for the collection to be
fetched, with or without the sort.
collection. When the query also fetches another collection, that one
is loaded once the query has run, because Hibernate would read it
from the columns of the join of the criteria.
that would repeat bag elements are deferred until after the main query,
and the complete collections are initialized before results are
returned. This applies with either compatibility setting. A query
that projects values loads no collection and is not affected.
scrollof a criteria query runs the query of itslist, withthe same deferred fetches, so it returns the same rows. A scroll
reads its rows later, so a deferred collection is loaded with all of
its elements when it is first read.
A fetch that a mapping declares counts as fetched only where Hibernate
joins it: not at or beyond hibernate.max_fetch_depth joins from the
queried class, where Hibernate loads it with a query of its own
(review 5868034911 of #16853).
With the grails.gorm.leftJoinAssociationSort setting, joins introduced
only for sorting are left joins. Without it they remain inner joins and
can leave out instances whose collection is empty. Deferring fetches that
would multiply bag elements applies in both modes.
Results that change
scrollleaves a deferred collection to load when it is first read. A criteriascrollthat joins a bag and sorts by another collection returns the rows of the samelist, so with the setting off it no longer repeats its rows for each element of the fetched bag. Duplicate removal within each static-list result or page and every sort-map entry through a deferred fetch are retained.The utility-only isFetchRequested and fetchesAnotherCollection methods are now private. The remaining cross-package helpers are shared by the query, criteria-builder and static-list implementations so they apply the same fetch rules.
Verification
At 6767dce, the full Hibernate 5 core suite reported 2,903 passed, 168 skipped and zero failures, and
codeStyleof the Hibernate 5 core module passes. 6767dce runs a criteriascrollwith the deferred fetches of itslist(reviews 6161888053 and 6162665815): with the setting on, a scroll that joined one bag and sorted by another failed with aMultipleBagFetchException; its spec fails without the change in both setting modes. At 51f5ddd, which merges7.0.xwith #17070 and #17071 (ad82e63), the association sort, join type, fetch and pagination specs pass in both setting modes, and at 377917b, before that merge,codeStyleof the Hibernate 5 core module passes. 377917b keeps the join type of a deferred bag fetch for a sort that used it (review 6153740585); its spec fails without the change with the setting off. At 76d31a7, before the later merges and review rounds, the full Hibernate 5 core suite reported 2,839 passed, 168 skipped and zero failures, with root codeStyle, RAT, dependency-version validation and the guide build.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