You are viewing a plain text version of this content. The canonical link for it is here.
Posted to notifications@grails.apache.org by "jamesfredley (via GitHub)" <gi...@apache.org> on 2026/02/19 22:54:47 UTC

[PR] Fix @Where and DetachedCriteria query methods ignoring @Transactional(connection) [grails-core]

jamesfredley opened a new pull request, #15418:
URL: https://github.com/apache/grails-core/pull/15418

   ## Summary
   
   Fixes #15416
   
   Data Service methods using `@Where` annotations or `DetachedCriteria`-based queries (`count()`, `list()`, `findBy*()`) were ignoring the class-level `@Transactional(connection)` annotation, causing queries to execute against the default datasource instead of the specified connection.
   
   Reproducer: https://github.com/jamesfredley/grails-15416-where-connection-routing
   
   ## Root Cause
   
   Two issues were found:
   
   ### 1. Wrong method node passed to `findConnectionId()`
   
   Both `AbstractWhereImplementer` and `AbstractDetachedCriteriaServiceImplementor` called `findConnectionId(newMethodNode)` instead of `findConnectionId(abstractMethodNode)`.
   
   - `newMethodNode` belongs to the generated `$ServiceImplementation` class, which does not carry the `@Transactional` annotation
   - `abstractMethodNode` belongs to the original interface/abstract class where `@Transactional(connection)` is declared
   - `findConnectionId()` resolves the connection by walking up to `methodNode.getDeclaringClass()` to find `@Transactional` - so passing the wrong node meant it could never find the annotation
   
   This is the same class of bug fixed in #15395 for `SaveImplementer`, `DeleteImplementer`, and `FindAndDeleteImplementer`.
   
   ### 2. `build()` after `withConnection()` in `AbstractWhereImplementer`
   
   In the `@Where` code path, the original order was:
   1. `query = new DetachedCriteria(Foo)`
   2. `query = query.withConnection('secondary')` - sets `connectionName`
   3. `query = query.build(closure)` - internally calls `clone()`, which does **not** copy `connectionName`
   
   The `clone()` call inside `build()` creates a new `DetachedCriteria` instance without the connection setting, so the connection was silently lost.
   
   Fixed by reordering to: `new DetachedCriteria` -> `build(closure)` -> `withConnection(name)`.
   
   > **Note**: `AbstractDetachedCriteria.clone()` not copying `connectionName` is arguably a separate bug. The non-`@Where` path in `AbstractDetachedCriteriaServiceImplementor` is not affected because it does not call `build()` after `withConnection()`.
   
   ## Changes
   
   | File | Change |
   |------|--------|
   | `AbstractWhereImplementer.groovy` | `findConnectionId(newMethodNode)` -> `findConnectionId(abstractMethodNode)` + reorder `build()`/`withConnection()` |
   | `AbstractDetachedCriteriaServiceImplementor.groovy` | `findConnectionId(newMethodNode)` -> `findConnectionId(abstractMethodNode)` |
   
   ## Tests
   
   ### Unit Tests (`WhereConnectionRoutingSpec`) - 5 tests
   - Verifies `@Where` method generates `withConnection()` call when `@Transactional(connection)` is present
   - Verifies `@Where` method does NOT generate `withConnection()` when no connection specified
   - Verifies `DetachedCriteria` `count()` generates `withConnection()` call
   - Verifies `DetachedCriteria` `list()` generates `withConnection()` call
   - Verifies `DetachedCriteria` `findByName()` generates `withConnection()` call
   
   ### Integration Tests (`WhereQueryMultiDataSourceSpec`) - 5 tests
   - Uses two real H2 in-memory databases (default + secondary)
   - Domain class mapped with `datasource 'ALL'`
   - Inserts data only into secondary, verifies queries route correctly:
     - `@Where`-annotated method returns data from secondary
     - `@Where`-annotated method returns empty from default (proving isolation)
     - `count()` routes to secondary
     - `list()` routes to secondary
     - `findByName()` routes to secondary
   
   All existing `ServiceTransformSpec` tests (30) continue to pass with no regressions.


-- 
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] Fix @Where and DetachedCriteria query methods ignoring @Transactional(connection) [grails-core]

Posted by "jamesfredley (via GitHub)" <gi...@apache.org>.
jamesfredley commented on code in PR #15418:
URL: https://github.com/apache/grails-core/pull/15418#discussion_r2835782842


##########
grails-data-hibernate5/core/src/test/groovy/org/grails/orm/hibernate/connections/WhereQueryMultiDataSourceSpec.groovy:
##########
@@ -0,0 +1,188 @@
+/*
+ *  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.connections
+
+import org.hibernate.dialect.H2Dialect
+import spock.lang.AutoCleanup
+import spock.lang.Issue
+import spock.lang.Shared
+import spock.lang.Specification
+
+import grails.gorm.annotation.Entity
+import grails.gorm.services.Service
+import grails.gorm.services.Where
+import grails.gorm.transactions.Transactional
+import org.grails.datastore.gorm.GormEnhancer
+import org.grails.datastore.gorm.GormEntity
+import org.grails.datastore.mapping.core.DatastoreUtils
+import org.grails.orm.hibernate.HibernateDatastore
+
+@Issue("https://github.com/apache/grails-core/issues/15416")
+class WhereQueryMultiDataSourceSpec extends Specification {
+
+    @Shared Map config = [
+            'dataSource.url':"jdbc:h2:mem:defaultDB;LOCK_TIMEOUT=10000",
+            'dataSource.dbCreate': 'create-drop',
+            'dataSource.dialect': H2Dialect.name,
+            'dataSource.formatSql': 'true',
+            'hibernate.flush.mode': 'COMMIT',
+            'hibernate.cache.queries': 'true',
+            'hibernate.hbm2ddl.auto': 'create-drop',
+            'dataSources.secondary':[url:"jdbc:h2:mem:secondaryDB;LOCK_TIMEOUT=10000"],
+    ]
+
+    @Shared @AutoCleanup HibernateDatastore datastore = new HibernateDatastore(
+            DatastoreUtils.createPropertyResolver(config), Item
+    )
+
+    @Shared ItemQueryService itemQueryService
+
+    void setupSpec() {
+        itemQueryService = datastore
+                .getDatastoreForConnection('secondary')
+                .getService(ItemQueryService)
+    }
+
+    void cleanup() {
+        def secondaryApi = GormEnhancer.findStaticApi(Item, 'secondary')
+        secondaryApi.withNewTransaction {
+            secondaryApi.executeUpdate('delete from Item')
+        }
+        def defaultApi = GormEnhancer.findStaticApi(Item)
+        defaultApi.withNewTransaction {
+            defaultApi.executeUpdate('delete from Item')
+        }
+    }
+
+    void "@Where query routes to secondary datasource"() {
+        given:
+        saveToSecondary('Cheap', 10.0)
+        saveToSecondary('Expensive', 500.0)
+
+        when:
+        def results = itemQueryService.findByMinAmount(100.0)
+
+        then:
+        results.size() == 1
+        results[0].name == 'Expensive'
+    }
+
+    void "@Where query does not return data from default datasource"() {
+        given: 'an item saved to secondary'
+        saveToSecondary('OnSecondary', 50.0)
+
+        and: 'a different item saved directly to default'
+        saveToDefault('OnDefault', 999.0)
+
+        when: 'querying via @Where for amount >= 500 on secondary-bound service'
+        def results = itemQueryService.findByMinAmount(500.0)
+
+        then: 'only secondary data is searched - default item is NOT found'
+        results.size() == 0
+    }
+
+    void "count routes to secondary datasource"() {
+        given:
+        saveToSecondary('A', 1.0)
+        saveToSecondary('B', 2.0)
+
+        and: 'an item on default that should not be counted'
+        saveToDefault('C', 3.0)
+
+        expect:
+        itemQueryService.count() == 2
+    }
+
+    void "list routes to secondary datasource"() {
+        given:
+        saveToSecondary('X', 10.0)
+        saveToSecondary('Y', 20.0)
+
+        and: 'an item on default that should not be listed'
+        saveToDefault('Z', 30.0)
+
+        when:
+        def all = itemQueryService.list()
+
+        then:
+        all.size() == 2
+    }
+
+    void "findByName routes to secondary datasource"() {
+        given:
+        saveToSecondary('Unique', 77.0)
+
+        when:
+        def found = itemQueryService.findByName('Unique')
+
+        then:
+        found != null
+        found.name == 'Unique'
+        found.amount == 77.0
+    }
+
+    private void saveToSecondary(String name, Double amount) {
+        def api = GormEnhancer.findStaticApi(Item, 'secondary')

Review Comment:
   This came from an issue preventing Data Services from using @CompileStatic with injected services.  But not the case here.  



-- 
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] Fix @Where and DetachedCriteria query methods ignoring @Transactional(connection) [grails-core]

Posted by "jdaugherty (via GitHub)" <gi...@apache.org>.
jdaugherty commented on code in PR #15418:
URL: https://github.com/apache/grails-core/pull/15418#discussion_r2835201599


##########
grails-datamapping-core/src/main/groovy/org/grails/datastore/gorm/services/implementers/AbstractWhereImplementer.groovy:
##########
@@ -96,16 +96,16 @@ abstract class AbstractWhereImplementer extends AbstractReadOperationImplementer
             body.addStatement(
                     declS(queryVar, ctorX(getDetachedCriteriaType(domainClassNode), args(classX(domainClassNode.plainNodeReference))))
             )
-            Expression connectionId = findConnectionId(newMethodNode)
+            body.addStatement(
+                    assignS(queryVar, callX(queryVar, 'build', closureExpression))

Review Comment:
   If we want to ticket it for the future I'm ok with that 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] Fix @Where and DetachedCriteria query methods ignoring @Transactional(connection) [grails-core]

Posted by "jamesfredley (via GitHub)" <gi...@apache.org>.
jamesfredley commented on code in PR #15418:
URL: https://github.com/apache/grails-core/pull/15418#discussion_r2835075549


##########
grails-datamapping-core/src/main/groovy/org/grails/datastore/gorm/services/implementers/AbstractWhereImplementer.groovy:
##########
@@ -96,16 +96,16 @@ abstract class AbstractWhereImplementer extends AbstractReadOperationImplementer
             body.addStatement(
                     declS(queryVar, ctorX(getDetachedCriteriaType(domainClassNode), args(classX(domainClassNode.plainNodeReference))))
             )
-            Expression connectionId = findConnectionId(newMethodNode)
+            body.addStatement(
+                    assignS(queryVar, callX(queryVar, 'build', closureExpression))

Review Comment:
   This is going to be complex, since TCK does not currently support multiple data sources, but I will present a potential solution, since I think it should. 



-- 
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] Fix @Where and DetachedCriteria query methods ignoring @Transactional(connection) [grails-core]

Posted by "jdaugherty (via GitHub)" <gi...@apache.org>.
jdaugherty commented on code in PR #15418:
URL: https://github.com/apache/grails-core/pull/15418#discussion_r2830958658


##########
grails-datamapping-core/src/main/groovy/org/grails/datastore/gorm/services/implementers/AbstractWhereImplementer.groovy:
##########
@@ -96,16 +96,16 @@ abstract class AbstractWhereImplementer extends AbstractReadOperationImplementer
             body.addStatement(
                     declS(queryVar, ctorX(getDetachedCriteriaType(domainClassNode), args(classX(domainClassNode.plainNodeReference))))
             )
-            Expression connectionId = findConnectionId(newMethodNode)
+            body.addStatement(
+                    assignS(queryVar, callX(queryVar, 'build', closureExpression))

Review Comment:
   These changes are in core, but there are additional tests in hibernate.  That strongly tells me the test should be part of the TCK.



##########
grails-data-hibernate5/core/src/test/groovy/org/grails/orm/hibernate/connections/WhereQueryMultiDataSourceSpec.groovy:
##########
@@ -0,0 +1,187 @@
+/*
+ *  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.connections
+
+import org.hibernate.dialect.H2Dialect
+import spock.lang.AutoCleanup
+import spock.lang.Issue
+import spock.lang.Shared
+import spock.lang.Specification
+
+import grails.gorm.annotation.Entity
+import grails.gorm.services.Service
+import grails.gorm.services.Where
+import grails.gorm.transactions.Transactional
+import org.grails.datastore.gorm.GormEnhancer
+import org.grails.datastore.gorm.GormEntity
+import org.grails.datastore.mapping.core.DatastoreUtils
+import org.grails.orm.hibernate.HibernateDatastore
+
+@Issue("https://github.com/apache/grails-core/issues/15416")
+class WhereQueryMultiDataSourceSpec extends Specification {
+
+    @Shared Map config = [
+            'dataSource.url':"jdbc:h2:mem:defaultDB;LOCK_TIMEOUT=10000",
+            'dataSource.dbCreate': 'create-drop',
+            'dataSource.dialect': H2Dialect.name,
+            'dataSource.formatSql': 'true',
+            'hibernate.flush.mode': 'COMMIT',
+            'hibernate.cache.queries': 'true',
+            'hibernate.hbm2ddl.auto': 'create-drop',
+            'dataSources.secondary':[url:"jdbc:h2:mem:secondaryDB;LOCK_TIMEOUT=10000"],
+    ]
+
+    @Shared @AutoCleanup HibernateDatastore datastore = new HibernateDatastore(
+            DatastoreUtils.createPropertyResolver(config), Item
+    )
+
+    @Shared ItemQueryService itemQueryService
+
+    void setupSpec() {
+        itemQueryService = datastore
+                .getDatastoreForConnection('secondary')
+                .getService(ItemQueryService)
+    }
+
+    void setup() {
+        def api = GormEnhancer.findStaticApi(Item, 'secondary')
+        api.withNewTransaction {
+            api.executeUpdate('delete from Item')

Review Comment:
   Is this from test pollution? Why isn't this in cleanup? 



-- 
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] Fix @Where and DetachedCriteria query methods ignoring @Transactional(connection) [grails-core]

Posted by "jamesfredley (via GitHub)" <gi...@apache.org>.
jamesfredley commented on code in PR #15418:
URL: https://github.com/apache/grails-core/pull/15418#discussion_r2835210520


##########
grails-data-hibernate5/core/src/test/groovy/org/grails/orm/hibernate/connections/WhereQueryMultiDataSourceSpec.groovy:
##########
@@ -0,0 +1,187 @@
+/*
+ *  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.connections
+
+import org.hibernate.dialect.H2Dialect
+import spock.lang.AutoCleanup
+import spock.lang.Issue
+import spock.lang.Shared
+import spock.lang.Specification
+
+import grails.gorm.annotation.Entity
+import grails.gorm.services.Service
+import grails.gorm.services.Where
+import grails.gorm.transactions.Transactional
+import org.grails.datastore.gorm.GormEnhancer
+import org.grails.datastore.gorm.GormEntity
+import org.grails.datastore.mapping.core.DatastoreUtils
+import org.grails.orm.hibernate.HibernateDatastore
+
+@Issue("https://github.com/apache/grails-core/issues/15416")
+class WhereQueryMultiDataSourceSpec extends Specification {
+
+    @Shared Map config = [
+            'dataSource.url':"jdbc:h2:mem:defaultDB;LOCK_TIMEOUT=10000",
+            'dataSource.dbCreate': 'create-drop',
+            'dataSource.dialect': H2Dialect.name,
+            'dataSource.formatSql': 'true',
+            'hibernate.flush.mode': 'COMMIT',
+            'hibernate.cache.queries': 'true',
+            'hibernate.hbm2ddl.auto': 'create-drop',
+            'dataSources.secondary':[url:"jdbc:h2:mem:secondaryDB;LOCK_TIMEOUT=10000"],
+    ]
+
+    @Shared @AutoCleanup HibernateDatastore datastore = new HibernateDatastore(
+            DatastoreUtils.createPropertyResolver(config), Item
+    )
+
+    @Shared ItemQueryService itemQueryService
+
+    void setupSpec() {
+        itemQueryService = datastore
+                .getDatastoreForConnection('secondary')
+                .getService(ItemQueryService)
+    }
+
+    void setup() {
+        def api = GormEnhancer.findStaticApi(Item, 'secondary')
+        api.withNewTransaction {
+            api.executeUpdate('delete from Item')

Review Comment:
   Fixed - moved the data deletion from `setup()` to `cleanup()` so each test cleans up after itself regardless of pass/fail. See commit 98e9b51.



##########
grails-datamapping-core/src/main/groovy/org/grails/datastore/gorm/services/implementers/AbstractWhereImplementer.groovy:
##########
@@ -96,16 +96,16 @@ abstract class AbstractWhereImplementer extends AbstractReadOperationImplementer
             body.addStatement(
                     declS(queryVar, ctorX(getDetachedCriteriaType(domainClassNode), args(classX(domainClassNode.plainNodeReference))))
             )
-            Expression connectionId = findConnectionId(newMethodNode)
+            body.addStatement(
+                    assignS(queryVar, callX(queryVar, 'build', closureExpression))

Review Comment:
   Done - added a full TCK test (`WhereQueryConnectionRoutingSpec`) with domain class, service interface, and multi-datasource support in both the Hibernate and MongoDB TCK managers. The test validates @Where, count, list, and findByName all route to the correct secondary datasource.
   
   Verified passing on:
   - Hibernate5: 5/5 pass
   - MongoDB: 5/5 pass
   - SimpleMap: skipped (no multi-datasource support)
   
   See commit 98e9b51.



-- 
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] Fix @Where and DetachedCriteria query methods ignoring @Transactional(connection) [grails-core]

Posted by "jamesfredley (via GitHub)" <gi...@apache.org>.
jamesfredley commented on code in PR #15418:
URL: https://github.com/apache/grails-core/pull/15418#discussion_r2830619072


##########
grails-datamapping-core/src/test/groovy/grails/gorm/services/WhereConnectionRoutingSpec.groovy:
##########
@@ -0,0 +1,207 @@
+/*
+ *  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.services
+
+import grails.gorm.transactions.Transactional
+import org.grails.datastore.gorm.services.Implemented
+import org.grails.datastore.gorm.services.implementers.FindAllWhereImplementer
+import org.grails.datastore.gorm.services.implementers.FindOneWhereImplementer
+import org.grails.datastore.gorm.services.implementers.CountWhereImplementer
+import org.grails.datastore.gorm.services.implementers.CountImplementer
+import org.grails.datastore.gorm.services.implementers.FindAllByImplementer
+import org.grails.datastore.gorm.services.implementers.FindAllImplementer
+import org.grails.datastore.gorm.services.implementers.FindOneImplementer
+import spock.lang.Specification
+
+class WhereConnectionRoutingSpec extends Specification {
+
+    void "test @Where method on interface with @Transactional(connection)"() {
+        when:"The service transform is applied to an interface with @Transactional(connection)"
+        Class service = new GroovyClassLoader().parseClass('''
+import grails.gorm.services.Service
+import grails.gorm.services.Where
+import grails.gorm.annotation.Entity
+import grails.gorm.transactions.Transactional
+
+@Service(Foo)
+@Transactional(connection = 'secondary')
+interface FooService {
+
+    @Where({ title ==~ pattern })
+    Foo findByTitle(String pattern)
+}
+@Entity
+class Foo {
+    String title
+    static mapping = {
+        datasource 'secondary'
+    }
+}
+''')
+
+        then:
+        service.isInterface()
+
+        when:"the impl is obtained"
+        Class impl = service.classLoader.loadClass("\$FooServiceImplementation")
+
+        then:"The impl is valid"
+        impl.getAnnotation(Transactional) != null
+        impl.getAnnotation(Transactional).connection() == 'secondary'
+        impl.getMethod("findByTitle", String).getAnnotation(Implemented).by() == FindOneWhereImplementer
+    }
+
+    void "test @Where method on abstract class with @Transactional(connection)"() {
+        when:"The service transform is applied to an abstract class"
+        Class service = new GroovyClassLoader().parseClass('''
+import grails.gorm.services.Service
+import grails.gorm.services.Where
+import grails.gorm.annotation.Entity
+import grails.gorm.transactions.Transactional
+
+@Service(Foo)
+@Transactional(connection = 'secondary')
+abstract class FooService {
+
+    @Where({ title ==~ pattern })
+    abstract List<Foo> searchByTitle(String pattern)
+}
+@Entity
+class Foo {
+    String title
+    static mapping = {
+        datasource 'secondary'
+    }
+}
+''')
+
+        then:
+        !service.isInterface()
+
+        when:"the impl is obtained"
+        Class impl = service.classLoader.loadClass("\$FooServiceImplementation")
+
+        then:"The impl is valid"
+        impl.getAnnotation(Transactional) != null
+        impl.getAnnotation(Transactional).connection() == 'secondary'
+        impl.getMethod("searchByTitle", String).getAnnotation(Implemented).by() == FindAllWhereImplementer
+    }
+
+    void "test count method uses connection-aware implementer"() {
+        when:"The service transform is applied to an interface with count()"
+        Class service = new GroovyClassLoader().parseClass('''
+import grails.gorm.services.Service
+import grails.gorm.annotation.Entity
+import grails.gorm.transactions.Transactional
+
+@Service(Foo)
+@Transactional(connection = 'secondary')
+interface FooService {
+    Number count()
+}
+@Entity
+class Foo {
+    String title
+    static mapping = {
+        datasource 'secondary'
+    }
+}
+''')
+
+        then:
+        service.isInterface()
+
+        when:"the impl is obtained"
+        Class impl = service.classLoader.loadClass("\$FooServiceImplementation")
+
+        then:"The impl is valid"
+        impl.getAnnotation(Transactional) != null
+        impl.getAnnotation(Transactional).connection() == 'secondary'
+        impl.getMethod("count").getAnnotation(Implemented).by() == CountImplementer
+    }
+
+    void "test list and findAll methods use connection-aware implementer"() {
+        when:"The service transform is applied to an interface with list and findAll methods"
+        Class service = new GroovyClassLoader().parseClass('''
+import grails.gorm.services.Service
+import grails.gorm.annotation.Entity
+import grails.gorm.transactions.Transactional
+
+@Service(Foo)
+@Transactional(connection = 'secondary')
+interface FooService {
+    List<Foo> list()
+    List<Foo> findAllByTitle(String title)
+    Foo find(Serializable id)
+}
+@Entity
+class Foo {
+    String title
+    static mapping = {
+        datasource 'secondary'
+    }
+}
+''')
+
+        then:
+        service.isInterface()
+
+        when:"the impl is obtained"
+        Class impl = service.classLoader.loadClass("\$FooServiceImplementation")
+
+        then:"The impl is valid"
+        impl.getAnnotation(Transactional) != null
+        impl.getAnnotation(Transactional).connection() == 'secondary'
+        impl.getMethod("list").getAnnotation(Implemented).by() == FindAllImplementer
+        impl.getMethod("findAllByTitle", String).getAnnotation(Implemented).by() == FindAllByImplementer
+        impl.getMethod("find", Serializable).getAnnotation(Implemented).by() == FindOneImplementer
+    }
+

Review Comment:
   Added `findByName(String)` to the unit test's service interface and asserted it maps to `FindOneByImplementer`. Both unit and integration tests now cover `findByName` routing.



-- 
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] Fix @Where and DetachedCriteria query methods ignoring @Transactional(connection) [grails-core]

Posted by "jdaugherty (via GitHub)" <gi...@apache.org>.
jdaugherty commented on code in PR #15418:
URL: https://github.com/apache/grails-core/pull/15418#discussion_r2835768276


##########
grails-data-hibernate5/core/src/test/groovy/org/grails/orm/hibernate/connections/WhereQueryMultiDataSourceSpec.groovy:
##########
@@ -0,0 +1,188 @@
+/*
+ *  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.connections
+
+import org.hibernate.dialect.H2Dialect
+import spock.lang.AutoCleanup
+import spock.lang.Issue
+import spock.lang.Shared
+import spock.lang.Specification
+
+import grails.gorm.annotation.Entity
+import grails.gorm.services.Service
+import grails.gorm.services.Where
+import grails.gorm.transactions.Transactional
+import org.grails.datastore.gorm.GormEnhancer
+import org.grails.datastore.gorm.GormEntity
+import org.grails.datastore.mapping.core.DatastoreUtils
+import org.grails.orm.hibernate.HibernateDatastore
+
+@Issue("https://github.com/apache/grails-core/issues/15416")
+class WhereQueryMultiDataSourceSpec extends Specification {
+
+    @Shared Map config = [
+            'dataSource.url':"jdbc:h2:mem:defaultDB;LOCK_TIMEOUT=10000",
+            'dataSource.dbCreate': 'create-drop',
+            'dataSource.dialect': H2Dialect.name,
+            'dataSource.formatSql': 'true',
+            'hibernate.flush.mode': 'COMMIT',
+            'hibernate.cache.queries': 'true',
+            'hibernate.hbm2ddl.auto': 'create-drop',
+            'dataSources.secondary':[url:"jdbc:h2:mem:secondaryDB;LOCK_TIMEOUT=10000"],
+    ]
+
+    @Shared @AutoCleanup HibernateDatastore datastore = new HibernateDatastore(
+            DatastoreUtils.createPropertyResolver(config), Item
+    )
+
+    @Shared ItemQueryService itemQueryService
+
+    void setupSpec() {
+        itemQueryService = datastore
+                .getDatastoreForConnection('secondary')
+                .getService(ItemQueryService)
+    }
+
+    void cleanup() {
+        def secondaryApi = GormEnhancer.findStaticApi(Item, 'secondary')
+        secondaryApi.withNewTransaction {
+            secondaryApi.executeUpdate('delete from Item')
+        }
+        def defaultApi = GormEnhancer.findStaticApi(Item)
+        defaultApi.withNewTransaction {
+            defaultApi.executeUpdate('delete from Item')
+        }
+    }
+
+    void "@Where query routes to secondary datasource"() {
+        given:
+        saveToSecondary('Cheap', 10.0)
+        saveToSecondary('Expensive', 500.0)
+
+        when:
+        def results = itemQueryService.findByMinAmount(100.0)
+
+        then:
+        results.size() == 1
+        results[0].name == 'Expensive'
+    }
+
+    void "@Where query does not return data from default datasource"() {
+        given: 'an item saved to secondary'
+        saveToSecondary('OnSecondary', 50.0)
+
+        and: 'a different item saved directly to default'
+        saveToDefault('OnDefault', 999.0)
+
+        when: 'querying via @Where for amount >= 500 on secondary-bound service'
+        def results = itemQueryService.findByMinAmount(500.0)
+
+        then: 'only secondary data is searched - default item is NOT found'
+        results.size() == 0
+    }
+
+    void "count routes to secondary datasource"() {
+        given:
+        saveToSecondary('A', 1.0)
+        saveToSecondary('B', 2.0)
+
+        and: 'an item on default that should not be counted'
+        saveToDefault('C', 3.0)
+
+        expect:
+        itemQueryService.count() == 2
+    }
+
+    void "list routes to secondary datasource"() {
+        given:
+        saveToSecondary('X', 10.0)
+        saveToSecondary('Y', 20.0)
+
+        and: 'an item on default that should not be listed'
+        saveToDefault('Z', 30.0)
+
+        when:
+        def all = itemQueryService.list()
+
+        then:
+        all.size() == 2
+    }
+
+    void "findByName routes to secondary datasource"() {
+        given:
+        saveToSecondary('Unique', 77.0)
+
+        when:
+        def found = itemQueryService.findByName('Unique')
+
+        then:
+        found != null
+        found.name == 'Unique'
+        found.amount == 77.0
+    }
+
+    private void saveToSecondary(String name, Double amount) {
+        def api = GormEnhancer.findStaticApi(Item, 'secondary')

Review Comment:
   If we have the domain object, why aren't we testing the public apis?  It looks like you're calling the static, internal implementation instead.



-- 
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] Fix @Where and DetachedCriteria query methods ignoring @Transactional(connection) [grails-core]

Posted by "Copilot (via GitHub)" <gi...@apache.org>.
Copilot commented on code in PR #15418:
URL: https://github.com/apache/grails-core/pull/15418#discussion_r2830587457


##########
grails-datamapping-core/src/test/groovy/grails/gorm/services/WhereConnectionRoutingSpec.groovy:
##########
@@ -0,0 +1,207 @@
+/*
+ *  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.services
+
+import grails.gorm.transactions.Transactional
+import org.grails.datastore.gorm.services.Implemented
+import org.grails.datastore.gorm.services.implementers.FindAllWhereImplementer
+import org.grails.datastore.gorm.services.implementers.FindOneWhereImplementer
+import org.grails.datastore.gorm.services.implementers.CountWhereImplementer
+import org.grails.datastore.gorm.services.implementers.CountImplementer
+import org.grails.datastore.gorm.services.implementers.FindAllByImplementer
+import org.grails.datastore.gorm.services.implementers.FindAllImplementer
+import org.grails.datastore.gorm.services.implementers.FindOneImplementer
+import spock.lang.Specification
+
+class WhereConnectionRoutingSpec extends Specification {
+
+    void "test @Where method on interface with @Transactional(connection)"() {
+        when:"The service transform is applied to an interface with @Transactional(connection)"
+        Class service = new GroovyClassLoader().parseClass('''
+import grails.gorm.services.Service
+import grails.gorm.services.Where
+import grails.gorm.annotation.Entity
+import grails.gorm.transactions.Transactional
+
+@Service(Foo)
+@Transactional(connection = 'secondary')
+interface FooService {
+
+    @Where({ title ==~ pattern })
+    Foo findByTitle(String pattern)
+}
+@Entity
+class Foo {
+    String title
+    static mapping = {
+        datasource 'secondary'
+    }
+}
+''')
+
+        then:
+        service.isInterface()
+
+        when:"the impl is obtained"
+        Class impl = service.classLoader.loadClass("\$FooServiceImplementation")
+
+        then:"The impl is valid"
+        impl.getAnnotation(Transactional) != null
+        impl.getAnnotation(Transactional).connection() == 'secondary'
+        impl.getMethod("findByTitle", String).getAnnotation(Implemented).by() == FindOneWhereImplementer
+    }
+
+    void "test @Where method on abstract class with @Transactional(connection)"() {
+        when:"The service transform is applied to an abstract class"
+        Class service = new GroovyClassLoader().parseClass('''
+import grails.gorm.services.Service
+import grails.gorm.services.Where
+import grails.gorm.annotation.Entity
+import grails.gorm.transactions.Transactional
+
+@Service(Foo)
+@Transactional(connection = 'secondary')
+abstract class FooService {
+
+    @Where({ title ==~ pattern })
+    abstract List<Foo> searchByTitle(String pattern)
+}
+@Entity
+class Foo {
+    String title
+    static mapping = {
+        datasource 'secondary'
+    }
+}
+''')
+
+        then:
+        !service.isInterface()
+
+        when:"the impl is obtained"
+        Class impl = service.classLoader.loadClass("\$FooServiceImplementation")
+
+        then:"The impl is valid"
+        impl.getAnnotation(Transactional) != null
+        impl.getAnnotation(Transactional).connection() == 'secondary'
+        impl.getMethod("searchByTitle", String).getAnnotation(Implemented).by() == FindAllWhereImplementer
+    }
+
+    void "test count method uses connection-aware implementer"() {
+        when:"The service transform is applied to an interface with count()"
+        Class service = new GroovyClassLoader().parseClass('''
+import grails.gorm.services.Service
+import grails.gorm.annotation.Entity
+import grails.gorm.transactions.Transactional
+
+@Service(Foo)
+@Transactional(connection = 'secondary')
+interface FooService {
+    Number count()
+}
+@Entity
+class Foo {
+    String title
+    static mapping = {
+        datasource 'secondary'
+    }
+}
+''')
+
+        then:
+        service.isInterface()
+
+        when:"the impl is obtained"
+        Class impl = service.classLoader.loadClass("\$FooServiceImplementation")
+
+        then:"The impl is valid"
+        impl.getAnnotation(Transactional) != null
+        impl.getAnnotation(Transactional).connection() == 'secondary'
+        impl.getMethod("count").getAnnotation(Implemented).by() == CountImplementer
+    }
+
+    void "test list and findAll methods use connection-aware implementer"() {
+        when:"The service transform is applied to an interface with list and findAll methods"
+        Class service = new GroovyClassLoader().parseClass('''
+import grails.gorm.services.Service
+import grails.gorm.annotation.Entity
+import grails.gorm.transactions.Transactional
+
+@Service(Foo)
+@Transactional(connection = 'secondary')
+interface FooService {
+    List<Foo> list()
+    List<Foo> findAllByTitle(String title)
+    Foo find(Serializable id)
+}
+@Entity
+class Foo {
+    String title
+    static mapping = {
+        datasource 'secondary'
+    }
+}
+''')
+
+        then:
+        service.isInterface()
+
+        when:"the impl is obtained"
+        Class impl = service.classLoader.loadClass("\$FooServiceImplementation")
+
+        then:"The impl is valid"
+        impl.getAnnotation(Transactional) != null
+        impl.getAnnotation(Transactional).connection() == 'secondary'
+        impl.getMethod("list").getAnnotation(Implemented).by() == FindAllImplementer
+        impl.getMethod("findAllByTitle", String).getAnnotation(Implemented).by() == FindAllByImplementer
+        impl.getMethod("find", Serializable).getAnnotation(Implemented).by() == FindOneImplementer
+    }
+

Review Comment:
   The PR description says the unit tests verify DetachedCriteria `findByName()` routing, but this spec doesn't include any `findBy*()` method assertions (only `findAllByTitle` and `find`). Either add a unit test case that exercises a `findByName(String)` service method, or adjust the PR description to match what’s actually covered here (relying on the integration spec for `findByName`).



-- 
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] Fix @Where and DetachedCriteria query methods ignoring @Transactional(connection) [grails-core]

Posted by "bito-code-review[bot] (via GitHub)" <gi...@apache.org>.
bito-code-review[bot] commented on PR #15418:
URL: https://github.com/apache/grails-core/pull/15418#issuecomment-3930657151

   <!-- Bito Reply -->
   The suggestion is valid. The unit spec tests @Where method routing but lacks a findByName test, while the integration spec covers it. Adjust the PR description to clarify that integration tests verify DetachedCriteria findByName routing.


-- 
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] Fix @Where and DetachedCriteria query methods ignoring @Transactional(connection) [grails-core]

Posted by "jamesfredley (via GitHub)" <gi...@apache.org>.
jamesfredley commented on code in PR #15418:
URL: https://github.com/apache/grails-core/pull/15418#discussion_r2835780705


##########
grails-data-hibernate5/core/src/test/groovy/org/grails/orm/hibernate/connections/WhereQueryMultiDataSourceSpec.groovy:
##########
@@ -0,0 +1,188 @@
+/*
+ *  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.connections
+
+import org.hibernate.dialect.H2Dialect
+import spock.lang.AutoCleanup
+import spock.lang.Issue
+import spock.lang.Shared
+import spock.lang.Specification
+
+import grails.gorm.annotation.Entity
+import grails.gorm.services.Service
+import grails.gorm.services.Where
+import grails.gorm.transactions.Transactional
+import org.grails.datastore.gorm.GormEnhancer
+import org.grails.datastore.gorm.GormEntity
+import org.grails.datastore.mapping.core.DatastoreUtils
+import org.grails.orm.hibernate.HibernateDatastore
+
+@Issue("https://github.com/apache/grails-core/issues/15416")
+class WhereQueryMultiDataSourceSpec extends Specification {
+
+    @Shared Map config = [
+            'dataSource.url':"jdbc:h2:mem:defaultDB;LOCK_TIMEOUT=10000",
+            'dataSource.dbCreate': 'create-drop',
+            'dataSource.dialect': H2Dialect.name,
+            'dataSource.formatSql': 'true',
+            'hibernate.flush.mode': 'COMMIT',
+            'hibernate.cache.queries': 'true',
+            'hibernate.hbm2ddl.auto': 'create-drop',
+            'dataSources.secondary':[url:"jdbc:h2:mem:secondaryDB;LOCK_TIMEOUT=10000"],
+    ]
+
+    @Shared @AutoCleanup HibernateDatastore datastore = new HibernateDatastore(
+            DatastoreUtils.createPropertyResolver(config), Item
+    )
+
+    @Shared ItemQueryService itemQueryService
+
+    void setupSpec() {
+        itemQueryService = datastore
+                .getDatastoreForConnection('secondary')
+                .getService(ItemQueryService)
+    }
+
+    void cleanup() {
+        def secondaryApi = GormEnhancer.findStaticApi(Item, 'secondary')
+        secondaryApi.withNewTransaction {
+            secondaryApi.executeUpdate('delete from Item')
+        }
+        def defaultApi = GormEnhancer.findStaticApi(Item)
+        defaultApi.withNewTransaction {
+            defaultApi.executeUpdate('delete from Item')
+        }
+    }
+
+    void "@Where query routes to secondary datasource"() {
+        given:
+        saveToSecondary('Cheap', 10.0)
+        saveToSecondary('Expensive', 500.0)
+
+        when:
+        def results = itemQueryService.findByMinAmount(100.0)
+
+        then:
+        results.size() == 1
+        results[0].name == 'Expensive'
+    }
+
+    void "@Where query does not return data from default datasource"() {
+        given: 'an item saved to secondary'
+        saveToSecondary('OnSecondary', 50.0)
+
+        and: 'a different item saved directly to default'
+        saveToDefault('OnDefault', 999.0)
+
+        when: 'querying via @Where for amount >= 500 on secondary-bound service'
+        def results = itemQueryService.findByMinAmount(500.0)
+
+        then: 'only secondary data is searched - default item is NOT found'
+        results.size() == 0
+    }
+
+    void "count routes to secondary datasource"() {
+        given:
+        saveToSecondary('A', 1.0)
+        saveToSecondary('B', 2.0)
+
+        and: 'an item on default that should not be counted'
+        saveToDefault('C', 3.0)
+
+        expect:
+        itemQueryService.count() == 2
+    }
+
+    void "list routes to secondary datasource"() {
+        given:
+        saveToSecondary('X', 10.0)
+        saveToSecondary('Y', 20.0)
+
+        and: 'an item on default that should not be listed'
+        saveToDefault('Z', 30.0)
+
+        when:
+        def all = itemQueryService.list()
+
+        then:
+        all.size() == 2
+    }
+
+    void "findByName routes to secondary datasource"() {
+        given:
+        saveToSecondary('Unique', 77.0)
+
+        when:
+        def found = itemQueryService.findByName('Unique')
+
+        then:
+        found != null
+        found.name == 'Unique'
+        found.amount == 77.0
+    }
+
+    private void saveToSecondary(String name, Double amount) {
+        def api = GormEnhancer.findStaticApi(Item, 'secondary')

Review Comment:
   Good call - replaced all `GormEnhancer.findStaticApi`/`findInstanceApi` usage with the public domain class API (`Item.secondary.withNewTransaction`, `item.secondary.save()`, `Item.secondary.deleteAll`) in 5a50372074. Matches the pattern used in `MultipleDataSourcesWithEventsSpec`.



-- 
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] Fix @Where and DetachedCriteria query methods ignoring @Transactional(connection) [grails-core]

Posted by "jdaugherty (via GitHub)" <gi...@apache.org>.
jdaugherty merged PR #15418:
URL: https://github.com/apache/grails-core/pull/15418


-- 
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