Skip to content

where-query returning wrong result if its expression is not assigned to a variable #14596

Closed

Description

@zyro23

Task List

  • Steps to reproduce provided
  • Stacktrace (if present) provided
  • Example that reproduces the problem uploaded to Github
  • Full description of the issue provided (see below)

Steps to Reproduce

  1. check repro spec in sample app

Expected Behaviour

spec should pass

Actual Behaviour

Condition not satisfied:

Foo.where { bar == null }.count() == 0
    |                     |       |
    |                     1       false
    grails.gorm.DetachedCriteria@16d431b4

Expected :0

Actual   :1

maybe something with the DetachedCriteria transformations going wrong?

Environment Information

  • Operating System: win x64
  • GORM Version: 6.1.7
  • Grails Version (if using Grails): 3.3.1
  • JDK Version: oracle 8u131

Example Application

sample app will be referenced in a minute

Activity

  1. jeffscottbrown commented on Nov 18, 2017

    @jeffscottbrown
    Contributor

    I expect that only happens in a Spec. Is that correct?

  2. jeffscottbrown commented on Nov 18, 2017

    @jeffscottbrown
    Contributor

    I think the problem here can be demonstrated without even executing the query. The criteria associated with the DetachedCriteria is empty in the second case.

    @Transactional
    void "test query by association is null"() {
        new Foo(bar: new Bar()).save()
    
        when:
        def q = Foo.where { bar == null }
    
        then:
        q.criteria.size() == 1
        q.criteria[0] instanceof Query.IsNull
    
        and:
        // this fails because the criteria is empty
        Foo.where { bar == null }.criteria.size() == 1
    }

    The empty criteria explains why the query is returning all of the Foo.

  3. zyro23 commented on Nov 18, 2017

    @zyro23
    ContributorAuthor

    thanks @jeffbrown for confirmation.
    and no, this is not only happening in a spec. we observed this behavior in a live grails app (service method return statement):

    return someExistingDetachedCriteria.where { myAssociation == null}.count()
  4. jeffscottbrown commented on Nov 18, 2017

    @jeffscottbrown
    Contributor

    Thanks for the feedback.

  5. jeffscottbrown commented on Nov 18, 2017

    @jeffscottbrown
    Contributor

    The project at https://github.com/jeffbrown/issue1026 contains the following:

    https://github.com/jeffbrown/issue1026/blob/master/grails-app/domain/issue1026/Person.groovy

    package issue1026
    
    class Person {
        String firstName
    }

    https://github.com/jeffbrown/issue1026/blob/master/grails-app/init/issue1026/BootStrap.groovy

    package issue1026
    
    class BootStrap {
    
        def init = { servletContext ->
            new Person(firstName: 'Jeff').save()
            new Person(firstName: 'Jake').save()
            new Person(firstName: 'Zack').save()
        }
        def destroy = {
        }
    }

    https://github.com/jeffbrown/issue1026/blob/master/grails-app/services/issue1026/PersonService.groovy

    package issue1026
    
    import grails.gorm.transactions.Transactional
    
    @Transactional(readOnly = true)
    class PersonService {
    
        Number countPeopleThatHaveAFirstName() {
            Person.where {
                firstName != null
            }.count()
        }
    
        Number countPeopleWithNoFirstName() {
             Person.where {
                firstName == null
            }.count()
        }
    }

    https://github.com/jeffbrown/issue1026/blob/master/grails-app/controllers/issue1026/PersonController.groovy

    package issue1026
    
    class PersonController {
    
        PersonService personService
    
        def withFirstName() {
            def count = personService.countPeopleThatHaveAFirstName()
            render "There are $count people with a first name."
        }
    
        def withNoFirstName() {
            def count = personService.countPeopleWithNoFirstName()
            render "There are $count people with no first name."
        }
    }

    https://github.com/jeffbrown/issue1026/blob/master/src/integration-test/groovy/issue1026/PersonSpec.groovy

    package issue1026
    
    import geb.spock.GebSpec
    import grails.testing.mixin.integration.Integration
    
    @Integration
    class PersonSpec extends GebSpec {
    
        void "test retriving people with a first name"() {
            when:
            go '/person/withFirstName'
    
            then:
            $().text() == 'There are 3 people with a first name.'
        }
    
        void "test retriving people without a first name"() {
            when:
            go '/person/withNoFirstName'
    
            then:
            $().text() == 'There are 0 people with no first name.'
        }
    }

    That test passes.

  6. jeffscottbrown commented on Nov 18, 2017

    @jeffscottbrown
    Contributor

    I see the change at zyro23/issue1026@4d367b3...

    package issue1026
    
    import grails.gorm.DetachedCriteria
    import grails.gorm.transactions.Transactional
    
    @Transactional(readOnly = true)
    class PersonService {
    
        Number countPeopleThatHaveAFirstName() {
            createDetachedCriteria().where {
                firstName != null
            }.count()
        }
    
        Number countPeopleWithNoFirstName() {
             createDetachedCriteria().where {
                firstName == null
            }.count()
        }
    
        private DetachedCriteria<Person> createDetachedCriteria() {
            Person.where {}
        }
    }

    I think that would fail even if the result was assigned to a variable. I think all of the following would fail:

    package issue1026
    
    import grails.gorm.DetachedCriteria
    import grails.gorm.transactions.Transactional
    
    @Transactional(readOnly = true)
    class PersonService {
    
        Number countPeopleThatHaveAFirstName() {
            createDetachedCriteria().where {
                firstName != null
            }.count()
        }
    
        Number countPeopleWithNoFirstName() {
            def q = createDetachedCriteria().where {
                firstName == null
            }
            q.count()
        }
    
        private DetachedCriteria<Person> createDetachedCriteria() {
            Person.where {}
        }
    }
    package issue1026
    
    import grails.gorm.DetachedCriteria
    import grails.gorm.transactions.Transactional
    
    @Transactional(readOnly = true)
    class PersonService {
    
        Number countPeopleThatHaveAFirstName() {
            createDetachedCriteria().where {
                firstName != null
            }.count()
        }
    
        Number countPeopleWithNoFirstName() {
            def q = createDetachedCriteria().where {
                firstName == null
            }
            Long count = q.count()
            count
        }
    
        private DetachedCriteria<Person> createDetachedCriteria() {
            Person.where {}
        }
    }
    
    ```groovy
    package issue1026
    
    import grails.gorm.DetachedCriteria
    import grails.gorm.transactions.Transactional
    
    @Transactional(readOnly = true)
    class PersonService {
    
        Number countPeopleThatHaveAFirstName() {
            createDetachedCriteria().where {
                firstName != null
            }.count()
        }
    
        Number countPeopleWithNoFirstName() {
            Long count = createDetachedCriteria().where {
                firstName == null
            }.count()
            count
        }
    
        private DetachedCriteria<Person> createDetachedCriteria() {
            Person.where {}
        }
    }
  7. jeffscottbrown commented on Nov 18, 2017

    @jeffscottbrown
    Contributor

    I think this is a more simple way to demonstrate the problematic behavior:

    package issue1026
    
    import grails.gorm.DetachedCriteria
    import grails.gorm.transactions.Transactional
    
    @Transactional(readOnly = true)
    class PersonService {
    
        Number countPeopleThatHaveAFirstName() {
            new DetachedCriteria(Person).where {
                firstName != null
            }.count()
        }
    
        Number countPeopleWithNoFirstName() {
            new DetachedCriteria(Person).where {
                firstName == null
            }.count()
        }
    }
  8. jeffscottbrown commented on Nov 18, 2017

    @jeffscottbrown
    Contributor

    The change at jeffscottbrown/issue1026@79cecb0 causes one of the tests to fail.

  9. zyro23 commented on Nov 19, 2017

    @zyro23
    ContributorAuthor

    i tried debugging into the DetachedCriteriaTransformer by adding this to the different versions of jeffs sample app
    (BootStrap.init, breakpoints at transformTestHelper.parse and inside DetachedCriteriaTransformer):

    TransformTestHelper transformTestHelper = new TransformTestHelper(new DetachedCriteriaASTTransformation(), CompilePhase.CANONICALIZATION)
    transformTestHelper.parse(new File("grails-app/services/issue1026/PersonService.groovy"))

    in this example:

    new DetachedCriteria(Person).where {
        firstName == null
    }.count()

    it seems like the where closure is not transformed because the objectExpression it is called on is a ConstructorCallExpression which seems to be not handled by the transformer.
    ref. the if/elses here https://github.com/grails/grails-data-mapping/blob/v6.1.7/grails-datastore-gorm/src/main/groovy/org/grails/datastore/gorm/query/transform/DetachedCriteriaTransformer.java#L309

    and in this example:

    createDetachedCriteria().where {
        firstName == null
    }.count()
    
    private DetachedCriteria<Person> createDetachedCriteria() {
        Person.where {}
    }

    it also looks like the added/appended where closure is not transformed because this time, the objectExpression is a MethodCallExpression. but the targetType is this (i.e. PersonService), which is not a domain class.
    ref. https://github.com/grails/grails-data-mapping/blob/v6.1.7/grails-datastore-gorm/src/main/groovy/org/grails/datastore/gorm/query/transform/DetachedCriteriaTransformer.java#L358

    dont know what other possibilities there are to use where queries which are not properly transformed.

    i have to express that i am deeply worried about this kind of issue appearing. it produces wrong results out of code that is properly written, compiled without errors and seemingly runs just fine. no way for regular framework "end-users" to get whats going on.
    unfortunately, debugging ast transformations (and if its just to get to the point of understanding what happens) is overly complicated. abstraction and ease-of-use is all fine but i think it should not lead to a blackbox for users.

  10. jeffscottbrown commented on Nov 19, 2017

    @jeffscottbrown
    Contributor

    Thank you for the feedback.

  11. jamesfredley commented on Feb 26, 2026

    @jamesfredley
    Contributor

    This was reported against GORM 6.1.7 / Grails 3.3.1. Since then, the where-query AST transformation (DetachedCriteriaTransformer) has received several fixes in Grails 7.x that address variable handling and implicit-this resolution:

    • 4299a24 - fix: set implicitThis=false on delegate MethodCallExpressions in DetachedCriteriaTransformer
    • 2e3f6a8 - fix: where query composition fails when variable is re-assigned in if/else blocks
    • dee7d11 - fix: update variable type for constructor case in visitBinaryExpression

    These changes significantly reworked how the transformer handles inline vs. variable-assigned where expressions.

    If you are still experiencing this issue on Grails 7.x, please reopen with a minimal reproducer against the current version. Otherwise, we believe this has been addressed by the fixes above.

  12. jamesfredley commented on Jul 24, 2026

    @jamesfredley
    Contributor

    Thanks for the report and the detailed AST analysis. On current 8.0.x, the reported static Domain.where { property == null }.count() form now matches the variable-assigned form for both empty and matching result sets. The exact case is covered by WhereQueryOldIssueVerificationSpec with @Issue(#14596); the related transformer fixes landed on February 24, 2026 and the verification merged through PR #15460 on February 27, 2026. This closure is limited to the reported static Domain.where case; constructor and method-return receivers remain separate, unverified paths. Please reopen with a minimal current reproducer if the supported static form still differs.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions