Repository navigation
Apply a requested join type to updateAll and deleteAll - #17068
Conversation
Team.where { ... }.join('club', JoinType.INNER) lists and counts the
teams with a club, but deleteAll and updateAll on it ignored the join
type and deleted or updated the teams without a club as well. They now
modify the instances that list returns.
An update or a delete cannot join, so each requested join becomes a
restriction: a subquery that selects from the entity of the first
association on the path and joins the rest of it. deleteAll selects the
identifiers first when the path starts with a collection that has a
join table, because Hibernate deletes the join rows before the
instances with the same restriction. A one-to-one whose foreign key the
other class has is matched through the property that refers back.
MySQL, and MariaDB before 10.3, do not allow an update or a delete to
select from the table that it modifies. For a join that leads back to
the queried class, these dialects get an UnsupportedOperationException
that says to restrict the query with criteria instead.
Part 8 of the split of apache#16853.
jamesfredley
left a comment
There was a problem hiding this comment.
Requested changes. A bulk write with an inner join updates every row, including one with no association.
| if (associatedEntity == null && !(association instanceof Basic)) { | ||
| return null; | ||
| } | ||
| String joinAlias = "join" + index + '_' + i; |
There was a problem hiding this comment.
One row has a category. Another has none. An inner join of category and updateAll should change only the row that has a category. Both rows change, because the join's alias is the same as the outer alias. Give the join its own alias.
There was a problem hiding this comment.
Fixed in b3ae39f. The generated aliases for a requested bulk join and its owner subquery are now derived from the outer alias, so neither can shadow it.
The new public-API regression uses an entity whose decapitalized name equals the old generated alias, and checks both updateAll and deleteAll. Both failed before the fix; the requested-join specs in both sort-setting modes and the dialect spec now pass: 215 cases, 208 passed and 7 skipped. The module codeStyle check passes too.
jamesfredley
left a comment
There was a problem hiding this comment.
Requested changes. A bulk write ignores a join that a subquery asked for.
| if (!(criteria instanceof AbstractDetachedCriteria)) { | ||
| return query; | ||
| } | ||
| Map<String, JoinType> joinTypes = ((AbstractDetachedCriteria<?>) criteria).getJoinTypes(); |
There was a problem hiding this comment.
A subquery joins author as an inner join, so a book with no author is left out of the list. The same subquery in a bulk update still changes that book, because the join is ignored. Apply the join the subquery asked for.
jamesfredley
left a comment
There was a problem hiding this comment.
Requested changes. A bulk write ignores a join that a subquery asked for.
| if (!(criteria instanceof AbstractDetachedCriteria)) { | ||
| return query; | ||
| } | ||
| Map<String, JoinType> joinTypes = ((AbstractDetachedCriteria<?>) criteria).getJoinTypes(); |
There was a problem hiding this comment.
A subquery joins author as an inner join, so a book with no author is left out of the list. The same subquery in a bulk update still changes that book, because this only looks at the outer criteria. Apply the join the subquery asked for.
matrei
left a comment
There was a problem hiding this comment.
Reviewed at 07b71ee (base 7.0.x): ae6dbd1, b3ae39f and the merge of #17067's head, which leaves the diff of the two commits as it was. I compared list and count with updateAll and deleteAll on queries that request a join type:
- at this head, at #17067 (1814db6), on 7.0.x (aee4c04) and at the stack top (16bd465);
- with Hibernate 7 on 8.0.x (0518f48) and at #17079 (6de9334);
- for a to-one association, a right join, a nested path, a path through a collection, a
hasOne, a unidirectional collection with a join table, a many-to-many from both sides, and a collection of a basic type; - for a query without criteria, with a root alias, with two requested joins, and with a join type that a later fetch mode replaced;
- with discriminator multi-tenancy, for collections whose elements belong to tenants.
Without multi-tenancy, updateAll and deleteAll change here the rows that list returns in each of these cases, as at #17079. A subquery is the exception (point 3).
| 7.0.x | #17067 | This head and #17079 | |
|---|---|---|---|
Team.where { name ==~ '%First%' }.join('club', JoinType.INNER).updateAll(name: 'X'), also JoinType.RIGHT and join('players', JoinType.INNER) (list: 4) |
5 updated | 5 | 4 |
Player.where { … }.join('team.club', JoinType.INNER).updateAll(…) (list: 6) |
7 | 7 | 6 |
Team.where { … }.join('players.contract', JoinType.INNER).updateAll(…) (list: 4) |
7 | 7 | 4 |
deleteAll with an inner join of a unidirectional collection, or of a many-to-many (list: 1) |
2 deleted | 2 | 1 |
At #17067, list and count already leave the rows out while updateAll and deleteAll don't, so the two parts belong in the same release, as the description says. No setting, agreed.
Needs a fix
1. With discriminator multi-tenancy, updateAll fails for an inner join of a collection whose multi-tenant elements refer back to their owner. Shelves that aren't multi-tenant, with books that are. Under one tenant, list returns only the shelf that has a book of that tenant. updateAll with the same join fails with a syntax error:
Shelf.where { name ==~ '%shelf' }.join('books', JoinType.INNER) |
7.0.x | #17067 | This head | #17079 |
|---|---|---|---|---|
list() |
2 shelves | 1 | 1 | 1 |
updateAll(name: 'X') |
2 updated | 2 | throws | 1 |
The SQL that H2 rejects:
update mt_shelf set name=? where (name like ?) and (exists (select 1 from mt_book mtbook1_ where ? = mtbook1_.tenant_id and (mtbook1_.id in (select books2_.id from mt_book books2_ where mt_shelf.id=books2_.shelf_id and :tenantId.tenantId = books2_.tenant_id))))
Hibernate 5 renders MEMBER OF on a one-to-many as a subquery and leaves the parameter of the tenant filter in it unbound. A call that worked on 7.0.x now throws.
A unidirectional collection, which has a join table, works. updateAll and deleteAll change the one case that list returns there. For a collection whose elements refer back to the owner, matching them through that property, as in book.shelf = shelf, avoids MEMBER OF, as the commit already does for a hasOne. It would also keep the tenant filter in the one subquery.
2. The MySQL exception should be in "Results that change". On MySQL, and on MariaDB before 10.3, updateAll and deleteAll with a join type for a path back to the queried class, such as join('parent', JoinType.INNER), now throw an UnsupportedOperationException. The same holds for a path that starts with a collection of a basic type. On 7.0.x these calls updated or deleted rows. The note says so, but the description doesn't. It's a call that worked and now fails, which by #17061 the description has to name.
deleteAll through a join table already selects the identifiers first, in deleteByIdentifiers. In a statement of its own, that select doesn't run into the restriction of MySQL, which applies to a subquery of the update or delete itself. Doing the same for these paths, and for updateAll, would make them work there instead of throwing. Then the dialect check and the exception wouldn't be needed.
3. James's second comment holds: a subquery's requested join isn't applied to updateAll and deleteAll. Since #17067, list applies the join type that a subquery requests. applyRequestedJoins reads only the join types of the outer criteria:
list |
updateAll / deleteAll here, at the stack top and at #17079 |
|
|---|---|---|
new DetachedCriteria(Team).inList('id', Team.where { name ==~ '%First%' }.join('club', JoinType.INNER).id()), also Team.where { id in … } |
4 teams | 5 updated |
the same for Team.where { name == 'Empty Team' || name == 'Playerless First Team' }, one of them without a club |
1 | 2 deleted |
So the description's "They now modify the instances that list returns" doesn't hold for these. #17079 has the same gap.
4. Add run ci, and resolve the conflicts with 7.0.x, as on #17066 and #17067. Locally, the tests of grails-data-hibernate5-core pass at this head (1096 tests, 55 skipped).
Notes
-
The description names ae6dbd1 as the change to review. b3ae39f is on top of it now.
-
updateAllanddeleteAllwith criteria on an association, such asTeam.where { club.name == 'Chelsea' || name == 'Unattached First Team' }, throwJoins cannot be used in a DELETE or UPDATE operationon 7.0.x and on 8.0.x, with or without a join type. That isn't for this pull request. The description's "They now modify the instances that list returns" holds for queries without such criteria. -
With Hibernate 7 at #17079,
deleteAllof the cases with an inner join of their multi-tenant items deletes 2 whilelistreturns 1. I'll raise that on #17079. -
The imports of
AssociationSortSpecandWhereQueryWithAssociationSortSpecmove again, as in #17066 and #17067. -
As a fix that changes a result, this needs a second reviewer (#17061).
Select matching identifiers before bulk operations whose subqueries request joins. Correlate bidirectional collections through the owning property so tenant-filter parameters stay bound. Cover updates and deletes through nested criteria and tenant-scoped collection updates.
matrei
left a comment
There was a problem hiding this comment.
Reviewed again at b90b90b. The points from my first review are fixed:
- With discriminator multi-tenancy,
updateAllno longer throws for an inner join of a collection whose multi-tenant elements refer back to their owner.Shelf.where { name ==~ '%shelf' }.join('books', JoinType.INNER).updateAll(name: 'X')updates the one shelf thatlistreturns, as at #17079. - The description names the
UnsupportedOperationExceptionon MySQL, and on MariaDB before 10.3. updateAllanddeleteAllapply the join type that a subquery requests: they select the identifiers first, and then update or delete those. They now change the rows thatlistreturns, as at #17079, for:- the
inListandid insubqueries of my first review; - a subquery inside a subquery;
- a subquery in a query with a root alias;
- a subquery together with a join type that the outer query requests;
- a subquery that joins a many-to-many or a collection of a basic type;
- under a tenant, a subquery that joins the tenant's elements of a collection.
- the
- The pull request merges cleanly with 7.0.x and has
run ci, and CI passed with the tests.
That also answers James's comment on subqueries. Apart from these fixes, my probes from the first review give the same results here as at 07b71ee. #17079 (1cba001) has the same fixes, also for the multi-tenant deleteAll of my note 7, and otherwise gives the same results as at 6de9334. The tests of grails-data-hibernate5-core pass here (1135 tests, 60 skipped), and the guide builds.
Smaller points:
- With
modifyByIdentifiers, a path back to the queried class could work on MySQL too. The identifiers are selected in a statement of their own, and the update or the delete is then restricted by a list of values, not by a subquery of its own table. The calls would then keep working on MySQL, where they now throw, and the dialect check and the exception wouldn't be needed. - The description still names ae6dbd1 as the change to review. b3ae39f and b90b90b are part of it too.
- The imports of
WhereQueryWithAssociationSortSpecare reordered again here, and the two duplicatespock.langimports from #17067 are still there.
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 bulk update changes a team that the same query does not list.
| if (requestedJoin.getValue() == null || requestedJoin.getValue() == JoinType.LEFT) { | ||
| continue; | ||
| } | ||
| String restriction = buildRequestedJoinRestriction(criteria.getPersistentEntity(), requestedJoin.getKey(), index); |
There was a problem hiding this comment.
A team has players and no club. Listing it, sorted by club.name and joining players as an inner join, returns nothing. Updating through that same query renames the team. The write should change only the rows the list returns. Leave the team alone.
There was a problem hiding this comment.
The explicit INNER request for players is applied here; a team with players satisfies it. The list excludes this team because sorting by club.name adds another, implicit INNER join. The source audit identifies the bulk write ignoring that sort-induced restriction as pre-existing on 7.0.x. I narrowed the description to explicitly requested join restrictions and opened #17170 to decide and test the implicit-sort/bulk-write contract separately.
matrei
left a comment
There was a problem hiding this comment.
Third round, at f8445be. The one new commit is the merge of #17067's f9362bd: git diff b90b90b32f f8445bef35 shows its four lines and nothing else, and it dismissed my approval. It also settles two of my smaller points. The description no longer names a single commit to review, and WhereQueryWithAssociationSortSpec imports each class once, as at #17067.
CI passed, apart from build_grails of the Groovy Joint Validation Build. There MicronautErsatzRoundtripSpec failed at ersatz.verify() in the Micronaut example. That's unrelated, and of the same kind as the Ersatz failure on #17065 that passed on a rerun.
On James's comment of yesterday: the case holds, but it comes from the sort, not from this part. I ran it at this head, on 7.0.x (28f27fe), at #17079 (0973b8a) and on 8.0.x (99aedeb):
Team.where { name == 'Unattached First Team' }.sort('club.name').join('players', JoinType.INNER), a team with a player and no club |
list |
count |
updateAll(name: 'X') |
|---|---|---|---|
| 7.0.x | nothing | throws (H2: "must be in the GROUP BY list") | 1 |
| This head | nothing | 0 | 1 |
This head, with grails.gorm.leftJoinAssociationSort: true |
the team | 1 | 1 |
| #17079, without and with the setting | nothing, the team | 0, 1 | 1, 1 |
| 8.0.x | nothing | 1 | 1 |
Without the join, Team.where { name == 'Unattached First Team' }.sort('club.name') gives the same results on each of them. While the setting is off, the sort joins club with an inner join, which leaves the team out of list. An update or a delete doesn't apply a sort, on 7.0.x either. That is the old result that #17065 keeps by default. With the setting on, list, count and updateAll agree, and #17079 returns the same with and without it. Applying the sort's inner join to updateAll would let a sort decide what an update changes, and would set Hibernate 5 apart from Hibernate 7, so I wouldn't change it.
Optional
The note says that updateAll and deleteAll "update or delete the instances that list returns". That holds for the join type, but not for the instances that a sort by an association leaves out of list while the setting is off. Maybe a sentence after it:
A sort is not applied to an update or a delete. While
grails.gorm.leftJoinAssociationSortis off, a sort by a property of an association leaves the instances whose association isnullout oflist, andupdateAllanddeleteAllstill change them.
My optional point from round 2 on modifyByIdentifiers and MySQL stands. It needn't hold this part.
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 bulk update still changes a team that the same query does not list.
| } | ||
|
|
||
| org.hibernate.query.Query query = session.createQuery(jpaQueryInfo.getQuery()); | ||
| org.hibernate.query.Query query = session.createQuery(applyRequestedJoins(jpaQueryInfo.getQuery(), criteria)); |
There was a problem hiding this comment.
A team has players and no club. Listing it, sorted by club.name and joining players as an inner join, returns nothing. Updating through that same query renames the team. The write should change only the rows the list returns. Leave the team alone.
This comment has been minimized.
This comment has been minimized.
matrei
left a comment
There was a problem hiding this comment.
Fourth round, at f8ec784. It merges #17067's 4301e58 and adds nothing to it: my own merge of f8445be and 4301e58 gives the same tree. The push dismissed my approval of round 3.
The description now says that updateAll and deleteAll apply the join types that the query requests, and that #17170 tracks the instances that a sort leaves out of list. That's the case of James's comment, so the description and my round-3 table now agree. My optional sentence for the note stands. It can also go with #17170.
CI passed with the tests.
As a fix that changes a result, this needs a second approval under #17061.
borinquenkid
left a comment
There was a problem hiding this comment.
Approved. One nit: the docs say writes change exactly what list returns, which is stronger than the code guarantees (the bulk-update case is tracked in #17170).
sbglasius
left a comment
There was a problem hiding this comment.
This is an AI assisted review
The approach looks right to me, and there's good test coverage, including tenant filters and the dialect matrix. Two things:
- MySQL / MariaDB < 10.3 rejection (
HibernateSession.java:436):modifyByIdentifiersalready selects the identifiers in a separate statement and then updates or deletes by id. That avoids the "can't select from the table being modified" limit. Could the self-referencing path fall back to it instead of throwingUnsupportedOperationException? Thenjoin('parent', JoinType.INNER).deleteAll()would work on every dialect, and the docs and upgrade note wouldn't need the MySQL caveat. - Two id-batching paths (
:221and:302):deleteByIdentifierscuts the WHERE clause off an HQL string, which breaks if the builder's prefix ever changes.modifyByIdentifiersbuilds its query from the criteria. Could the join-table delete case usemodifyByIdentifierstoo, so only one path is left?
Nit: restrictsThroughJoinTable (:287) silently swallows RuntimeException. A narrower catch, or a comment saying why, would help.
On MySQL, and MariaDB before 10.3, a requested join whose path leads back to the queried class, or starts with a collection of a basic type, made updateAll and deleteAll throw UnsupportedOperationException. They now select the identifiers first and update or delete by them, as they already did for a join requested by a subquery, so these calls work on every dialect. A delete through a collection that has a join table uses the same path, which replaces the second id-batching implementation that cut the WHERE clause off the generated HQL. The path walk that builds a restriction now also reports whether it goes through a join table, so the check no longer catches RuntimeException from the persister. Duplicate and null identifiers that a join selects are dropped before batching. The guide, the upgrade note and the upgrade skill drop the MySQL caveat, no longer say that bulk writes change exactly what list returns, and say that a sort is not applied to an update or a delete.
|
Pushed 140aa7b. It merges 7.0.x, which now has #17067, and addresses the review. sbglasius's review
borinquenkid's nit, and matrei's optional sentence: the guide, the upgrade note and the skill now say that |
Description
Part 8 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 #17067, which is merged. 7.0.x is merged in, so the diff now shows only this part.
Team.where { ... }.join('club', JoinType.INNER) lists and counts the
teams with a club, but deleteAll and updateAll on it ignored the join
type and deleted or updated the teams without a club as well. They now
apply those explicitly requested join restrictions to the write.
An update or a delete cannot join, so each requested join becomes a
restriction: a subquery that selects from the entity of the first
association on the path and joins the rest of it. deleteAll selects the
identifiers first when the path starts with a collection that has a
join table, because Hibernate deletes the join rows before the
instances with the same restriction. A one-to-one whose foreign key the
other class has is matched through the property that refers back.
MySQL, and MariaDB before 10.3, do not allow an update or a delete to
select from the table that it modifies. For a join that leads back to
the queried class, or that starts with a collection of a basic type,
these dialects select the identifiers first and update or delete by
them, as deleteAll does for a join table.
Results that change
updateAllanddeleteAllapply the join types explicitly requested by the query, so the writes respect those join restrictions aslistdoes. This is the other half of the previous branch: without itlistwould return 4 rows anddeleteAlldelete 5.JoinType.LEFT.The upgrade guide has a note under Grails 7.0.18, and the upgrade skill has the same entry.
The result changes also include subqueries that request a join type: updateAll and deleteAll first select matching identifiers with those joins and tenant filters, then modify the identifiers in batches. Bidirectional collection joins correlate through the owning property to keep tenant-filter parameters bound.
This change covers explicitly requested join restrictions. An implicit association-sort join can still filter
listwhile the bulk write ignores that sort-induced restriction. The source audit identifies that mismatch as pre-existing on 7.0.x; #17170 tracks the separate bulk-write/sort contract and its regression coverage.On MySQL and MariaDB before 10.3, a requested path back to the modified table, including a path that starts with a collection of a basic type, is applied by selecting the identifiers first, so these calls work on every dialect. Existing unsupported association criteria in bulk operations are outside this change.
Verification
At 140aa7b, which merges 7.0.x with #17067 and adds the review fixes,
RequestedJoinBulkOperationDialectSpec(14 cases),AssociationJoinTypeSpecin both sort-setting modes (240 cases, 7 skipped) andMultiTenancyRequestedJoinSpec(9 cases) pass, as does the module codeStyle check; the full suite runs in CI. At f8ec784 the full Hibernate 5 core suite passed (1,217 cases, zero failures, 60 skipped). Root codeStyle, RAT (zero unknown licenses), dependency-version validation and the guide build passed. The new subquery update/delete and tenant-scoped collection regressions failed before the changes and pass now.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