borinquenkid commented on code in PR #16539:
URL: https://github.com/apache/grails-core/pull/16539#discussion_r4231949089


##########
grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/hibernate/GrailsHibernatePersistentEntity.java:
##########
@@ -384,9 +385,10 @@ default boolean isLazy(HibernatePersistentProperty 
property) {
     default void sortOrIndexForeignKeyColumns(SimpleValue value) {
         PersistentClass pc = getPersistentClass();
         KeyValue identifier = pc != null ? pc.getIdentifier() : null;
-        int[] originalOrder = identifier instanceof Component c ? 
c.sortProperties() : null;
+        Component component = identifier instanceof Component c ? c : null;
+        int[] originalOrder = component != null ? component.sortProperties() : 
null;
         if (originalOrder != null) {
-            value.sortColumns(originalOrder);
+            value.sortColumns(toColumnPermutation(originalOrder, 
partColumnSpans(component, originalOrder)));
         } else {

Review Comment:
   Done in 8f46242382: `BidirectionalOneToManyLinker.link` disables the 
collection key's own foreign key, so the to-one side's key is the only one. For 
a simple identifier the two were already the same `ForeignKey`, so that DDL is 
unchanged, and a feature pins it. `CompositeForeignKeyRegistrationOrderSpec` 
now runs all 6 chain orders, all 24 hub orders and 6 orders of a bidirectional 
`PrbHubChild`, and asserts no duplicate foreign key name in the metadata. The 
full suite is green.
   



##########
grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/domainbinding/binder/CompositeForeignKeyRegistrationOrderSpec.groovy:
##########
@@ -0,0 +1,128 @@
+/*
+ *  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.binder
+
+import org.grails.orm.hibernate.HibernateDatastore
+import org.hibernate.dialect.H2Dialect
+import spock.lang.Specification
+import spock.lang.Unroll
+
+/**
+ * An application registers its entities in class-path scan order, so an 
entity is often bound before
+ * the entity its composite foreign key references. The key must still be 
aligned with the referenced
+ * identifier once that identifier is bound, exactly as when the referenced 
entity is registered first.
+ * The entities are the ones of {@link CompositeForeignKeyColumnTypesSpec}, 
which registers every
+ * referenced entity first.
+ */
+class CompositeForeignKeyRegistrationOrderSpec extends Specification {
+
+    private static final List<List<String>> LEAF_KEY = [
+            ['prb_middle_grand_parent_alpha', 'prb_grand_alpha'],
+            ['prb_middle_grand_parent_zeta', 'prb_grand_zeta'],
+            ['prb_middle_name', 'name']]
+
+    private static final List<List<String>> HUB_KEY = [
+            ['prb_hub_ace', 'ace'],
+            ['prb_hub_grand_alpha', 'prb_grand_alpha'],
+            ['prb_hub_grand_zeta', 'prb_grand_zeta'],
+            ['prb_hub_zed', 'zed']]
+
+    private static Map<String, Object> config(List<Class> classes) {
+        [
+                'dataSource.url'        : 
"jdbc:h2:mem:compositeFkOrder${classes*.simpleName.join('')};LOCK_TIMEOUT=10000".toString(),
+                'dataSource.dbCreate'   : 'create-drop',
+                'dataSource.dialect'    : H2Dialect.name,
+                'hibernate.hbm2ddl.auto': 'create',
+        ]
+    }
+
+    @Unroll
+    void "the keys of a three level composite chain registered as #order are 
aligned with the keys they reference"() {
+        given:
+        HibernateDatastore datastore = new HibernateDatastore(config(classes), 
classes as Class[])
+
+        when:
+        Map<String, List<List<String>>> middleKeys = 
ForeignKeyPairs.of(datastore, 'PRB_MIDDLE')
+        Map<String, List<List<String>>> leafKeys = 
ForeignKeyPairs.of(datastore, 'PRB_LEAF')
+
+        then:
+        middleKeys == [prb_grand: [['prb_grand_alpha', 'alpha'], 
['prb_grand_zeta', 'zeta']]]
+        leafKeys == [prb_middle: LEAF_KEY]
+
+        when:
+        PrbGrand.withNewTransaction {
+            PrbGrand grand = new PrbGrand(zeta: 'z', alpha: 
'a').save(failOnError: true)
+            PrbMiddle middle = new PrbMiddle(name: 'm', grandParent: 
grand).save(failOnError: true)
+            new PrbLeaf(name: 'l', middle: middle).save(failOnError: true, 
flush: true)
+        }
+
+        then:
+        PrbLeaf.withNewSession {
+            PrbLeaf leaf = PrbLeaf.findByName('l')
+            leaf.middle.name == 'm' && leaf.middle.grandParent.alpha == 'a' && 
leaf.middle.grandParent.zeta == 'z'

Review Comment:
   Agreed, that one is separate. It is pinned as a `@PendingFeature` in 
`InverseHasManyCompositeIdentifierOrderSpec` with your `composite('zeta', 
'alpha')` repro (the name-order variant passes), and I'm opening a follow-up 
issue with your cause and what you tried.
   



-- 
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: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]

Reply via email to