Copilot commented on code in PR #16816: URL: https://github.com/apache/grails-core/pull/16816#discussion_r4433893471
########## grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/query/FunctionCallingCriterionHandler.java: ########## @@ -0,0 +1,110 @@ +/* + * 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.query; + +import java.util.ArrayList; +import java.util.Collection; + +import jakarta.persistence.criteria.Expression; +import jakarta.persistence.criteria.Predicate; + +import org.hibernate.query.criteria.HibernateCriteriaBuilder; + +import org.springframework.core.convert.ConversionService; + +import org.grails.datastore.mapping.core.exceptions.ConfigurationException; +import org.grails.datastore.mapping.query.Query; +import org.grails.datastore.mapping.query.criteria.FunctionCallingCriterion; + +/** + * Handles criteria that apply a SQL/HQL function to a property before comparison, + * such as {@code upper(name) == 'A'} or {@code year(birthDate) > 2000}. + * + * @since 8.0.1 + */ +public class FunctionCallingCriterionHandler implements InternalCriterionHandler<FunctionCallingCriterion> { + + @Override + @SuppressWarnings("unchecked") + public Predicate handle(CriterionContext context, FunctionCallingCriterion criterion) { + String functionName = criterion.getFunctionName(); + if (criterion.isOnValue()) { + throw new UnsupportedOperationException("A function on the value of a comparison is not supported: " + functionName); + } + Expression<?> propertyPath = context.resolvePath(criterion.getProperty()); + if (propertyPath == null) { + throw new ConfigurationException("Cannot resolve property [" + criterion.getProperty() + "] in a " + functionName + " function call"); + } + HibernateCriteriaBuilder criteriaBuilder = context.getCriteriaBuilder(); + Expression<?> left = applyFunction(criteriaBuilder, functionName, propertyPath); + Query.PropertyCriterion wrapped = criterion.getPropertyCriterion(); + Object value = convertFunctionValue(context.getConversionService(), functionName, wrapped.getValue()); Review Comment: A `Query.In` constructed with `QueryableCriteria` stores its operand in `getSubquery()` and leaves `getValues()` empty. This handler instead converts that operand as a scalar and later builds IN from the empty values collection, so a function query against a projected DetachedCriteria silently matches no rows. Detect the subquery before scalar conversion and build an IN subquery typed from the function expression. ########## grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/query/PredicateGenerator.java: ########## @@ -120,8 +89,99 @@ public interface CriterionHandlerProvider { public static final Map<Class<? extends Query.Criterion>, CriterionHandler> CUSTOM_HANDLERS = new ConcurrentHashMap<>(); + private static final Map<Class<? extends Query.QueryElement>, InternalCriterionHandler<?>> BUILTIN_HANDLERS = + new ConcurrentHashMap<>(); + private static final AtomicBoolean SERVICE_LOADERS_INITIALIZED = new AtomicBoolean(false); + static { + registerBuiltinHandlers(); + } + + private static void registerBuiltinHandlers() { + registerHandler(Query.IdEquals.class, (context, idEquals) -> { + String propertyName = context.getEntity().getIdentity().getName(); + Expression<?> propertyPath = context.resolvePath(propertyName); + return context.getCriteriaBuilder().equal(propertyPath, context.convertValue(propertyName, idEquals.getValue(), propertyPath)); + }); + registerHandler(SqlRestriction.class, new SqlRestrictionCriterionHandler()); + registerHandler(Query.DistinctProjection.class, (context, criterion) -> context.getCriteriaBuilder().conjunction()); + registerHandler(HibernateAlias.class, (context, criterion) -> null); + registerHandler(DetachedAssociationCriteria.class, AssociationCriterionHandler::handleDetachedAssociationCriteria); + registerHandler(HibernateAssociationQuery.class, AssociationCriterionHandler::handleHibernateAssociationQuery); + registerHandler(FunctionCallingCriterion.class, new FunctionCallingCriterionHandler()); + registerHandler(Query.Exists.class, new ExistsCriterionHandler()); + registerHandler(Query.NotExists.class, new NotExistsCriterionHandler()); + registerHandler(Query.Junction.class, new JunctionCriterionHandler()); + registerHandler(Query.Conjunction.class, new JunctionCriterionHandler()); + registerHandler(Query.Disjunction.class, new JunctionCriterionHandler()); + registerHandler(Query.Negation.class, new JunctionCriterionHandler()); + registerHandler(Query.SubqueryCriterion.class, new SubqueryCriterionHandler()); + registerHandler(Query.EqualsAll.class, new SubqueryCriterionHandler()); + registerHandler(Query.NotEqualsAll.class, new SubqueryCriterionHandler()); + registerHandler(Query.GreaterThanAll.class, new SubqueryCriterionHandler()); + registerHandler(Query.GreaterThanSome.class, new SubqueryCriterionHandler()); + registerHandler(Query.GreaterThanEqualsAll.class, new SubqueryCriterionHandler()); + registerHandler(Query.GreaterThanEqualsSome.class, new SubqueryCriterionHandler()); + registerHandler(Query.LessThanAll.class, new SubqueryCriterionHandler()); + registerHandler(Query.LessThanSome.class, new SubqueryCriterionHandler()); + registerHandler(Query.LessThanEqualsAll.class, new SubqueryCriterionHandler()); + registerHandler(Query.LessThanEqualsSome.class, new SubqueryCriterionHandler()); + registerHandler(Query.NotIn.class, new SubqueryCriterionHandler()); + registerHandler(Query.PropertyNameCriterion.class, new PropertyNameCriterionHandler()); + registerHandler(Query.IsNull.class, new PropertyNameCriterionHandler()); + registerHandler(Query.IsNotNull.class, new PropertyNameCriterionHandler()); + registerHandler(Query.IsEmpty.class, new PropertyNameCriterionHandler()); + registerHandler(Query.IsNotEmpty.class, new PropertyNameCriterionHandler()); + registerHandler(Query.PropertyComparisonCriterion.class, new PropertyComparisonCriterionHandler()); + registerHandler(Query.EqualsProperty.class, new PropertyComparisonCriterionHandler()); + registerHandler(Query.NotEqualsProperty.class, new PropertyComparisonCriterionHandler()); + registerHandler(Query.GreaterThanProperty.class, new PropertyComparisonCriterionHandler()); + registerHandler(Query.GreaterThanEqualsProperty.class, new PropertyComparisonCriterionHandler()); + registerHandler(Query.LessThanProperty.class, new PropertyComparisonCriterionHandler()); + registerHandler(Query.LessThanEqualsProperty.class, new PropertyComparisonCriterionHandler()); + registerHandler(Query.PropertyCriterion.class, new PropertyCriterionHandler()); + registerHandler(Query.Equals.class, new PropertyCriterionHandler()); + registerHandler(Query.NotEquals.class, new PropertyCriterionHandler()); + registerHandler(Query.Like.class, new PropertyCriterionHandler()); + registerHandler(Query.ILike.class, new PropertyCriterionHandler()); + registerHandler(Query.RLike.class, new PropertyCriterionHandler()); + registerHandler(Query.GreaterThan.class, new PropertyCriterionHandler()); + registerHandler(Query.GreaterThanEquals.class, new PropertyCriterionHandler()); + registerHandler(Query.LessThan.class, new PropertyCriterionHandler()); + registerHandler(Query.LessThanEquals.class, new PropertyCriterionHandler()); + registerHandler(Query.Between.class, new PropertyCriterionHandler()); + registerHandler(Query.In.class, new PropertyCriterionHandler()); + registerHandler(Query.SizeEquals.class, new PropertyCriterionHandler()); + registerHandler(Query.SizeNotEquals.class, new PropertyCriterionHandler()); + registerHandler(Query.SizeGreaterThan.class, new PropertyCriterionHandler()); + registerHandler(Query.SizeGreaterThanEquals.class, new PropertyCriterionHandler()); + registerHandler(Query.SizeLessThan.class, new PropertyCriterionHandler()); + registerHandler(Query.SizeLessThanEquals.class, new PropertyCriterionHandler()); + registerHandler(EqualsIgnoreCase.class, new PropertyCriterionHandler()); + } + + private static <T extends Query.QueryElement> void registerHandler(Class<T> type, InternalCriterionHandler<? super T> handler) { + BUILTIN_HANDLERS.put(type, handler); + } + + @SuppressWarnings("unchecked") + private static InternalCriterionHandler<Query.QueryElement> findHandler(Class<?> criterionClass) { + InternalCriterionHandler<?> handler = BUILTIN_HANDLERS.get(criterionClass); + if (handler != null) { + return (InternalCriterionHandler<Query.QueryElement>) handler; + } + + for (Map.Entry<Class<? extends Query.QueryElement>, InternalCriterionHandler<?>> entry : BUILTIN_HANDLERS.entrySet()) { + if (entry.getKey().isAssignableFrom(criterionClass)) { + InternalCriterionHandler<?> matched = entry.getValue(); + BUILTIN_HANDLERS.put((Class<? extends Query.QueryElement>) criterionClass, matched); + return (InternalCriterionHandler<Query.QueryElement>) matched; + } + } Review Comment: The fallback selects the first assignable entry from an unordered map rather than the most specific registered superclass. An unregistered subclass of `Query.Equals` can therefore select `PropertyNameCriterionHandler`, which throws instead of performing equality, and that incorrect selection is cached. Walk the superclass chain from nearest to farthest before caching the handler. ########## grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/query/FunctionCallingCriterionHandler.java: ########## @@ -0,0 +1,110 @@ +/* + * 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.query; + +import java.util.ArrayList; +import java.util.Collection; + +import jakarta.persistence.criteria.Expression; +import jakarta.persistence.criteria.Predicate; + +import org.hibernate.query.criteria.HibernateCriteriaBuilder; + +import org.springframework.core.convert.ConversionService; + +import org.grails.datastore.mapping.core.exceptions.ConfigurationException; +import org.grails.datastore.mapping.query.Query; +import org.grails.datastore.mapping.query.criteria.FunctionCallingCriterion; + +/** + * Handles criteria that apply a SQL/HQL function to a property before comparison, + * such as {@code upper(name) == 'A'} or {@code year(birthDate) > 2000}. + * + * @since 8.0.1 + */ +public class FunctionCallingCriterionHandler implements InternalCriterionHandler<FunctionCallingCriterion> { + + @Override + @SuppressWarnings("unchecked") + public Predicate handle(CriterionContext context, FunctionCallingCriterion criterion) { + String functionName = criterion.getFunctionName(); + if (criterion.isOnValue()) { + throw new UnsupportedOperationException("A function on the value of a comparison is not supported: " + functionName); + } + Expression<?> propertyPath = context.resolvePath(criterion.getProperty()); + if (propertyPath == null) { + throw new ConfigurationException("Cannot resolve property [" + criterion.getProperty() + "] in a " + functionName + " function call"); + } + HibernateCriteriaBuilder criteriaBuilder = context.getCriteriaBuilder(); + Expression<?> left = applyFunction(criteriaBuilder, functionName, propertyPath); + Query.PropertyCriterion wrapped = criterion.getPropertyCriterion(); + Object value = convertFunctionValue(context.getConversionService(), functionName, wrapped.getValue()); + + if (wrapped instanceof Query.ILike) { + return criteriaBuilder.ilike((Expression<String>) left, (String) value); + } else if (wrapped instanceof Query.RLike rLike) { + return PropertyCriterionHandler.handleRLike(criteriaBuilder, (Expression<String>) left, rLike); + } else if (wrapped instanceof Query.Like) { + return criteriaBuilder.like((Expression<String>) left, (String) value); + } else if (wrapped instanceof Query.Equals) { + return criteriaBuilder.equal(left, value); + } else if (wrapped instanceof Query.NotEquals) { + return criteriaBuilder.notEqual(left, value); Review Comment: Function-wrapped comparisons bypass the normal null handling: upper(name) == null and upper(name) != null reach these branches as Equals/NotEquals with a null value, producing binary comparisons with NULL that match no rows. Non-null NotEquals also drops null function results, unlike PropertyCriterionHandler.handleNotEquals. Use IS NULL/IS NOT NULL for null operands and preserve the existing null-inclusive NotEquals behavior for non-null operands. ########## grails-datastore-core/src/main/groovy/org/grails/datastore/mapping/query/jpa/JpaQueryBuilder.java: ########## @@ -605,6 +606,44 @@ public int handle(PersistentEntity entity, Query.Criterion criterion, StringBuil } }); + queryHandlers.put(FunctionCallingCriterion.class, new QueryHandler() { + public int handle(PersistentEntity entity, Query.Criterion criterion, StringBuilder q, StringBuilder whereClause, String logicalName, int position, List parameters, ConversionService conversionService, boolean allowJoins, boolean hibernateCompatible) { + FunctionCallingCriterion functionCriterion = (FunctionCallingCriterion) criterion; + String name = functionCriterion.getProperty(); + validateProperty(entity, name, FunctionCallingCriterion.class); + if (functionCriterion.isOnValue()) { + throw new InvalidDataAccessResourceUsageException("A function on the value of a comparison is not supported: " + functionCriterion.getFunctionName()); + } + Query.PropertyCriterion wrapped = functionCriterion.getPropertyCriterion(); + whereClause.append(functionCriterion.getFunctionName()) + .append(OPEN_BRACKET) + .append(logicalName) + .append(DOT) + .append(name) + .append(CLOSE_BRACKET); + if (wrapped instanceof Query.In in) { + whereClause.append(" IN ("); + for (Iterator i = in.getValues().iterator(); i.hasNext();) { Review Comment: For `new Query.In(property, queryableCriteria)`, `getValues()` is empty and the actual operand is exposed by `getSubquery()`. Ignoring it here renders `function(property) IN ()` instead of the requested subselect, causing function-based bulk update/delete restrictions with a subquery to fail. Add subquery rendering and propagate the parameter positions it consumes. ########## grails-datastore-core/src/main/groovy/org/grails/datastore/mapping/query/jpa/JpaQueryBuilder.java: ########## @@ -605,6 +606,44 @@ public int handle(PersistentEntity entity, Query.Criterion criterion, StringBuil } }); + queryHandlers.put(FunctionCallingCriterion.class, new QueryHandler() { + public int handle(PersistentEntity entity, Query.Criterion criterion, StringBuilder q, StringBuilder whereClause, String logicalName, int position, List parameters, ConversionService conversionService, boolean allowJoins, boolean hibernateCompatible) { + FunctionCallingCriterion functionCriterion = (FunctionCallingCriterion) criterion; + String name = functionCriterion.getProperty(); + validateProperty(entity, name, FunctionCallingCriterion.class); + if (functionCriterion.isOnValue()) { + throw new InvalidDataAccessResourceUsageException("A function on the value of a comparison is not supported: " + functionCriterion.getFunctionName()); + } + Query.PropertyCriterion wrapped = functionCriterion.getPropertyCriterion(); + whereClause.append(functionCriterion.getFunctionName()) + .append(OPEN_BRACKET) + .append(logicalName) + .append(DOT) + .append(name) + .append(CLOSE_BRACKET); + if (wrapped instanceof Query.In in) { + whereClause.append(" IN ("); + for (Iterator i = in.getValues().iterator(); i.hasNext();) { + whereClause.append(PARAMETER_PREFIX).append(++position); + if (i.hasNext()) { + whereClause.append(COMMA); + } + parameters.add(i.next()); Review Comment: The iterator is not advanced until after the separator check, so `i.hasNext()` is always true inside this loop, including for the last element. A function-based IN query therefore renders `IN (:p1,:p2,)` (or `IN (:p1,)`), which fails to parse when `updateAll`/`deleteAll` executes it. Consume the current value before checking whether another separator is needed. ########## grails-datastore-core/src/main/groovy/org/grails/datastore/mapping/query/jpa/JpaQueryBuilder.java: ########## @@ -605,6 +606,44 @@ public int handle(PersistentEntity entity, Query.Criterion criterion, StringBuil } }); + queryHandlers.put(FunctionCallingCriterion.class, new QueryHandler() { + public int handle(PersistentEntity entity, Query.Criterion criterion, StringBuilder q, StringBuilder whereClause, String logicalName, int position, List parameters, ConversionService conversionService, boolean allowJoins, boolean hibernateCompatible) { + FunctionCallingCriterion functionCriterion = (FunctionCallingCriterion) criterion; + String name = functionCriterion.getProperty(); + validateProperty(entity, name, FunctionCallingCriterion.class); + if (functionCriterion.isOnValue()) { + throw new InvalidDataAccessResourceUsageException("A function on the value of a comparison is not supported: " + functionCriterion.getFunctionName()); + } + Query.PropertyCriterion wrapped = functionCriterion.getPropertyCriterion(); Review Comment: `Query.ILike` extends `Query.Like`, so `functionOperator` matches the Like check first and function-based case-insensitive restrictions become case-sensitive in bulk queries. Handle ILike separately here and render `lower(function(property)) LIKE lower(:pN)`, as the existing ILike handler does; simply returning `ILIKE` would break non-Hibernate JPQL consumers. -- 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: [email protected] For queries about this service, please contact Infrastructure at: [email protected]
