Skip to content

fix: resolve three where-query bugs (#14344, #14480, #14569) - #15460

Merged
jamesfredley merged 6 commits into
apache:7.0.xfrom
jamesfredley:fix/where-query-bugs
Feb 27, 2026
Merged

jamesfredley merged 6 commits into
apache:7.0.xfrom
jamesfredley:fix/where-query-bugs

Conversation

@jamesfredley

@jamesfredley jamesfredley commented Feb 26, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Fixes three long-standing where-query bugs verified through reproduction tests against the current 7.0.x codebase.

Reproducer app: https://github.com/jamesfredley/grails-where-query-bugs-pr1


Bug 1: size() not supported in JpaQueryBuilder (#14344)

Symptom: Using size() in a where query that goes through the JPA path (deleteAll(), updateAll()) throws:

Criterion of type class org.grails.datastore.mapping.query.Query$SizeEquals not supported

The Hibernate native path (list(), get()) handles size() correctly via AbstractHibernateCriterionAdapter, but the JPA path in JpaQueryBuilder had no handlers for size criteria.

Broken pattern:

Library.where { books.size() == 0 }.deleteAll()  // throws exception
Library.where { books.size() > 5 }.updateAll(active: false)  // throws exception

Root cause: JpaQueryBuilder.queryHandlers map was missing entries for Query.SizeEquals, SizeNotEquals, SizeGreaterThan, SizeGreaterThanEquals, SizeLessThan, and SizeLessThanEquals. These criterion types were never registered, so any size comparison hit the "not supported" fallback.

Fix: Register 6 size comparison query handlers in JpaQueryBuilder that generate SIZE(alias.property) <op> ?N JPQL, plus a shared handleSizeComparison() helper:

// JpaQueryBuilder.java - new handler (x6, one per operator)
queryHandlers.put(Query.SizeEquals.class, new QueryHandler() {
    public int handle(...) {
        return handleSizeComparison(entity, (Query.PropertyCriterion) criterion,
            whereClause, logicalName, position, parameters, conversionService, "=", hibernateCompatible);
    }
});

// Shared helper generates: SIZE(alias.property) = ?N
protected static int handleSizeComparison(..., String operator, ...) {
    whereClause.append("SIZE(").append(logicalName).append(DOT)
               .append(name).append(") ").append(operator)
               .append(PARAMETER_PREFIX).append(++position);
    parameters.add(size);
    return position;
}

Bug 2: countBy dynamic finder drops where clause (#14480)

Symptom: When calling countByX() on a DetachedCriteria built with .where{}, the where clause criteria are silently dropped. The count returns the total for the dynamic finder match, ignoring the where filter entirely.

Broken pattern:

def expensive = Product.where { price > 100.0 }
expensive.countByCategory('electronics')
// Expected: 2 (Laptop $999 + Monitor $499)
// Actual:   3 (all electronics - Mouse $29 included)

Root cause: CountByFinder.buildQuery() was missing the applyDetachedCriteria() call. Compare with FindAllByFinder which correctly includes it:

// FindAllByFinder.buildQuery() - CORRECT
protected Query buildQuery(...) {
    applyAdditionalCriteria(q, invocation.getCriteria());
    applyDetachedCriteria(q, invocation.getDetachedCriteria());  // applies where clause
    ...
}

// CountByFinder.buildQuery() - BEFORE FIX (missing line)
protected Query buildQuery(...) {
    applyAdditionalCriteria(q, invocation.getCriteria());
    // applyDetachedCriteria was never called!
    ...
}

Fix: One-line addition in CountByFinder.buildQuery():

applyDetachedCriteria(q, invocation.getDetachedCriteria());

Bug 3: DetachedCriteria.count() returns wrong value with projections (#14569)

Symptom: When a DetachedCriteria has user-defined projections (e.g., groupProperty + count()), calling .count() returns the wrong value - typically the count from the first grouped row instead of the number of result rows.

Broken pattern:

def criteria = new DetachedCriteria(OrderItem).build {
    projections {
        groupProperty('category')
        count()
    }
}
criteria.count()
// Expected: 2 (two categories: widgets, gadgets)
// Actual:   value from first group row's count projection

Root cause: DetachedCriteria.count() calls withPopulatedQuery() then appends query.projections().count() alongside the existing user projections. The generated SQL ends up as:

-- What gets generated (WRONG):
SELECT category, count(*), count(*) FROM order_item GROUP BY category
-- Returns first row's count, not the number of rows

-- What should happen:
SELECT count(*) FROM (SELECT category, count(*) FROM order_item GROUP BY category)

Fix: When user projections already exist, count() falls back to list().size() to get the correct row count:

Number count(Map args = Collections.emptyMap(), Closure additionalCriteria = null) {
    if (!projections.isEmpty()) {
        // User projections exist - count the grouped result rows
        return ((List) withPopulatedQuery(args, additionalCriteria) { Query query ->
            query.list()
        }).size()
    }
    // No user projections - standard count works correctly
    (Number) withPopulatedQuery(args, additionalCriteria) { Query query ->
        query.projections().count()
        query.singleResult()
    }
}

The single-argument count(Closure) overload was also updated to delegate to the main method instead of duplicating the (now-buggy) original logic.


Changes

File Module Change
JpaQueryBuilder.java grails-datastore-core Register 6 size comparison query handlers + handleSizeComparison() helper
CountByFinder.java grails-datamapping-core Add missing applyDetachedCriteria(q, invocation.getDetachedCriteria())
DetachedCriteria.groovy grails-datamapping-core When user projections exist, count() falls back to list().size()
WhereQueryOldIssueVerificationSpec.groovy grails-data-hibernate5-core New: 9 tests verifying 8 old where-query issues against 7.x

Verification

The new WhereQueryOldIssueVerificationSpec covers all 8 issues from the open where-query triage:

Issue Title Status
#14596 where-query wrong result if not assigned to var Fixed (already in 7.x)
#14622 multi-level association wrong result Fixed (already in 7.x)
#14480 countBy drops where clause Fixed in this PR
#11202 where queries not filtering in tests Fixed (already in 7.x)
#14636 many-to-many sorting exception Fixed (already in 7.x)
#14610 basic collection type 'in' query Pending (future PR, marked @PendingFeature)
#14569 count() with projections Fixed in this PR
#14600 findAllBy bidirectional hasMany Fixed (already in 7.x)

All existing tests pass: grails-data-hibernate5-core (585 tests), grails-datamapping-core, grails-datastore-core.

Fixes #14344
Fixes #14480
Fixes #14569

…he#14569)

- Add size() query handlers to JpaQueryBuilder for deleteAll/updateAll (apache#14344)
- Add missing applyDetachedCriteria call in CountByFinder (apache#14480)
- Fix DetachedCriteria.count() returning wrong value with projections (apache#14569)
- Add verification test spec covering 8 old where-query issues

Fixes apache#14344
Fixes apache#14480
Fixes apache#14569

Assisted-by: Claude Code <[email protected]>

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Fixes multiple long-standing GORM where-query inconsistencies across the JPA query builder, dynamic finders, and DetachedCriteria.count(), and adds a consolidated regression/verification spec for historical where-query issues.

Changes:

  • Add missing size() comparison criterion handlers to JpaQueryBuilder so deleteAll() / updateAll() can support size-based where queries.
  • Fix countBy* dynamic finder behavior to correctly apply detached criteria (where clause) during query building.
  • Adjust DetachedCriteria.count() behavior when user-defined projections exist to avoid returning incorrect values.

Reviewed changes

Copilot reviewed 4 out of 4 changed files in this pull request and generated 5 comments.

File Description
grails-datastore-core/src/main/groovy/org/grails/datastore/mapping/query/jpa/JpaQueryBuilder.java Registers size-comparison query handlers and implements SIZE(...) predicate generation.
grails-datamapping-core/src/main/groovy/org/grails/datastore/gorm/finders/CountByFinder.java Ensures detached criteria are applied so countBy* honors where-query restrictions.
grails-datamapping-core/src/main/groovy/grails/gorm/DetachedCriteria.groovy Changes count() behavior under projections to avoid incorrect counts.
grails-data-hibernate5/core/src/test/groovy/grails/gorm/tests/WhereQueryOldIssueVerificationSpec.groovy Adds a verification spec covering multiple historical where-query issues.

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

@jamesfredley jamesfredley self-assigned this Feb 26, 2026
@jamesfredley jamesfredley moved this to In Progress in Apache Grails Feb 26, 2026
@borinquenkid

Copy link
Copy Markdown
Member

I was very careful not to touch data mapping level because it could have effects on the other implementations. I would suggest making changes for 7.0 on the hibernate level and making changes on the data mapper level on the 8.0 branch to ensure the hibernate layer does not get affected.

@jdaugherty

Copy link
Copy Markdown
Contributor

The more I've thought about this, if this can't be supported by hibernate and it's not been supported by Grails historically, then this is really a feature request and not a bug request. We should fix this in Hibernate 7 (sounds like it already is) and clean up the error handling in Grails 7 to indicate it's not supported.

Remove unused DetachedCriteria and Transactional imports from the
verification test spec.

Assisted-by: Claude Code <[email protected]>
When user-defined projections exist, count() falls back to list().size()
due to a Hibernate 5 limitation. Log a warning so developers are aware
of the potential performance and memory implications.

Assisted-by: Claude Code <[email protected]>
@jamesfredley

Copy link
Copy Markdown
Contributor Author

The following comment and warning have been added.

            // This will be resolved properly in Grails 8 with Hibernate 7's
            // JpaSelectCriteria.from(Subquery) support for derived tables.
            log.warn('DetachedCriteria.count() with user-defined projections cannot use a SQL count query ' +
                    'due to a Hibernate 5 limitation. All grouped result rows will be loaded into memory to ' +
                    'determine the count. This may impact performance on large result sets. ' +
                    'This will be resolved in Grails 8 (Hibernate 7) which supports derived table subqueries.')
            return ((List) withPopulatedQuery(args, additionalCriteria) { Query query ->
                query.list()
            }).size()

@jamesfredley
jamesfredley dismissed jdaugherty’s stale review February 27, 2026 21:13

added a comment and log.warn() when the "correct" but slow solution executes.

@jamesfredley
jamesfredley merged commit 0f33370 into apache:7.0.x Feb 27, 2026
27 checks passed
@github-project-automation github-project-automation Bot moved this from In Progress to Done in Apache Grails Feb 27, 2026
@jamesfredley
jamesfredley deleted the fix/where-query-bugs branch February 27, 2026 21:22
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

Status: Done

5 participants