Search code examples
grailsgrails-orm

GORM Where query composition on return value


I noticed some behaviour I don't quite understand. It's possible to chain where queries as long as the preceding where query wasn't returned from a function.

def w = Subscription.where { topicId == 1 }
w.where { user.id == 1 }.findAll()

//works as expected


def f() {
    Subscription.where { topicId == 1 }
}
f().where { user.id == 1 }.findAll()

//doesn't filter by user.id


def f() {
    Subscription.where { topicId == 1 }
}
f().build { eq 'user.id', 1L }

//works

I don't mind using DetachedCriteria#build(). I'd just like to understand :-D

--- Edit

Grails 2.4.2


Solution

  • Grails contains a global AST transformation...

    that transforms where methods into detached criteria queries.

    It essentially looks for uses of where() and changes the code so that it uses detached criterias. Most likely, calling where() as you are, on the return of a method, particularly a method which returns Object, is not being acknowledged up by the AST, so the query basically ends up being unchanged and doing nothing.

    It's nothing that Groovy is doing, but rather something Grails-specific. I do not claim a full, nor anything near full, understanding of what's happening, but you can get the gist of it by looking at the DetachedCriteriaTransformer source code.