borinquenkid commented on code in PR #16816: URL: https://github.com/apache/grails-core/pull/16816#discussion_r4449306185
########## 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: Null operands now become IS NULL / IS NOT NULL. A non-null `!=` deliberately leaves null rows out, as Hibernate 5 and plain SQL do (see 781d0f355b), so I'm keeping that. ########## 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: Fixed at the branch tip: the function-wrapped `In` handles the subquery operand. ########## 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: Fixed at the branch tip: the function-wrapped `In` handles the subquery operand. ########## 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: Fixed at the branch tip: handler lookup walks the superclass chain. ########## 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: Fixed at the branch tip: ILike is checked before Like and renders as lower(..) like lower(..). ########## 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: No change: the loop calls next() before hasNext(), so no trailing separator is emitted. -- 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]
