borinquenkid commented on code in PR #16816: URL: https://github.com/apache/grails-core/pull/16816#discussion_r4434479539
########## 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: Addressed in d0ff76be16: `Query.In` with `in.getSubquery() != null` is now detected before scalar conversion and builds an `in` subquery predicate. ########## 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: Addressed in d0ff76be16: `Query.Equals` and `Query.NotEquals` now handle `null` (`cb.isNull` / `cb.isNotNull`), `QueryableCriteria` subqueries, and null-inclusive semantics for non-null `NotEquals`. ########## 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: Addressed in d0ff76be16: `findHandler` now walks `getSuperclass()` from nearest to farthest. ########## 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: Addressed in d0ff76be16: `Query.ILike` is now handled before `Query.Like` in `FunctionCallingCriterion` and renders `lower(function(property)) like lower(:pN)`. ########## 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: Addressed in d0ff76be16: `FunctionCallingCriterion` now checks `in.getSubquery() != null` and delegates to `buildSubQuery`, propagating parameter positions. ########## 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: Addressed in d0ff76be16: `i.next()` is now consumed before checking `i.hasNext()` when appending comma separators. -- 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]
