This is an automated email from the ASF dual-hosted git repository. borinquenkid pushed a commit to branch 9.0.x-h7-improvement-phase3 in repository https://gitbox.apache.org/repos/asf/grails-core.git
commit e4d6546596a33c70362a038b68885e2bdc1f25a7 Author: Walter Duque de Estrada <[email protected]> AuthorDate: Tue Oct 6 14:00:36 2026 -0500 fix: name the join key of a circular many-to-many in generated mode as the domain binder does The binder renames the join key of one side of a self-referencing many-to-many while it binds the other, so the side bound first (first property of the entity) keeps the default key name and the side bound second is named after its property. The generator renamed both sides, so a database created by the binder and then opened in generated mode would see update add new join table columns beside the old ones and not find the existing relationship rows. Co-Authored-By: Claude Sonnet 5.5 <[email protected]> --- .../domainbinding/jpa/GrailsDomainGenerator.groovy | 25 +- ...ratedDomainClassesCircularManyToManySpec.groovy | 271 +++++++++++++++++++++ ...eneratedDomainClassesDdlDifferentialSpec.groovy | 5 - .../GrailsDomainGeneratorDifferentialSpec.groovy | 24 +- 4 files changed, 307 insertions(+), 18 deletions(-) diff --git a/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/jpa/GrailsDomainGenerator.groovy b/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/jpa/GrailsDomainGenerator.groovy index 73811c6b23..e782f16a35 100644 --- a/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/jpa/GrailsDomainGenerator.groovy +++ b/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/jpa/GrailsDomainGenerator.groovy @@ -1445,7 +1445,8 @@ class GrailsDomainGenerator { /** * {@code ManyToOneBinder.prepareCircularManyToMany} gives a circular many-to-many that names no join key the key * {@code <property>_id}, by changing the mapping while it binds. The generator runs without that mutation, so it applies - * the rule itself. + * the rule itself, to the name of the element column (the binder binds it after the rename of the other side) and, for the + * key column, only where the binder renamed the key before it bound it, see {@link #boundBeforeInverseSide}. */ private ColumnFacets circularKeyName(HibernateManyToManyProperty property, ColumnFacets facets) { if (!property.isCircular() || property.hibernateMappedForm.hasJoinKeyMapping()) { @@ -1457,6 +1458,23 @@ class GrailsDomainGenerator { facets.read(), facets.write(), facets.comment()) } + /** + * Whether the binder binds the key of the collection of this many-to-many before the element of the collection of its + * inverse side. The element of a many-to-many is bound like the column of the other side and renames the join key of that + * side (it must be circular and name no join key), so the key of a circular side that is bound first keeps the default name + * and the key of one bound second is renamed. The collections are bound in the order of the properties of the entity + * ({@code persistentPropertiesToBind}), the superclass before its subclasses, so a side whose inverse side is not circular + * (it belongs to a superclass) is always bound second. + */ + private boolean boundBeforeInverseSide(HibernateManyToManyProperty property) { + HibernateAssociation inverse = property.hibernateInverseSide + if (inverse == null || !inverse.isCircular() || inverse.owner != property.owner) { + return false + } + List<String> order = property.hibernateOwner.persistentPropertiesToBind*.name + return order.indexOf(property.name) <= order.indexOf(inverse.name) + } + /** * @return why the generator cannot describe the collection of entities, or {@code null} when it can */ @@ -1585,7 +1603,10 @@ class GrailsDomainGenerator { table = tableForMany.getTableName(property) schema = joinTable?.schema != null ? joinTable.schema : entityFacets(property.hibernateOwner).schema() catalog = joinTable?.catalog - key = circularKeyName((HibernateManyToManyProperty) property, collectionKeyFacets(property)) + key = collectionKeyFacets(property) + if (!boundBeforeInverseSide((HibernateManyToManyProperty) property)) { + key = circularKeyName((HibernateManyToManyProperty) property, key) + } // ManyToOneBinder binds the element like the other side's own column: its name rules and its (never) nullable column element = circularKeyName(other, toOneColumnFacets(other)) mappedBy = property.owningSide ? null : other.name diff --git a/grails-data-hibernate7/core/src/test/groovy/grails/gorm/tests/generated/GeneratedDomainClassesCircularManyToManySpec.groovy b/grails-data-hibernate7/core/src/test/groovy/grails/gorm/tests/generated/GeneratedDomainClassesCircularManyToManySpec.groovy new file mode 100644 index 0000000000..1ceb33c18e --- /dev/null +++ b/grails-data-hibernate7/core/src/test/groovy/grails/gorm/tests/generated/GeneratedDomainClassesCircularManyToManySpec.groovy @@ -0,0 +1,271 @@ +/* + * 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.generated + +import java.sql.Connection +import java.sql.ResultSet +import java.sql.Statement +import java.util.concurrent.atomic.AtomicInteger + +import grails.gorm.annotation.Entity +import org.hibernate.mapping.Collection as HibernateCollection +import org.hibernate.mapping.Table +import spock.lang.AutoCleanup +import spock.lang.Specification +import spock.lang.Unroll + +import org.grails.orm.hibernate.HibernateDatastore + +/** + * A self-referencing many-to-many (one entity on both sides) over the generated classes names its join table columns as the + * domain binder does. The binder renames the join key of one side while it binds the other, so which side keeps the default key + * name depends on the order the two collections are bound in, which is the order of the properties of the entity. A user whose + * database was created by the binder and who turns generated mode on must not see {@code update} add new columns beside the old + * ones, and a relationship the binder wrote must still be read. + */ +class GeneratedDomainClassesCircularManyToManySpec extends Specification { + + static final AtomicInteger BOOTS = new AtomicInteger() + + @AutoCleanup + HibernateDatastore datastore + + private HibernateDatastore boot(List<Class> group, boolean generated) { + datastore?.close() + datastore = new HibernateDatastore([ + 'dataSource.url' : "jdbc:h2:mem:cmmCircular${BOOTS.incrementAndGet()};LOCK_TIMEOUT=10000".toString(), + 'dataSource.dbCreate' : 'create-drop', + 'hibernate.generatedDomainClasses': generated, + ], group as Class[]) + return datastore + } + + /** The collections and the join tables the boot model holds, as plain data. */ + private Map<String, Object> schema(List<Class> group, boolean generated) { + HibernateDatastore booted = boot(group, generated) + Map<String, Object> result = [:] + for (HibernateCollection collection : booted.metadata.collectionBindings) { + Table table = collection.collectionTable + result[collection.role] = [ + table : table.name, + inverse : collection.inverse, + key : collection.key.columns*.name, + element : collection.element.columns*.name, + columns : table.columns*.name, + primaryKey : table.primaryKey?.columns*.name, + foreignKeys: table.foreignKeys.values().collect { it.columns*.name }.sort { it.toString() }, + ] + } + return result + } + + @Unroll + void "the join tables of #label have the column names the domain binder gives them"() { + when: + Map<String, Object> binder = schema(group, false) + Map<String, Object> generated = schema(group, true) + + then: + !binder.isEmpty() + generated == binder + + where: + label | group + 'a bidirectional self many-to-many' | [CmFollowers] + 'the same with the properties declared the other way' | [CmFollowersSwapped] + 'the same with the properties and hasMany in two orders' | [CmFollowersMixed] + 'the same with names that sort the other way' | [CmZebras] + 'a self many-to-many inside a hierarchy' | [CmHierarchyRoot, CmHierarchySub] + 'a superclass collection and a circular subclass one' | [CmMammal, CmDog] + 'a unidirectional self many-to-many' | [CmFriends] + 'a first side that names its join key' | [CmKeyedFirst] + 'a second side that names its join key' | [CmKeyedSecond] + } + + void "the side bound first keeps the default key name and the side bound second is named after its property"() { + when: + Map<String, Object> generated = schema([CmFollowers], true) + + then: + generated['grails.gorm.tests.generated.CmFollowers.followers'].key == ['cm_followers_id'] + generated['grails.gorm.tests.generated.CmFollowers.followers'].element == ['following_id'] + generated['grails.gorm.tests.generated.CmFollowers.following'].key == ['following_id'] + generated['grails.gorm.tests.generated.CmFollowers.following'].element == ['followers_id'] + generated['grails.gorm.tests.generated.CmFollowers.followers'].primaryKey == ['cm_followers_id', 'following_id'] + } + + void "which side is bound first follows the order of the properties"() { + when: + Map<String, Object> generated = schema([CmFollowersSwapped], true) + + then: + generated['grails.gorm.tests.generated.CmFollowersSwapped.following'].key == ['cm_followers_swapped_id'] + generated['grails.gorm.tests.generated.CmFollowersSwapped.followers'].key == ['followers_id'] + } + + private static Map<String, List<String>> rows(HibernateDatastore booted, String sql) { + Map<String, List<String>> result = new TreeMap<String, List<String>>() + booted.connectionSources.defaultConnectionSource.dataSource.connection.withCloseable { Connection connection -> + connection.createStatement().withCloseable { Statement statement -> + statement.executeQuery(sql).withCloseable { ResultSet rs -> + while (rs.next()) { + result.computeIfAbsent(rs.getString(1)) { new ArrayList<String>() }.add(rs.getString(2)) + } + } + } + } + return result + } + + /** Writes a relationship through one side, then reads it through both sides, in a fresh session. */ + private Map<String, Object> behaviour(boolean generated) { + HibernateDatastore booted = boot([CmFollowers], generated) + Map<String, Object> result = [:] + CmFollowers.withTransaction { + CmFollowers a = new CmFollowers(name: 'a').save(failOnError: true) + CmFollowers b = new CmFollowers(name: 'b').save(failOnError: true) + a.addToFollowers(b) + a.save(flush: true, failOnError: true) + } + CmFollowers.withNewSession { + result.followersOfA = CmFollowers.findByName('a').followers*.name.sort() + result.followingOfA = CmFollowers.findByName('a').following*.name.sort() + result.followersOfB = CmFollowers.findByName('b').followers*.name.sort() + result.followingOfB = CmFollowers.findByName('b').following*.name.sort() + } + result.joinTables = ['cm_followers_followers', 'cm_followers_following'].collectEntries { String table -> + [table, rows(booted, "select 'x', count(*) from ${table}".toString())['x']] + } + return result + } + + void "a relationship written through one side is read through the sides exactly as with the domain binder"() { + when: + Map<String, Object> binder = behaviour(false) + Map<String, Object> generated = behaviour(true) + + then: + generated == binder + binder.followersOfA == ['b'] + binder.followingOfB == ['a'] + binder.followingOfA.isEmpty() + binder.followersOfB.isEmpty() + binder.joinTables == ['cm_followers_followers': ['1'], 'cm_followers_following': ['1']] + } +} + +@Entity +class CmFollowers { + String name + Set<CmFollowers> followers + Set<CmFollowers> following + static hasMany = [followers: CmFollowers, following: CmFollowers] + static mappedBy = [followers: 'following', following: 'followers'] + static belongsTo = [CmFollowers] +} + +@Entity +class CmFollowersSwapped { + String name + Set<CmFollowersSwapped> following + Set<CmFollowersSwapped> followers + static hasMany = [following: CmFollowersSwapped, followers: CmFollowersSwapped] + static mappedBy = [followers: 'following', following: 'followers'] + static belongsTo = [CmFollowersSwapped] +} + +@Entity +class CmFollowersMixed { + String name + Set<CmFollowersMixed> following + Set<CmFollowersMixed> followers + static hasMany = [followers: CmFollowersMixed, following: CmFollowersMixed] + static mappedBy = [followers: 'following', following: 'followers'] + static belongsTo = [CmFollowersMixed] +} + +@Entity +class CmZebras { + String name + Set<CmZebras> zebras + Set<CmZebras> apples + static hasMany = [zebras: CmZebras, apples: CmZebras] + static mappedBy = [zebras: 'apples', apples: 'zebras'] + static belongsTo = [CmZebras] +} + +@Entity +class CmHierarchyRoot { + String name +} + +@Entity +class CmHierarchySub extends CmHierarchyRoot { + Set<CmHierarchySub> pals + Set<CmHierarchySub> palOf + static hasMany = [pals: CmHierarchySub, palOf: CmHierarchySub] + static mappedBy = [pals: 'palOf', palOf: 'pals'] + static belongsTo = [CmHierarchySub] +} + +@Entity +class CmMammal { + String name + static hasMany = [dogs: CmDog] +} + +@Entity +class CmDog extends CmMammal { + static hasMany = [animals: CmMammal] + static belongsTo = [CmMammal] +} + +@Entity +class CmFriends { + String name + Set<CmFriends> friends + static hasMany = [friends: CmFriends] + static belongsTo = [CmFriends] +} + +@Entity +class CmKeyedFirst { + String name + Set<CmKeyedFirst> followers + Set<CmKeyedFirst> following + static hasMany = [followers: CmKeyedFirst, following: CmKeyedFirst] + static mappedBy = [followers: 'following', following: 'followers'] + static belongsTo = [CmKeyedFirst] + static mapping = { + followers joinTable: [name: 'cm_keyed_first_f', key: 'owner_ref', column: 'other_ref'] + } +} + +@Entity +class CmKeyedSecond { + String name + Set<CmKeyedSecond> followers + Set<CmKeyedSecond> following + static hasMany = [followers: CmKeyedSecond, following: CmKeyedSecond] + static mappedBy = [followers: 'following', following: 'followers'] + static belongsTo = [CmKeyedSecond] + static mapping = { + following joinTable: [name: 'cm_keyed_second_f', key: 'owner_ref', column: 'other_ref'] + } +} diff --git a/grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/domainbinding/jpa/GeneratedDomainClassesDdlDifferentialSpec.groovy b/grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/domainbinding/jpa/GeneratedDomainClassesDdlDifferentialSpec.groovy index 64978fe5d2..7f68a66914 100644 --- a/grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/domainbinding/jpa/GeneratedDomainClassesDdlDifferentialSpec.groovy +++ b/grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/domainbinding/jpa/GeneratedDomainClassesDdlDifferentialSpec.groovy @@ -63,7 +63,6 @@ class GeneratedDomainClassesDdlDifferentialSpec extends Specification { * The difference classes kept on purpose, each with the reason it cannot or should not be removed ({@code classify} names them). */ private static final List<Map> KNOWN = [ - [id: 'CIRCULAR_MANY_TO_MANY', reason: 'A self-referencing many-to-many (one entity on both sides) names its join table columns differently. The binder changes the mapping of the other side while it binds (ManyToOneBinder.prepareCircularManyToMany), so the key name of the side bound first is the default and of the side bound second is <property>_id: the result depends on second-pass order and the two sides name different columns of one table (a naming inconsistency, no data lo [...] [id: 'COLUMN_ORDER', reason: 'The order of the columns inside a table: Hibernate\'s column ordering strategy orders the generated tables by size and name, the binder\'s tables keep the order the binder created them in for the entities of a composite key whose column types the binder swaps (see COMPOSITE_KEY_ORDER) and for the table of a table id generator (next_val, sequence_name). A schema diff tool (Liquibase diff, hibernate validate) does not compare column order, and no a [...] [id: 'COMPOSITE_KEY_ORDER', reason: 'Foreign keys and primary keys over a composite identifier whose parts are mapped in an order other than the sorted one. Hibernate\'s @IdClass key is sorted by property name. (a) Types: the binder names the foreign key columns after the parts in the mapped order but gives them the types of the sorted referenced key, so a part of another type than its neighbour gets the NAME of the other part (child.parent_grand_parent_name is INTEGER, refer [...] [id: 'ENUM_COLUMN_EXTRAS', reason: 'A binder defect (pinned in GrailsDomainBinderOptionDefectSpec): EnumTypeBinder ignores the comment and default expressions of an enum column\'s mapping. The generated mode honours them, so a database created by the binder lacks a default and a comment that the mapping states. Matching the binder would drop what the mapping says; decision for the lead (the 8.x line has the same defect).'], @@ -166,10 +165,6 @@ class GeneratedDomainClassesDdlDifferentialSpec extends Specification { if (kind in ['column comment', 'column default']) { return 'ENUM_COLUMN_EXTRAS' } - if (collection && (kind.endsWith('only in generated mode') || kind.endsWith('only in binder mode') || kind == 'primary key columns') && - d.table.endsWith('_followers') && d.group == 'GenMmSelf') { - return 'CIRCULAR_MANY_TO_MANY' - } if (collection && kind == 'column only in binder mode') { return 'MAP_UNUSED_COLUMN' } diff --git a/grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/domainbinding/jpa/GrailsDomainGeneratorDifferentialSpec.groovy b/grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/domainbinding/jpa/GrailsDomainGeneratorDifferentialSpec.groovy index cd39cafc11..620e26ab98 100644 --- a/grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/domainbinding/jpa/GrailsDomainGeneratorDifferentialSpec.groovy +++ b/grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/domainbinding/jpa/GrailsDomainGeneratorDifferentialSpec.groovy @@ -76,9 +76,9 @@ import org.grails.orm.hibernate.cfg.domainbinding.hibernate.GrailsHibernatePersi import org.grails.orm.hibernate.cfg.domainbinding.hibernate.HibernateBasicProperty import org.grails.orm.hibernate.cfg.domainbinding.hibernate.HibernateEmbeddedProperty import org.grails.orm.hibernate.cfg.domainbinding.hibernate.HibernateEnumProperty +import org.grails.orm.hibernate.cfg.domainbinding.hibernate.HibernateManyToManyProperty import org.grails.orm.hibernate.cfg.domainbinding.hibernate.HibernatePersistentProperty import org.grails.orm.hibernate.cfg.domainbinding.hibernate.HibernateSimpleIdentityProperty -import org.grails.orm.hibernate.cfg.domainbinding.hibernate.HibernateManyToManyProperty import org.grails.orm.hibernate.cfg.domainbinding.hibernate.HibernateManyToOneProperty import org.grails.orm.hibernate.cfg.domainbinding.hibernate.HibernateOneToManyProperty import org.grails.orm.hibernate.cfg.domainbinding.hibernate.HibernateToManyEntityProperty @@ -1588,14 +1588,16 @@ class GrailsDomainGeneratorDifferentialSpec extends HibernateGormDatastoreSpec { } /** - * The key and element column names of a circular many-to-many depend on the order the binder's second passes run: - * {@code ManyToOneBinder.prepareCircularManyToMany} renames the join key of the other side while it binds one side, so the - * side that runs first keeps the default key name. The generator states the names the binder would give once both sides - * are prepared, which is consistent on both sides; the difference is listed, not reported. + * This comparison reads the mapping after the binder has bound it, and {@code ManyToOneBinder.prepareCircularManyToMany} + * writes the renamed join key into the mapping of a circular many-to-many while it binds, so the generator, which sees that + * written key as a mapped one, states the renamed name for both sides, where the binder bound the side bound first before + * the rename. The generator flow itself never sees the written key (it runs on the unbound mapping): the key names are + * compared against the binder's own in {@code GeneratedDomainClassesDdlDifferentialSpec} and + * {@code GeneratedDomainClassesCircularManyToManySpec}, which boot both modes. The element column is compared here. */ - private static List<String> circularOrFound(HibernateToManyEntityProperty property, List<String> found, Map<String, Integer> known) { + private static List<String> circularKeyOrFound(HibernateToManyEntityProperty property, List<String> found, Map<String, Integer> known) { if (!found.isEmpty() && property instanceof HibernateManyToManyProperty && property.isCircular()) { - known['a circular many-to-many names the key of its first-bound side by default, because the binder renames the join keys of a circular many-to-many while it binds, so the two sides name different columns of one join table']++ + known['the binder writes the renamed join key of a circular many-to-many into the mapping while it binds, so a generator that reads the bound mapping states the renamed key for the side the binder bound first (the generator flow reads the unbound mapping; the DDL differential compares the key names)']++ return [] } return found @@ -1653,10 +1655,10 @@ class GrailsDomainGeneratorDifferentialSpec extends HibernateGormDatastoreSpec { "${where} ${facet}: generator=${values[0]} binder=${values[1]}".toString() }) // Hibernate copies the size of the referenced identifier onto the element column after binding - found.addAll(circularOrFound(property, compareValueColumn("${where} element".toString(), facets.element(), collection.element, collection.collectionTable, true), known)) + found.addAll(compareValueColumn("${where} element".toString(), facets.element(), collection.element, collection.collectionTable, true)) found.addAll(compareCollectionTableIndexes(where, collection)) } - found.addAll(circularOrFound(property, compareValueColumns("${where} key".toString(), facets.keys(), collection.key, collection.collectionTable, true), known)) + found.addAll(circularKeyOrFound(property, compareValueColumns("${where} key".toString(), facets.keys(), collection.key, collection.collectionTable, true), known)) if (!((DependantValue) collection.key).updateable) { known['the binder makes the key of an entity collection not updatable when its owner has several unidirectional to-many properties; Hibernate then writes no join table rows, and annotations cannot state it']++ } @@ -1745,8 +1747,8 @@ class GrailsDomainGeneratorDifferentialSpec extends HibernateGormDatastoreSpec { Property a = new Property() a.value = (org.hibernate.mapping.Value) triple[1] List<String> leaf = compareAnnotatedLeaf("${where} ${part}".toString(), b, a, ((ColumnFacets) triple[2]).sqlType(), part != 'index', known) - if (!leaf.isEmpty() && part != 'index' && facets.manyToMany() && circularSelf) { - known['a circular many-to-many names the key of its first-bound side by default, because the binder renames the join keys of a circular many-to-many while it binds, so the two sides name different columns of one join table']++ + if (!leaf.isEmpty() && part == 'key' && facets.manyToMany() && circularSelf) { + known['the binder writes the renamed join key of a circular many-to-many into the mapping while it binds, so a generator that reads the bound mapping states the renamed key for the side the binder bound first (the generator flow reads the unbound mapping; the DDL differential compares the key names)']++ } else if (inverseManyToMany && !leaf.isEmpty() && part != 'index') { known['the binder names the key and element columns of the inverse side of a many-to-many from its own mapping, so they differ from the owning side\'s when only the owner names them; Hibernate uses the owning side\'s']++ } else {
