You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@grails.apache.org by bo...@apache.org on 2026/04/15 20:48:36 UTC
(grails-core) 07/24: H7 fix Query Generation
This is an automated email from the ASF dual-hosted git repository.
borinquenkid pushed a commit to branch 8.0.x-hibernate7-dev
in repository https://gitbox.apache.org/repos/asf/grails-core.git
commit edbe4f4879d257abb2b543fd0d11f287c4c4e6b8
Author: Walter Duque de Estrada <wb...@mac.com>
AuthorDate: Mon Apr 13 14:42:48 2026 -0500
H7 fix Query Generation
---
.../grails/orm/hibernate/query/AliasRegistry.java | 78 ++++
.../orm/hibernate/query/ExpressionResolver.java | 129 ++++++
.../grails/orm/hibernate/query/JoinTracker.java | 62 +++
.../hibernate/query/JpaCriteriaQueryCreator.java | 124 ++++--
.../orm/hibernate/query/JpaQueryContext.java | 206 +++-------
.../orm/hibernate/query/PredicateGenerator.java | 450 +++++++++++++--------
.../hibernatequery/PredicateGeneratorSpec.groovy | 90 +++--
.../orm/hibernate/query/AliasRegistrySpec.groovy | 97 +++++
.../hibernate/query/ExpressionResolverSpec.groovy | 136 +++++++
.../orm/hibernate/query/JoinTrackerSpec.groovy | 75 ++++
.../orm/hibernate/query/JpaQueryContextSpec.groovy | 99 +++++
11 files changed, 1156 insertions(+), 390 deletions(-)
diff --git a/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/query/AliasRegistry.java b/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/query/AliasRegistry.java
new file mode 100644
index 0000000000..4c834fc43c
--- /dev/null
+++ b/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/query/AliasRegistry.java
@@ -0,0 +1,78 @@
+/*
+ * Copyright 2024-2025 the original author or authors.
+ *
+ * Licensed 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 jakarta.persistence.criteria.Expression;
+import java.util.HashMap;
+import java.util.Map;
+
+/**
+ * Registry for user-defined and auto-generated aliases in a JPA query.
+ *
+ * @author walterduquedeestrada
+ * @since 7.0.0
+ */
+public class AliasRegistry {
+ private final Map<String, HibernateAlias> definitions = new HashMap<>();
+ private final Map<String, Expression<?>> realizedExpressions = new HashMap<>();
+ private final AliasRegistry parent;
+
+ public AliasRegistry() {
+ this.parent = null;
+ }
+
+ public AliasRegistry(AliasRegistry parent) {
+ this.parent = parent;
+ }
+
+ public void define(String alias, HibernateAlias definition) {
+ definitions.put(alias, definition);
+ }
+
+ public void realize(String alias, Expression<?> expression) {
+ realizedExpressions.put(alias, expression);
+ }
+
+ public boolean isDefined(String alias) {
+ if (definitions.containsKey(alias) || realizedExpressions.containsKey(alias)) {
+ return true;
+ }
+ if (parent != null) {
+ return parent.isDefined(alias);
+ }
+ return false;
+ }
+
+ public HibernateAlias getDefinition(String alias) {
+ HibernateAlias def = definitions.get(alias);
+ if (def == null && parent != null) {
+ return parent.getDefinition(alias);
+ }
+ return def;
+ }
+
+ public Expression<?> getRealized(String alias) {
+ Expression<?> expr = realizedExpressions.get(alias);
+ if (expr == null && parent != null) {
+ return parent.getRealized(alias);
+ }
+ return expr;
+ }
+
+ public boolean hasRealized(String alias) {
+ return realizedExpressions.containsKey(alias) || (parent != null && parent.hasRealized(alias));
+ }
+}
diff --git a/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/query/ExpressionResolver.java b/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/query/ExpressionResolver.java
new file mode 100644
index 0000000000..2c46a90bbc
--- /dev/null
+++ b/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/query/ExpressionResolver.java
@@ -0,0 +1,129 @@
+/*
+ * Copyright 2024-2025 the original author or authors.
+ *
+ * Licensed 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 jakarta.persistence.criteria.Expression;
+import jakarta.persistence.criteria.From;
+import jakarta.persistence.criteria.Path;
+
+/**
+ * Resolves string paths and aliases into JPA Expressions and Paths.
+ *
+ * @author walterduquedeestrada
+ * @since 7.0.0
+ */
+public class ExpressionResolver {
+ private final AliasRegistry aliasRegistry;
+ private final JoinTracker joinTracker;
+
+ public ExpressionResolver(AliasRegistry aliasRegistry, JoinTracker joinTracker) {
+ this.aliasRegistry = aliasRegistry;
+ this.joinTracker = joinTracker;
+ }
+
+ public Expression<?> resolve(String path) {
+ if (path == null) return null;
+
+ if (path.equals("{alias}") || path.equals("root")) {
+ return joinTracker.getRoot();
+ }
+ if (path.startsWith("{alias}.")) {
+ return getPath(joinTracker.getRoot(), path.substring(8));
+ }
+
+ String cleanPath = path;
+ if (cleanPath.startsWith("root.")) {
+ cleanPath = cleanPath.substring(5);
+ }
+
+ // 1. Check for materialized aliases (Materialized Selects/Joins)
+ if (aliasRegistry.hasRealized(cleanPath)) {
+ return aliasRegistry.getRealized(cleanPath);
+ }
+
+ // 2. Handle alias:property
+ if (cleanPath.contains(grails.orm.HibernateCriteriaBuilder.ALIAS_SEPARATOR)) {
+ String[] parts = cleanPath.split(grails.orm.HibernateCriteriaBuilder.ALIAS_SEPARATOR);
+ return resolveFromAlias(parts[0], parts[1]);
+ }
+
+ // 3. Handle alias.property
+ if (cleanPath.contains(".")) {
+ int dotIdx = cleanPath.indexOf(".");
+ String aliasCandidate = cleanPath.substring(0, dotIdx);
+ if (aliasRegistry.isDefined(aliasCandidate)) {
+ return resolveFromAlias(aliasCandidate, cleanPath.substring(dotIdx + 1));
+ }
+ }
+
+ // 4. Check Join Tracker (Already joined paths)
+ From<?, ?> joined = joinTracker.getJoin(cleanPath);
+ if (joined != null) {
+ return joined;
+ }
+
+ // 5. Fallback to Root path resolution
+ return getPath(joinTracker.getRoot(), cleanPath);
+ }
+
+ private Expression<?> resolveFromAlias(String alias, String subPath) {
+ // 1. Check if already realized in THIS or PARENT registry
+ Expression<?> aliased = aliasRegistry.getRealized(alias);
+ if (aliased != null) {
+ if (aliased instanceof From<?, ?> from) {
+ return getPath(from, subPath);
+ }
+ return aliased; // It's a non-From expression (projection alias)
+ }
+
+ // 2. Check if already joined in THIS or PARENT JoinTracker (correlated joins)
+ aliased = joinTracker.getJoin(alias);
+ if (aliased != null) {
+ aliasRegistry.realize(alias, aliased);
+ return getPath((From<?, ?>) aliased, subPath);
+ }
+
+ // 3. If defined but not joined, materialize it on the CURRENT root
+ if (aliasRegistry.isDefined(alias)) {
+ HibernateAlias def = aliasRegistry.getDefinition(alias);
+ if (def != null && def.path() != null) {
+ aliased = joinTracker.getRoot().join(def.path(), def.joinType());
+ aliasRegistry.realize(alias, aliased);
+ joinTracker.addJoin(alias, (From<?, ?>) aliased);
+ return getPath((From<?, ?>) aliased, subPath);
+ }
+ }
+
+ return null;
+ }
+
+ private Path<?> getPath(From<?, ?> from, String path) {
+ if (from == null || path == null) return null;
+ try {
+ if (path.contains(".")) {
+ String[] parts = path.split("\\.");
+ Path<?> p = from;
+ for (String part : parts) {
+ p = p.get(part);
+ }
+ return p;
+ }
+ return from.get(path);
+ } catch (Exception e) {
+ return null;
+ }
+ }
+}
diff --git a/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/query/JoinTracker.java b/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/query/JoinTracker.java
new file mode 100644
index 0000000000..8539111d23
--- /dev/null
+++ b/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/query/JoinTracker.java
@@ -0,0 +1,62 @@
+/*
+ * Copyright 2024-2025 the original author or authors.
+ *
+ * Licensed 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 jakarta.persistence.criteria.From;
+import java.util.HashMap;
+import java.util.Map;
+
+/**
+ * Tracks physical JPA Joins and Roots to ensure consistency and avoid duplicate joins.
+ *
+ * @author walterduquedeestrada
+ * @since 7.0.0
+ */
+public class JoinTracker {
+ private final Map<String, From<?, ?>> joinsByPath = new HashMap<>();
+ private From<?, ?> root;
+ private final JoinTracker parent;
+
+ public JoinTracker(From<?, ?> root) {
+ this.root = root;
+ this.parent = null;
+ }
+
+ public JoinTracker(JoinTracker parent, From<?, ?> root) {
+ this.root = root;
+ this.parent = parent;
+ }
+
+ public void addJoin(String path, From<?, ?> from) {
+ joinsByPath.put(path, from);
+ }
+
+ public From<?, ?> getJoin(String path) {
+ From<?, ?> join = joinsByPath.get(path);
+ if (join == null && parent != null) {
+ return parent.getJoin(path);
+ }
+ return join;
+ }
+
+ public From<?, ?> getRoot() {
+ return root;
+ }
+
+ public void setRoot(From<?, ?> root) {
+ this.root = root;
+ }
+}
diff --git a/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/query/JpaCriteriaQueryCreator.java b/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/query/JpaCriteriaQueryCreator.java
index b1803a5a9b..dd8f555227 100644
--- a/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/query/JpaCriteriaQueryCreator.java
+++ b/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/query/JpaCriteriaQueryCreator.java
@@ -25,12 +25,15 @@ import jakarta.persistence.criteria.From;
import jakarta.persistence.criteria.Root;
import jakarta.persistence.criteria.Selection;
import org.grails.datastore.mapping.model.PersistentEntity;
+import org.grails.datastore.gorm.query.criteria.DetachedAssociationCriteria;
import org.grails.datastore.mapping.query.Query;
+import org.grails.orm.hibernate.cfg.domainbinding.hibernate.GrailsHibernatePersistentEntity;
import org.hibernate.query.criteria.HibernateCriteriaBuilder;
import org.hibernate.query.criteria.JpaCriteriaQuery;
import org.hibernate.query.criteria.JpaSubQuery;
import org.springframework.core.convert.ConversionService;
+import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
@@ -45,10 +48,11 @@ public class JpaCriteriaQueryCreator<T> {
private final Query.ProjectionList projections;
private final HibernateCriteriaBuilder criteriaBuilder;
- private final PersistentEntity entity;
+ private final GrailsHibernatePersistentEntity entity;
private final DetachedCriteria<?> detachedCriteria;
private final ConversionService conversionService;
private final HibernateQuery hibernateQuery;
+ private JpaQueryContext parentContext;
public JpaCriteriaQueryCreator(
Query.ProjectionList projections,
@@ -56,13 +60,13 @@ public class JpaCriteriaQueryCreator<T> {
PersistentEntity entity,
DetachedCriteria<?> detachedCriteria,
ConversionService conversionService) {
- this(projections, (HibernateCriteriaBuilder) criteriaBuilder, entity, detachedCriteria, conversionService, null);
+ this(projections, (HibernateCriteriaBuilder) criteriaBuilder, (GrailsHibernatePersistentEntity) entity, detachedCriteria, conversionService, null);
}
public JpaCriteriaQueryCreator(
Query.ProjectionList projections,
HibernateCriteriaBuilder criteriaBuilder,
- PersistentEntity entity,
+ GrailsHibernatePersistentEntity entity,
DetachedCriteria<?> detachedCriteria,
ConversionService conversionService,
HibernateQuery hibernateQuery) {
@@ -74,21 +78,40 @@ public class JpaCriteriaQueryCreator<T> {
this.hibernateQuery = hibernateQuery;
}
+ public void setParentContext(JpaQueryContext parentContext) {
+ this.parentContext = parentContext;
+ }
+
public JpaCriteriaQuery<?> createQuery() {
var projectionList = collectProjections();
var cq = createCriteriaQuery(projectionList);
Class<?> javaClass = entity.getJavaClass();
Root<?> root = cq.from(javaClass);
- var context = new JpaQueryContext(
- detachedCriteria,
- projectionList,
- hibernateQuery != null ? hibernateQuery.getAliases() : List.of(),
- root);
+
+ List<HibernateAlias> aliases = new ArrayList<>();
+ if (hibernateQuery != null) {
+ aliases.addAll(hibernateQuery.getAliases());
+ }
+ for (Query.Criterion criterion : detachedCriteria.getCriteria()) {
+ if (criterion instanceof HibernateAlias ha) {
+ aliases.add(ha);
+ }
+ }
+
+ var context = new JpaQueryContext(aliases, root);
+ if (parentContext != null) {
+ context.setParent(parentContext);
+ }
// Pass 1: Discover all projection aliases without full resolution
for (Query.Projection projection : projectionList) {
if (projection instanceof Query.PropertyProjection propertyProjection) {
+ if (propertyProjection.getPropertyName().contains(grails.orm.HibernateCriteriaBuilder.ALIAS_SEPARATOR)) {
+ String[] parts = propertyProjection.getPropertyName().split(grails.orm.HibernateCriteriaBuilder.ALIAS_SEPARATOR);
+ context.registerAlias(parts[0], new HibernateAlias(parts[0], parts[0]));
+ } else {
context.registerAliasFromPath(propertyProjection.getPropertyName());
+ }
} else if (projection instanceof Query.CountDistinctProjection countDistinctProjection) {
context.registerAliasFromPath(countDistinctProjection.getPropertyName());
}
@@ -104,20 +127,36 @@ public class JpaCriteriaQueryCreator<T> {
return cq;
}
+ @SuppressWarnings("unchecked")
public <T> void populateSubquery(JpaSubQuery<T> subquery) {
var projectionList = collectProjections();
Class<?> javaClass = entity.getJavaClass();
Root<?> root = subquery.from(javaClass);
- var context = new JpaQueryContext(
- detachedCriteria,
- projectionList,
- hibernateQuery != null ? hibernateQuery.getAliases() : List.of(),
- root);
+
+ List<HibernateAlias> aliases = new ArrayList<>();
+ if (hibernateQuery != null) {
+ aliases.addAll(hibernateQuery.getAliases());
+ }
+ for (Query.Criterion criterion : detachedCriteria.getCriteria()) {
+ if (criterion instanceof HibernateAlias ha) {
+ aliases.add(ha);
+ }
+ }
+
+ var context = new JpaQueryContext(aliases, root);
+ if (parentContext != null) {
+ context.setParent(parentContext);
+ }
// Pass 1: Discover all projection aliases
for (Query.Projection projection : projectionList) {
if (projection instanceof Query.PropertyProjection propertyProjection) {
+ if (propertyProjection.getPropertyName().contains(grails.orm.HibernateCriteriaBuilder.ALIAS_SEPARATOR)) {
+ String[] parts = propertyProjection.getPropertyName().split(grails.orm.HibernateCriteriaBuilder.ALIAS_SEPARATOR);
+ context.registerAlias(parts[0], new HibernateAlias(parts[0], parts[0]));
+ } else {
context.registerAliasFromPath(propertyProjection.getPropertyName());
+ }
} else if (projection instanceof Query.CountDistinctProjection countDistinctProjection) {
context.registerAliasFromPath(countDistinctProjection.getPropertyName());
}
@@ -129,14 +168,20 @@ public class JpaCriteriaQueryCreator<T> {
var translator = new JpaProjectionTranslator(criteriaBuilder, context);
- var aliasedProjections = new java.util.concurrent.atomic.AtomicInteger(0);
var projectionExpressions = projectionList.stream()
.map(translator::translate)
.filter(Objects::nonNull)
- .map(expr -> expr.alias("col_" + aliasedProjections.getAndIncrement()))
.toList();
if (!projectionExpressions.isEmpty()) {
- subquery.multiselect(projectionExpressions.toArray(new Selection<?>[0]));
+ if (projectionExpressions.size() > 1 || subquery.getResultType().equals(Tuple.class)) {
+ subquery.multiselect(projectionExpressions.toArray(new Selection<?>[0]));
+ } else {
+ subquery.select((Expression) projectionExpressions.get(0));
+ }
+ } else if (subquery.getResultType().equals(entity.getJavaClass())) {
+ subquery.select((Expression) root);
+ } else if (projectionList.isEmpty() && subquery.getResultType().equals(entity.getIdentity().getType())) {
+ subquery.select((Expression) root.get(entity.getIdentity().getName()));
}
Expression<?>[] groupByPaths = collectGroupProjections().stream()
@@ -155,12 +200,16 @@ public class JpaCriteriaQueryCreator<T> {
}
private JpaCriteriaQuery<?> createCriteriaQuery(List<Query.Projection> projections) {
- if (projections.size() > 1) {
+ List<Query.Projection> expressionProjections = projections.stream()
+ .filter(p -> !(p instanceof Query.DistinctProjection))
+ .toList();
+
+ if (expressionProjections.size() > 1) {
return (JpaCriteriaQuery<?>) criteriaBuilder.createTupleQuery();
- } else if (projections.isEmpty()) {
+ } else if (expressionProjections.isEmpty()) {
return (JpaCriteriaQuery<?>) criteriaBuilder.createQuery(entity.getJavaClass());
} else {
- var first = projections.get(0);
+ var first = expressionProjections.get(0);
if (first instanceof Query.CountProjection || first instanceof Query.CountDistinctProjection) {
return (JpaCriteriaQuery<?>) criteriaBuilder.createQuery(Long.class);
} else if (first instanceof Query.PropertyProjection propertyProjection) {
@@ -184,7 +233,7 @@ public class JpaCriteriaQueryCreator<T> {
@SuppressWarnings("unchecked")
private <T> void assignProjections(
List<Query.Projection> projections, CriteriaQuery<T> cq, JpaProjectionTranslator translator, JpaQueryContext context) {
- if (projections.stream().anyMatch(Query.DistinctProjection.class::isInstance)) {
+ if (projections.stream().anyMatch(p -> p instanceof Query.DistinctProjection || p instanceof Query.DistinctPropertyProjection)) {
cq.distinct(true);
}
var projectionExpressions = projections.stream()
@@ -192,7 +241,7 @@ public class JpaCriteriaQueryCreator<T> {
.filter(Objects::nonNull)
.toList();
if (!projectionExpressions.isEmpty()) {
- if (cq.getResultType().equals(Tuple.class)) {
+ if (cq.getResultType().equals(Tuple.class) && projectionExpressions.size() > 1) {
cq.select((Selection<? extends T>) criteriaBuilder.tuple(projectionExpressions.toArray(new Selection<?>[0])));
} else {
cq.select((Selection<? extends T>) projectionExpressions.get(0));
@@ -236,12 +285,41 @@ public class JpaCriteriaQueryCreator<T> {
}
}
+ private void discoverAliases(List<Query.Criterion> criteria, JpaQueryContext context) {
+ if (criteria == null) return;
+ for (Query.Criterion criterion : criteria) {
+ if (criterion instanceof HibernateAlias ha) {
+ // If the alias is already defined in parent and materialized, just link it
+ if (!context.hasAlias(ha.alias())) {
+ context.registerAlias(ha.alias(), ha);
+ }
+ } else if (criterion instanceof DetachedAssociationCriteria<?> dac) {
+ if (dac.getAlias() != null) {
+ context.registerAlias(dac.getAlias(), new HibernateAlias(dac.getAssociationPath(), dac.getAlias()));
+ }
+ discoverAliases(dac.getCriteria(), context);
+ } else if (criterion instanceof Query.PropertyNameCriterion pnc) {
+ String propertyName = pnc.getProperty();
+ if (propertyName.contains(".")) {
+ String alias = propertyName.substring(0, propertyName.indexOf("."));
+ // Only register if not already known in this or parent context
+ if (!context.hasAlias(alias)) {
+ context.registerAlias(alias, new HibernateAlias(alias, alias));
+ }
+ }
+ } else if (criterion instanceof Query.Junction junction) {
+ discoverAliases(junction.getCriteria(), context);
+ }
+ }
+ }
+
private void assignCriteria(
- AbstractQuery<?> cq, Root<?> root, JpaQueryContext context, PersistentEntity entity) {
+ AbstractQuery<?> cq, Root<?> root, JpaQueryContext context, GrailsHibernatePersistentEntity entity) {
List<Query.Criterion> criteriaList = detachedCriteria.getCriteria();
if (!criteriaList.isEmpty()) {
+ discoverAliases(criteriaList, context);
var predicateGenerator = new PredicateGenerator(criteriaBuilder, conversionService);
- var predicate = predicateGenerator.generate(criteriaList, cq, root, context, entity);
+ var predicate = predicateGenerator.generate(cq, root, criteriaList, context, entity);
if (predicate != null) {
cq.where(predicate);
}
diff --git a/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/query/JpaQueryContext.java b/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/query/JpaQueryContext.java
index 1f35fb706b..d65e61775c 100644
--- a/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/query/JpaQueryContext.java
+++ b/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/query/JpaQueryContext.java
@@ -18,212 +18,122 @@ package org.grails.orm.hibernate.query;
import jakarta.persistence.criteria.Expression;
import jakarta.persistence.criteria.From;
import jakarta.persistence.criteria.Path;
-import org.hibernate.query.criteria.JpaExpression;
-import java.util.HashMap;
import java.util.List;
-import java.util.Map;
-import grails.gorm.DetachedCriteria;
-import org.grails.datastore.mapping.model.PersistentEntity;
-import org.grails.datastore.mapping.query.Query;
/**
- * A class that provides the {@link From} and {@link Path} for a given alias or property path.
+ * Orchestrator for JPA query translation state (Aliases, Joins, Expressions).
*
- * @author burt
+ * TODO: Better separation of concerns between JpaQueryContext and ExpressionResolver.
+ * It is a bit icky that AliasRegistry and JoinTracker are passed into ExpressionResolver.
+ *
+ * @author walterduquedeestrada
* @author graemerocher
* @since 7.0.0
*/
public class JpaQueryContext implements Cloneable {
- private final Map<String, From<?, ?>> fromMap = new HashMap<>();
- private final Map<String, Expression<?>> aliasMap = new HashMap<>();
- private From<?, ?> root;
+ private final AliasRegistry aliasRegistry;
+ private final JoinTracker joinTracker;
+ private final ExpressionResolver resolver;
+ private JpaQueryContext parent;
- public JpaQueryContext() {
+ public JpaQueryContext(From<?, ?> root) {
+ this(null, null, root);
}
- public JpaQueryContext(
- DetachedCriteria<?> detachedCriteria,
- List<Query.Projection> projections,
- List<HibernateAlias> aliases,
- From<?, ?> root) {
- this.root = root;
+ public JpaQueryContext(List<HibernateAlias> aliases, From<?, ?> root) {
+ this(null, aliases, root);
}
- /**
- * Constructor for PredicateGenerator subqueries.
- */
- public JpaQueryContext(
- JpaQueryContext parent,
- PersistentEntity entity,
- List<Query.Criterion> criteria,
- List<Object> arguments,
- Map<?, ?> fetchStrategies,
- Map<?, ?> joinTypes,
- From<?, ?> root) {
- this.root = root;
- if (parent != null) {
- this.fromMap.putAll(parent.fromMap);
- this.aliasMap.putAll(parent.aliasMap);
- }
+ public JpaQueryContext(JpaQueryContext parent, From<?, ?> root) {
+ this(parent, null, root);
}
/**
- * Constructor for simpler subqueries or clones.
+ * Internal constructor for subqueries and base initialization.
*/
- public JpaQueryContext(
- JpaQueryContext parent,
- DetachedCriteria<?> detachedCriteria,
- List<Object> aliases,
- From<?, ?> root) {
- this.root = root;
- if (parent != null) {
- this.fromMap.putAll(parent.fromMap);
- this.aliasMap.putAll(parent.aliasMap);
+ public JpaQueryContext(JpaQueryContext parent, List<HibernateAlias> aliases, From<?, ?> root) {
+ this.parent = parent;
+ this.joinTracker = new JoinTracker(parent != null ? parent.getJoinTracker() : null, root);
+ this.aliasRegistry = new AliasRegistry(parent != null ? parent.getAliasRegistry() : null);
+ this.resolver = new ExpressionResolver(aliasRegistry, joinTracker);
+ if (aliases != null) {
+ for (HibernateAlias alias : aliases) {
+ aliasRegistry.define(alias.alias(), alias);
+ }
+ }
+ if (root != null) {
+ this.joinTracker.addJoin("root", root);
}
}
+ protected JoinTracker getJoinTracker() {
+ return joinTracker;
+ }
+
+ protected AliasRegistry getAliasRegistry() {
+ return aliasRegistry;
+ }
+
public void setRoot(From<?, ?> root) {
- this.root = root;
+ this.joinTracker.setRoot(root);
+ this.joinTracker.addJoin("root", root);
+ }
+
+ public void setParent(JpaQueryContext parent) {
+ this.parent = parent;
}
public From<?, ?> getRoot() {
- return root;
+ return joinTracker.getRoot();
}
public void addFrom(String path, From<?, ?> from) {
- fromMap.put(path, from);
+ joinTracker.addJoin(path, from);
}
public From<?, ?> getFrom(String path) {
- return fromMap.get(path);
+ return joinTracker.getJoin(path);
}
public void registerAlias(String alias, Expression<?> expression) {
- aliasMap.put(alias, expression);
+ aliasRegistry.realize(alias, expression);
+ }
+
+ public void registerAlias(String alias, HibernateAlias definition) {
+ aliasRegistry.define(alias, definition);
}
public void registerAliasFromPath(String path) {
if (path != null && path.contains(grails.orm.HibernateCriteriaBuilder.ALIAS_SEPARATOR)) {
String alias = path.split(grails.orm.HibernateCriteriaBuilder.ALIAS_SEPARATOR)[0];
- if (!aliasMap.containsKey(alias)) {
- aliasMap.put(alias, null); // Placeholder to mark it as a known alias
+ if (!aliasRegistry.isDefined(alias) && !aliasRegistry.hasRealized(alias)) {
+ aliasRegistry.define(alias, null); // Mark as known
}
}
}
public boolean hasAlias(String alias) {
- if (alias == null) return false;
- String key = alias;
- if (key.contains(grails.orm.HibernateCriteriaBuilder.ALIAS_SEPARATOR)) {
- key = key.split(grails.orm.HibernateCriteriaBuilder.ALIAS_SEPARATOR)[0];
- }
- return aliasMap.containsKey(key);
+ return aliasRegistry.isDefined(alias) || aliasRegistry.hasRealized(alias);
}
public Expression<?> getAliasedExpression(String alias) {
- if (alias == null) return null;
- String key = alias;
- if (key.contains(grails.orm.HibernateCriteriaBuilder.ALIAS_SEPARATOR)) {
- key = key.split(grails.orm.HibernateCriteriaBuilder.ALIAS_SEPARATOR)[0];
- }
-
- if (aliasMap.containsKey(key)) {
- return aliasMap.get(key);
- }
- if (key.startsWith("root.")) {
- String stripped = key.substring(5);
- if (aliasMap.containsKey(stripped)) {
- return aliasMap.get(stripped);
- }
- }
- return null;
+ return aliasRegistry.getRealized(alias);
}
public Expression<?> getFullyQualifiedExpression(String path) {
- Expression<?> aliased = getAliasedExpression(path);
- if (aliased != null) {
- return aliased;
- }
-
- if (path.equals("root")) {
- return root;
- }
-
- String propertyName = path;
- if (propertyName.startsWith("root.")) {
- propertyName = propertyName.substring(5);
- }
-
- String alias = null;
- if (propertyName.contains(grails.orm.HibernateCriteriaBuilder.ALIAS_SEPARATOR)) {
- String[] parts = propertyName.split(grails.orm.HibernateCriteriaBuilder.ALIAS_SEPARATOR);
- alias = parts[0];
- propertyName = parts[1];
- }
-
- Expression<?> expression = getAliasedExpression(alias != null ? alias : propertyName);
- if (expression == null) {
- expression = getFullyQualifiedPath(propertyName);
- }
-
- if (alias != null && expression instanceof JpaExpression) {
- ((JpaExpression<?>) expression).alias(alias);
- registerAlias(alias, expression);
- }
-
- return expression;
+ return resolver.resolve(path);
}
public Path<?> getFullyQualifiedPath(String path) {
- if (hasAlias(path)) {
- Expression<?> aliased = getAliasedExpression(path);
- if (aliased instanceof Path<?>) {
- return (Path<?>) aliased;
- }
- return null; // Known alias, not a path
- }
-
- String propertyName = path;
- if (propertyName.contains(grails.orm.HibernateCriteriaBuilder.ALIAS_SEPARATOR)) {
- propertyName = propertyName.split(grails.orm.HibernateCriteriaBuilder.ALIAS_SEPARATOR)[1];
- }
-
- if (propertyName.startsWith("root.")) {
- propertyName = propertyName.substring(5);
- }
-
- if (hasAlias(propertyName)) {
- Expression<?> aliased = getAliasedExpression(propertyName);
- if (aliased instanceof Path<?>) {
- return (Path<?>) aliased;
- }
- return null; // Known alias, not a path
- }
-
- if (propertyName.equals("root")) {
- return root;
- }
-
- String[] parts = propertyName.split("\\.");
- if (hasAlias(parts[0])) {
- return null;
- }
-
- Path<?> p = root;
- for (String part : parts) {
- p = p.get(part);
- }
- return p;
+ Expression<?> resolved = resolver.resolve(path);
+ return resolved instanceof Path<?> path1 ? path1 : null;
}
@Override
public JpaQueryContext clone() {
try {
- JpaQueryContext cloned = (JpaQueryContext) super.clone();
- cloned.fromMap.putAll(this.fromMap);
- cloned.aliasMap.putAll(this.aliasMap);
- return cloned;
+ return (JpaQueryContext) super.clone();
} catch (CloneNotSupportedException e) {
throw new AssertionError();
}
diff --git a/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/query/PredicateGenerator.java b/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/query/PredicateGenerator.java
index 90b1dd45b2..3d675404a5 100644
--- a/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/query/PredicateGenerator.java
+++ b/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/query/PredicateGenerator.java
@@ -18,59 +18,37 @@
*/
package org.grails.orm.hibernate.query;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Collection;
-import java.util.List;
-import java.util.Objects;
-import java.util.stream.Stream;
-
-import groovy.util.logging.Slf4j;
-
-import jakarta.persistence.criteria.AbstractQuery;
-import jakarta.persistence.criteria.CriteriaBuilder;
-import jakarta.persistence.criteria.CriteriaQuery;
-import jakarta.persistence.criteria.Expression;
-import jakarta.persistence.criteria.From;
-import jakarta.persistence.criteria.Path;
-import jakarta.persistence.criteria.Predicate;
-import jakarta.persistence.criteria.Root;
-import jakarta.persistence.criteria.Subquery;
-
-import org.hibernate.query.criteria.HibernateCriteriaBuilder;
-import org.hibernate.query.criteria.JpaExpression;
-import org.hibernate.query.criteria.JpaInPredicate;
-import org.hibernate.query.criteria.JpaSubQuery;
-import org.hibernate.query.sqm.tree.domain.SqmPath;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import org.springframework.core.convert.ConversionService;
-
import grails.gorm.DetachedCriteria;
-import org.grails.datastore.gorm.GormEntity;
+import jakarta.persistence.criteria.*;
import org.grails.datastore.gorm.query.criteria.DetachedAssociationCriteria;
-import org.grails.datastore.mapping.core.exceptions.ConfigurationException;
-import org.grails.datastore.mapping.model.PersistentEntity;
import org.grails.datastore.mapping.model.PersistentProperty;
-import org.grails.datastore.mapping.model.types.Association;
import org.grails.datastore.mapping.query.Query;
+import org.grails.datastore.mapping.query.Projections;
import org.grails.datastore.mapping.query.api.QueryableCriteria;
+import org.grails.datastore.mapping.core.exceptions.ConfigurationException;
+import org.grails.orm.hibernate.cfg.domainbinding.hibernate.GrailsHibernatePersistentEntity;
+import org.grails.orm.hibernate.cfg.domainbinding.hibernate.HibernatePersistentProperty;
+import org.grails.orm.hibernate.cfg.domainbinding.hibernate.HibernateToManyProperty;
+import org.hibernate.query.criteria.HibernateCriteriaBuilder;
+import org.hibernate.query.criteria.JpaSubQuery;
+import org.springframework.core.convert.ConversionService;
-@Slf4j
-@SuppressWarnings({
- "PMD.DataflowAnomalyAnalysis",
- "PMD.AvoidLiteralsInIfCondition",
- "PMD.AvoidDuplicateLiterals",
- "unchecked",
- "rawtypes"
-})
-public class PredicateGenerator {
+import java.util.Collection;
+import java.util.List;
+import java.util.Objects;
+import java.util.stream.Collectors;
- private static final Logger log = LoggerFactory.getLogger(PredicateGenerator.class);
+/**
+ * A class that generates predicates for a given list of criteria.
+ *
+ * @author walterduquedeestrada
+ * @author graemerocher
+ * @since 7.0.0
+ */
+public class PredicateGenerator {
- private final ConversionService conversionService;
private final HibernateCriteriaBuilder criteriaBuilder;
+ private final ConversionService conversionService;
public PredicateGenerator(HibernateCriteriaBuilder criteriaBuilder, ConversionService conversionService) {
this.criteriaBuilder = criteriaBuilder;
@@ -79,27 +57,22 @@ public class PredicateGenerator {
public Predicate[] getPredicates(
AbstractQuery<?> criteriaQuery,
- From<?, ?> root_,
- List<? extends Query.QueryElement> criteriaList,
+ From<?, ?> root,
+ List<? extends Query.QueryElement> criteria,
JpaQueryContext fromsByProvider,
- PersistentEntity entity) {
-
- List<Predicate> list = criteriaList.stream()
- .map(criterion -> handleCriterion(criteriaQuery, root_, fromsByProvider, entity, criterion))
+ GrailsHibernatePersistentEntity entity) {
+ return criteria.stream()
+ .map(c -> handleCriterion(criteriaQuery, root, fromsByProvider, entity, c))
.filter(Objects::nonNull)
- .toList();
-
- if (list.isEmpty()) {
- list = List.of(criteriaBuilder.equal(criteriaBuilder.literal(1), criteriaBuilder.literal(1)));
- }
- return list.toArray(new Predicate[0]);
+ .toList()
+ .toArray(new Predicate[0]);
}
- private Predicate handleCriterion(
+ public Predicate handleCriterion(
AbstractQuery<?> criteriaQuery,
From<?, ?> root,
JpaQueryContext fromsByProvider,
- PersistentEntity entity,
+ GrailsHibernatePersistentEntity entity,
Query.QueryElement criterion) {
if (criterion instanceof Query.Junction junction) {
@@ -110,6 +83,12 @@ public class PredicateGenerator {
return handleAssociationCriteria(criteriaQuery, fromsByProvider, c);
} else if (criterion instanceof HibernateAssociationQuery haq) {
return handleHibernateAssociationQuery(criteriaQuery, fromsByProvider, haq);
+ } else if (criterion instanceof Query.SubqueryCriterion c) {
+ return handleSubqueryCriterion(criteriaQuery, root, fromsByProvider, entity, c);
+ } else if (criterion instanceof Query.IdEquals idEquals) {
+ String propertyName = entity.getIdentity().getName();
+ Expression<?> propertyPath = fromsByProvider.getFullyQualifiedExpression(propertyName);
+ return criteriaBuilder.equal(propertyPath, convertValue(entity, propertyName, idEquals.getValue(), propertyPath));
} else if (criterion instanceof Query.PropertyCriterion pc) {
return handlePropertyCriterion(criteriaQuery, root, fromsByProvider, entity, pc);
} else if (criterion instanceof Query.PropertyComparisonCriterion c) {
@@ -118,168 +97,225 @@ public class PredicateGenerator {
return handlePropertyNameCriterion(fromsByProvider, c);
} else if (criterion instanceof Query.Exists c) {
return handleExists(
- criteriaQuery, root, fromsByProvider, c.getSubquery().getPersistentEntity(), c);
+ criteriaQuery, fromsByProvider, c);
} else if (criterion instanceof Query.NotExists c) {
- PersistentEntity childEntity = c.getSubquery().getPersistentEntity();
return criteriaBuilder.not(handleExists(
- criteriaQuery, root, fromsByProvider, childEntity, new Query.Exists(c.getSubquery())));
+ criteriaQuery, fromsByProvider, new Query.Exists(c.getSubquery())));
} else if (criterion instanceof HibernateAlias) {
return null; // Metadata only, handled by JpaQueryContext
}
throw new IllegalArgumentException("Unsupported criterion: " + criterion);
}
+ @SuppressWarnings("unchecked")
+ private Predicate handleSubqueryCriterion(AbstractQuery<?> criteriaQuery, From<?, ?> root, JpaQueryContext fromsByProvider, GrailsHibernatePersistentEntity entity, Query.SubqueryCriterion c) {
+ Expression<?> propertyPath = fromsByProvider.getFullyQualifiedExpression(c.getProperty());
+ QueryableCriteria qc = c.getValue();
+
+ // If it's a comparison criterion, we expect the subquery to return the same type as the property
+ Class<?> expectedType = propertyPath != null ? propertyPath.getJavaType() : qc.getPersistentEntity().getJavaClass();
+
+ Subquery<?> subquery = criteriaQuery.subquery(expectedType);
+ var creator = new JpaCriteriaQueryCreator(new Query.ProjectionList(), criteriaBuilder, (GrailsHibernatePersistentEntity) qc.getPersistentEntity(), (DetachedCriteria) qc, conversionService);
+ creator.setParentContext(fromsByProvider);
+
+ // If the subquery has no projections, we default to projecting the SAME property name if available on the subquery entity
+ if (qc.getProjections().isEmpty()) {
+ PersistentProperty prop = qc.getPersistentEntity().getPropertyByName(c.getProperty());
+ if (prop != null) {
+ qc.getProjections().add(Projections.property(c.getProperty()));
+ }
+ }
+
+ creator.populateSubquery((JpaSubQuery) subquery);
+
+ if (c instanceof Query.EqualsAll) {
+ return criteriaBuilder.equal(propertyPath, (Expression) criteriaBuilder.all(subquery));
+ } else if (c instanceof Query.NotEqualsAll) {
+ return criteriaBuilder.notEqual(propertyPath, (Expression) criteriaBuilder.all(subquery));
+ } else if (c instanceof Query.GreaterThanAll) {
+ return criteriaBuilder.greaterThan((Expression<? extends Comparable>) propertyPath, (Expression) criteriaBuilder.all(subquery));
+ } else if (c instanceof Query.GreaterThanSome) {
+ return criteriaBuilder.greaterThan((Expression<? extends Comparable>) propertyPath, (Expression) criteriaBuilder.some(subquery));
+ } else if (c instanceof Query.GreaterThanEqualsAll) {
+ return criteriaBuilder.greaterThanOrEqualTo((Expression<? extends Comparable>) propertyPath, (Expression) criteriaBuilder.all(subquery));
+ } else if (c instanceof Query.GreaterThanEqualsSome) {
+ return criteriaBuilder.greaterThanOrEqualTo((Expression<? extends Comparable>) propertyPath, (Expression) criteriaBuilder.some(subquery));
+ } else if (c instanceof Query.LessThanAll) {
+ return criteriaBuilder.lessThan((Expression<? extends Comparable>) propertyPath, (Expression) criteriaBuilder.all(subquery));
+ } else if (c instanceof Query.LessThanSome) {
+ return criteriaBuilder.lessThan((Expression<? extends Comparable>) propertyPath, (Expression) criteriaBuilder.some(subquery));
+ } else if (c instanceof Query.LessThanEqualsAll) {
+ return criteriaBuilder.lessThanOrEqualTo((Expression<? extends Comparable>) propertyPath, (Expression) criteriaBuilder.all(subquery));
+ } else if (c instanceof Query.LessThanEqualsSome) {
+ return criteriaBuilder.lessThanOrEqualTo((Expression<? extends Comparable>) propertyPath, (Expression) criteriaBuilder.some(subquery));
+ } else if (c instanceof Query.NotIn) {
+ return criteriaBuilder.not(propertyPath.in(subquery));
+ }
+
+ throw new UnsupportedOperationException("Unsupported subquery criterion: " + c.getClass().getName());
+ }
+
private Predicate handleJunction(
AbstractQuery<?> criteriaQuery,
From<?, ?> root_,
JpaQueryContext fromsByProvider,
- PersistentEntity entity,
+ GrailsHibernatePersistentEntity entity,
Query.Junction junction) {
- var predicates = getPredicates(criteriaQuery, root_, junction.getCriteria(), fromsByProvider, entity);
- if (junction instanceof Query.Disjunction) {
- return criteriaBuilder.or(predicates);
- } else if (junction instanceof Query.Conjunction) {
+ List<Query.Criterion> criteriaList = junction.getCriteria();
+ Predicate[] predicates = getPredicates(criteriaQuery, root_, criteriaList, fromsByProvider, entity);
+ if (junction instanceof Query.Conjunction) {
return criteriaBuilder.and(predicates);
+ } else if (junction instanceof Query.Disjunction) {
+ return criteriaBuilder.or(predicates);
} else if (junction instanceof Query.Negation) {
- if (predicates.length != 1) {
- log.error("Must have a single predicate behind a not");
- throw new RuntimeException("Must have a single predicate behind a not");
+ if (predicates.length > 1) {
+ throw new IllegalArgumentException("Negation does not support multiple predicates in this context. Use conjunction or disjunction within negation.");
}
- return criteriaBuilder.not(predicates[0]);
+ return criteriaBuilder.not(criteriaBuilder.and(predicates));
}
- return null;
+ throw new IllegalArgumentException("Unsupported junction: " + junction);
}
private Predicate handleAssociationCriteria(
AbstractQuery<?> criteriaQuery,
JpaQueryContext fromsByProvider,
- DetachedAssociationCriteria<?> c) {
-
- From<?, ?> child = (From<?, ?>) fromsByProvider.getFullyQualifiedPath(c.getAssociationPath());
- PersistentEntity associatedEntity = c.getAssociation().getAssociatedEntity();
-
- JpaQueryContext childTablesByName = new JpaQueryContext(
- fromsByProvider,
- associatedEntity,
- c.getCriteria(),
- java.util.Collections.emptyList(),
- c.getFetchStrategies(),
- c.getJoinTypes(),
- child);
-
- return criteriaBuilder.and(getPredicates(criteriaQuery, child, c.getCriteria(), childTablesByName, associatedEntity));
+ DetachedAssociationCriteria<?> associationCriteria) {
+ String associationName = associationCriteria.getAssociationPath();
+ From<?, ?> associationRoot = fromsByProvider.getFrom(associationName);
+ if (associationRoot == null) {
+ // Check if we already have it in our parent or alias map
+ Expression<?> expr = fromsByProvider.getFullyQualifiedExpression(associationName);
+ if (expr instanceof From<?,?> from) {
+ associationRoot = from;
+ } else {
+ associationRoot = fromsByProvider.getRoot().join(associationName);
+ fromsByProvider.addFrom(associationName, associationRoot);
+ }
+ }
+
+ // Create a nested context for this association
+ JpaQueryContext nestedContext = new JpaQueryContext(fromsByProvider, null, associationRoot);
+
+ GrailsHibernatePersistentEntity associatedEntity = (GrailsHibernatePersistentEntity) associationCriteria.getPersistentEntity();
+ List<Query.Criterion> criteriaList = associationCriteria.getCriteria();
+ return criteriaBuilder.and(getPredicates(criteriaQuery, associationRoot, criteriaList, nestedContext, associatedEntity));
}
private Predicate handleHibernateAssociationQuery(
AbstractQuery<?> criteriaQuery,
JpaQueryContext fromsByProvider,
- HibernateAssociationQuery haq) {
- From<?, ?> child = (From<?, ?>) fromsByProvider.getFullyQualifiedPath(haq.associationPath);
- JpaQueryContext childFroms = new JpaQueryContext(
- fromsByProvider,
- haq.getEntity(),
- haq.getAssociationCriteria(),
- java.util.Collections.emptyList(),
- java.util.Collections.emptyMap(),
- java.util.Collections.emptyMap(),
- child);
- return criteriaBuilder.and(
- getPredicates(criteriaQuery, child, haq.getAssociationCriteria(), childFroms, haq.getEntity()));
+ HibernateAssociationQuery associationQuery) {
+ String associationName = associationQuery.associationPath;
+ From<?, ?> associationRoot = fromsByProvider.getFrom(associationName);
+ if (associationRoot == null) {
+ Expression<?> expr = fromsByProvider.getFullyQualifiedExpression(associationName);
+ if (expr instanceof From<?,?> from) {
+ associationRoot = from;
+ } else {
+ associationRoot = fromsByProvider.getRoot().join(associationName, JoinType.INNER);
+ fromsByProvider.addFrom(associationName, associationRoot);
+ }
+ }
+
+ // Create a nested context for this association
+ JpaQueryContext nestedContext = new JpaQueryContext(fromsByProvider, null, associationRoot);
+
+ GrailsHibernatePersistentEntity associatedEntity = associationQuery.getEntity();
+ List<Query.Criterion> criteriaList = associationQuery.getAssociationCriteria();
+ return criteriaBuilder.and(getPredicates(criteriaQuery, associationRoot, criteriaList, nestedContext, associatedEntity));
}
+ @SuppressWarnings("unchecked")
private Predicate handlePropertyCriterion(
AbstractQuery<?> criteriaQuery,
From<?, ?> root,
JpaQueryContext fromsByProvider,
- PersistentEntity entity,
+ GrailsHibernatePersistentEntity entity,
Query.PropertyCriterion pc) {
-
String propertyName = pc.getProperty();
- if (!"id".equals(propertyName) &&
- !propertyName.contains(".") &&
- entity.getPropertyByName(propertyName) == null &&
- !fromsByProvider.hasAlias(propertyName)) {
- throw new ConfigurationException("Property [" + propertyName + "] is not a valid property of [" + entity.getName() + "]");
- }
-
Expression<?> propertyPath = fromsByProvider.getFullyQualifiedExpression(propertyName);
if (pc instanceof Query.Equals) {
- return handleEquals(criteriaQuery, pc, propertyPath);
+ return handleEquals(criteriaQuery, pc, propertyPath, fromsByProvider, entity);
} else if (pc instanceof Query.NotEquals) {
- return criteriaBuilder.not(handleEquals(criteriaQuery, pc, propertyPath));
- } else if (pc instanceof Query.Like) {
- return criteriaBuilder.like((Expression<String>) propertyPath, (String) convertValue(entity, propertyName, pc.getValue()));
+ return criteriaBuilder.not(handleEquals(criteriaQuery, pc, propertyPath, fromsByProvider, entity));
} else if (pc instanceof Query.ILike) {
- return criteriaBuilder.like(criteriaBuilder.lower((Expression<String>) propertyPath), ((String) convertValue(entity, propertyName, pc.getValue())).toLowerCase());
+ return criteriaBuilder.ilike((Expression<String>) propertyPath, (String) convertValue(entity, propertyName, pc.getValue(), propertyPath));
} else if (pc instanceof Query.RLike rLike) {
- return criteriaBuilder.like((Expression<String>) propertyPath, (String) convertValue(entity, propertyName, pc.getValue()));
+ return handleRLike((Expression<String>) propertyPath, rLike);
+ } else if (pc instanceof Query.Like) {
+ return criteriaBuilder.like((Expression<String>) propertyPath, (String) convertValue(entity, propertyName, pc.getValue(), propertyPath));
} else if (pc instanceof Query.GreaterThan) {
- Object value = convertValue(entity, propertyName, pc.getValue());
- if (value instanceof Number) {
- return criteriaBuilder.gt((Expression<? extends Number>) propertyPath, (Number) value);
- } else {
- return criteriaBuilder.greaterThan((Expression<? extends Comparable>) propertyPath, (Comparable) value);
- }
+ return criteriaBuilder.greaterThan((Expression<? extends Comparable>) propertyPath, (Expression) convertComparisonValue(entity, propertyName, pc.getValue(), fromsByProvider, propertyPath));
} else if (pc instanceof Query.GreaterThanEquals) {
- Object value = convertValue(entity, propertyName, pc.getValue());
- if (value instanceof Number) {
- return criteriaBuilder.ge((Expression<? extends Number>) propertyPath, (Number) value);
- } else {
- return criteriaBuilder.greaterThanOrEqualTo((Expression<? extends Comparable>) propertyPath, (Comparable) value);
- }
+ return criteriaBuilder.greaterThanOrEqualTo((Expression<? extends Comparable>) propertyPath, (Expression) convertComparisonValue(entity, propertyName, pc.getValue(), fromsByProvider, propertyPath));
} else if (pc instanceof Query.LessThan) {
- Object value = convertValue(entity, propertyName, pc.getValue());
- if (value instanceof Number) {
- return criteriaBuilder.lt((Expression<? extends Number>) propertyPath, (Number) value);
- } else {
- return criteriaBuilder.lessThan((Expression<? extends Comparable>) propertyPath, (Comparable) value);
- }
+ return criteriaBuilder.lessThan((Expression<? extends Comparable>) propertyPath, (Expression) convertComparisonValue(entity, propertyName, pc.getValue(), fromsByProvider, propertyPath));
} else if (pc instanceof Query.LessThanEquals) {
- Object value = convertValue(entity, propertyName, pc.getValue());
- if (value instanceof Number) {
- return criteriaBuilder.le((Expression<? extends Number>) propertyPath, (Number) value);
- } else {
- return criteriaBuilder.lessThanOrEqualTo((Expression<? extends Comparable>) propertyPath, (Comparable) value);
- }
+ return criteriaBuilder.lessThanOrEqualTo((Expression<? extends Comparable>) propertyPath, (Expression) convertComparisonValue(entity, propertyName, pc.getValue(), fromsByProvider, propertyPath));
} else if (pc instanceof Query.In) {
- Collection<?> values = (Collection<?>) pc.getValue();
- var in = criteriaBuilder.in(propertyPath);
- for (Object value : values) {
- ((CriteriaBuilder.In)in).value(convertValue(entity, propertyName, value));
+ Object value = pc.getValue();
+ if (value instanceof QueryableCriteria qc) {
+ Class<?> expectedType = propertyPath != null ? propertyPath.getJavaType() : qc.getPersistentEntity().getJavaClass();
+ Subquery<?> subquery = criteriaQuery.subquery(expectedType);
+ var creator = new JpaCriteriaQueryCreator(new Query.ProjectionList(), criteriaBuilder, (GrailsHibernatePersistentEntity) qc.getPersistentEntity(), (DetachedCriteria) qc, conversionService);
+ creator.setParentContext(fromsByProvider);
+ if (qc.getProjections().isEmpty() && propertyPath != null) {
+ PersistentProperty prop = qc.getPersistentEntity().getPropertyByName(propertyName);
+ if (prop != null) {
+ qc.getProjections().add(Projections.property(propertyName));
+ }
+ }
+ creator.populateSubquery((JpaSubQuery) subquery);
+ return propertyPath.in(subquery);
+ }
+ if (value instanceof Collection<?> collection) {
+ List<Object> converted = collection.stream()
+ .map(v -> convertValue(entity, propertyName, v, propertyPath))
+ .collect(Collectors.toList());
+ return propertyPath.in(converted);
}
- return in;
+ return propertyPath.in((Collection<?>) convertValue(entity, propertyName, value, propertyPath));
} else if (pc instanceof Query.Between between) {
- return criteriaBuilder.between((Expression<? extends Comparable>) propertyPath, (Comparable) convertValue(entity, propertyName, between.getFrom()), (Comparable) convertValue(entity, propertyName, between.getTo()));
- } else if (((Object)pc) instanceof Query.IsNull) {
- return criteriaBuilder.isNull(propertyPath);
- } else if (((Object)pc) instanceof Query.IsNotNull) {
- return criteriaBuilder.isNotNull(propertyPath);
- } else if (((Object)pc) instanceof Query.IsEmpty) {
- return criteriaBuilder.isEmpty((Expression<Collection>) propertyPath);
- } else if (((Object)pc) instanceof Query.IsNotEmpty) {
- return criteriaBuilder.isNotEmpty((Expression<Collection>) propertyPath);
- } else if (pc instanceof Query.SizeEquals sizeEquals) {
- return criteriaBuilder.equal(criteriaBuilder.size((Expression<Collection>) propertyPath), (Integer) sizeEquals.getValue());
- } else if (pc instanceof Query.SizeNotEquals sizeNotEquals) {
- return criteriaBuilder.notEqual(criteriaBuilder.size((Expression<Collection>) propertyPath), (Integer) sizeNotEquals.getValue());
- } else if (pc instanceof Query.SizeGreaterThan sizeGreaterThan) {
- return criteriaBuilder.gt(criteriaBuilder.size((Expression<Collection>) propertyPath), (Integer) sizeGreaterThan.getValue());
- } else if (pc instanceof Query.SizeGreaterThanEquals sizeGreaterThanEquals) {
- return criteriaBuilder.ge(criteriaBuilder.size((Expression<Collection>) propertyPath), (Integer) sizeGreaterThanEquals.getValue());
- } else if (pc instanceof Query.SizeLessThan sizeLessThan) {
- return criteriaBuilder.lt(criteriaBuilder.size((Expression<Collection>) propertyPath), (Integer) sizeLessThan.getValue());
- } else if (pc instanceof Query.SizeLessThanEquals sizeLessThanEquals) {
- return criteriaBuilder.le(criteriaBuilder.size((Expression<Collection>) propertyPath), (Integer) sizeLessThanEquals.getValue());
+ return criteriaBuilder.between((Expression<? extends Comparable>) propertyPath, (Comparable) convertValue(entity, propertyName, between.getFrom(), propertyPath), (Comparable) convertValue(entity, propertyName, between.getTo(), propertyPath));
+ } else if (pc instanceof Query.SizeEquals) {
+ return criteriaBuilder.equal(criteriaBuilder.size((Expression<java.util.Collection<?>>) propertyPath), (Integer) pc.getValue());
+ } else if (pc instanceof Query.SizeNotEquals) {
+ return criteriaBuilder.notEqual(criteriaBuilder.size((Expression<java.util.Collection<?>>) propertyPath), (Integer) pc.getValue());
+ } else if (pc instanceof Query.SizeGreaterThan) {
+ return criteriaBuilder.greaterThan(criteriaBuilder.size((Expression<java.util.Collection<?>>) propertyPath), (Integer) pc.getValue());
+ } else if (pc instanceof Query.SizeGreaterThanEquals) {
+ return criteriaBuilder.greaterThanOrEqualTo(criteriaBuilder.size((Expression<java.util.Collection<?>>) propertyPath), (Integer) pc.getValue());
+ } else if (pc instanceof Query.SizeLessThan) {
+ return criteriaBuilder.lessThan(criteriaBuilder.size((Expression<java.util.Collection<?>>) propertyPath), (Integer) pc.getValue());
+ } else if (pc instanceof Query.SizeLessThanEquals) {
+ return criteriaBuilder.lessThanOrEqualTo(criteriaBuilder.size((Expression<java.util.Collection<?>>) propertyPath), (Integer) pc.getValue());
}
throw new UnsupportedOperationException("Unsupported criterion: " + pc.getClass().getName());
}
+ private Predicate handleRLike(Expression<String> propertyPath, Query.RLike c) {
+ String pattern = c.getValue().toString().replaceAll("^/|/$", "");
+ return criteriaBuilder.equal(
+ criteriaBuilder.function(
+ GrailsRLikeFunctionContributor.RLIKE,
+ Boolean.class,
+ propertyPath,
+ criteriaBuilder.literal(pattern)),
+ true);
+ }
+
+ @SuppressWarnings("unchecked")
private Predicate handlePropertyComparisonCriterion(JpaQueryContext fromsByProvider, Query.PropertyComparisonCriterion c) {
Expression<?> propertyPath = fromsByProvider.getFullyQualifiedExpression(c.getProperty());
Expression<?> otherPropertyPath = fromsByProvider.getFullyQualifiedExpression(c.getOtherProperty());
+ if (propertyPath == null || otherPropertyPath == null) {
+ return null;
+ }
+
if (c instanceof Query.EqualsProperty) {
return criteriaBuilder.equal(propertyPath, otherPropertyPath);
} else if (c instanceof Query.NotEqualsProperty) {
@@ -304,46 +340,104 @@ public class PredicateGenerator {
} else if (((Object)c) instanceof Query.IsNotNull) {
return criteriaBuilder.isNotNull(propertyPath);
} else if (((Object)c) instanceof Query.IsEmpty) {
- return criteriaBuilder.isEmpty((Expression<Collection>) propertyPath);
+ return criteriaBuilder.isEmpty((Expression<java.util.Collection<?>>) propertyPath);
} else if (((Object)c) instanceof Query.IsNotEmpty) {
- return criteriaBuilder.isNotEmpty((Expression<Collection>) propertyPath);
+ return criteriaBuilder.isNotEmpty((Expression<java.util.Collection<?>>) propertyPath);
}
throw new UnsupportedOperationException("Unsupported property name criterion: " + c.getClass().getName());
}
- private Predicate handleEquals(AbstractQuery<?> criteriaQuery, Query.PropertyCriterion pc, Expression<?> propertyPath) {
+ @SuppressWarnings("unchecked")
+ private Predicate handleEquals(AbstractQuery<?> criteriaQuery, Query.PropertyCriterion pc, Expression<?> propertyPath, JpaQueryContext fromsByProvider, GrailsHibernatePersistentEntity entity) {
if (pc.getValue() instanceof QueryableCriteria qc) {
- Subquery<?> subquery = criteriaQuery.subquery(qc.getPersistentEntity().getJavaClass());
- new JpaCriteriaQueryCreator(new Query.ProjectionList(), criteriaBuilder, qc.getPersistentEntity(), (DetachedCriteria) qc, conversionService).populateSubquery((JpaSubQuery)subquery);
+ Class<?> expectedType = propertyPath != null ? propertyPath.getJavaType() : qc.getPersistentEntity().getJavaClass();
+ Subquery<?> subquery = criteriaQuery.subquery(expectedType);
+ var creator = new JpaCriteriaQueryCreator(new Query.ProjectionList(), criteriaBuilder, (GrailsHibernatePersistentEntity) qc.getPersistentEntity(), (DetachedCriteria) qc, conversionService);
+ creator.setParentContext(fromsByProvider);
+
+ if (qc.getProjections().isEmpty() && propertyPath != null) {
+ String propertyName = pc.getProperty();
+ if (propertyName.contains(grails.orm.HibernateCriteriaBuilder.ALIAS_SEPARATOR)) {
+ propertyName = propertyName.split(grails.orm.HibernateCriteriaBuilder.ALIAS_SEPARATOR)[1];
+ }
+ PersistentProperty prop = qc.getPersistentEntity().getPropertyByName(propertyName);
+ if (prop != null) {
+ qc.getProjections().add(Projections.property(propertyName));
+ }
+ }
+
+ creator.populateSubquery((JpaSubQuery)subquery);
return criteriaBuilder.equal(propertyPath, subquery);
} else {
- return criteriaBuilder.equal(propertyPath, convertValue(null, pc.getProperty(), pc.getValue()));
+ return criteriaBuilder.equal(propertyPath, convertComparisonValue(entity, pc.getProperty(), pc.getValue(), fromsByProvider, propertyPath));
}
}
+ @SuppressWarnings("unchecked")
private Predicate handleExists(
AbstractQuery<?> criteriaQuery,
- From<?, ?> root,
JpaQueryContext fromsByProvider,
- PersistentEntity entity,
Query.Exists exists) {
QueryableCriteria subqueryCriteria = exists.getSubquery();
- Subquery<?> subquery = criteriaQuery.subquery(entity.getJavaClass());
- new JpaCriteriaQueryCreator(new Query.ProjectionList(), criteriaBuilder, entity, (DetachedCriteria) subqueryCriteria, conversionService).populateSubquery((JpaSubQuery)subquery);
+ GrailsHibernatePersistentEntity subqueryEntity = (GrailsHibernatePersistentEntity) subqueryCriteria.getPersistentEntity();
+ Subquery<?> subquery = criteriaQuery.subquery(subqueryEntity.getJavaClass());
+ var creator = new JpaCriteriaQueryCreator(new Query.ProjectionList(), criteriaBuilder, subqueryEntity, (DetachedCriteria) subqueryCriteria, conversionService);
+ creator.setParentContext(fromsByProvider);
+ creator.populateSubquery((JpaSubQuery)subquery);
return criteriaBuilder.exists(subquery);
}
- private Object convertValue(PersistentEntity entity, String propertyName, Object value) {
+ private Object convertValue(GrailsHibernatePersistentEntity entity, String propertyName, Object value, Expression<?> propertyPath) {
if (value == null) {
- return null;
+ throw new ConfigurationException("Null value for property [" + propertyName + "] is not allowed in comparison criteria.");
}
- if (conversionService.canConvert(value.getClass(), Object.class)) {
- return conversionService.convert(value, Object.class);
+
+ Class<?> targetType = propertyPath != null ? propertyPath.getJavaType() : null;
+
+ if (targetType == null && entity != null) {
+ HibernatePersistentProperty prop = (HibernatePersistentProperty) entity.getPropertyByName(propertyName);
+ if (prop != null) {
+ targetType = prop.getType();
+ }
+ }
+
+ if (targetType != null && Collection.class.isAssignableFrom(targetType) && entity != null) {
+ HibernatePersistentProperty prop = (HibernatePersistentProperty) entity.getPropertyByName(propertyName);
+ if (prop instanceof HibernateToManyProperty toMany) {
+ targetType = toMany.getComponentType();
+ }
+ }
+
+ if (targetType != null && conversionService.canConvert(value.getClass(), targetType)) {
+ if (!Collection.class.isAssignableFrom(targetType) || Collection.class.isAssignableFrom(value.getClass())) {
+ return conversionService.convert(value, targetType);
+ }
}
return value;
}
- public Predicate generate(List<Query.Criterion> criteriaList, AbstractQuery<?> cq, From<?, ?> root, JpaQueryContext tablesByName, PersistentEntity entity) {
+ @SuppressWarnings("unchecked")
+ private Object convertComparisonValue(GrailsHibernatePersistentEntity entity, String propertyName, Object value, JpaQueryContext context, Expression<?> propertyPath) {
+ if (value instanceof PropertyArithmetic pa) {
+ Expression<Number> left = (Expression<Number>) context.getFullyQualifiedExpression(pa.propertyName());
+ Expression<Number> right = (Expression<Number>) criteriaBuilder.literal(pa.operand());
+
+ return switch (pa.operator()) {
+ case MULTIPLY -> criteriaBuilder.prod(left, right);
+ case DIVIDE -> criteriaBuilder.quot(left, right);
+ case ADD -> criteriaBuilder.sum(left, right);
+ case SUBTRACT -> criteriaBuilder.diff(left, right);
+ };
+ }
+ Object converted = convertValue(entity, propertyName, value, propertyPath);
+ if (!(converted instanceof Expression)) {
+ return criteriaBuilder.literal(converted);
+ }
+ return converted;
+ }
+
+ public Predicate generate(
+ AbstractQuery<?> cq, From<?, ?> root, List<Query.Criterion> criteriaList, JpaQueryContext tablesByName, GrailsHibernatePersistentEntity entity) {
Predicate[] predicates = getPredicates(cq, root, criteriaList, tablesByName, entity);
return criteriaBuilder.and(predicates);
}
diff --git a/grails-data-hibernate7/core/src/test/groovy/grails/gorm/specs/hibernatequery/PredicateGeneratorSpec.groovy b/grails-data-hibernate7/core/src/test/groovy/grails/gorm/specs/hibernatequery/PredicateGeneratorSpec.groovy
index 76faa884e2..3b5394d3af 100644
--- a/grails-data-hibernate7/core/src/test/groovy/grails/gorm/specs/hibernatequery/PredicateGeneratorSpec.groovy
+++ b/grails-data-hibernate7/core/src/test/groovy/grails/gorm/specs/hibernatequery/PredicateGeneratorSpec.groovy
@@ -25,9 +25,10 @@ import grails.gorm.specs.HibernateGormDatastoreSpec
import jakarta.persistence.criteria.CriteriaQuery
import jakarta.persistence.criteria.Expression
import jakarta.persistence.criteria.Root
+import org.hibernate.query.criteria.JpaExpression
import org.grails.datastore.mapping.model.PersistentEntity
import org.grails.datastore.mapping.query.Query
-
+import org.grails.orm.hibernate.cfg.domainbinding.hibernate.GrailsHibernatePersistentEntity
import org.grails.orm.hibernate.query.JpaQueryContext
import org.grails.orm.hibernate.query.PredicateGenerator
import org.grails.orm.hibernate.query.PropertyArithmetic
@@ -41,7 +42,7 @@ class PredicateGeneratorSpec extends HibernateGormDatastoreSpec {
CriteriaQuery query
Root root
JpaQueryContext fromProvider
- PersistentEntity personEntity
+ GrailsHibernatePersistentEntity personEntity
void setupSpec() {
manager.addAllDomainClasses([PredicateGeneratorSpecPerson, PredicateGeneratorSpecPet, PredicateGeneratorSpecFace])
@@ -51,9 +52,9 @@ class PredicateGeneratorSpec extends HibernateGormDatastoreSpec {
cb = sessionFactory.getCriteriaBuilder()
query = cb.createQuery(PredicateGeneratorSpecPerson)
root = query.from(PredicateGeneratorSpecPerson)
- personEntity = session.datastore.mappingContext.getPersistentEntity(PredicateGeneratorSpecPerson.name)
- fromProvider = new JpaQueryContext(new DetachedCriteria(PredicateGeneratorSpecPerson),[], root)
- predicateGenerator = new PredicateGenerator(session.datastore.mappingContext.conversionService)
+ personEntity = session.datastore.mappingContext.getPersistentEntity(PredicateGeneratorSpecPerson.name) as GrailsHibernatePersistentEntity
+ fromProvider = new JpaQueryContext(root)
+ predicateGenerator = new PredicateGenerator(cb, session.datastore.mappingContext.conversionService)
}
def "test getPredicates with Equals criterion"() {
@@ -61,7 +62,7 @@ class PredicateGeneratorSpec extends HibernateGormDatastoreSpec {
List criteria = [new Query.Equals("firstName", "Bob")]
when:
- def predicates = predicateGenerator.getPredicates(cb, query, root, criteria, fromProvider, personEntity)
+ def predicates = predicateGenerator.getPredicates(query, root, criteria, fromProvider, personEntity)
then:
predicates.length == 1
@@ -72,7 +73,7 @@ class PredicateGeneratorSpec extends HibernateGormDatastoreSpec {
List criteria = [new Query.Between("age", 20, 30)]
when:
- def predicates = predicateGenerator.getPredicates(cb, query, root, criteria, fromProvider, personEntity)
+ def predicates = predicateGenerator.getPredicates(query, root, criteria, fromProvider, personEntity)
then:
predicates.length == 1
@@ -83,7 +84,7 @@ class PredicateGeneratorSpec extends HibernateGormDatastoreSpec {
List criteria = [new Query.In("firstName", ["Bob", "Alice"])]
when:
- def predicates = predicateGenerator.getPredicates(cb, query, root, criteria, fromProvider, personEntity)
+ def predicates = predicateGenerator.getPredicates(query, root, criteria, fromProvider, personEntity)
then:
predicates.length == 1
@@ -96,7 +97,7 @@ class PredicateGeneratorSpec extends HibernateGormDatastoreSpec {
.add(new Query.Equals("lastName", "Smith"))]
when:
- def predicates = predicateGenerator.getPredicates(cb, query, root, criteria, fromProvider, personEntity)
+ def predicates = predicateGenerator.getPredicates(query, root, criteria, fromProvider, personEntity)
then:
predicates.length == 1
@@ -107,7 +108,7 @@ class PredicateGeneratorSpec extends HibernateGormDatastoreSpec {
List criteria = [new Query.Exists(new DetachedCriteria(PredicateGeneratorSpecPet).eq("name", "Lucky"))]
when:
- def predicates = predicateGenerator.getPredicates(cb, query, root, criteria, fromProvider, personEntity)
+ def predicates = predicateGenerator.getPredicates(query, root, criteria, fromProvider, personEntity)
then:
predicates.length == 1
@@ -119,7 +120,7 @@ class PredicateGeneratorSpec extends HibernateGormDatastoreSpec {
List criteria = [new Query.In("id", subCriteria)]
when:
- def predicates = predicateGenerator.getPredicates(cb, query, root, criteria, fromProvider, personEntity)
+ def predicates = predicateGenerator.getPredicates(query, root, criteria, fromProvider, personEntity)
then: "no exception thrown during subquery join creation"
noExceptionThrown()
@@ -133,9 +134,15 @@ class PredicateGeneratorSpec extends HibernateGormDatastoreSpec {
eq('f.name', 'Funny')
}
List criteria = [new Query.In("id", subCriteria)]
+
+ // Register the expected join response for face
+ def faceJoin = Mock(jakarta.persistence.criteria.Join)
+ def namePath = Mock(jakarta.persistence.criteria.Path)
+ // Note: In real scenarios creator would join, in this spec we are testing PredicateGenerator's ability
+ // to handle the subquery traversal.
when:
- def predicates = predicateGenerator.getPredicates(cb, query, root, criteria, fromProvider, personEntity)
+ def predicates = predicateGenerator.getPredicates(query, root, criteria, fromProvider, personEntity)
then: "the alias 'f' is correctly resolved"
noExceptionThrown()
@@ -149,7 +156,7 @@ class PredicateGeneratorSpec extends HibernateGormDatastoreSpec {
.add(new Query.Equals("firstName", "Alice"))]
when:
- def predicates = predicateGenerator.getPredicates(cb, query, root, criteria, fromProvider, personEntity)
+ def predicates = predicateGenerator.getPredicates(query, root, criteria, fromProvider, personEntity)
then:
predicates.length == 1
@@ -160,7 +167,7 @@ class PredicateGeneratorSpec extends HibernateGormDatastoreSpec {
List criteria = [new Query.Negation().add(new Query.Equals("firstName", "Bob"))]
when:
- def predicates = predicateGenerator.getPredicates(cb, query, root, criteria, fromProvider, personEntity)
+ def predicates = predicateGenerator.getPredicates(query, root, criteria, fromProvider, personEntity)
then:
predicates.length == 1
@@ -171,7 +178,7 @@ class PredicateGeneratorSpec extends HibernateGormDatastoreSpec {
List criteria = [new Query.EqualsProperty("firstName", "lastName")]
when:
- def predicates = predicateGenerator.getPredicates(cb, query, root, criteria, fromProvider, personEntity)
+ def predicates = predicateGenerator.getPredicates(query, root, criteria, fromProvider, personEntity)
then:
predicates.length == 1
@@ -185,7 +192,7 @@ class PredicateGeneratorSpec extends HibernateGormDatastoreSpec {
]
when:
- def predicates = predicateGenerator.getPredicates(cb, query, root, criteria, fromProvider, personEntity)
+ def predicates = predicateGenerator.getPredicates(query, root, criteria, fromProvider, personEntity)
then:
predicates.length == 2
@@ -196,7 +203,7 @@ class PredicateGeneratorSpec extends HibernateGormDatastoreSpec {
List criteria = [new Query.SizeEquals("pets", 2)]
when:
- def predicates = predicateGenerator.getPredicates(cb, query, root, criteria, fromProvider, personEntity)
+ def predicates = predicateGenerator.getPredicates(query, root, criteria, fromProvider, personEntity)
then:
predicates.length == 1
@@ -207,7 +214,7 @@ class PredicateGeneratorSpec extends HibernateGormDatastoreSpec {
List criteria = [new Query.GreaterThan("age", new PropertyArithmetic("salary", PropertyArithmetic.Operator.MULTIPLY, 10))]
when:
- def predicates = predicateGenerator.getPredicates(cb, query, root, criteria, fromProvider, personEntity)
+ def predicates = predicateGenerator.getPredicates(query, root, criteria, fromProvider, personEntity)
then:
predicates.length == 1
@@ -218,10 +225,11 @@ class PredicateGeneratorSpec extends HibernateGormDatastoreSpec {
List criteria = [new Query.In("nicknames", ["Bob", "Alice"])]
// Ensure nicknames is joined in fromProvider
- fromProvider = new JpaQueryContext(new DetachedCriteria(PredicateGeneratorSpecPerson), [], root)
+ fromProvider = new JpaQueryContext(root)
+ fromProvider.addFrom("nicknames", root.join("nicknames"))
when:
- def predicates = predicateGenerator.getPredicates(cb, query, root, criteria, fromProvider, personEntity)
+ def predicates = predicateGenerator.getPredicates(query, root, criteria, fromProvider, personEntity)
then:
predicates.length == 1
@@ -233,7 +241,7 @@ class PredicateGeneratorSpec extends HibernateGormDatastoreSpec {
List criteria = [new Query.DistinctProjection()]
when:
- def predicates = predicateGenerator.getPredicates(cb, query, root, criteria, fromProvider, personEntity)
+ def predicates = predicateGenerator.getPredicates(query, root, criteria, fromProvider, personEntity)
then:
predicates.length == 1
@@ -244,7 +252,7 @@ class PredicateGeneratorSpec extends HibernateGormDatastoreSpec {
List criteria = [new Query.NotExists(new DetachedCriteria(PredicateGeneratorSpecPet).eq("name", "Lucky"))]
when:
- def predicates = predicateGenerator.getPredicates(cb, query, root, criteria, fromProvider, personEntity)
+ def predicates = predicateGenerator.getPredicates(query, root, criteria, fromProvider, personEntity)
then:
predicates.length == 1
@@ -258,7 +266,7 @@ class PredicateGeneratorSpec extends HibernateGormDatastoreSpec {
]
when:
- def predicates = predicateGenerator.getPredicates(cb, query, root, criteria, fromProvider, personEntity)
+ def predicates = predicateGenerator.getPredicates(query, root, criteria, fromProvider, personEntity)
then:
predicates.length == 2
@@ -272,7 +280,7 @@ class PredicateGeneratorSpec extends HibernateGormDatastoreSpec {
]
when:
- def predicates = predicateGenerator.getPredicates(cb, query, root, criteria, fromProvider, personEntity)
+ def predicates = predicateGenerator.getPredicates(query, root, criteria, fromProvider, personEntity)
then:
predicates.length == 2
@@ -283,7 +291,7 @@ class PredicateGeneratorSpec extends HibernateGormDatastoreSpec {
List criteria = [new Query.NotEqualsProperty("firstName", "lastName")]
when:
- def predicates = predicateGenerator.getPredicates(cb, query, root, criteria, fromProvider, personEntity)
+ def predicates = predicateGenerator.getPredicates(query, root, criteria, fromProvider, personEntity)
then:
predicates.length == 1
@@ -299,7 +307,7 @@ class PredicateGeneratorSpec extends HibernateGormDatastoreSpec {
]
when:
- def predicates = predicateGenerator.getPredicates(cb, query, root, criteria, fromProvider, personEntity)
+ def predicates = predicateGenerator.getPredicates(query, root, criteria, fromProvider, personEntity)
then:
predicates.length == 4
@@ -311,7 +319,7 @@ class PredicateGeneratorSpec extends HibernateGormDatastoreSpec {
List<Query.QueryElement> criteria = [unsupportedCriterion]
when:
- predicateGenerator.getPredicates(cb, query, root, criteria, fromProvider, personEntity)
+ predicateGenerator.getPredicates(query, root, criteria, fromProvider, personEntity)
then:
thrown(IllegalArgumentException)
@@ -323,7 +331,7 @@ class PredicateGeneratorSpec extends HibernateGormDatastoreSpec {
List criteria = [alias, new Query.Equals("firstName", "Bob")]
when:
- def predicates = predicateGenerator.getPredicates(cb, query, root, criteria, fromProvider, personEntity)
+ def predicates = predicateGenerator.getPredicates(query, root, criteria, fromProvider, personEntity)
then:
predicates.length == 1
@@ -337,7 +345,7 @@ class PredicateGeneratorSpec extends HibernateGormDatastoreSpec {
List criteria = [negation]
when:
- predicateGenerator.getPredicates(cb, query, root, criteria, fromProvider, personEntity)
+ predicateGenerator.getPredicates(query, root, criteria, fromProvider, personEntity)
then:
thrown(RuntimeException)
@@ -348,7 +356,7 @@ class PredicateGeneratorSpec extends HibernateGormDatastoreSpec {
List criteria = [new Query.Equals("nonExistentProperty", "value")]
when:
- predicateGenerator.getPredicates(cb, query, root, criteria, fromProvider, personEntity)
+ predicateGenerator.getPredicates(query, root, criteria, fromProvider, personEntity)
then:
thrown(Exception)
@@ -359,7 +367,7 @@ class PredicateGeneratorSpec extends HibernateGormDatastoreSpec {
List criteria = [new Query.NotEquals("firstName", "Bob")]
when:
- def predicates = predicateGenerator.getPredicates(cb, query, root, criteria, fromProvider, personEntity)
+ def predicates = predicateGenerator.getPredicates(query, root, criteria, fromProvider, personEntity)
then:
predicates.length == 1
@@ -370,7 +378,7 @@ class PredicateGeneratorSpec extends HibernateGormDatastoreSpec {
List criteria = [new Query.IdEquals(1L)]
when:
- def predicates = predicateGenerator.getPredicates(cb, query, root, criteria, fromProvider, personEntity)
+ def predicates = predicateGenerator.getPredicates(query, root, criteria, fromProvider, personEntity)
then:
predicates.length == 1
@@ -386,7 +394,7 @@ class PredicateGeneratorSpec extends HibernateGormDatastoreSpec {
]
when:
- def predicates = predicateGenerator.getPredicates(cb, query, root, criteria, fromProvider, personEntity)
+ def predicates = predicateGenerator.getPredicates(query, root, criteria, fromProvider, personEntity)
then:
predicates.length == 4
@@ -397,7 +405,7 @@ class PredicateGeneratorSpec extends HibernateGormDatastoreSpec {
List criteria = [new Query.GreaterThan("age", null)]
when:
- predicateGenerator.getPredicates(cb, query, root, criteria, fromProvider, personEntity)
+ predicateGenerator.getPredicates(query, root, criteria, fromProvider, personEntity)
then:
thrown(Exception)
@@ -409,7 +417,7 @@ class PredicateGeneratorSpec extends HibernateGormDatastoreSpec {
List criteria = [new Query.Equals("firstName", sb)]
when:
- def predicates = predicateGenerator.getPredicates(cb, query, root, criteria, fromProvider, personEntity)
+ def predicates = predicateGenerator.getPredicates(query, root, criteria, fromProvider, personEntity)
then:
predicates.length == 1
@@ -420,7 +428,7 @@ class PredicateGeneratorSpec extends HibernateGormDatastoreSpec {
List criteria = [new Query.RLike("firstName", "^B.*")]
when:
- def predicates = predicateGenerator.getPredicates(cb, query, root, criteria, fromProvider, personEntity)
+ def predicates = predicateGenerator.getPredicates(query, root, criteria, fromProvider, personEntity)
then:
predicates.length == 1
@@ -432,7 +440,7 @@ class PredicateGeneratorSpec extends HibernateGormDatastoreSpec {
List criteria = [new Query.NotIn("id", subCriteria)]
when:
- def predicates = predicateGenerator.getPredicates(cb, query, root, criteria, fromProvider, personEntity)
+ def predicates = predicateGenerator.getPredicates(query, root, criteria, fromProvider, personEntity)
then:
predicates.length == 1
@@ -454,7 +462,7 @@ class PredicateGeneratorSpec extends HibernateGormDatastoreSpec {
]
when:
- def predicates = predicateGenerator.getPredicates(cb, query, root, criteria, fromProvider, personEntity)
+ def predicates = predicateGenerator.getPredicates(query, root, criteria, fromProvider, personEntity)
then:
predicates.length == 9
@@ -472,7 +480,7 @@ class PredicateGeneratorSpec extends HibernateGormDatastoreSpec {
]
when:
- def predicates = predicateGenerator.getPredicates(cb, query, root, criteria, fromProvider, personEntity)
+ def predicates = predicateGenerator.getPredicates(query, root, criteria, fromProvider, personEntity)
then:
predicates.length == 6
@@ -493,12 +501,12 @@ class PredicateGeneratorSpec extends HibernateGormDatastoreSpec {
def "handlePropertyCriterion resolves aliased expression"() {
given:
- Expression aliasedExpr = Mock(Expression)
+ Expression aliasedExpr = root.get("firstName")
fromProvider.registerAlias("myAlias", aliasedExpr)
List criteria = [new Query.Equals("myAlias", "Bob")]
when:
- def predicates = predicateGenerator.getPredicates(cb, query, root, criteria, fromProvider, personEntity)
+ def predicates = predicateGenerator.getPredicates(query, root, criteria, fromProvider, personEntity)
then:
predicates.length == 1
diff --git a/grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/query/AliasRegistrySpec.groovy b/grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/query/AliasRegistrySpec.groovy
new file mode 100644
index 0000000000..b5b77d4c83
--- /dev/null
+++ b/grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/query/AliasRegistrySpec.groovy
@@ -0,0 +1,97 @@
+/*
+ * Copyright 2024-2025 the original author or authors.
+ *
+ * Licensed 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 jakarta.persistence.criteria.Expression
+import jakarta.persistence.criteria.JoinType
+import spock.lang.Specification
+
+/**
+ * Unit tests for AliasRegistry.
+ */
+class AliasRegistrySpec extends Specification {
+
+ def "test define and check alias"() {
+ given:
+ def registry = new AliasRegistry()
+ def definition = new HibernateAlias("face", "f", JoinType.INNER)
+
+ when:
+ registry.define("f", definition)
+
+ then:
+ registry.isDefined("f")
+ registry.getDefinition("f") == definition
+ !registry.hasRealized("f")
+ }
+
+ def "test realize and check alias"() {
+ given:
+ def registry = new AliasRegistry()
+ def expression = Mock(Expression)
+
+ when:
+ registry.realize("f", expression)
+
+ then:
+ registry.hasRealized("f")
+ registry.getRealized("f") == expression
+ }
+
+ def "test parent delegation for definitions"() {
+ given:
+ def parent = new AliasRegistry()
+ def child = new AliasRegistry(parent)
+ def definition = new HibernateAlias("face", "f", JoinType.INNER)
+
+ when:
+ parent.define("f", definition)
+
+ then:
+ child.isDefined("f")
+ child.getDefinition("f") == definition
+ }
+
+ def "test parent delegation for realization"() {
+ given:
+ def parent = new AliasRegistry()
+ def child = new AliasRegistry(parent)
+ def expression = Mock(Expression)
+
+ when:
+ parent.realize("f", expression)
+
+ then:
+ child.hasRealized("f")
+ child.getRealized("f") == expression
+ }
+
+ def "test child override"() {
+ given:
+ def parent = new AliasRegistry()
+ def child = new AliasRegistry(parent)
+ def parentExpr = Mock(Expression)
+ def childExpr = Mock(Expression)
+
+ when:
+ parent.realize("f", parentExpr)
+ child.realize("f", childExpr)
+
+ then:
+ child.getRealized("f") == childExpr
+ parent.getRealized("f") == parentExpr
+ }
+}
diff --git a/grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/query/ExpressionResolverSpec.groovy b/grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/query/ExpressionResolverSpec.groovy
new file mode 100644
index 0000000000..44534d7371
--- /dev/null
+++ b/grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/query/ExpressionResolverSpec.groovy
@@ -0,0 +1,136 @@
+/*
+ * Copyright 2024-2025 the original author or authors.
+ *
+ * Licensed 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 jakarta.persistence.criteria.From
+import jakarta.persistence.criteria.Path
+import jakarta.persistence.criteria.Join
+import jakarta.persistence.criteria.JoinType
+import jakarta.persistence.criteria.Expression
+import spock.lang.Specification
+
+/**
+ * Unit tests for ExpressionResolver.
+ */
+class ExpressionResolverSpec extends Specification {
+
+ def "test resolve simple property path"() {
+ given:
+ def root = Mock(From)
+ def propPath = Mock(Path)
+ def joinTracker = new JoinTracker(root)
+ def aliasRegistry = new AliasRegistry()
+ def resolver = new ExpressionResolver(aliasRegistry, joinTracker)
+
+ when:
+ def result = resolver.resolve("firstName")
+
+ then:
+ 1 * root.get("firstName") >> propPath
+ result == propPath
+ }
+
+ def "test resolve {alias} returns root"() {
+ given:
+ def root = Mock(From)
+ def joinTracker = new JoinTracker(root)
+ def resolver = new ExpressionResolver(new AliasRegistry(), joinTracker)
+
+ expect:
+ resolver.resolve("{alias}") == root
+ resolver.resolve("root") == root
+ }
+
+ def "test resolve with alias:property separator"() {
+ given:
+ def root = Mock(From)
+ def faceJoin = Mock(Join)
+ def namePath = Mock(Path)
+ def aliasRegistry = new AliasRegistry()
+ aliasRegistry.define("f", new HibernateAlias("face", "f", JoinType.INNER))
+ def joinTracker = new JoinTracker(root)
+ def resolver = new ExpressionResolver(aliasRegistry, joinTracker)
+
+ when:
+ def result = resolver.resolve("f:name")
+
+ then:
+ 1 * root.join("face", JoinType.INNER) >> faceJoin
+ 1 * faceJoin.get("name") >> namePath
+ result == namePath
+ aliasRegistry.getRealized("f") == faceJoin
+ joinTracker.getJoin("f") == faceJoin
+ }
+
+ def "test resolve with dot notation alias.property"() {
+ given:
+ def root = Mock(From)
+ def faceJoin = Mock(Join)
+ def namePath = Mock(Path)
+ def aliasRegistry = new AliasRegistry()
+ aliasRegistry.define("f", new HibernateAlias("face", "f", JoinType.INNER))
+ def joinTracker = new JoinTracker(root)
+ def resolver = new ExpressionResolver(aliasRegistry, joinTracker)
+
+ when:
+ def result = resolver.resolve("f.name")
+
+ then:
+ 1 * root.join("face", JoinType.INNER) >> faceJoin
+ 1 * faceJoin.get("name") >> namePath
+ result == namePath
+ }
+
+ def "test resolve using already joined path"() {
+ given:
+ def root = Mock(From)
+ def nicknamesJoin = Mock(Join)
+ def joinTracker = new JoinTracker(root)
+ joinTracker.addJoin("nicknames", nicknamesJoin)
+ def resolver = new ExpressionResolver(new AliasRegistry(), joinTracker)
+
+ expect:
+ resolver.resolve("nicknames") == nicknamesJoin
+ }
+
+ def "test resolve with parent context (correlated subquery)"() {
+ given:
+ // Parent context
+ def parentRoot = Mock(From)
+ def faceJoin = Mock(Join)
+ def parentAliasRegistry = new AliasRegistry()
+ parentAliasRegistry.define("f", new HibernateAlias("face", "f", JoinType.INNER))
+ parentAliasRegistry.realize("f", faceJoin)
+ def parentJoinTracker = new JoinTracker(parentRoot)
+ parentJoinTracker.addJoin("f", faceJoin)
+
+ // Subquery context
+ def subRoot = Mock(From)
+ def aliasRegistry = new AliasRegistry(parentAliasRegistry)
+ def joinTracker = new JoinTracker(parentJoinTracker, subRoot)
+ def resolver = new ExpressionResolver(aliasRegistry, joinTracker)
+
+ def namePath = Mock(Path)
+
+ when:
+ def result = resolver.resolve("f.name")
+
+ then:
+ 0 * subRoot.join(_, _) // Should NOT join on subquery root
+ 1 * faceJoin.get("name") >> namePath
+ result == namePath
+ }
+}
diff --git a/grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/query/JoinTrackerSpec.groovy b/grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/query/JoinTrackerSpec.groovy
new file mode 100644
index 0000000000..8482b16330
--- /dev/null
+++ b/grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/query/JoinTrackerSpec.groovy
@@ -0,0 +1,75 @@
+/*
+ * Copyright 2024-2025 the original author or authors.
+ *
+ * Licensed 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 jakarta.persistence.criteria.From
+import spock.lang.Specification
+
+/**
+ * Unit tests for JoinTracker.
+ */
+class JoinTrackerSpec extends Specification {
+
+ def "test root and joins"() {
+ given:
+ def root = Mock(From)
+ def tracker = new JoinTracker(root)
+ def join = Mock(From)
+
+ when:
+ tracker.addJoin("face", join)
+
+ then:
+ tracker.getRoot() == root
+ tracker.getJoin("face") == join
+ }
+
+ def "test parent delegation"() {
+ given:
+ def parentRoot = Mock(From)
+ def parent = new JoinTracker(parentRoot)
+ def subRoot = Mock(From)
+ def child = new JoinTracker(parent, subRoot)
+
+ def parentJoin = Mock(From)
+
+ when:
+ parent.addJoin("face", parentJoin)
+
+ then:
+ child.getJoin("face") == parentJoin
+ child.getRoot() == subRoot
+ }
+
+ def "test child override join"() {
+ given:
+ def parentRoot = Mock(From)
+ def parent = new JoinTracker(parentRoot)
+ def subRoot = Mock(From)
+ def child = new JoinTracker(parent, subRoot)
+
+ def parentJoin = Mock(From)
+ def childJoin = Mock(From)
+
+ when:
+ parent.addJoin("face", parentJoin)
+ child.addJoin("face", childJoin)
+
+ then:
+ child.getJoin("face") == childJoin
+ parent.getJoin("face") == parentJoin
+ }
+}
diff --git a/grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/query/JpaQueryContextSpec.groovy b/grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/query/JpaQueryContextSpec.groovy
new file mode 100644
index 0000000000..7d699fed9e
--- /dev/null
+++ b/grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/query/JpaQueryContextSpec.groovy
@@ -0,0 +1,99 @@
+/*
+ * Copyright 2024-2025 the original author or authors.
+ *
+ * Licensed 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 jakarta.persistence.criteria.From
+import jakarta.persistence.criteria.Join
+import jakarta.persistence.criteria.JoinType
+import jakarta.persistence.criteria.Path
+import spock.lang.Specification
+
+/**
+ * Unit tests for JpaQueryContext as an orchestrator.
+ */
+class JpaQueryContextSpec extends Specification {
+
+ def "test root management"() {
+ given:
+ def root = Mock(From)
+ def context = new JpaQueryContext(root)
+
+ expect:
+ context.getRoot() == root
+ context.getFullyQualifiedExpression("root") == root
+ context.getFullyQualifiedExpression("{alias}") == root
+ }
+
+ def "test alias registration and resolution"() {
+ given:
+ def root = Mock(From)
+ def context = new JpaQueryContext(root)
+ def faceJoin = Mock(Join)
+ def namePath = Mock(Path)
+
+ when: "defining an alias"
+ context.registerAlias("f", new HibernateAlias("face", "f", JoinType.INNER))
+
+ then:
+ context.hasAlias("f")
+ context.getAliasedExpression("f") == null // Not realized yet
+
+ when: "resolving a path through the alias"
+ def result = context.getFullyQualifiedExpression("f.name")
+
+ then:
+ 1 * root.join("face", JoinType.INNER) >> faceJoin
+ 1 * faceJoin.get("name") >> namePath
+ result == namePath
+ context.getAliasedExpression("f") == faceJoin
+ }
+
+ def "test subquery context delegation"() {
+ given:
+ def parentRoot = Mock(From)
+ def parentContext = new JpaQueryContext(parentRoot)
+ def faceJoin = Mock(Join)
+ parentContext.registerAlias("f", faceJoin)
+ parentContext.addFrom("f", faceJoin)
+
+ def subRoot = Mock(From)
+ def subContext = new JpaQueryContext(parentContext, null, subRoot)
+
+ def namePath = Mock(Path)
+
+ when: "resolving parent alias in subquery"
+ def result = subContext.getFullyQualifiedExpression("f.name")
+
+ then:
+ 0 * subRoot.join(_, _)
+ 1 * faceJoin.get("name") >> namePath
+ result == namePath
+ }
+
+ def "test addFrom tracking"() {
+ given:
+ def root = Mock(From)
+ def context = new JpaQueryContext(root)
+ def join = Mock(Join)
+
+ when:
+ context.addFrom("nicknames", join)
+
+ then:
+ context.getFrom("nicknames") == join
+ context.getFullyQualifiedExpression("nicknames") == join
+ }
+}