4

According to the Gorm 6 documentation section 7.4 the Where Query returns a DetachedCriteria, which provides a method count() that is supposed to return the number of records returned by the query. In fact, as far as I can tell, if dc is an instance of DetachedCriteria, then

dc.count() == dc.list().size()

must hold true.

In the case of a Where Query containing a projection, count() seems to return something else. In this simple example:

query = Runner.where {
    projections {
        groupProperty 'finishPosition'
        rowCount()
    }
}

println "query.count() ${query.count()}"
println "query.list().size() ${query.list().size()}"

the result printed is:

query.count() 576
query.list().size() 22

If I also print query.list(), it appears as

query.list() [[14, 576], [12, 1945], [8, 5682], [17, 78], [1, 91842], [15, 174], [10, 3836], [11, 2873], [4, 90688], [18, 36], [0, 336177], [16, 110], [6, 63957], [19, 6], [2, 91669], [21, 2], [3, 91550], [20, 4], [13, 956], [5, 72852], [9, 4811], [7, 6238]]

that is, list() and list.size() are consistent (and match an SQL query on the underlying database).

Does anyone have any ideas about why count() seems to off in this case? I find it interesting that the number returned by count() - 576 - is the same as the projection rowCount() for the first record returned...

For the time being, I guess I'll use query.list().size().

MonetsChemist
  • 165
  • 10
  • Are there 576 total rows in whatever table the `Runner` instances are stored in? – Jeff Scott Brown May 11 '18 at 15:31
  • No, there are 866062 rows in the table. – MonetsChemist May 11 '18 at 16:13
  • Just for interest, I ran the same query on a different property of the table - 'distanceRun'. The value returned by query.count() was 69449; the rowCount() for the first projection record returned was also 69449. Seems like this might be a clue. And the number of records actually returned was 42. – MonetsChemist May 11 '18 at 16:19
  • I just "discovered" that if I use a regular Criteria for this query and pass in offset, max parameters to ensure that a PageResultList is returned, the getTotalCount() call on that PagedResultList gives me back the total number of records in the domain class and not the number of projected records. So....... I'm guessing that the expected result from count() is also the total number of records in the domain class. Does that sound right? – MonetsChemist May 11 '18 at 16:56
  • I have filed an issue on Grails GitHub for this https://github.com/monetschemist/grails-where-count-problem – MonetsChemist May 15 '18 at 21:18

0 Answers0