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 8c4b99c39dbfe4784ba3dcba365c9c36720f5ba2
Author: Walter Duque de Estrada <[email protected]>
AuthorDate: Tue Oct 6 14:28:56 2026 -0500

    fix: audit the optimistic locking version in generated mode as the domain 
binder does
    
    Envers skips the property it recognises as the @Version of an annotated 
entity by default (do_not_audit_optimistic_locking_field=true). The domain 
binder gives Envers no @Version, so existing audit tables have the version 
column; the generated carriers carry @Version, so the column was missing from 
the audit table and inserts into an existing one would not write it. Generated 
mode now defaults the setting to false unless the user configured it.
    
    Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
---
 .../HibernateMappingContextConfiguration.groovy    | 11 +++
 .../generated/GeneratedModeEnversSpec.groovy       | 99 +++++++++++++++++++++-
 2 files changed, 106 insertions(+), 4 deletions(-)

diff --git 
a/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/HibernateMappingContextConfiguration.groovy
 
b/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/HibernateMappingContextConfiguration.groovy
index f3c1eee3e0..63c4be38e5 100644
--- 
a/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/HibernateMappingContextConfiguration.groovy
+++ 
b/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/HibernateMappingContextConfiguration.groovy
@@ -95,6 +95,10 @@ class HibernateMappingContextConfiguration extends 
Configuration
         new AnnotationTypeFilter(MappedSuperclass, false),
     ] as TypeFilter[]
     private static final String FALSE_LITERAL = 'false'
+
+    // Literal copy of 
org.hibernate.envers.configuration.EnversSettings.DO_NOT_AUDIT_OPTIMISTIC_LOCKING_FIELD:
 Envers is not a
+    // dependency of this module
+    private static final String ENVERS_DO_NOT_AUDIT_OPTIMISTIC_LOCKING_FIELD = 
'org.hibernate.envers.do_not_audit_optimistic_locking_field'
     private final Class<? extends CurrentSessionContext> currentSessionContext 
= GrailsSessionContext
     private final Set<Class> additionalClasses = new HashSet<>()
     protected String sessionFactoryBeanName = 'sessionFactory'
@@ -366,6 +370,13 @@ class HibernateMappingContextConfiguration extends 
Configuration
         StandardServiceRegistryBuilder standardServiceRegistryBuilder =
                 
createStandardServiceRegistryBuilder(bootstrapServiceRegistry).applySettings((Map)
 properties)
 
+        if (generatedBinder != null && 
!properties.containsKey(ENVERS_DO_NOT_AUDIT_OPTIMISTIC_LOCKING_FIELD)) {
+            // Binder mode never marks the version as one for Envers, which 
therefore audits it as a plain property and the
+            // audit tables of an existing application have the column. A 
generated entity carries a JPA @Version, which
+            // Envers skips by default. A value the user sets always wins.
+            
standardServiceRegistryBuilder.applySetting(ENVERS_DO_NOT_AUDIT_OPTIMISTIC_LOCKING_FIELD,
 FALSE_LITERAL)
+        }
+
         Object dataSource = 
properties.get(JdbcSettings.JAKARTA_NON_JTA_DATASOURCE)
         if (dataSource instanceof DataSource) {
             
standardServiceRegistryBuilder.applySetting(JdbcSettings.JAKARTA_NON_JTA_DATASOURCE,
 dataSource)
diff --git 
a/grails-data-hibernate7/dbmigration/src/test/groovy/org/grails/plugins/databasemigration/generated/GeneratedModeEnversSpec.groovy
 
b/grails-data-hibernate7/dbmigration/src/test/groovy/org/grails/plugins/databasemigration/generated/GeneratedModeEnversSpec.groovy
index 855a350c05..d7810c12af 100644
--- 
a/grails-data-hibernate7/dbmigration/src/test/groovy/org/grails/plugins/databasemigration/generated/GeneratedModeEnversSpec.groovy
+++ 
b/grails-data-hibernate7/dbmigration/src/test/groovy/org/grails/plugins/databasemigration/generated/GeneratedModeEnversSpec.groovy
@@ -18,6 +18,7 @@
  */
 package org.grails.plugins.databasemigration.generated
 
+import groovy.sql.Sql
 import grails.gorm.annotation.Entity
 import org.hibernate.Session
 import org.hibernate.boot.spi.MetadataImplementor
@@ -141,7 +142,7 @@ class GeneratedModeEnversSpec extends Specification {
                 generatedTables.findAll { String name, List<String> columns -> 
!name.endsWith('_aud') }
 
         and: 'the audit table of the entity differs only in the columns named 
in the next feature'
-        binderTables['envers_book_aud'] - generatedTables['envers_book_aud'] 
== ['secret', 'version']
+        binderTables['envers_book_aud'] - generatedTables['envers_book_aud'] 
== ['secret']
         generatedTables['envers_book_aud'] - binderTables['envers_book_aud'] 
== []
 
         and: 'the revisions and the audit queries return the same'
@@ -158,15 +159,81 @@ class GeneratedModeEnversSpec extends Specification {
         then: 'binder mode audits both, because Envers reads the getter of a 
property accessed property and the Groovy field is the one annotated, and the 
version has no @Version annotation to recognise'
         binder['envers_book_aud'].containsAll(['secret', 'version'])
 
-        and: 'generated mode puts the annotation on the field Envers reads and 
the version carries @Version'
+        and: 'generated mode puts the annotation on the field Envers reads, 
and audits the version as binder mode does'
         !generated['envers_book_aud'].contains('secret')
-        !generated['envers_book_aud'].contains('version')
+        generated['envers_book_aud'].contains('version')
 
-        and: 'Envers\' own setting audits the version in generated mode too'
+        and: 'Envers\' own setting, which a user can still set, gives the same'
         generatedWithVersion['envers_book_aud'].contains('version')
         !generatedWithVersion['envers_book_aud'].contains('secret')
     }
 
+    def "a user value of the Envers optimistic locking setting wins over the 
generated mode default"() {
+        when:
+        Map generated = columnsByTable(boot(true, [EnversVersioned],
+                ['hibernate.additionalProperties': 
['org.hibernate.envers.do_not_audit_optimistic_locking_field': 'true']]))
+
+        then:
+        !generated['envers_versioned_aud'].contains('version')
+        generated['envers_versioned_aud'].contains('name')
+    }
+
+    private static Map versionAudit(HibernateDatastore datastore, String 
table, String versionColumn) {
+        Map result = [:]
+        Sql sql = new Sql((javax.sql.DataSource) 
datastore.connectionSources.defaultConnectionSource.dataSource)
+        try {
+            result.rows = versionColumn == null ? null :
+                    sql.rows("select revtype, $versionColumn as v from $table 
order by rev".toString())
+                            .collect { [it.revtype, it.v] }
+            result.columns = sql.rows("select column_name, data_type, 
is_nullable from information_schema.columns where lower(table_name) = ${table} 
order by column_name")
+                    .collect { [it.column_name.toLowerCase(), it.data_type, 
it.is_nullable] }
+        } finally {
+            sql.close()
+        }
+        return result
+    }
+
+    private static void changeTwice(Class type, String field) {
+        Long id
+        type.withTransaction {
+            id = type.newInstance(name: 'a').save(flush: true, failOnError: 
true).id
+        }
+        2.times { int i ->
+            type.withTransaction {
+                def found = type.get(id)
+                found.name = "b${i}".toString()
+                found.save(flush: true, failOnError: true)
+            }
+        }
+        type.withTransaction {
+            type.get(id).delete(flush: true)
+        }
+    }
+
+    def "the audit table and its rows carry the optimistic locking version as 
in binder mode for #type.simpleName"() {
+        when:
+        HibernateDatastore binderDatastore = boot(false, [type])
+        changeTwice(type, 'name')
+        Map binder = versionAudit(binderDatastore, table, versionColumn)
+        HibernateDatastore generatedDatastore = boot(true, [type])
+        changeTwice(type, 'name')
+        Map generated = versionAudit(generatedDatastore, table, versionColumn)
+
+        then: 'the audit table has the same columns, types and nullability'
+        binder.columns == generated.columns
+        binder.columns*.getAt(0).contains(versionColumn) == hasVersion
+
+        and: 'the version written at each revision is the same'
+        binder.rows == generated.rows
+        !hasVersion || binder.rows*.getAt(1).any { it != null }
+
+        where:
+        type                | table                    | versionColumn | 
hasVersion
+        EnversVersioned     | 'envers_versioned_aud'   | 'version'     | true
+        EnversUnversioned   | 'envers_unversioned_aud' | null          | false
+        EnversCustomVersion | 'envers_custom_version_aud' | 'lock_no'  | true
+    }
+
     private static Map shelfHistory() {
         Long shelfId
         EnversShelf.withTransaction {
@@ -246,3 +313,27 @@ class EnversItem {
     String label
     static belongsTo = [shelf: EnversShelf]
 }
+
+@Audited
+@Entity
+class EnversVersioned {
+    String name
+}
+
+@Audited
+@Entity
+class EnversUnversioned {
+    String name
+    static mapping = {
+        version false
+    }
+}
+
+@Audited
+@Entity
+class EnversCustomVersion {
+    String name
+    static mapping = {
+        version 'lock_no'
+    }
+}

Reply via email to