You are viewing a plain text version of this content. The canonical link for it is here.
Posted to notifications@grails.apache.org by "borinquenkid (via GitHub)" <gi...@apache.org> on 2026/10/21 01:12:25 UTC
[PR] Hibernate 7: write the rows of unidirectional hasMany collections that share a join table [grails-core]
borinquenkid opened a new pull request, #16701:
URL: https://github.com/apache/grails-core/pull/16701
> Stacked on #16686: the base is `fix/h7-multiple-hasmany-8.0.x`, so the diff is this change alone. Retarget to `8.0.x` once #16686 merges.
Fixes #16699
## What
An owner with two unidirectional `hasMany` to the same class and no `joinTable` mapping shares one join table between them, with a key column each. `CollectionKeyColumnUpdater` made the key of each collection **not updatable** in that case, the rule from #10811. Hibernate 7's collection persister writes no rows for a collection whose key is not updatable, so every `addTo*` on such an owner was dropped silently, even with `failOnError: true` (the second shape of #16665, and @jdaugherty's probe on #16686).
* `CollectionKeyColumnUpdater` now keeps the key nullable and **always updatable**; the sibling counting is gone. The Hibernate 5 binder made every collection key non-updatable, which Hibernate 5 tolerated; on Hibernate 7 the flag only loses data. The native generator of the 9.x branches already treats the rule as a defect and keeps the key updatable.
* Hibernate creates the implicit unique key of the shared table for the **first** collection only, over its key column and the element column (`Set.createPrimaryKey` creates none when the table has one already). A row of a later collection leaves that key column null, so on a database that treats nulls as equal in a unique constraint two of its rows for one element, from two owners, are duplicates. The new `SharedJoinTableUniqueKeyBinder`, run by `GrailsSecondPass` right after `createAllKeys`, adds the key columns of every sharing collection to that unique key: the shared table of `hasMany = [roles: Role, denyRoles: Role]` ends up with `UNIQUE (owner_roles_id, owner_deny_roles_id, role_id)`. A unique key the mapping declares explicitly, a collection with a join table of its own, and a bidirectional one-to-many are left as Hibernate binds them.
## Tests
* `SharedJoinTableUniqueKeyBinderSpec` (new): the unique key of a shared table, of two tables of their own, and of a bidirectional one-to-many, read from the boot metadata; both shared keys updatable.
* `CollectionKeyColumnUpdaterSpec`: the shared-table case now expects an updatable key.
* `MultipleUnidirectionalHasManySpec`: a role added to each of two associations sharing a table is read back through its own association; one role denied by two groups is written once per group.
* Without the fix, four cases fail (both shared-table round trips, the updater case, the unique-key case).
Verified: `:grails-data-hibernate7-core:test` 3,791 tests, the one failure being the Oracle container failing to start locally, green on rerun; `checkstyleMain`, `codenarcMain`, `codenarcTest` clean.
## Out of scope
Two unidirectional hasMany **Lists** (or Maps) sharing a join table are a separate, pre-existing defect: the second list's primary key overwrites the first's and both index columns are NOT NULL. Until now their rows were dropped silently as well; with updatable keys the insert fails with a `DataIntegrityViolationException` instead. Filed as #16700.
On the 9.x branches the native generator will need to state the same extended unique key on a shared `@JoinTable`, since Hibernate's annotation binder skips the second unique key in the same way; the differential against the classic oracle flags it at merge-up.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@grails.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Hibernate 7: write the rows of unidirectional hasMany collections that share a join table [grails-core]
Posted by "borinquenkid (via GitHub)" <gi...@apache.org>.
borinquenkid commented on code in PR #16701:
URL: https://github.com/apache/grails-core/pull/16701#discussion_r4359456817
##########
grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/secondpass/SharedJoinTableUniqueKeyBinder.java:
##########
@@ -0,0 +1,83 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * https://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.grails.orm.hibernate.cfg.domainbinding.secondpass;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import org.hibernate.mapping.Collection;
+import org.hibernate.mapping.Column;
+import org.hibernate.mapping.Selectable;
+import org.hibernate.mapping.Table;
+import org.hibernate.mapping.UniqueKey;
+
+/**
+ * Completes the implicit unique key of a join table that several collections of one owner share.
+ *
+ * <p>Two unidirectional {@code hasMany} to the same class without a {@code joinTable} mapping share one join table, with a
+ * key column for each of them and one element column. Hibernate creates the table's unique key when it creates the keys of
+ * the first collection, over that collection's key column and the element column, and creates none for the others, as the
+ * table has a unique key already ({@code Set.createPrimaryKey}). A row of a later collection leaves the first key column
+ * null, so on a database that treats nulls as equal in a unique constraint two of its rows for the same element, from two
+ * owners, are duplicates. This binder adds the key columns of every collection to that unique key once the collection's
+ * keys are created, so a row is unique by the key column of its own collection and the element.</p>
+ *
+ * <p>A unique key the mapping declares explicitly is left alone, and so is a collection without a join table or whose
+ * key the other side owns.</p>
+ *
+ * @since 8.0.1
+ */
+public class SharedJoinTableUniqueKeyBinder {
+
+ /** Adds the key columns of the collection to the implicit unique key of its join table that covers its element. */
+ public void bind(Collection collection) {
+ Table table = collection.getCollectionTable();
+ if (table == null || collection.isInverse() || collection.isOneToMany() || collection.getKey() == null) {
+ return;
+ }
+ List<Column> keyColumns = collection.getKey().getColumns();
+ List<Column> elementColumns = columnsOf(collection);
+ if (keyColumns.isEmpty() || elementColumns.isEmpty()) {
+ return;
+ }
+ for (UniqueKey uniqueKey : table.getUniqueKeys().values()) {
+ if (uniqueKey.isExplicit() || !elementColumns.stream().allMatch(uniqueKey::containsColumn)) {
+ continue;
+ }
+ for (Column column : keyColumns) {
+ if (!uniqueKey.containsColumn(column)) {
+ uniqueKey.addColumn(column);
Review Comment:
Reworked in 9066f901f1, by dialect. You are right that one widened key rejects nothing where nulls are distinct, and that is most of what Grails runs on. The constraint now takes the shape the database needs, through `SharedJoinTableUniqueness`, keyed on the dialect the way `RegexDialectPattern` is:
- **Default** (H2, PostgreSQL, MySQL, MariaDB, and SQL Server and DB2, whose Hibernate unique delegates render a filtered unique index): one unique key per association over its own key column and the element. The binder keeps the key Hibernate made for the first association and creates the missing one for each later association.
- **Oracle**: one unique key over the key columns of every sharing association and the element. Oracle compares the non-null columns of a partially null row, so a row collides only with a row of its own association for the same element, while a key per association would reject the rows of the other association, null in that key column and equal in the element.
The binder is no longer constructed inside a method: it is built once in `CollectionBinder` with the metadata context, injected into `CollectionSecondPassBinder`, which now owns key creation, and the `GrailsSecondPass` interface is gone.
Tests: `SharedJoinTableHibernate7Spec` runs the scenario on H2, PostgreSQL, MySQL, MariaDB and Oracle through Testcontainers, as `RLikeHibernate7Spec` does: the same member twice in one association of one group, from two sessions on a `version false` owner, fails with `DataIntegrityViolationException`, while the same member in the other association, in another group, and denied by two groups is accepted. `SharedJoinTableUniqueKeyBinderSpec` renders the DDL for each dialect with the dialect's own exporters, SQL Server's filtered index and DB2's `exclude null keys` index included, so the two without containers are asserted too.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@grails.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Hibernate 7: write the rows of unidirectional hasMany collections that share a join table [grails-core]
Posted by "borinquenkid (via GitHub)" <gi...@apache.org>.
borinquenkid commented on PR #16701:
URL: https://github.com/apache/grails-core/pull/16701#issuecomment-6387619828
Two more commits, both local fixes found after the last review:
- `5af2cd2a3f`: the pending removal features point at #16691; #16745 was closed as its duplicate.
- `d5774b0d45`: fixes #16748 (`is empty` / `is not empty` on an association that shares a join table and a key column saw the rows of the other one). Hibernate 7 puts the restriction of a many-to-many collection on the join to the element, which the `select 1` of its `exists` subquery never renders; `size()` applies it. `RestrictedCollectionSqmTranslatorFactory`, registered as `hibernate.query.sqm.translator` unless the application sets one, translates `is [not] empty` as `size(...) = 0 / > 0` for a restricted many-to-many collection only; a dialect with its own translator (Sybase) keeps it. Single-table update and delete are covered, multi-table ones are not (documented). Covered for HQL, criteria, negation, update, both shared shapes, and a restricted one-to-many that keeps Hibernate's translation. Full core suite (with the Db2 branch on top): 4275 tests, the only 3 failures the Oracle container not starting locally.
The Hibernate bug itself is drafted for the Hibernate Jira.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@grails.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Hibernate 7: write the rows of unidirectional hasMany collections that share a join table [grails-core]
Posted by "borinquenkid (via GitHub)" <gi...@apache.org>.
borinquenkid commented on code in PR #16701:
URL: https://github.com/apache/grails-core/pull/16701#discussion_r4365820792
##########
grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/secondpass/CollectionKeyColumnUpdater.java:
##########
@@ -36,28 +43,11 @@ public CollectionKeyColumnUpdater(CollectionKeyBinder collectionKeyBinder) {
this.collectionKeyBinder = collectionKeyBinder;
}
- /** Creates the key, sets it on the collection, and updates its columns. */
+ /** Creates the key, sets it on the collection, and makes its columns nullable and the key updatable. */
public void bind(HibernateToManyProperty property) {
DependantValue key = collectionKeyBinder.bind(property);
key.getColumns().stream().filter(Objects::nonNull).forEach(column -> column.setNullable(true));
- Table collectionTable = property.getCollection().getCollectionTable();
- long unidirectionalCount = property.getHibernateOwner()
- .getPersistentPropertiesToBind()
- .stream()
- .filter(HibernateToManyProperty::isBoundAsCollection)
- .map(HibernateToManyProperty.class::cast)
- .filter(p -> !p.isBidirectional())
- .filter(p -> Objects.equals(p.getCollection().getCollectionTable(), collectionTable))
- .count();
-
- // Collections of basic values or enums (HibernateToManyCollectionProperty) always keep an updatable key: they
- // have no inverse side, and Hibernate writes no rows for a collection whose key is not updatable.
- // For entity collections (HibernateToManyEntityProperty) the key is non-updatable only when the owner has
- // two or more unidirectional to-many properties that share this collection's join table, the rule for issue
- // 10811. Unidirectional collections with join tables of their own keep an updatable key, as they have no
- // second key column to leave null. A to-many that is not bound as a collection (a serializable or user type)
- // has no join table and no Hibernate collection, so it is neither counted nor asked for one.
- key.setUpdateable(property instanceof HibernateToManyCollectionProperty || unidirectionalCount <= 1);
+ key.setUpdateable(true);
Review Comment:
Fixed in 1e99b6e1ae, with a reproduction first: an account whose `roles` and `denyRoles` share a table and the key column `account_id` lost its denied roles when `roles` was cleared. Each collection of a shared table is now restricted to the rows that have a value in its own element columns (`where role_id is not null`), which limits Hibernate's delete of all the rows of a collection and its loads alike. `SharedJoinTableBulkDeleteSpec` clears one association and asserts the other remains, and fails without the restriction.
##########
grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/secondpass/SharedJoinTableUniqueKeyBinder.java:
##########
@@ -0,0 +1,175 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * https://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.grails.orm.hibernate.cfg.domainbinding.secondpass;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import org.hibernate.boot.model.naming.Identifier;
+import org.hibernate.boot.model.naming.ImplicitIndexNameSource;
+import org.hibernate.boot.model.naming.ImplicitNamingStrategy;
+import org.hibernate.boot.model.naming.ImplicitUniqueKeyNameSource;
+import org.hibernate.boot.spi.MetadataBuildingContext;
+import org.hibernate.dialect.Dialect;
+import org.hibernate.mapping.Collection;
+import org.hibernate.mapping.Column;
+import org.hibernate.mapping.Selectable;
+import org.hibernate.mapping.Table;
+
+/**
+ * Gives every collection with a join table a uniqueness constraint of its own over its key column and the element,
+ * so that a join table several collections of one owner share stays unique per collection.
+ *
+ * <p>Two unidirectional {@code hasMany} to the same class without a {@code joinTable} mapping share one join table,
+ * with a key column for each of them and one element column. Hibernate creates the table's implicit unique key when
+ * it creates the keys of the first collection, over that collection's key column and the element column, and creates
+ * none for the others, as the table has a unique key already ({@code Set.createPrimaryKey}). This binder runs after
+ * the keys of each collection are created and completes what is missing, in the shape the database needs
+ * ({@link SharedJoinTableUniqueness}). A collection whose table is its own already has its constraint and is left as
+ * Hibernate bound it, and so is a collection without a join table or whose key the other side owns.</p>
+ *
+ * @since 8.0.1
+ */
+public class SharedJoinTableUniqueKeyBinder {
+
+ private final MetadataBuildingContext metadataBuildingContext;
+ private final SharedJoinTableUniqueness uniqueness;
+
+ /** Resolves the uniqueness for the dialect of the metadata being built. */
+ public SharedJoinTableUniqueKeyBinder(MetadataBuildingContext metadataBuildingContext) {
+ this(metadataBuildingContext, metadataBuildingContext.getMetadataCollector().getDatabase().getDialect());
+ }
+
+ SharedJoinTableUniqueKeyBinder(MetadataBuildingContext metadataBuildingContext, Dialect dialect) {
+ this.metadataBuildingContext = metadataBuildingContext;
+ this.uniqueness = SharedJoinTableUniqueness.forDialect(dialect);
+ }
+
+ /** The uniqueness this binder applies. */
+ public SharedJoinTableUniqueness getUniqueness() {
+ return uniqueness;
+ }
+
+ /**
+ * Gives a set the uniqueness constraint over its key columns and its element on its join table. A list or a map
+ * is keyed by its index, which its table has as part of the primary key, and a bag has no key at all; their
+ * elements repeat by design, so they are left as Hibernate bound them.
+ */
+ public void bind(Collection collection) {
+ Table table = collection.getCollectionTable();
+ if (!collection.isSet() || table == null || collection.isInverse() ||
+ collection.isOneToMany() || collection.getKey() == null) {
+ return;
+ }
+ List<Column> keyColumns = collection.getKey().getColumns();
+ List<Column> elementColumns = columnsOf(collection);
+ if (keyColumns.isEmpty() || elementColumns.isEmpty()) {
+ return;
+ }
+ uniqueness.apply(table, keyColumns, elementColumns, new ImplicitNaming(table));
Review Comment:
Fixed in 1e99b6e1ae: the unique key is not added when an element column is a large object, as in `Set.createPrimaryKey`. A basic collection's element cannot be mapped to a LOB through the GORM mapping (`type:` applies to the property), so the check is tested against a real CLOB column from the metadata (`SharedJoinTableUniqueKeyBinderSpec`, `hasLobColumn`).
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@grails.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Hibernate 7: write the rows of unidirectional hasMany collections that share a join table [grails-core]
Posted by "testlens-app[bot] (via GitHub)" <gi...@apache.org>.
testlens-app[bot] commented on PR #16701:
URL: https://github.com/apache/grails-core/pull/16701#issuecomment-6376672730
## 🔎 No tests executed 🔎
🏷️ Commit: 04016e1f3603470d4b5b09f7db34f34010fa47c8
▶️ Tests: 0 executed
⚪️ Checks: 28/28 completed
---
_Learn more about TestLens at [testlens.app/docs](https://testlens.app/docs/features/pr-comment/)._
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@grails.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Hibernate 7: write the rows of unidirectional hasMany collections that share a join table [grails-core]
Posted by "borinquenkid (via GitHub)" <gi...@apache.org>.
borinquenkid commented on PR #16701:
URL: https://github.com/apache/grails-core/pull/16701#issuecomment-6399691557
Stacked on the upstream fix for apache/grails-core#16691 (PR #16757):
- Removing one element of a set on a join table deleted every row of the association for the owner because Hibernate 7 restricts row deletion by the key and only non-nullable element columns (and GORM join-table element columns are nullable).
- That behavior was upstream in Hibernate 7's row delete mechanics across all join table sets (shared or unshared).
- PR #16757 introduced `JoinTableCollectionPersister` and `GormPersisterClassResolver` to restrict deletion by the key and element column.
- With PR #16757 merged into this branch, the three removal features in `SharedJoinTableBulkDeleteSpec` are unpended and verified.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@grails.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Hibernate 7: write the rows of unidirectional hasMany collections that share a join table [grails-core]
Posted by "borinquenkid (via GitHub)" <gi...@apache.org>.
borinquenkid commented on PR #16701:
URL: https://github.com/apache/grails-core/pull/16701#issuecomment-6379239565
Pushed 1cbfaecc4c. Since the last round:
- A shared join table with one key column and an element column per association failed on Oracle (ORA-00001 on the second association); the Oracle key now takes the columns of every association that shares a column with it. runs that mapping on H2, PostgreSQL, MySQL, MariaDB and Oracle and failed on Oracle before.
- Each collection of a shared table is restricted to its own rows, so clearing one association keeps the other.
- The 8.0.0 constructor of and the deprecated on the three passes are kept.
- The duplicate-row cases now also duplicate a row of the second association; with the per-association key removed they fail on all five databases, where before only Oracle did.
Three things found while testing are not fixed here and are tracked: removing one element of a set deletes every row of the association for the owner, shared table or not, also on the base of this PR (#16745; three pending features pin it), DB2's unique index null semantics are unverified (#16746), and `is empty` / `is not empty` on an association that shares a key column also sees the rows of the other one, which the restriction does not reach (#16748; one pending feature). A set cannot share a join table with a list or a map, since the list's index column is not null; the binder's javadoc says so.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@grails.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Hibernate 7: write the rows of unidirectional hasMany collections that share a join table [grails-core]
Posted by "testlens-app[bot] (via GitHub)" <gi...@apache.org>.
testlens-app[bot] commented on PR #16701:
URL: https://github.com/apache/grails-core/pull/16701#issuecomment-6379608621
## 🔎 No tests executed 🔎
🏷️ Commit: 142f6f150980ccf00dee520bba5c341d2bbc9d78
▶️ Tests: 0 executed
⚪️ Checks: 41/41 completed
---
_Learn more about TestLens at [testlens.app/docs](https://testlens.app/docs/features/pr-comment/)._
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@grails.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Hibernate 7: write the rows of unidirectional hasMany collections that share a join table [grails-core]
Posted by "testlens-app[bot] (via GitHub)" <gi...@apache.org>.
testlens-app[bot] commented on PR #16701:
URL: https://github.com/apache/grails-core/pull/16701#issuecomment-6305531323
## 🚨 Jobs failed without executing tests 🚨
### Failed Jobs without Test Failures
❌ [Coverage / Coverage - grails-gradle \(ubuntu-24.04\)](https://github.com/apache/grails-core/actions/runs/39525947360/job/118980498269?pr=16701)
🏷️ Commit: b2853301885176b5c629a734c34389bae41924e8
▶️ Tests: 0 executed
🟡 Checks: 7/76 completed
### Rerun Controls
Click the checkbox to trigger a rerun:
🔲 **Rerun jobs**
---
_Learn more about TestLens at [testlens.app/docs](https://testlens.app/docs/features/pr-comment/)._
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@grails.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Hibernate 7: write the rows of unidirectional hasMany collections that share a join table [grails-core]
Posted by "borinquenkid (via GitHub)" <gi...@apache.org>.
borinquenkid commented on PR #16701:
URL: https://github.com/apache/grails-core/pull/16701#issuecomment-6417379723
Stacked on the upstream fix for apache/grails-core#16691 (PR #16757):
- Removing one element of a set on a join table deleted every row of the association for the owner because Hibernate 7 restricts row deletion by the key and only non-nullable element columns (and GORM join-table element columns are nullable).
- That behavior was upstream in Hibernate 7's row delete mechanics across all join table sets (shared or unshared).
- PR #16757 introduced `JoinTableCollectionPersister` and `GormPersisterClassResolver` to restrict deletion by the key and element column.
- With PR #16757 merged into this branch, the three removal features in `SharedJoinTableBulkDeleteSpec` are unpended and verified.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@grails.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Hibernate 7: write the rows of unidirectional hasMany collections that share a join table [grails-core]
Posted by "testlens-app[bot] (via GitHub)" <gi...@apache.org>.
testlens-app[bot] commented on PR #16701:
URL: https://github.com/apache/grails-core/pull/16701#issuecomment-6417386580
## 🔎 No tests executed 🔎
🏷️ Commit: e635103fa2afa171f9b7ed0a82aba93f6dcc9e65
▶️ Tests: 0 executed
⚪️ Checks: 46/46 completed
---
_Learn more about TestLens at [testlens.app/docs](https://testlens.app/docs/features/pr-comment/)._
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@grails.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Hibernate 7: write the rows of unidirectional hasMany collections that share a join table [grails-core]
Posted by "codecov[bot] (via GitHub)" <gi...@apache.org>.
codecov[bot] commented on PR #16701:
URL: https://github.com/apache/grails-core/pull/16701#issuecomment-6306158550
## [Codecov](https://app.codecov.io/gh/apache/grails-core/pull/16701?dropdown=coverage&src=pr&el=h1&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) Report
:white_check_mark: All modified and coverable lines are covered by tests.
:white_check_mark: Project coverage is 62.1155%. Comparing base ([`7138500`](https://app.codecov.io/gh/apache/grails-core/commit/7138500ed15923c96c6eb17e0d5c1dca838a36d9?dropdown=coverage&el=desc&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache)) to head ([`b285330`](https://app.codecov.io/gh/apache/grails-core/commit/b2853301885176b5c629a734c34389bae41924e8?dropdown=coverage&el=desc&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache)).
<details><summary>Additional details and impacted files</summary>
[](https://app.codecov.io/gh/apache/grails-core/pull/16701?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache)
```diff
@@ Coverage Diff @@
## fix/h7-multiple-hasmany-8.0.x #16701 +/- ##
=======================================================================
- Coverage 62.1164% 62.1155% -0.0009%
+ Complexity 26777 26774 -3
=======================================================================
Files 2237 2237
Lines 110433 110433
Branches 20152 20152
=======================================================================
- Hits 68597 68596 -1
Misses 32616 32616
- Partials 9220 9221 +1
```
[see 1 file with indirect coverage changes](https://app.codecov.io/gh/apache/grails-core/pull/16701/indirect-changes?src=pr&el=tree-more&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache)
</details>
<details><summary> :rocket: New features to boost your workflow: </summary>
- :snowflake: [Test Analytics](https://docs.codecov.com/docs/test-analytics): Detect flaky tests, report on failures, and find test suite problems.
- :package: [JS Bundle Analysis](https://docs.codecov.com/docs/javascript-bundle-analysis): Save yourself from yourself by tracking and limiting bundle sizes in JS merges.
</details>
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@grails.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Hibernate 7: write the rows of unidirectional hasMany collections that share a join table [grails-core]
Posted by "jamesfredley (via GitHub)" <gi...@apache.org>.
jamesfredley commented on code in PR #16701:
URL: https://github.com/apache/grails-core/pull/16701#discussion_r4338912975
##########
grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/domainbinding/secondpass/SharedJoinTableUniqueKeyBinderSpec.groovy:
##########
@@ -0,0 +1,136 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * https://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.grails.orm.hibernate.cfg.domainbinding.secondpass
+
+import grails.gorm.annotation.Entity
+import grails.gorm.tests.HibernateGormDatastoreSpec
+import org.hibernate.mapping.Collection
+import org.hibernate.mapping.Table
+import org.hibernate.mapping.UniqueKey
+import spock.lang.Subject
+
+/**
+ * The join table two unidirectional hasMany associations to the same class share gets one implicit unique key from
+ * Hibernate, over the first association's key column and the element column. The binder adds the key column of every
+ * association that shares the table, so a row is unique by the key column of its own association and the element.
+ * An association with a join table of its own, and one whose key the other side owns, are left as Hibernate binds them.
+ */
+
+class SharedJoinTableUniqueKeyBinderSpec extends HibernateGormDatastoreSpec {
+
+ void setupSpec() {
+ manager.registerDomainClasses(SjtOwner, SjtSeparateOwner, SjtParent, SjtChild, SjtRole)
+ }
+
+ private Collection collectionOf(Class owner, String property) {
+ datastore.metadata.getCollectionBinding("${owner.name}.${property}".toString())
+ }
+
+ private static List<List<String>> uniqueKeyColumns(Table table) {
+ table.uniqueKeys.values().collect { UniqueKey key -> key.columns*.name.sort() }.sort()
+ }
+
+ void "the shared join table has one unique key over the key column of each association and the element"() {
+ given:
+ Collection roles = collectionOf(SjtOwner, 'roles')
+ Collection denyRoles = collectionOf(SjtOwner, 'denyRoles')
+
+ expect: 'both associations share the table'
+ roles.collectionTable.is(denyRoles.collectionTable)
+ roles.collectionTable.columns*.name.sort() == ['sjt_owner_deny_roles_id', 'sjt_owner_roles_id', 'sjt_role_id']
+
+ and: 'its unique key covers both key columns and the element column'
+ uniqueKeyColumns(roles.collectionTable) == [['sjt_owner_deny_roles_id', 'sjt_owner_roles_id', 'sjt_role_id']]
+
+ and: 'both keys are updatable, so rows of both associations are written'
+ roles.key.updateable
+ denyRoles.key.updateable
+ }
+
+ void "an association with a join table of its own keeps the unique key Hibernate creates for it"() {
+ given:
+ Collection roles = collectionOf(SjtSeparateOwner, 'roles')
+ Collection denyRoles = collectionOf(SjtSeparateOwner, 'denyRoles')
+
+ expect:
+ !roles.collectionTable.is(denyRoles.collectionTable)
+ uniqueKeyColumns(roles.collectionTable) == [['sjt_role_id', 'sjt_separate_owner_roles_id']]
+ uniqueKeyColumns(denyRoles.collectionTable) == [['sjt_role_id', 'sjt_separate_owner_deny_roles_id']]
+ }
+
+ void "a bidirectional one-to-many has no join table and is left alone"() {
+ given:
+ Collection children = collectionOf(SjtParent, 'children')
+
+ expect:
+ children.inverse
+ children.collectionTable.name == 'sjt_child'
+ children.collectionTable.uniqueKeys.isEmpty()
+ }
+
+ void "bind leaves a collection without a join table or without a key alone"() {
+ given:
+ Collection children = collectionOf(SjtParent, 'children')
+ int before = children.collectionTable.uniqueKeys.size()
+
+ when:
+ new Object()
Review Comment:
This does not test the guard. `new Object()` never calls the binder, and `children` has both a table and a key, so neither advertised condition is exercised. The assertion passes no matter what `bind` does.
Replace it with a real call that hits each early return (no table, inverse, one-to-many, null key), or delete the feature. The bidirectional one-to-many feature above already covers the inverse case through the public mapping path; keep that.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@grails.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Hibernate 7: write the rows of unidirectional hasMany collections that share a join table [grails-core]
Posted by "jamesfredley (via GitHub)" <gi...@apache.org>.
jamesfredley commented on code in PR #16701:
URL: https://github.com/apache/grails-core/pull/16701#discussion_r4364488224
##########
grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/secondpass/CollectionKeyColumnUpdater.java:
##########
@@ -36,28 +43,11 @@ public CollectionKeyColumnUpdater(CollectionKeyBinder collectionKeyBinder) {
this.collectionKeyBinder = collectionKeyBinder;
}
- /** Creates the key, sets it on the collection, and updates its columns. */
+ /** Creates the key, sets it on the collection, and makes its columns nullable and the key updatable. */
public void bind(HibernateToManyProperty property) {
DependantValue key = collectionKeyBinder.bind(property);
key.getColumns().stream().filter(Objects::nonNull).forEach(column -> column.setNullable(true));
- Table collectionTable = property.getCollection().getCollectionTable();
- long unidirectionalCount = property.getHibernateOwner()
- .getPersistentPropertiesToBind()
- .stream()
- .filter(HibernateToManyProperty::isBoundAsCollection)
- .map(HibernateToManyProperty.class::cast)
- .filter(p -> !p.isBidirectional())
- .filter(p -> Objects.equals(p.getCollection().getCollectionTable(), collectionTable))
- .count();
-
- // Collections of basic values or enums (HibernateToManyCollectionProperty) always keep an updatable key: they
- // have no inverse side, and Hibernate writes no rows for a collection whose key is not updatable.
- // For entity collections (HibernateToManyEntityProperty) the key is non-updatable only when the owner has
- // two or more unidirectional to-many properties that share this collection's join table, the rule for issue
- // 10811. Unidirectional collections with join tables of their own keep an updatable key, as they have no
- // second key column to leave null. A to-many that is not bound as a collection (a serializable or user type)
- // has no join table and no Hibernate collection, so it is neither counted nor asked for one.
- key.setUpdateable(property instanceof HibernateToManyCollectionProperty || unidirectionalCount <= 1);
+ key.setUpdateable(true);
Review Comment:
Enabling the key also enables Hibernate's bulk collection delete. For `MuhSharedAccount`, clearing `roles` emits `delete from muh_shared_account_roles where account_id=?` and deletes `denyRoles` too. The unique key does not limit that delete.
Restrict a collection-wide delete to that association's rows before enabling writes. Please clear one collection and assert the other remains.
##########
grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/secondpass/SharedJoinTableUniqueKeyBinder.java:
##########
@@ -0,0 +1,175 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * https://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.grails.orm.hibernate.cfg.domainbinding.secondpass;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import org.hibernate.boot.model.naming.Identifier;
+import org.hibernate.boot.model.naming.ImplicitIndexNameSource;
+import org.hibernate.boot.model.naming.ImplicitNamingStrategy;
+import org.hibernate.boot.model.naming.ImplicitUniqueKeyNameSource;
+import org.hibernate.boot.spi.MetadataBuildingContext;
+import org.hibernate.dialect.Dialect;
+import org.hibernate.mapping.Collection;
+import org.hibernate.mapping.Column;
+import org.hibernate.mapping.Selectable;
+import org.hibernate.mapping.Table;
+
+/**
+ * Gives every collection with a join table a uniqueness constraint of its own over its key column and the element,
+ * so that a join table several collections of one owner share stays unique per collection.
+ *
+ * <p>Two unidirectional {@code hasMany} to the same class without a {@code joinTable} mapping share one join table,
+ * with a key column for each of them and one element column. Hibernate creates the table's implicit unique key when
+ * it creates the keys of the first collection, over that collection's key column and the element column, and creates
+ * none for the others, as the table has a unique key already ({@code Set.createPrimaryKey}). This binder runs after
+ * the keys of each collection are created and completes what is missing, in the shape the database needs
+ * ({@link SharedJoinTableUniqueness}). A collection whose table is its own already has its constraint and is left as
+ * Hibernate bound it, and so is a collection without a join table or whose key the other side owns.</p>
+ *
+ * @since 8.0.1
+ */
+public class SharedJoinTableUniqueKeyBinder {
+
+ private final MetadataBuildingContext metadataBuildingContext;
+ private final SharedJoinTableUniqueness uniqueness;
+
+ /** Resolves the uniqueness for the dialect of the metadata being built. */
+ public SharedJoinTableUniqueKeyBinder(MetadataBuildingContext metadataBuildingContext) {
+ this(metadataBuildingContext, metadataBuildingContext.getMetadataCollector().getDatabase().getDialect());
+ }
+
+ SharedJoinTableUniqueKeyBinder(MetadataBuildingContext metadataBuildingContext, Dialect dialect) {
+ this.metadataBuildingContext = metadataBuildingContext;
+ this.uniqueness = SharedJoinTableUniqueness.forDialect(dialect);
+ }
+
+ /** The uniqueness this binder applies. */
+ public SharedJoinTableUniqueness getUniqueness() {
+ return uniqueness;
+ }
+
+ /**
+ * Gives a set the uniqueness constraint over its key columns and its element on its join table. A list or a map
+ * is keyed by its index, which its table has as part of the primary key, and a bag has no key at all; their
+ * elements repeat by design, so they are left as Hibernate bound them.
+ */
+ public void bind(Collection collection) {
+ Table table = collection.getCollectionTable();
+ if (!collection.isSet() || table == null || collection.isInverse() ||
+ collection.isOneToMany() || collection.getKey() == null) {
+ return;
+ }
+ List<Column> keyColumns = collection.getKey().getColumns();
+ List<Column> elementColumns = columnsOf(collection);
+ if (keyColumns.isEmpty() || elementColumns.isEmpty()) {
+ return;
+ }
+ uniqueness.apply(table, keyColumns, elementColumns, new ImplicitNaming(table));
Review Comment:
Hibernate skips a unique key when a set element has a CLOB or BLOB, because that column cannot be indexed. This call adds the key anyway. On H2, `unique (owner_id, clob_column)` fails table creation.
Keep that exclusion. Do not treat a missing key on an unshared table as an incomplete shared-table mapping.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@grails.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Hibernate 7: write the rows of unidirectional hasMany collections that share a join table [grails-core]
Posted by "testlens-app[bot] (via GitHub)" <gi...@apache.org>.
testlens-app[bot] commented on PR #16701:
URL: https://github.com/apache/grails-core/pull/16701#issuecomment-6371320708
## 🔎 No tests executed 🔎
🏷️ Commit: f1bdd129a053a9ec6e6002d7141e15271256e3ed
▶️ Tests: 0 executed
⚪️ Checks: 41/41 completed
---
_Learn more about TestLens at [testlens.app/docs](https://testlens.app/docs/features/pr-comment/)._
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@grails.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Hibernate 7: write the rows of unidirectional hasMany collections that share a join table [grails-core]
Posted by "testlens-app[bot] (via GitHub)" <gi...@apache.org>.
testlens-app[bot] commented on PR #16701:
URL: https://github.com/apache/grails-core/pull/16701#issuecomment-6387621573
## 🔎 No tests executed 🔎
🏷️ Commit: d5774b0d457a744916abc76cefc6d536ad441cee
▶️ Tests: 0 executed
⚪️ Checks: 26/26 completed
---
_Learn more about TestLens at [testlens.app/docs](https://testlens.app/docs/features/pr-comment/)._
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@grails.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Hibernate 7: write the rows of unidirectional hasMany collections that share a join table [grails-core]
Posted by "testlens-app[bot] (via GitHub)" <gi...@apache.org>.
testlens-app[bot] commented on PR #16701:
URL: https://github.com/apache/grails-core/pull/16701#issuecomment-6376733775
## 🔎 No tests executed 🔎
🏷️ Commit: c33382d0bd7274567f0517534f41cc470823d171
▶️ Tests: 0 executed
⚪️ Checks: 41/41 completed
---
_Learn more about TestLens at [testlens.app/docs](https://testlens.app/docs/features/pr-comment/)._
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@grails.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Hibernate 7: write the rows of unidirectional hasMany collections that share a join table [grails-core]
Posted by "testlens-app[bot] (via GitHub)" <gi...@apache.org>.
testlens-app[bot] commented on PR #16701:
URL: https://github.com/apache/grails-core/pull/16701#issuecomment-6379242140
## 🔎 No tests executed 🔎
🏷️ Commit: 1cbfaecc4cdb308a2f9333e9e6bb5006c4389223
▶️ Tests: 0 executed
⚪️ Checks: 41/41 completed
---
_Learn more about TestLens at [testlens.app/docs](https://testlens.app/docs/features/pr-comment/)._
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@grails.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Hibernate 7: write the rows of unidirectional hasMany collections that share a join table [grails-core]
Posted by "testlens-app[bot] (via GitHub)" <gi...@apache.org>.
testlens-app[bot] commented on PR #16701:
URL: https://github.com/apache/grails-core/pull/16701#issuecomment-6343727171
## 🔎 No tests executed 🔎
🏷️ Commit: e859b125a8025043c1c1dfb3835a186c5d7dd328
▶️ Tests: 0 executed
⚪️ Checks: 41/41 completed
---
_Learn more about TestLens at [testlens.app/docs](https://testlens.app/docs/features/pr-comment/)._
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@grails.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Hibernate 7: write the rows of unidirectional hasMany collections that share a join table [grails-core]
Posted by "testlens-app[bot] (via GitHub)" <gi...@apache.org>.
testlens-app[bot] commented on PR #16701:
URL: https://github.com/apache/grails-core/pull/16701#issuecomment-6373225064
## 🔎 No tests executed 🔎
🏷️ Commit: 0225ab4763d694ee6281ad3196320ae254398fdf
▶️ Tests: 0 executed
⚪️ Checks: 41/41 completed
---
_Learn more about TestLens at [testlens.app/docs](https://testlens.app/docs/features/pr-comment/)._
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@grails.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Hibernate 7: write the rows of unidirectional hasMany collections that share a join table [grails-core]
Posted by "borinquenkid (via GitHub)" <gi...@apache.org>.
borinquenkid commented on code in PR #16701:
URL: https://github.com/apache/grails-core/pull/16701#discussion_r4359460379
##########
grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/domainbinding/secondpass/SharedJoinTableUniqueKeyBinderSpec.groovy:
##########
@@ -0,0 +1,136 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * https://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.grails.orm.hibernate.cfg.domainbinding.secondpass
+
+import grails.gorm.annotation.Entity
+import grails.gorm.tests.HibernateGormDatastoreSpec
+import org.hibernate.mapping.Collection
+import org.hibernate.mapping.Table
+import org.hibernate.mapping.UniqueKey
+import spock.lang.Subject
+
+/**
+ * The join table two unidirectional hasMany associations to the same class share gets one implicit unique key from
+ * Hibernate, over the first association's key column and the element column. The binder adds the key column of every
+ * association that shares the table, so a row is unique by the key column of its own association and the element.
+ * An association with a join table of its own, and one whose key the other side owns, are left as Hibernate binds them.
+ */
+
+class SharedJoinTableUniqueKeyBinderSpec extends HibernateGormDatastoreSpec {
+
+ void setupSpec() {
+ manager.registerDomainClasses(SjtOwner, SjtSeparateOwner, SjtParent, SjtChild, SjtRole)
+ }
+
+ private Collection collectionOf(Class owner, String property) {
+ datastore.metadata.getCollectionBinding("${owner.name}.${property}".toString())
+ }
+
+ private static List<List<String>> uniqueKeyColumns(Table table) {
+ table.uniqueKeys.values().collect { UniqueKey key -> key.columns*.name.sort() }.sort()
+ }
+
+ void "the shared join table has one unique key over the key column of each association and the element"() {
+ given:
+ Collection roles = collectionOf(SjtOwner, 'roles')
+ Collection denyRoles = collectionOf(SjtOwner, 'denyRoles')
+
+ expect: 'both associations share the table'
+ roles.collectionTable.is(denyRoles.collectionTable)
+ roles.collectionTable.columns*.name.sort() == ['sjt_owner_deny_roles_id', 'sjt_owner_roles_id', 'sjt_role_id']
+
+ and: 'its unique key covers both key columns and the element column'
+ uniqueKeyColumns(roles.collectionTable) == [['sjt_owner_deny_roles_id', 'sjt_owner_roles_id', 'sjt_role_id']]
+
+ and: 'both keys are updatable, so rows of both associations are written'
+ roles.key.updateable
+ denyRoles.key.updateable
+ }
+
+ void "an association with a join table of its own keeps the unique key Hibernate creates for it"() {
+ given:
+ Collection roles = collectionOf(SjtSeparateOwner, 'roles')
+ Collection denyRoles = collectionOf(SjtSeparateOwner, 'denyRoles')
+
+ expect:
+ !roles.collectionTable.is(denyRoles.collectionTable)
+ uniqueKeyColumns(roles.collectionTable) == [['sjt_role_id', 'sjt_separate_owner_roles_id']]
+ uniqueKeyColumns(denyRoles.collectionTable) == [['sjt_role_id', 'sjt_separate_owner_deny_roles_id']]
+ }
+
+ void "a bidirectional one-to-many has no join table and is left alone"() {
+ given:
+ Collection children = collectionOf(SjtParent, 'children')
+
+ expect:
+ children.inverse
+ children.collectionTable.name == 'sjt_child'
+ children.collectionTable.uniqueKeys.isEmpty()
+ }
+
+ void "bind leaves a collection without a join table or without a key alone"() {
+ given:
+ Collection children = collectionOf(SjtParent, 'children')
+ int before = children.collectionTable.uniqueKeys.size()
+
+ when:
+ new Object()
Review Comment:
Replaced in 9066f901f1: the feature now calls `bind` on the bidirectional collection from the metadata, the one whose key the other side owns, and asserts the table gains neither a unique key nor an index. The dialect resolution has a row per dialect, and the DDL feature applies the uniqueness to a hand-built shared table and renders it with each dialect's exporters.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@grails.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Hibernate 7: write the rows of unidirectional hasMany collections that share a join table [grails-core]
Posted by "testlens-app[bot] (via GitHub)" <gi...@apache.org>.
testlens-app[bot] commented on PR #16701:
URL: https://github.com/apache/grails-core/pull/16701#issuecomment-6364777835
## 🔎 No tests executed 🔎
🏷️ Commit: 9066f901f13974e7428a124237038606d3ed0988
▶️ Tests: 0 executed
⚪️ Checks: 30/30 completed
---
_Learn more about TestLens at [testlens.app/docs](https://testlens.app/docs/features/pr-comment/)._
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@grails.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Hibernate 7: write the rows of unidirectional hasMany collections that share a join table [grails-core]
Posted by "jdaugherty (via GitHub)" <gi...@apache.org>.
jdaugherty commented on code in PR #16701:
URL: https://github.com/apache/grails-core/pull/16701#discussion_r4361167375
##########
grails-data-hibernate7/core/src/test/groovy/grails/gorm/tests/SharedJoinTableHibernate7Spec.groovy:
##########
@@ -0,0 +1,142 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * https://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package grails.gorm.tests
+
+import java.time.Duration
+
+import grails.gorm.annotation.Entity
+import org.testcontainers.mariadb.MariaDBContainer
+import org.testcontainers.mysql.MySQLContainer
+import org.testcontainers.oracle.OracleContainer
+import org.testcontainers.postgresql.PostgreSQLContainer
+import org.springframework.dao.DataIntegrityViolationException
+import org.testcontainers.spock.Testcontainers
+import spock.lang.Requires
+import spock.lang.Shared
+
+/**
+ * A join table two unidirectional hasMany associations share is unique per association on every database: the
+ * same member twice in one association of one owner is rejected, while the same member in the other association,
+ * in the same association of another owner, and denied by two owners is allowed. The last case is the one a unique
+ * key per association over a nullable key column breaks on Oracle, and the first the one a single key over every key
+ * column breaks where nulls are distinct.
+ */
+@Testcontainers
+@Requires({ isDockerAvailable() })
Review Comment:
The class-level `@Requires` skips the H2 row together with the container rows, so without Docker the rejection of a repeated member in the same association runs nowhere: `MultipleUnidirectionalHasManySpec` writes to the shared table but never asserts that a duplicate is refused, and the binder spec checks the metadata, not the database. An H2-only feature for that case in `MultipleUnidirectionalHasManySpec` would keep the regression test in the plain module run. Non-blocking.
##########
grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/domainbinding/secondpass/SharedJoinTableUniqueKeyBinderSpec.groovy:
##########
@@ -0,0 +1,263 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * https://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.grails.orm.hibernate.cfg.domainbinding.secondpass
+
+import grails.gorm.annotation.Entity
+import grails.gorm.tests.HibernateGormDatastoreSpec
+import org.hibernate.boot.model.relational.internal.SqlStringGenerationContextImpl
+import org.hibernate.boot.spi.MetadataBuildingContext
+import org.hibernate.dialect.DB2Dialect
+import org.hibernate.dialect.Dialect
+import org.hibernate.dialect.H2Dialect
+import org.hibernate.dialect.MariaDBDialect
+import org.hibernate.dialect.MySQLDialect
+import org.hibernate.dialect.OracleDialect
+import org.hibernate.dialect.PostgreSQLDialect
+import org.hibernate.dialect.SQLServerDialect
+import org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentImpl
+import org.hibernate.mapping.Collection
+import org.hibernate.mapping.Column
+import org.hibernate.mapping.Table
+import org.hibernate.mapping.UniqueKey
+import spock.lang.Unroll
+
+/**
+ * The join table two unidirectional hasMany associations to the same class share gets one implicit unique key from
+ * Hibernate, over the first association's key column and the element column, and nothing for the second. The binder
+ * gives every association a constraint of its own over its key column and the element, in the shape the database
+ * needs: a unique key where nulls are distinct or the dialect renders a filtered unique index, and on Oracle, which
+ * compares the non-null columns of a row, one unique key over every association's key column and the element. An association with a join table of its own, and one whose key the other side
+ * owns, are left as Hibernate binds them.
+ */
+class SharedJoinTableUniqueKeyBinderSpec extends HibernateGormDatastoreSpec {
+
+ void setupSpec() {
+ manager.registerDomainClasses(SjtOwner, SjtSeparateOwner, SjtParent, SjtChild, SjtRole)
+ }
+
+ private Collection collectionOf(Class owner, String property) {
+ datastore.metadata.getCollectionBinding("${owner.name}.${property}".toString())
+ }
+
+ private static List<List<String>> uniqueKeyColumns(Table table) {
+ table.uniqueKeys.values().collect { UniqueKey key -> key.columns*.name.sort() }.sort()
+ }
+
+ void "the shared join table has a unique key per association, over its own key column and the element"() {
+ given:
+ Collection roles = collectionOf(SjtOwner, 'roles')
+ Collection denyRoles = collectionOf(SjtOwner, 'denyRoles')
+
+ expect: 'both associations share the table'
+ roles.collectionTable.is(denyRoles.collectionTable)
+ roles.collectionTable.columns*.name.sort() == ['sjt_owner_deny_roles_id', 'sjt_owner_roles_id', 'sjt_role_id']
+
+ and: 'each association is unique by its own key column and the element; H2 treats nulls as distinct'
+ uniqueKeyColumns(roles.collectionTable) == [
+ ['sjt_owner_deny_roles_id', 'sjt_role_id'],
+ ['sjt_owner_roles_id', 'sjt_role_id']
+ ]
+ roles.collectionTable.indexes.isEmpty()
+
+ and: 'both keys are updatable, so rows of both associations are written'
+ roles.key.updateable
+ denyRoles.key.updateable
+ }
+
+ void "an association with a join table of its own keeps the unique key Hibernate creates for it"() {
Review Comment:
When the guard is narrowed, please cover the three collection kinds it excludes here, from the metadata as this feature does: a `List`, a `Map` and a `Collection` (bag) hasMany whose tables gain no unique key. And in `MultipleUnidirectionalHasManySpec`, or a spec of its own, a save and read-back of a list with a repeated element, a map with one value under two keys, and a bag with a repeated element. The module suite was green at this commit, so nothing in it saves a repeated element into a list, map or bag today.
##########
grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/secondpass/SharedJoinTableUniqueKeyBinder.java:
##########
@@ -0,0 +1,170 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * https://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.grails.orm.hibernate.cfg.domainbinding.secondpass;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import org.hibernate.boot.model.naming.Identifier;
+import org.hibernate.boot.model.naming.ImplicitIndexNameSource;
+import org.hibernate.boot.model.naming.ImplicitNamingStrategy;
+import org.hibernate.boot.model.naming.ImplicitUniqueKeyNameSource;
+import org.hibernate.boot.spi.MetadataBuildingContext;
+import org.hibernate.dialect.Dialect;
+import org.hibernate.mapping.Collection;
+import org.hibernate.mapping.Column;
+import org.hibernate.mapping.Selectable;
+import org.hibernate.mapping.Table;
+
+/**
+ * Gives every collection with a join table a uniqueness constraint of its own over its key column and the element,
+ * so that a join table several collections of one owner share stays unique per collection.
+ *
+ * <p>Two unidirectional {@code hasMany} to the same class without a {@code joinTable} mapping share one join table,
+ * with a key column for each of them and one element column. Hibernate creates the table's implicit unique key when
+ * it creates the keys of the first collection, over that collection's key column and the element column, and creates
+ * none for the others, as the table has a unique key already ({@code Set.createPrimaryKey}). This binder runs after
+ * the keys of each collection are created and completes what is missing, in the shape the database needs
+ * ({@link SharedJoinTableUniqueness}). A collection whose table is its own already has its constraint and is left as
+ * Hibernate bound it, and so is a collection without a join table or whose key the other side owns.</p>
+ *
+ * @since 8.0.1
+ */
+public class SharedJoinTableUniqueKeyBinder {
+
+ private final MetadataBuildingContext metadataBuildingContext;
+ private final SharedJoinTableUniqueness uniqueness;
+
+ /** Resolves the uniqueness for the dialect of the metadata being built. */
+ public SharedJoinTableUniqueKeyBinder(MetadataBuildingContext metadataBuildingContext) {
+ this(metadataBuildingContext, metadataBuildingContext.getMetadataCollector().getDatabase().getDialect());
+ }
+
+ SharedJoinTableUniqueKeyBinder(MetadataBuildingContext metadataBuildingContext, Dialect dialect) {
+ this.metadataBuildingContext = metadataBuildingContext;
+ this.uniqueness = SharedJoinTableUniqueness.forDialect(dialect);
+ }
+
+ /** The uniqueness this binder applies. */
+ public SharedJoinTableUniqueness getUniqueness() {
+ return uniqueness;
+ }
+
+ /** Gives the collection a uniqueness constraint over its key columns and its element on its join table. */
+ public void bind(Collection collection) {
+ Table table = collection.getCollectionTable();
+ if (table == null || collection.isInverse() || collection.isOneToMany() || collection.getKey() == null) {
Review Comment:
This guard lets every collection with a join table through, and `createCollectionKeys` is now called from the list and map binders as well as from `bindSetSecondPass`, which the bag of a `Collection`-typed property also goes through (`CollectionBinder.registerSecondPass`, the `else` branch). On the `DEFAULT` path the table of each of those gets a unique key over (key, element) that Hibernate never made: their primary key is (key, index), or absent for a bag, so `coveredByPrimaryKey` and `present` are both false and `SharedJoinTableUniqueness` line 99 adds one.
Reproduced at 9066f901f1 against its base 8b7515a7c0 with one spec on H2 (`:grails-data-hibernate7-core:test`): six properties of two owners, each saved with a repeated element and read back after a session clear.
| property | base | this PR | unique index the PR adds (H2 `information_schema.indexes`) |
|---|---|---|---|
| `List<String> nicknames = ['a', 'a']` | passes | `DuplicateKeyException` | `(p16701_owner_id, nicknames_java_lang_string)` |
| `List<Role> roles = [role, role]` | passes | `DuplicateKeyException` | `(p16701_owner_roles_id, p16701_role_id)` |
| `Map<String, String> attrs = [k1: 'v', k2: 'v']` | passes | `DuplicateKeyException` | `(p16701_owner_id, attrs_elt)` |
| `Map<String, Role> roleMap = [a: role, b: role]` | passes | `DuplicateKeyException` | `(p16701_owner_role_map_id, p16701_role_id)` |
| `Collection<String> labels = ['x', 'x']` | passes | `DuplicateKeyException` | `(p16701_bag_owner_id, labels_java_lang_string)` |
| `Collection<Role> bagRoles = [role, role]` | passes | `DuplicateKeyException` | `(p16701_bag_owner_bag_roles_id, p16701_role_id)` |
The base schema has no unique index on any of the six tables. Oracle is not affected, since its path only widens a unique key that already exists, so this is every other database.
A list, a map and a bag may hold an element twice, so the binder has to skip them: return here unless `collection.isSet()` (a sorted set is a `Set` too). With that in place the existing `coveredByPrimaryKey` and `present` checks already leave a set on a table of its own alone, so the "shared" part needs no sibling lookup.
##########
grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/secondpass/GrailsSecondPass.java:
##########
@@ -1,28 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * https://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.grails.orm.hibernate.cfg.domainbinding.secondpass;
-
-import org.hibernate.mapping.Collection;
-
-public interface GrailsSecondPass {
Review Comment:
`GrailsSecondPass` is a public interface that shipped in v8.0.0 (added in 9c8ba25a0a), and this removes it in the 8.0.1 patch. Nothing in the repository references it any more, and a mixin with one default method is unlikely to have implementors outside, but a patch release deleting a public type is not something a user can see coming. Deprecating it for one release, or at least a line in the PR body saying it is gone, would be the safer shape. Non-blocking.
##########
grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/secondpass/SharedJoinTableUniqueness.java:
##########
@@ -0,0 +1,145 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * https://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.grails.orm.hibernate.cfg.domainbinding.secondpass;
+
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Set;
+
+import org.hibernate.dialect.Dialect;
+import org.hibernate.dialect.OracleDialect;
+import org.hibernate.mapping.Column;
+import org.hibernate.mapping.Table;
+import org.hibernate.mapping.UniqueKey;
+
+/**
+ * How a join table that several collections of one owner share keeps the rows of each collection unique, by
+ * database.
+ *
+ * <p>Such a table has a key column per collection and one element column, and every row leaves the key columns of
+ * the other collections null. A row is unique by the key column of its own collection and the element, so each
+ * collection needs a constraint of its own over those two; one constraint over all key columns would hold a null in
+ * every row and reject nothing on a database that treats nulls as distinct. What that per-collection constraint has
+ * to look like depends on how the database compares a null in a unique key:</p>
+ * <ul>
+ * <li>{@link #DEFAULT}: a unique key over the key column and the element. H2, PostgreSQL, MySQL and MariaDB treat
+ * nulls as distinct, so the rows of the other collections, null in this key column, never collide. SQL Server and
+ * DB2 compare nulls as equal, but Hibernate's unique delegate for them renders a unique key over nullable columns as
+ * a filtered unique index that leaves null rows out, which comes to the same.</li>
+ * <li>{@link #ORACLE}: Oracle compares the non-null columns of a partially null row, so a unique key per
+ * collection would reject the rows of the other collections, null in that key column and equal in the element.
+ * One unique key over the key columns of every collection and the element is right there: a row collides only
+ * with a row that is non-null in the same key column, that is a row of its own collection, for the same element.
+ * Hibernate renders that key as a plain constraint on Oracle, where it is what is wanted; on a database that treats
+ * nulls as distinct the same key would hold a null in every row and reject nothing, which is why it is Oracle's
+ * alone.</li>
+ * </ul>
+ *
+ * @since 8.0.1
+ */
+public enum SharedJoinTableUniqueness {
+
+ /** Oracle: one unique key over the key columns of every collection sharing the table and the element. */
+ ORACLE(OracleDialect.class) {
+ @Override
+ void apply(Table table, List<Column> keyColumns, List<Column> elementColumns, Naming naming) {
+ List<Column> own = concat(keyColumns, elementColumns);
+ if (coveredByPrimaryKey(table, own)) {
+ return;
+ }
+ // the unique key Hibernate created for the first collection sharing this table takes the key columns of
+ // every later one: Oracle compares the non-null columns of a row, so a row collides only with a row of
+ // its own collection for the same element, and a plain key per collection would reject the rows of the
+ // other collections, null in that key column and equal in the element
+ for (UniqueKey uniqueKey : table.getUniqueKeys().values()) {
+ if (uniqueKey.isExplicit() || !elementColumns.stream().allMatch(uniqueKey::containsColumn)) {
+ continue;
+ }
+ for (Column column : keyColumns) {
+ if (!uniqueKey.containsColumn(column)) {
+ uniqueKey.addColumn(column);
+ }
+ }
+ }
+ }
+ },
+
+ /** Every other database: a unique key per collection over its key column and the element. */
+ DEFAULT(Dialect.class) {
+ @Override
+ void apply(Table table, List<Column> keyColumns, List<Column> elementColumns, Naming naming) {
Review Comment:
Reproduced on H2 at 9066f901f1 against the base for lists and maps of basic values and of entities, and also for a `Collection`-typed hasMany: the bag goes through `SetSecondPass` and `bindSetSecondPass`, so it gets the same unique key over (key, element), having no primary key at all. All six save a repeated element on the base and fail with `DuplicateKeyException` here. The table of results and the guard suggestion are on `SharedJoinTableUniqueKeyBinder.bind`.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@grails.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Hibernate 7: write the rows of unidirectional hasMany collections that share a join table [grails-core]
Posted by "borinquenkid (via GitHub)" <gi...@apache.org>.
borinquenkid commented on PR #16701:
URL: https://github.com/apache/grails-core/pull/16701#issuecomment-6416782060
Stacked on the upstream fix for apache/grails-core#16691 (PR #16757):
- Removing one element of a set on a join table deleted every row of the association for the owner because Hibernate 7 restricts row deletion by the key and only non-nullable element columns (and GORM join-table element columns are nullable).
- That behavior was upstream in Hibernate 7's row delete mechanics across all join table sets (shared or unshared).
- PR #16757 introduced `JoinTableCollectionPersister` and `GormPersisterClassResolver` to restrict deletion by the key and element column.
- With PR #16757 merged into this branch, the three removal features in `SharedJoinTableBulkDeleteSpec` are unpended and verified.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@grails.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Hibernate 7: write the rows of unidirectional hasMany collections that share a join table [grails-core]
Posted by "borinquenkid (via GitHub)" <gi...@apache.org>.
borinquenkid commented on code in PR #16701:
URL: https://github.com/apache/grails-core/pull/16701#discussion_r4362625537
##########
grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/secondpass/SharedJoinTableUniqueKeyBinder.java:
##########
@@ -0,0 +1,170 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * https://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.grails.orm.hibernate.cfg.domainbinding.secondpass;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import org.hibernate.boot.model.naming.Identifier;
+import org.hibernate.boot.model.naming.ImplicitIndexNameSource;
+import org.hibernate.boot.model.naming.ImplicitNamingStrategy;
+import org.hibernate.boot.model.naming.ImplicitUniqueKeyNameSource;
+import org.hibernate.boot.spi.MetadataBuildingContext;
+import org.hibernate.dialect.Dialect;
+import org.hibernate.mapping.Collection;
+import org.hibernate.mapping.Column;
+import org.hibernate.mapping.Selectable;
+import org.hibernate.mapping.Table;
+
+/**
+ * Gives every collection with a join table a uniqueness constraint of its own over its key column and the element,
+ * so that a join table several collections of one owner share stays unique per collection.
+ *
+ * <p>Two unidirectional {@code hasMany} to the same class without a {@code joinTable} mapping share one join table,
+ * with a key column for each of them and one element column. Hibernate creates the table's implicit unique key when
+ * it creates the keys of the first collection, over that collection's key column and the element column, and creates
+ * none for the others, as the table has a unique key already ({@code Set.createPrimaryKey}). This binder runs after
+ * the keys of each collection are created and completes what is missing, in the shape the database needs
+ * ({@link SharedJoinTableUniqueness}). A collection whose table is its own already has its constraint and is left as
+ * Hibernate bound it, and so is a collection without a join table or whose key the other side owns.</p>
+ *
+ * @since 8.0.1
+ */
+public class SharedJoinTableUniqueKeyBinder {
+
+ private final MetadataBuildingContext metadataBuildingContext;
+ private final SharedJoinTableUniqueness uniqueness;
+
+ /** Resolves the uniqueness for the dialect of the metadata being built. */
+ public SharedJoinTableUniqueKeyBinder(MetadataBuildingContext metadataBuildingContext) {
+ this(metadataBuildingContext, metadataBuildingContext.getMetadataCollector().getDatabase().getDialect());
+ }
+
+ SharedJoinTableUniqueKeyBinder(MetadataBuildingContext metadataBuildingContext, Dialect dialect) {
+ this.metadataBuildingContext = metadataBuildingContext;
+ this.uniqueness = SharedJoinTableUniqueness.forDialect(dialect);
+ }
+
+ /** The uniqueness this binder applies. */
+ public SharedJoinTableUniqueness getUniqueness() {
+ return uniqueness;
+ }
+
+ /** Gives the collection a uniqueness constraint over its key columns and its element on its join table. */
+ public void bind(Collection collection) {
+ Table table = collection.getCollectionTable();
+ if (table == null || collection.isInverse() || collection.isOneToMany() || collection.getKey() == null) {
Review Comment:
Fixed in f1bdd129a0: `bind` returns unless `collection.isSet()`. I reproduced your six properties first: with the guard removed, a list, a map and a bag with a repeated element fail to save with a duplicate key on H2, PostgreSQL, MySQL and MariaDB. A bag went through the set second pass and got the key as well, as you found. With the guard, the set on a table of its own is still left alone by the primary key and `present` checks, as you said.
##########
grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/domainbinding/secondpass/SharedJoinTableUniqueKeyBinderSpec.groovy:
##########
@@ -0,0 +1,263 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * https://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.grails.orm.hibernate.cfg.domainbinding.secondpass
+
+import grails.gorm.annotation.Entity
+import grails.gorm.tests.HibernateGormDatastoreSpec
+import org.hibernate.boot.model.relational.internal.SqlStringGenerationContextImpl
+import org.hibernate.boot.spi.MetadataBuildingContext
+import org.hibernate.dialect.DB2Dialect
+import org.hibernate.dialect.Dialect
+import org.hibernate.dialect.H2Dialect
+import org.hibernate.dialect.MariaDBDialect
+import org.hibernate.dialect.MySQLDialect
+import org.hibernate.dialect.OracleDialect
+import org.hibernate.dialect.PostgreSQLDialect
+import org.hibernate.dialect.SQLServerDialect
+import org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentImpl
+import org.hibernate.mapping.Collection
+import org.hibernate.mapping.Column
+import org.hibernate.mapping.Table
+import org.hibernate.mapping.UniqueKey
+import spock.lang.Unroll
+
+/**
+ * The join table two unidirectional hasMany associations to the same class share gets one implicit unique key from
+ * Hibernate, over the first association's key column and the element column, and nothing for the second. The binder
+ * gives every association a constraint of its own over its key column and the element, in the shape the database
+ * needs: a unique key where nulls are distinct or the dialect renders a filtered unique index, and on Oracle, which
+ * compares the non-null columns of a row, one unique key over every association's key column and the element. An association with a join table of its own, and one whose key the other side
+ * owns, are left as Hibernate binds them.
+ */
+class SharedJoinTableUniqueKeyBinderSpec extends HibernateGormDatastoreSpec {
+
+ void setupSpec() {
+ manager.registerDomainClasses(SjtOwner, SjtSeparateOwner, SjtParent, SjtChild, SjtRole)
+ }
+
+ private Collection collectionOf(Class owner, String property) {
+ datastore.metadata.getCollectionBinding("${owner.name}.${property}".toString())
+ }
+
+ private static List<List<String>> uniqueKeyColumns(Table table) {
+ table.uniqueKeys.values().collect { UniqueKey key -> key.columns*.name.sort() }.sort()
+ }
+
+ void "the shared join table has a unique key per association, over its own key column and the element"() {
+ given:
+ Collection roles = collectionOf(SjtOwner, 'roles')
+ Collection denyRoles = collectionOf(SjtOwner, 'denyRoles')
+
+ expect: 'both associations share the table'
+ roles.collectionTable.is(denyRoles.collectionTable)
+ roles.collectionTable.columns*.name.sort() == ['sjt_owner_deny_roles_id', 'sjt_owner_roles_id', 'sjt_role_id']
+
+ and: 'each association is unique by its own key column and the element; H2 treats nulls as distinct'
+ uniqueKeyColumns(roles.collectionTable) == [
+ ['sjt_owner_deny_roles_id', 'sjt_role_id'],
+ ['sjt_owner_roles_id', 'sjt_role_id']
+ ]
+ roles.collectionTable.indexes.isEmpty()
+
+ and: 'both keys are updatable, so rows of both associations are written'
+ roles.key.updateable
+ denyRoles.key.updateable
+ }
+
+ void "an association with a join table of its own keeps the unique key Hibernate creates for it"() {
Review Comment:
Added in f1bdd129a0. `SharedJoinTableUniqueKeyBinderSpec` binds, from the metadata, a `List<String>`, a `List<Role>`, a `Map<String, String>`, a `Map<String, Role>`, a `Collection<String>` and a `Collection<Role>` hasMany, on the H2 and the Oracle dialect, and asserts none gains a unique key or an index (the lists and maps have their primary key, the bags none); it fails for all twelve rows without the guard. `MultipleUnidirectionalHasManySpec` saves and reads back a repeated element in each of the six on plain H2, and `SharedJoinTableHibernate7Spec` does the same on H2, PostgreSQL, MySQL, MariaDB and Oracle. Each collection that points at the same class maps its own join table in those entities, because two associations to one class with a list among them share a table, which is a separate matter.
##########
grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/secondpass/GrailsSecondPass.java:
##########
@@ -1,28 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * https://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.grails.orm.hibernate.cfg.domainbinding.secondpass;
-
-import org.hibernate.mapping.Collection;
-
-public interface GrailsSecondPass {
Review Comment:
Kept in f1bdd129a0 as a deprecated type, with its original default method and a javadoc that says the second passes no longer implement it and what creates the keys now. Nothing in the repository references it.
##########
grails-data-hibernate7/core/src/test/groovy/grails/gorm/tests/SharedJoinTableHibernate7Spec.groovy:
##########
@@ -0,0 +1,142 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * https://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package grails.gorm.tests
+
+import java.time.Duration
+
+import grails.gorm.annotation.Entity
+import org.testcontainers.mariadb.MariaDBContainer
+import org.testcontainers.mysql.MySQLContainer
+import org.testcontainers.oracle.OracleContainer
+import org.testcontainers.postgresql.PostgreSQLContainer
+import org.springframework.dao.DataIntegrityViolationException
+import org.testcontainers.spock.Testcontainers
+import spock.lang.Requires
+import spock.lang.Shared
+
+/**
+ * A join table two unidirectional hasMany associations share is unique per association on every database: the
+ * same member twice in one association of one owner is rejected, while the same member in the other association,
+ * in the same association of another owner, and denied by two owners is allowed. The last case is the one a unique
+ * key per association over a nullable key column breaks on Oracle, and the first the one a single key over every key
+ * column breaks where nulls are distinct.
+ */
+@Testcontainers
+@Requires({ isDockerAvailable() })
Review Comment:
Added in f1bdd129a0, in `MultipleUnidirectionalHasManySpec` so it runs without Docker: the same role allowed twice by one account of a shared table is refused with a `DataIntegrityViolationException`, while denying the same role by the same account is accepted, because it is the other association. The container spec keeps the rejection across the other databases.
##########
grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/secondpass/SharedJoinTableUniqueness.java:
##########
@@ -0,0 +1,145 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * https://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.grails.orm.hibernate.cfg.domainbinding.secondpass;
+
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Set;
+
+import org.hibernate.dialect.Dialect;
+import org.hibernate.dialect.OracleDialect;
+import org.hibernate.mapping.Column;
+import org.hibernate.mapping.Table;
+import org.hibernate.mapping.UniqueKey;
+
+/**
+ * How a join table that several collections of one owner share keeps the rows of each collection unique, by
+ * database.
+ *
+ * <p>Such a table has a key column per collection and one element column, and every row leaves the key columns of
+ * the other collections null. A row is unique by the key column of its own collection and the element, so each
+ * collection needs a constraint of its own over those two; one constraint over all key columns would hold a null in
+ * every row and reject nothing on a database that treats nulls as distinct. What that per-collection constraint has
+ * to look like depends on how the database compares a null in a unique key:</p>
+ * <ul>
+ * <li>{@link #DEFAULT}: a unique key over the key column and the element. H2, PostgreSQL, MySQL and MariaDB treat
+ * nulls as distinct, so the rows of the other collections, null in this key column, never collide. SQL Server and
+ * DB2 compare nulls as equal, but Hibernate's unique delegate for them renders a unique key over nullable columns as
+ * a filtered unique index that leaves null rows out, which comes to the same.</li>
+ * <li>{@link #ORACLE}: Oracle compares the non-null columns of a partially null row, so a unique key per
+ * collection would reject the rows of the other collections, null in that key column and equal in the element.
+ * One unique key over the key columns of every collection and the element is right there: a row collides only
+ * with a row that is non-null in the same key column, that is a row of its own collection, for the same element.
+ * Hibernate renders that key as a plain constraint on Oracle, where it is what is wanted; on a database that treats
+ * nulls as distinct the same key would hold a null in every row and reject nothing, which is why it is Oracle's
+ * alone.</li>
+ * </ul>
+ *
+ * @since 8.0.1
+ */
+public enum SharedJoinTableUniqueness {
+
+ /** Oracle: one unique key over the key columns of every collection sharing the table and the element. */
+ ORACLE(OracleDialect.class) {
+ @Override
+ void apply(Table table, List<Column> keyColumns, List<Column> elementColumns, Naming naming) {
+ List<Column> own = concat(keyColumns, elementColumns);
+ if (coveredByPrimaryKey(table, own)) {
+ return;
+ }
+ // the unique key Hibernate created for the first collection sharing this table takes the key columns of
+ // every later one: Oracle compares the non-null columns of a row, so a row collides only with a row of
+ // its own collection for the same element, and a plain key per collection would reject the rows of the
+ // other collections, null in that key column and equal in the element
+ for (UniqueKey uniqueKey : table.getUniqueKeys().values()) {
+ if (uniqueKey.isExplicit() || !elementColumns.stream().allMatch(uniqueKey::containsColumn)) {
+ continue;
+ }
+ for (Column column : keyColumns) {
+ if (!uniqueKey.containsColumn(column)) {
+ uniqueKey.addColumn(column);
+ }
+ }
+ }
+ }
+ },
+
+ /** Every other database: a unique key per collection over its key column and the element. */
+ DEFAULT(Dialect.class) {
+ @Override
+ void apply(Table table, List<Column> keyColumns, List<Column> elementColumns, Naming naming) {
Review Comment:
Fixed in f1bdd129a0, for lists, maps and bags: the binder acts only on a set. Your map with one value under two keys fails to save without the guard on H2, PostgreSQL, MySQL and MariaDB, and saves with it on all five databases (`SharedJoinTableHibernate7Spec`).
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@grails.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Hibernate 7: write the rows of unidirectional hasMany collections that share a join table [grails-core]
Posted by "jamesfredley (via GitHub)" <gi...@apache.org>.
jamesfredley commented on code in PR #16701:
URL: https://github.com/apache/grails-core/pull/16701#discussion_r4365978316
##########
grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/secondpass/CollectionKeyColumnUpdater.java:
##########
@@ -36,28 +43,11 @@ public CollectionKeyColumnUpdater(CollectionKeyBinder collectionKeyBinder) {
this.collectionKeyBinder = collectionKeyBinder;
}
- /** Creates the key, sets it on the collection, and updates its columns. */
+ /** Creates the key, sets it on the collection, and makes its columns nullable and the key updatable. */
public void bind(HibernateToManyProperty property) {
DependantValue key = collectionKeyBinder.bind(property);
key.getColumns().stream().filter(Objects::nonNull).forEach(column -> column.setNullable(true));
- Table collectionTable = property.getCollection().getCollectionTable();
- long unidirectionalCount = property.getHibernateOwner()
- .getPersistentPropertiesToBind()
- .stream()
- .filter(HibernateToManyProperty::isBoundAsCollection)
- .map(HibernateToManyProperty.class::cast)
- .filter(p -> !p.isBidirectional())
- .filter(p -> Objects.equals(p.getCollection().getCollectionTable(), collectionTable))
- .count();
-
- // Collections of basic values or enums (HibernateToManyCollectionProperty) always keep an updatable key: they
- // have no inverse side, and Hibernate writes no rows for a collection whose key is not updatable.
- // For entity collections (HibernateToManyEntityProperty) the key is non-updatable only when the owner has
- // two or more unidirectional to-many properties that share this collection's join table, the rule for issue
- // 10811. Unidirectional collections with join tables of their own keep an updatable key, as they have no
- // second key column to leave null. A to-many that is not bound as a collection (a serializable or user type)
- // has no join table and no Hibernate collection, so it is neither counted nor asked for one.
- key.setUpdateable(property instanceof HibernateToManyCollectionProperty || unidirectionalCount <= 1);
+ key.setUpdateable(true);
Review Comment:
When a shared-table set has two elements, removing one deletes both. Hibernate's row-delete predicate omits the nullable element columns, and `is not null` does not tell the two elements apart. The pending removal tests in `SharedJoinTableBulkDeleteSpec` show this. The key used to be non-updatable, so this path is new.
Fix the row delete, or rewrite the surviving rows, before enabling updates. Please remove one element and assert the other remains.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@grails.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Hibernate 7: write the rows of unidirectional hasMany collections that share a join table [grails-core]
Posted by "jdaugherty (via GitHub)" <gi...@apache.org>.
jdaugherty commented on code in PR #16701:
URL: https://github.com/apache/grails-core/pull/16701#discussion_r4383761007
##########
grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/secondpass/SharedJoinTableUniqueKeyBinder.java:
##########
@@ -0,0 +1,286 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * https://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.grails.orm.hibernate.cfg.domainbinding.secondpass;
+
+import java.util.ArrayList;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Set;
+
+import org.hibernate.MappingException;
+import org.hibernate.boot.Metadata;
+import org.hibernate.boot.model.naming.Identifier;
+import org.hibernate.boot.model.naming.ImplicitIndexNameSource;
+import org.hibernate.boot.model.naming.ImplicitNamingStrategy;
+import org.hibernate.boot.model.naming.ImplicitUniqueKeyNameSource;
+import org.hibernate.boot.spi.MetadataBuildingContext;
+import org.hibernate.dialect.Dialect;
+import org.hibernate.mapping.Collection;
+import org.hibernate.mapping.Column;
+import org.hibernate.mapping.IdentifierCollection;
+import org.hibernate.mapping.IndexedCollection;
+import org.hibernate.mapping.Selectable;
+import org.hibernate.mapping.Table;
+import org.hibernate.mapping.Value;
+
+/**
+ * Gives every collection with a join table a uniqueness constraint of its own over its key column and the element,
+ * so that a join table several collections of one owner share stays unique per collection.
+ *
+ * <p>Two unidirectional {@code hasMany} to the same class without a {@code joinTable} mapping share one join table,
+ * with a key column for each of them and one element column. Hibernate creates the table's implicit unique key when
+ * it creates the keys of the first collection, over that collection's key column and the element column, and creates
+ * none for the others, as the table has a unique key already ({@code Set.createPrimaryKey}). This binder runs after
+ * the keys of each collection are created and completes what is missing, in the shape the database needs
+ * ({@link SharedJoinTableUniqueness}). A collection whose table is its own already has its constraint and is left as
+ * Hibernate bound it, and so is a collection without a join table, whose key the other side owns, or whose element is
+ * a large object, which cannot be indexed and which Hibernate leaves without a key too. It also restricts
+ * each collection of a shared table to its own rows, which Hibernate's removal of all the rows of a collection by its
+ * key would otherwise not.</p>
+ *
+ * <p>Hibernate applies the restriction to the statements that load, count, join and delete the rows of a collection,
+ * but loses it in the test of emptiness ({@code is empty}, {@code is not empty}); GORM translates that test as a size
+ * test for a restricted many-to-many collection instead, through
+ * {@link org.grails.orm.hibernate.query.RestrictedCollectionSqmTranslatorFactory} (apache/grails-core#16748), except in
+ * an update or delete of an entity whose hierarchy spans several tables.</p>
+ *
+ * <p>A set cannot share a join table with a list or a map: the index column of a list or a map is not null, and the
+ * rows of the set leave it null, so saving the set fails on the first insert.</p>
+ *
+ * @since 8.0.1
+ */
+public class SharedJoinTableUniqueKeyBinder {
+
+ private final MetadataBuildingContext metadataBuildingContext;
+ private final SharedJoinTableUniqueness uniqueness;
+
+ /** Resolves the uniqueness for the dialect of the metadata being built. */
+ public SharedJoinTableUniqueKeyBinder(MetadataBuildingContext metadataBuildingContext) {
+ this(metadataBuildingContext, metadataBuildingContext.getMetadataCollector().getDatabase().getDialect());
+ }
+
+ SharedJoinTableUniqueKeyBinder(MetadataBuildingContext metadataBuildingContext, Dialect dialect) {
+ this.metadataBuildingContext = metadataBuildingContext;
+ this.uniqueness = SharedJoinTableUniqueness.forDialect(dialect);
+ }
+
+ /** The uniqueness this binder applies. */
+ public SharedJoinTableUniqueness getUniqueness() {
+ return uniqueness;
+ }
+
+ /**
+ * Gives a set the uniqueness constraint over its key columns and its element on its join table. A list or a map
+ * is keyed by its index, which its table has as part of the primary key, and a bag has no key at all; their
+ * elements repeat by design, so they are left as Hibernate bound them.
+ */
+ public void bind(Collection collection) {
+ Table table = collection.getCollectionTable();
+ if (table == null || collection.isInverse() || collection.isOneToMany() || collection.getKey() == null) {
+ return;
+ }
+ restrictRowsToOwnCollection(collection, table);
+ if (!collection.isSet()) {
+ return;
+ }
+ List<Column> keyColumns = collection.getKey().getColumns();
+ List<Column> elementColumns = columnsOf(collection);
+ if (keyColumns.isEmpty() || elementColumns.isEmpty() || hasLobColumn(collection.getMetadata(), elementColumns)) {
+ return;
+ }
+ uniqueness.apply(table, keyColumns, elementColumns, new ImplicitNaming(table));
+ }
+
+ /**
+ * Hibernate removes all the rows of a collection with one statement on its key, and loads them with one. On a join
+ * table several collections share, a key column two of them use would take the rows of the other collection
+ * along, so each collection of such a table is restricted to the rows that have a value in its own element
+ * columns. The collections that share the table are found among the bindings of the metadata; one whose element is
+ * not bound yet is restricted when its own pass runs, which finds the others bound.
+ */
+ private void restrictRowsToOwnCollection(Collection collection, Table table) {
+ if (!hasColumnsOfOthers(collection, table)) {
+ return;
+ }
+ List<Collection> sharing = new ArrayList<>();
+ for (Collection other : metadataBuildingContext.getMetadataCollector().getCollectionBindings()) {
+ if (other.getCollectionTable() == table && !other.isInverse() && !other.isOneToMany() && other.getKey() != null) {
+ sharing.add(other);
+ }
+ }
+ if (sharing.size() < 2) {
+ return;
+ }
+ Dialect dialect = metadataBuildingContext.getMetadataCollector().getDatabase().getDialect();
+ for (Collection member : sharing) {
+ List<String> present = new ArrayList<>();
+ for (Column column : columnsOf(member)) {
+ present.add(column.getQuotedName(dialect) + " is not null");
+ }
+ if (present.isEmpty()) {
+ continue;
+ }
+ String restriction = String.join(" and ", present);
+ String where = member.getWhere();
+ if (where == null || where.isBlank()) {
+ member.setWhere(restriction);
+ } else if (!where.contains(restriction)) {
+ member.setWhere("(" + where + ") and " + restriction);
+ }
+ }
+ }
+
+ /**
+ * Whether the table holds a column that the collection does not use: its key, element, index and identifier
+ * columns are its own, and a column besides those belongs to another collection that shares the table. A table
+ * only this collection uses is not searched for the others, which keeps the binding of an application with many
+ * collections linear. The collection of a shared table that is bound first finds none, and the one bound after
+ * it restricts both.
+ */
+ private static boolean hasColumnsOfOthers(Collection collection, Table table) {
Review Comment:
Non-blocking. `hasColumnsOfOthers` is also true for the default shape, `hasMany = [allow: Member, deny: Member]` with no mapping. There each association has its own key column and both share the element column, so both collections get the same `member_id is not null`. The binder spec pins this for `SjtOwner` (`roles.where == 'sjt_role_id is not null'`, lines 104-105). The predicate separates nothing in that shape, because each association's rows are already selected and deleted by its own key column. Captured with a statement inspector on H2 at e635103fa2:
```
load: ... where a1_0.p16701_group_allow_id=? and (a1_0.p16701_member_id is not null)
clear: delete from p16701_group_p16701_member where p16701_group_allow_id=? and ((p16701_member_id is not null))
is empty: ... where (select count(*) from p16701_group_p16701_member d1_0 where (d1_0.p16701_member_id is not null) and pg1_0.id=d1_0.p16701_group_deny_id)=0
```
An owner with a table of its own keeps `not exists(select 1 ...)` for `is empty`. Because the default shape now `hasWhereRestrictions()`, `RestrictedCollectionSqmTranslatorFactory` also turns its emptiness test into a count. The restriction is needed only when the sharing collections have a key column in common, which is the `joinTable` shape of `SjtbdAccount` in `SharedJoinTableBulkDeleteSpec`. Restricting only that case would leave the SQL of the most common shared shape as it was, and would keep the translator override to the one case that needs it.
##########
grails-doc/src/en/guide/upgrading/upgrading80x.adoc:
##########
@@ -1460,7 +1460,7 @@ A type that spans several columns no longer implements `UserType` with several `
Under Hibernate 7, an owner with two or more unidirectional `hasMany` associations wrote no rows to their join tables: an element added to any of them was lost at flush (issue https://github.com/apache/grails-core/issues/16665[#16665]). This is fixed when each association has a join table of its own, which is the default for associations to different classes (`item_roles` and `item_tags` for `static hasMany = [roles: Role, tags: Tag]`) and also the case when two associations to the same class map different tables with `joinTable`. Each such join table is written, as under Hibernate 5.
-Two unidirectional associations to the same class share one join table by default, named after the owner and the element class, with a key column per association (`item_role` with `item_roles_id` and `item_deny_roles_id` for `static hasMany = [roles: Role, denyRoles: Role]`). Such a table is read, but new elements are not written, and neither are those of associations that `joinTable` maps onto one table. That is issue https://github.com/apache/grails-core/issues/10811[#10811] and is not fixed by this change; name a `joinTable` per association to give each its own table.
+Two unidirectional associations to the same class share one join table by default, named after the owner and the element class, with a key column per association (`item_role` with `item_roles_id` and `item_deny_roles_id` for `static hasMany = [roles: Role, denyRoles: Role]`). Such a shared table is now written as well: each association keeps its rows unique by its own key column and the element. A list or a map is left as it was: its join table is keyed by the index, and its elements may repeat. On most databases that is a unique key per association; on Oracle and on Db2 for Linux, UNIX and Windows, which compare the non-null columns of a partially null row in a unique key, it is one unique key over the key columns of both associations and the element. A schema created by an earlier Grails 8 release has the single unique key Hibernate made for the first association: `dbCreate` of `update` adds the second one, and on Oracle and Db2 for Linux, UNIX and Windows a migration has to repla
ce that key with the wider one.
Review Comment:
Two small things in this paragraph. The list-and-map sentence sits between "each association keeps its rows unique by its own key column and the element" and "On most databases that is a unique key per association", so "that" now reads as the list's key. Moving it after the Oracle and Db2 sentence fixes the reading, and a bag belongs in it too, since it is also left without the key.
Also, GORM now sets `hibernate.query.sqm.translator` unless the application sets it. The next paragraph says that an application with its own `hibernate.persister.resolver` keeps it and loses the #16691 fix. A matching sentence for the translator would say the same about `is empty` on associations that share a key column (#16748).
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@grails.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Hibernate 7: write the rows of unidirectional hasMany collections that share a join table [grails-core]
Posted by "borinquenkid (via GitHub)" <gi...@apache.org>.
borinquenkid commented on PR #16701:
URL: https://github.com/apache/grails-core/pull/16701#issuecomment-6417051960
Stacked on the upstream fix for apache/grails-core#16691 (PR #16757):
- Removing one element of a set on a join table deleted every row of the association for the owner because Hibernate 7 restricts row deletion by the key and only non-nullable element columns (and GORM join-table element columns are nullable).
- That behavior was upstream in Hibernate 7's row delete mechanics across all join table sets (shared or unshared).
- PR #16757 introduced `JoinTableCollectionPersister` and `GormPersisterClassResolver` to restrict deletion by the key and element column.
- With PR #16757 merged into this branch, the three removal features in `SharedJoinTableBulkDeleteSpec` are unpended and verified.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@grails.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Hibernate 7: write the rows of unidirectional hasMany collections that share a join table [grails-core]
Posted by "borinquenkid (via GitHub)" <gi...@apache.org>.
borinquenkid merged PR #16701:
URL: https://github.com/apache/grails-core/pull/16701
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@grails.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Hibernate 7: write the rows of unidirectional hasMany collections that share a join table [grails-core]
Posted by "jamesfredley (via GitHub)" <gi...@apache.org>.
jamesfredley commented on code in PR #16701:
URL: https://github.com/apache/grails-core/pull/16701#discussion_r4338912955
##########
grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/secondpass/SharedJoinTableUniqueKeyBinder.java:
##########
@@ -0,0 +1,83 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * https://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.grails.orm.hibernate.cfg.domainbinding.secondpass;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import org.hibernate.mapping.Collection;
+import org.hibernate.mapping.Column;
+import org.hibernate.mapping.Selectable;
+import org.hibernate.mapping.Table;
+import org.hibernate.mapping.UniqueKey;
+
+/**
+ * Completes the implicit unique key of a join table that several collections of one owner share.
+ *
+ * <p>Two unidirectional {@code hasMany} to the same class without a {@code joinTable} mapping share one join table, with a
+ * key column for each of them and one element column. Hibernate creates the table's unique key when it creates the keys of
+ * the first collection, over that collection's key column and the element column, and creates none for the others, as the
+ * table has a unique key already ({@code Set.createPrimaryKey}). A row of a later collection leaves the first key column
+ * null, so on a database that treats nulls as equal in a unique constraint two of its rows for the same element, from two
+ * owners, are duplicates. This binder adds the key columns of every collection to that unique key once the collection's
+ * keys are created, so a row is unique by the key column of its own collection and the element.</p>
+ *
+ * <p>A unique key the mapping declares explicitly is left alone, and so is a collection without a join table or whose
+ * key the other side owns.</p>
+ *
+ * @since 8.0.1
+ */
+public class SharedJoinTableUniqueKeyBinder {
+
+ /** Adds the key columns of the collection to the implicit unique key of its join table that covers its element. */
+ public void bind(Collection collection) {
+ Table table = collection.getCollectionTable();
+ if (table == null || collection.isInverse() || collection.isOneToMany() || collection.getKey() == null) {
+ return;
+ }
+ List<Column> keyColumns = collection.getKey().getColumns();
+ List<Column> elementColumns = columnsOf(collection);
+ if (keyColumns.isEmpty() || elementColumns.isEmpty()) {
+ return;
+ }
+ for (UniqueKey uniqueKey : table.getUniqueKeys().values()) {
+ if (uniqueKey.isExplicit() || !elementColumns.stream().allMatch(uniqueKey::containsColumn)) {
+ continue;
+ }
+ for (Column column : keyColumns) {
+ if (!uniqueKey.containsColumn(column)) {
+ uniqueKey.addColumn(column);
Review Comment:
Adding the sibling key here weakens the constraint it is meant to extend. For `roles` and `denyRoles` sharing a join table, the implicit key becomes `UNIQUE(roles_id, deny_roles_id, role_id)`. A real `roles` row is `(roles_id=1, deny_roles_id=NULL, role_id=7)`. PostgreSQL, MySQL, and default H2 treat those NULLs as distinct, so that row can be inserted twice. The old `(roles_id, role_id)` constraint rejected the duplicate.
Keep a per-association uniqueness constraint on `(own_collection_key, element)` for NULL-distinct dialects. Where the dialect treats NULLs as equal, use a null-safe or partial index instead of one widened constraint that is NULL for every normal row.
Please add a regression that rejects duplicate membership of the same role in the same collection, and still allows that role in the other collection and in another owner. The current specs do not catch this.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@grails.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org