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 91e3390360b1250b43ea8f7b31b70e5fccf4665a
Author: Walter Duque de Estrada <[email protected]>
AuthorDate: Thu Oct 8 14:39:30 2026 -0500

    feat: accept a precision or a scale on the discriminator column in native 
domain binding
    
    The generated mode refused a discriminator column that sets a precision or 
a scale because @DiscriminatorColumn cannot state them. The domain binder boots 
such a mapping and the DDL is the same, since a string, integer or character 
column ignores both. The generator now accepts it and the aligner puts the 
values on the discriminator column of the model, as the binder does, so the 
model and the schema stay equal; the generator differential compares them too.
    
    Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
---
 .../domainbinding/jpa/DiscriminatorFacets.groovy   |   8 +-
 .../jpa/GeneratedDomainClassBinder.groovy          |  23 ++++
 .../domainbinding/jpa/GrailsDomainGenerator.groovy |  12 +-
 .../GeneratedDomainClassesDiscriminatorSpec.groovy | 146 +++++++++++++++++++++
 .../GrailsDomainGeneratorDifferentialSpec.groovy   |   4 +-
 .../advancedGORMFeatures/nativeDomainBinding.adoc  |   5 +-
 6 files changed, 183 insertions(+), 15 deletions(-)

diff --git 
a/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/jpa/DiscriminatorFacets.groovy
 
b/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/jpa/DiscriminatorFacets.groovy
index 5ef69a3064..978da91068 100644
--- 
a/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/jpa/DiscriminatorFacets.groovy
+++ 
b/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/jpa/DiscriminatorFacets.groovy
@@ -28,7 +28,9 @@ import jakarta.persistence.DiscriminatorType
  * <p>Exactly one of {@code column} and {@code formula} is set. {@code length} 
and {@code sqlType} are {@code null}
  * when the mapping does not state them. {@code typeName} is the Hibernate 
type name the binder puts on the
  * discriminator value ({@code string} unless the mapping says otherwise) and 
{@code type} is the JPA discriminator
- * type that stands for it.</p>
+ * type that stands for it. {@code precision} and {@code scale} are the ones 
the mapping gives the column: no annotation states
+ * them on a discriminator, and they change nothing in the DDL of a string, 
integer or character column, but the binder puts them
+ * on the column of the model, so the aligner does the same.</p>
  *
  * @since 9.0
  */
@@ -40,5 +42,7 @@ record DiscriminatorFacets(
     DiscriminatorType type,
     Integer length,
     String sqlType,
-    boolean insertable) {
+    boolean insertable,
+    Integer precision,
+    Integer scale) {
 }
diff --git 
a/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/jpa/GeneratedDomainClassBinder.groovy
 
b/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/jpa/GeneratedDomainClassBinder.groovy
index 50b8ba38d4..70586b01ef 100644
--- 
a/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/jpa/GeneratedDomainClassBinder.groovy
+++ 
b/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/jpa/GeneratedDomainClassBinder.groovy
@@ -348,6 +348,7 @@ class GeneratedDomainClassBinder implements 
SessionFactoryBuilderFactory {
         if (persistentClass instanceof RootClass) {
             // the generated root forces its discriminator so that Hibernate 
adds no check constraint; the binder never forces it
             ((RootClass) persistentClass).forceDiscriminator = false
+            alignDiscriminator((RootClass) persistentClass, entity)
             alignIdentifier((RootClass) persistentClass, generated, metadata)
         }
         for (Property property : persistentClass.declaredProperties) {
@@ -356,6 +357,28 @@ class GeneratedDomainClassBinder implements 
SessionFactoryBuilderFactory {
         alignUniqueKeys(persistentClass, entity)
     }
 
+    /**
+     * The mapping can give the discriminator column a precision and a scale, 
which {@code @DiscriminatorColumn} cannot state. They change
+     * nothing in the DDL of the string, integer or character column, but the 
domain binder puts them on the column of the model, so the
+     * same is done here and a schema comparison finds the same column.
+     */
+    private void alignDiscriminator(RootClass root, 
GrailsHibernatePersistentEntity entity) {
+        DiscriminatorFacets discriminator = 
generator.hierarchyFacets(entity).discriminator()
+        if (discriminator == null || root.discriminator == null) {
+            return
+        }
+        for (Selectable selectable : root.discriminator.selectables) {
+            if (selectable instanceof Column) {
+                if (discriminator.precision() != null) {
+                    ((Column) selectable).precision = discriminator.precision()
+                }
+                if (discriminator.scale() != null) {
+                    ((Column) selectable).scale = discriminator.scale()
+                }
+            }
+        }
+    }
+
     /**
      * Hibernate's annotation binder names the unique keys of a table and 
marks them as stated by the user: the schema then has
      * them as named constraints, and the key an {@code orderingUniqueKey} 
gives the primary key is named too. The domain binder's keys
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 3a5fda574d..f3a8dc321f 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
@@ -921,7 +921,7 @@ class GrailsDomainGenerator {
      * {@code getDiscriminatorValue}, and a joined subclass's key column is 
named like its identifier column.
      *
      * @throws UnsupportedOperationException for a hierarchy that mixes 
strategies (annotations state the strategy
-     *     once, on the root) or whose discriminator has no annotation 
equivalent
+     *     once, on the root) or whose discriminator has a type other than 
string, integer or character
      */
     HierarchyFacets hierarchyFacets(GrailsHibernatePersistentEntity entity) {
         boolean root = entity.isRoot()
@@ -971,19 +971,15 @@ class GrailsDomainGenerator {
         DiscriminatorType type = discriminatorType(entity, typeName)
         boolean insertable = config?.insertable == null || config.insertable
         if (config?.formula != null) {
-            return new DiscriminatorFacets(null, config.formula, typeName, 
type, null, null, insertable)
+            return new DiscriminatorFacets(null, config.formula, typeName, 
type, null, null, insertable, null, null)
         }
         ColumnConfig columnConfig = config?.column
         Column column = new Column()
         columnConfigBinder.bindColumnConfigToColumn(column, columnConfig, null)
-        if (column.precision != null || column.scale != null) {
-            throw new UnsupportedOperationException(
-                    "The discriminator column of [${entity.name}] sets a 
precision or a scale, " +
-                            'which @DiscriminatorColumn cannot state')
-        }
         return new DiscriminatorFacets(
                 columnConfig?.name != null ? columnConfig.name : 
GrailsDomainBinder.DEFAULT_DISCRIMINATOR_COLUMN_NAME,
-                null, typeName, type, column.length?.intValue(), 
column.sqlType, insertable)
+                null, typeName, type, column.length?.intValue(), 
column.sqlType, insertable,
+                column.precision?.intValue(), column.scale?.intValue())
     }
 
     private static DiscriminatorType 
discriminatorType(GrailsHibernatePersistentEntity entity, String typeName) {
diff --git 
a/grails-data-hibernate7/core/src/test/groovy/grails/gorm/tests/generated/GeneratedDomainClassesDiscriminatorSpec.groovy
 
b/grails-data-hibernate7/core/src/test/groovy/grails/gorm/tests/generated/GeneratedDomainClassesDiscriminatorSpec.groovy
new file mode 100644
index 0000000000..30a1023ea7
--- /dev/null
+++ 
b/grails-data-hibernate7/core/src/test/groovy/grails/gorm/tests/generated/GeneratedDomainClassesDiscriminatorSpec.groovy
@@ -0,0 +1,146 @@
+/*
+ * 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
+ *
+ *   http://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.util.concurrent.atomic.AtomicInteger
+
+import grails.gorm.annotation.Entity
+import org.hibernate.mapping.Table
+import spock.lang.AutoCleanup
+import spock.lang.Specification
+import spock.lang.Unroll
+
+import org.grails.orm.hibernate.HibernateDatastore
+
+/**
+ * A discriminator column with a precision or a scale. {@code 
@DiscriminatorColumn} cannot state them and they change nothing in the
+ * DDL of a string or an integer column, but the domain binder puts them on 
the column, and a mapping that sets them must boot in the
+ * generated mode as it does in the domain binder, with the same column.
+ */
+class GeneratedDomainClassesDiscriminatorSpec 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:gdd${BOOTS.incrementAndGet()};LOCK_TIMEOUT=10000".toString(),
+                'dataSource.dbCreate'             : 'create-drop',
+                'hibernate.generatedDomainClasses': generated,
+        ], group as Class[])
+        return datastore
+    }
+
+    /** The columns of the boot model with their SQL type and nullability, and 
the precision and scale the model holds for the discriminator. */
+    private Map<String, Map> schema(List<Class> group, boolean generated) {
+        HibernateDatastore booted = boot(group, generated)
+        Map<String, Map> result = new TreeMap<String, Map>()
+        for (Table table : booted.metadata.collectTableMappings()) {
+            if (table.physicalTable) {
+                result[table.name] = table.columns.collectEntries { 
org.hibernate.mapping.Column column ->
+                    String discriminator = column.name == 'kind' ? " 
precision=${column.precision} scale=${column.scale}" : ''
+                    [(column.name): 
"${column.getSqlType(booted.metadata)}${column.nullable ? '' : ' not 
null'}${discriminator}".toString()]
+                }
+            }
+        }
+        return result
+    }
+
+    @Unroll
+    void "#label: the generated mode creates the discriminator column of the 
domain binder, with its precision and scale"() {
+        when:
+        Map<String, Map> binder = schema(group, false)
+        Map<String, Map> generated = schema(group, true)
+
+        then:
+        generated == binder
+        generated[table]['kind'] == column
+
+        where:
+        label                                   | group                        
    | table          | column
+        'a string discriminator with both'      | [GddStringBase, 
GddStringSub]    | 'gdd_string_base' | 'varchar(255) not null precision=5 
scale=2'
+        'an integer discriminator with a precision' | [GddIntBase, GddIntSub]  
    | 'gdd_int_base'    | 'integer not null precision=5 scale=null'
+    }
+
+    @Unroll
+    void "#label: the rows of the hierarchy are stored and found by the 
discriminator in both modes"() {
+        when:
+        Map<Boolean, List> results = [false, true].collectEntries { boolean 
generated ->
+            boot(group, generated)
+            [(generated): this."${cycle}"()]
+        }
+
+        then:
+        results[true] == results[false]
+        results[true] == [2, 1, ['sub']]
+
+        where:
+        label                | group                         | cycle
+        'a string discriminator' | [GddStringBase, GddStringSub] | 
'stringCycle'
+        'an integer discriminator' | [GddIntBase, GddIntSub]     | 'intCycle'
+    }
+
+    private List stringCycle() {
+        GddStringBase.withTransaction {
+            new GddStringBase(name: 'base').save(failOnError: true)
+            new GddStringSub(name: 'sub', more: 'x').save(failOnError: true, 
flush: true)
+        }
+        return GddStringBase.withNewSession { [GddStringBase.count(), 
GddStringSub.count(), GddStringSub.list()*.name] }
+    }
+
+    private List intCycle() {
+        GddIntBase.withTransaction {
+            new GddIntBase(name: 'base').save(failOnError: true)
+            new GddIntSub(name: 'sub', more: 'x').save(failOnError: true, 
flush: true)
+        }
+        return GddIntBase.withNewSession { [GddIntBase.count(), 
GddIntSub.count(), GddIntSub.list()*.name] }
+    }
+}
+
+@Entity
+class GddStringBase {
+    String name
+    static mapping = {
+        discriminator column: [name: 'kind', precision: 5, scale: 2]
+    }
+}
+
+@Entity
+class GddStringSub extends GddStringBase {
+    String more
+}
+
+@Entity
+class GddIntBase {
+    String name
+    static mapping = {
+        discriminator value: '1', type: 'integer', column: [name: 'kind', 
precision: 5]
+    }
+}
+
+@Entity
+class GddIntSub extends GddIntBase {
+    String more
+    static mapping = {
+        discriminator value: '2'
+    }
+}
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 5229b4c7bf..dc4e81e26d 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
@@ -1286,7 +1286,7 @@ class GrailsDomainGeneratorDifferentialSpec extends 
HibernateGormDatastoreSpec {
         }
     }
 
-    /** The discriminator the binder put on the root: a column or a formula, 
its type, length and whether it is inserted. */
+    /** The discriminator the binder put on the root: a column or a formula, 
its type, length, precision, scale and whether it is inserted. */
     private List<String> compareDiscriminator(GrailsHibernatePersistentEntity 
entity, DiscriminatorFacets facets, RootClass root) {
         String where = "${entity.name} discriminator"
         if ((facets != null) != (root.discriminator != null)) {
@@ -1306,6 +1306,8 @@ class GrailsDomainGeneratorDifferentialSpec extends 
HibernateGormDatastoreSpec {
         ]
         if (!columns.isEmpty()) {
             pairs.length = [facets.length(), columns[0].length?.intValue()]
+            pairs.precision = [facets.precision(), 
columns[0].precision?.intValue()]
+            pairs.scale = [facets.scale(), columns[0].scale?.intValue()]
             if (facets.sqlType() != null) {
                 pairs.sqlType = [facets.sqlType(), columns[0].sqlType]
             }
diff --git 
a/grails-data-hibernate7/docs/src/docs/asciidoc/advancedGORMFeatures/nativeDomainBinding.adoc
 
b/grails-data-hibernate7/docs/src/docs/asciidoc/advancedGORMFeatures/nativeDomainBinding.adoc
index d638353a6b..3f127e08bd 100644
--- 
a/grails-data-hibernate7/docs/src/docs/asciidoc/advancedGORMFeatures/nativeDomainBinding.adoc
+++ 
b/grails-data-hibernate7/docs/src/docs/asciidoc/advancedGORMFeatures/nativeDomainBinding.adoc
@@ -69,6 +69,7 @@ For the domain classes in GORM's own test suites, both 
bindings produce the same
 * A natural id (`id natural: [...]`) may name an embedded object (the unique 
key spans its columns, in the order of the embedded class), and a name that is 
no property of the class is skipped without a message, as with classic binding.
 * A natural id declared on a subclass adds a unique key to the table of the 
hierarchy (the table of the subclass in a joined hierarchy), over the columns 
of the named properties in the order the mapping names them, and makes those 
properties updatable only when the natural id is `mutable`. Classic binding 
also marks the properties as natural identifiers, and with Hibernate 7 that 
makes every load of the subclass entity fail with a `NullPointerException`; 
native binding does not mark them [...]
 * `insertable: false` and `updatable: false` are honored on a property with a 
column. On an embedded object they apply to every column of the object. On a 
`hasMany` and on the inverse side of a one-to-one (the side with no column) 
both bindings ignore them: the collection is written through its own table, and 
the foreign key lives on the other side.
+* A `discriminator` column may set `precision` and `scale`. They change 
nothing in the DDL of a string, integer or character column, in both bindings.
 * Identifier generators, inheritance strategies (single table, joined and 
table-per-concrete-class), discriminators, natural ids, optimistic locking, 
lazy and eager fetching, cascades, sorting, batch size and `cache` usage are 
mapped as with classic binding.
 
 [[nativeDomainBinding-refused]]
@@ -96,10 +97,6 @@ Nothing is ignored silently. A mapping that boots is bound 
the way it is written
 | `Collection property [...]: the type [...] mapped on the collection property 
names neither a class nor serializable ...` or `... a custom collection type (a 
UserCollectionType) is mapped on a collection of basic values ...`
 | Remove the `type`, or use `'serializable'` or a `UserType` class to store 
the collection in one column. Classic binding does not boot with a registered 
type name (it fails with `Could not load requested class`), and neither with a 
custom collection type on a collection of basic values.
 
-| A `discriminator` column with `precision` or `scale`.
-| `The discriminator column of [...] sets a precision or a scale, which 
@DiscriminatorColumn cannot state`
-| Remove them. Use `length` to size the column.
-
 | A composite identifier that is combined with something the mapping does not 
state faithfully: a many-to-many, a map or a join table that involves an entity 
with a composite identifier, a composite identifier part that is the inverse 
side of a one-to-one, a foreign key mapped with a different number of columns 
than the identifier has properties, or a composite identifier referring to a 
deeply nested composite identifier.
 | `... composite identifier ...`, naming the entity and the part.
 | Give the entity a single-column identifier, or map the relationship with a 
domain class of its own.

Reply via email to