use of com.blazebit.persistence.parser.expression.PathReference in project blaze-persistence by Blazebit.
the class ConstantifiedJoinNodeAttributeCollector method visit.
@Override
public void visit(PathExpression expr) {
PathReference pathReference = expr.getPathReference();
if (pathReference == null) {
((SelectInfo) aliasManager.getAliasInfo(expr.toString())).getExpression().accept(this);
return;
}
JoinNode baseNode = (JoinNode) pathReference.getBaseNode();
if (pathReference.getField() == null) {
if (inKey) {
// We constantify collection as a whole to a single element when reaching this point
Map<String, Boolean> attributes = new HashMap<>(1);
attributes.put(KEY_FUNCTION, innerJoin);
constantifiedJoinNodeAttributes.put(baseNode, attributes);
} else if (baseNode.getType() instanceof ManagedType<?>) {
// Here we have a predicate like `d = d2` which is the same as `d.id = d2.id`
Map<String, Boolean> attributes = constantifiedJoinNodeAttributes.get(baseNode);
if (attributes == null) {
attributes = new HashMap<>();
constantifiedJoinNodeAttributes.put(baseNode, attributes);
}
ExtendedManagedType<?> managedType = metamodel.getManagedType(ExtendedManagedType.class, baseNode.getManagedType());
for (SingularAttribute<?, ?> idAttribute : managedType.getIdAttributes()) {
addAttribute("", idAttribute, attributes);
}
}
return;
}
ExtendedManagedType<?> managedType = metamodel.getManagedType(ExtendedManagedType.class, baseNode.getManagedType());
ExtendedAttribute<?, ?> extendedAttribute = managedType.getAttribute(pathReference.getField());
Attribute attr = extendedAttribute.getAttribute();
// We constantify collection as a whole to a single element when reaching this point
if (attr instanceof PluralAttribute<?, ?, ?>) {
if (inKey) {
Map<String, Boolean> attributes = new HashMap<>(1);
attributes.put(KEY_FUNCTION, innerJoin);
constantifiedJoinNodeAttributes.put(baseNode, attributes);
}
return;
}
int dotIndex = expr.getField().lastIndexOf('.');
SingularAttribute<?, ?> singularAttr = (SingularAttribute<?, ?>) attr;
String associationName = getSingleValuedIdAccessAssociationName(pathReference.getField(), extendedAttribute);
Object baseNodeKey;
String prefix;
if (associationName == null) {
baseNodeKey = baseNode;
prefix = attr.getDeclaringType() instanceof EmbeddableType<?> ? pathReference.getField().substring(0, dotIndex + 1) : "";
} else {
baseNodeKey = new AbstractMap.SimpleEntry<>(baseNode, associationName);
if (attr.getDeclaringType() instanceof EmbeddableType<?>) {
prefix = pathReference.getField().substring(associationName.length() + 1, dotIndex + 1);
} else {
prefix = "";
}
}
Map<String, Boolean> attributes = constantifiedJoinNodeAttributes.get(baseNodeKey);
if (attributes == null) {
attributes = new HashMap<>();
constantifiedJoinNodeAttributes.put(baseNodeKey, attributes);
}
addAttribute(prefix, singularAttr, attributes);
StringBuilder attributeNameBuilder = null;
Map<String, Boolean> baseNodeAttributes = null;
String associationNamePrefix = associationName == null ? "" : associationName + '.';
// Also add all attributes to the set that resolve to the same column names i.e. which are essentially equivalent
Map<String, Boolean> newAttributes = new HashMap<>();
for (Map.Entry<String, Boolean> entry : attributes.entrySet()) {
String attribute = entry.getKey();
if (attribute != KEY_FUNCTION) {
for (ExtendedAttribute<?, ?> columnEquivalentAttribute : managedType.getAttribute(associationNamePrefix + attribute).getColumnEquivalentAttributes()) {
List<Attribute<?, ?>> attributePath = columnEquivalentAttribute.getAttributePath();
String attributeName;
if (attributePath.size() == 1) {
attributeName = attributePath.get(0).getName();
} else {
if (attributeNameBuilder == null) {
attributeNameBuilder = new StringBuilder();
} else {
attributeNameBuilder.setLength(0);
}
attributeNameBuilder.append(attributePath.get(0).getName());
for (int i = 1; i < attributePath.size(); i++) {
attributeNameBuilder.append('.');
attributeNameBuilder.append(attributePath.get(i).getName());
}
attributeName = attributeNameBuilder.toString();
}
// Be careful with single valued association ids, they have a different baseNodeKey
if (!associationNamePrefix.isEmpty() && !attributeName.startsWith(associationNamePrefix)) {
if (baseNodeAttributes == null) {
baseNodeAttributes = constantifiedJoinNodeAttributes.get(baseNode);
if (baseNodeAttributes == null) {
baseNodeAttributes = new HashMap<>();
constantifiedJoinNodeAttributes.put(baseNode, baseNodeAttributes);
}
}
baseNodeAttributes.put(attributeName, entry.getValue());
} else {
newAttributes.put(attributeName, entry.getValue());
}
}
}
}
attributes.putAll(newAttributes);
}
use of com.blazebit.persistence.parser.expression.PathReference in project blaze-persistence by Blazebit.
the class EqualityCheckingVisitor method visit.
@Override
public Boolean visit(PathExpression expression) {
if (referenceExpression.getClass() != expression.getClass()) {
return Boolean.TRUE;
}
PathExpression reference = (PathExpression) referenceExpression;
List<PathElementExpression> referenceExpressions = reference.getExpressions();
List<PathElementExpression> expressions = expression.getExpressions();
PathExpression leftMostPathExpression = ExpressionUtils.getLeftMostPathExpression(expression);
int size = expressions.size();
if (leftMostPathExpression.getExpressions().get(0) instanceof PropertyExpression) {
PropertyExpression propertyExpression = (PropertyExpression) leftMostPathExpression.getExpressions().get(0);
if (ArrayExpression.ELEMENT_NAME.equals(propertyExpression.getProperty())) {
try {
leftMostPathExpression.getExpressions().set(0, new PropertyExpression(alias));
for (int i = 0; i < size; i++) {
referenceExpression = referenceExpressions.get(i);
if (expressions.get(i).accept(this)) {
return Boolean.TRUE;
}
}
return Boolean.FALSE;
} finally {
leftMostPathExpression.getExpressions().set(0, propertyExpression);
}
}
}
PathReference referencePathReference = reference.getPathReference();
PathReference pathReference = expression.getPathReference();
if (referencePathReference == null || pathReference == null) {
return reference.equals(expression) ? Boolean.FALSE : Boolean.TRUE;
}
if (referencePathReference.getBaseNode() != pathReference.getBaseNode()) {
return Boolean.TRUE;
}
return Objects.equals(referencePathReference.getField(), pathReference.getField()) ? Boolean.FALSE : Boolean.TRUE;
}
use of com.blazebit.persistence.parser.expression.PathReference in project blaze-persistence by Blazebit.
the class ConstantifiedJoinNodeAttributeCollector method isConstant.
private boolean isConstant(Expression expression) {
if (isParameterOrLiteral(expression)) {
return true;
}
if (expression instanceof PathExpression) {
PathReference pathReference = ((PathExpression) expression).getPathReference();
if (pathReference == null) {
AliasInfo aliasInfo = aliasManager.getAliasInfo(expression.toString());
return aliasInfo instanceof SelectInfo && isConstant(((SelectInfo) aliasInfo).getExpression());
}
JoinNode baseNode = (JoinNode) pathReference.getBaseNode();
do {
if (baseNode.getParentTreeNode() == null) {
return isConstantified(baseNode);
} else {
if (baseNode.getParentTreeNode().getAttribute().isCollection()) {
return false;
}
}
baseNode = baseNode.getParent();
} while (baseNode != null);
}
return false;
}
use of com.blazebit.persistence.parser.expression.PathReference in project blaze-persistence by Blazebit.
the class ResolvingQueryGenerator method renderEquality.
private void renderEquality(Expression left, Expression right, boolean negated, PredicateQuantifier quantifier) {
final String operator;
if (negated) {
operator = " <> ";
} else {
operator = " = ";
}
BooleanLiteralRenderingContext oldBooleanLiteralRenderingContext = setBooleanLiteralRenderingContext(BooleanLiteralRenderingContext.PLAIN);
// TODO: Currently we assume that types can be inferred, and render parameters through but e.g. ":param1 = :param2" will fail
ParameterRenderingMode oldParameterRenderingMode = setParameterRenderingMode(ParameterRenderingMode.PLACEHOLDER);
Expression expressionToSplit = needsEmbeddableSplitting(left, right);
if (jpaProvider.needsAssociationToIdRewriteInOnClause() && clauseType == ClauseType.JOIN) {
boolean rewritten = renderAssociationIdIfPossible(left);
sb.append(operator);
if (quantifier != PredicateQuantifier.ONE) {
sb.append(quantifier.toString());
}
rewritten |= renderAssociationIdIfPossible(right);
if (rewritten) {
rewriteToIdParam(left);
rewriteToIdParam(right);
}
} else {
if (expressionToSplit == null || dbmsDialect.supportsAnsiRowValueConstructor() || !(left instanceof ParameterExpression) && !(right instanceof ParameterExpression)) {
left.accept(this);
sb.append(operator);
if (quantifier != PredicateQuantifier.ONE) {
sb.append(quantifier.toString());
}
right.accept(this);
} else {
// We split the path and the parameter expression accordingly
// TODO: Try to handle map key expressions, although no JPA provider supports de-referencing map keys
PathExpression pathExpression = (PathExpression) expressionToSplit;
ParameterExpression parameterExpression;
if (left instanceof ParameterExpression) {
parameterExpression = (ParameterExpression) left;
} else {
parameterExpression = (ParameterExpression) right;
}
PathReference pathReference = pathExpression.getPathReference();
EmbeddableType<?> embeddableType = (EmbeddableType<?>) pathReference.getType();
String parameterName = parameterExpression.getName();
Map<String, List<String>> parameterAccessPaths = new HashMap<>();
ParameterManager.ParameterImpl<?> parameter = parameterManager.getParameter(parameterName);
sb.append('(');
for (Attribute<?, ?> attribute : embeddableType.getAttributes()) {
((JoinNode) pathReference.getBaseNode()).appendDeReference(sb, pathReference.getField() + "." + attribute.getName(), externalRepresentation);
String embeddedPropertyName = attribute.getName();
String subParamName = "_" + parameterName + "_" + embeddedPropertyName.replace('.', '_');
sb.append(operator);
sb.append(":").append(subParamName);
if (parameter.getTransformer() == null) {
parameterManager.registerParameterName(subParamName, false, null, null);
}
parameterAccessPaths.put(subParamName, Arrays.asList(embeddedPropertyName.split("\\.")));
sb.append(" AND ");
}
sb.setLength(sb.length() - " AND ".length());
sb.append(')');
if (parameter.getTransformer() == null) {
parameter.setTransformer(new SplittingParameterTransformer(parameterManager, entityMetamodel, embeddableType.getJavaType(), parameterAccessPaths));
}
}
}
setBooleanLiteralRenderingContext(oldBooleanLiteralRenderingContext);
setParameterRenderingMode(oldParameterRenderingMode);
}
use of com.blazebit.persistence.parser.expression.PathReference in project blaze-persistence by Blazebit.
the class JoinManager method implicitJoin.
@SuppressWarnings("checkstyle:methodlength")
public void implicitJoin(Expression expression, boolean joinAllowed, boolean singularJoinAllowed, boolean objectLeafAllowed, String targetTypeName, ClauseType fromClause, JoinType joinType, JoinNode currentJoinNode, Set<String> currentlyResolvingAliases, boolean fromSubquery, boolean fromSelectAlias, boolean joinRequired, boolean idRemovable, boolean fetch, boolean reuseExisting) {
PathExpression pathExpression;
if (expression instanceof PathExpression) {
pathExpression = (PathExpression) expression;
List<PathElementExpression> pathElements = pathExpression.getExpressions();
int pathElementSize = pathElements.size();
PathElementExpression elementExpr = pathElements.get(pathElements.size() - 1);
int singleValuedAssociationNameStartIndex = -1;
int singleValuedAssociationNameEndIndex = -1;
JoinNode current = null;
List<String> resultFields = new ArrayList<>();
JoinResult currentResult;
JoinNode possibleRoot;
int startIndex = 0;
Expression aliasedExpression;
String alias;
// If joinable select alias, it is guaranteed to have only a single element
if (pathExpression.getExpressions().size() == 1 && currentlyResolvingAliases != null && !currentlyResolvingAliases.contains(alias = pathExpression.toString()) && (aliasedExpression = getJoinableSelectAlias(pathExpression, fromClause == ClauseType.SELECT, fromSubquery)) != null) {
// this check is necessary to prevent infinite recursion in the case of e.g. SELECT name AS name
if (!fromSelectAlias) {
try {
currentlyResolvingAliases.add(alias);
// we have to do this implicit join because we might have to adjust the selectOnly flag in the referenced join nodes
implicitJoin(aliasedExpression, joinAllowed, singularJoinAllowed, true, null, fromClause, currentlyResolvingAliases, fromSubquery, true, joinRequired, false);
} finally {
currentlyResolvingAliases.remove(alias);
}
}
return;
} else if (isExternal(pathExpression)) {
// try to correlate the path expression and use the correlation alias here instead
String correlatedAlias = addRoot(null, pathExpression, null, false, true);
if (correlatedAlias != null) {
pathElements.clear();
pathElements.addAll(expressionFactory.createPathExpression(correlatedAlias).getExpressions());
pathElementSize = pathElements.size();
elementExpr = pathExpression.getExpressions().get(pathExpression.getExpressions().size() - 1);
}
PathElementExpression firstElement = pathElements.get(0);
if (firstElement instanceof PropertyExpression) {
AliasInfo aliasInfo = aliasManager.getAliasInfo(((PropertyExpression) firstElement).getProperty());
if (pathElements.size() == 1) {
JoinManager manager;
if (aliasInfo.getAliasOwner() == aliasManager) {
manager = this;
} else {
manager = parent;
}
manager.implicitJoin(pathExpression, true, true, true, targetTypeName, fromClause, currentlyResolvingAliases, true, fromSelectAlias, joinRequired, false);
return;
} else {
current = ((JoinAliasInfo) aliasInfo).getJoinNode();
startIndex = 1;
}
} else if (firstElement instanceof TreatExpression) {
current = implicitJoinTreatExpression((TreatExpression) firstElement, true, true, fromClause, JoinType.LEFT, null, currentlyResolvingAliases, fromSubquery, fromSelectAlias, true, false, false, true);
startIndex = 1;
if (pathElements.size() == 1) {
return;
}
} else {
throw new IllegalArgumentException("Unsupported correlation with expression: " + pathExpression);
}
}
// Skip root speculation if this is just a single element path
if (current == null && pathElements.size() > 1 && (possibleRoot = getRootNode(pathElements.get(0))) != null) {
startIndex = 1;
current = possibleRoot;
}
if (pathElements.size() > startIndex + 1) {
currentResult = implicitJoin(current, pathExpression, fromClause, joinType, currentJoinNode, currentlyResolvingAliases, startIndex, pathElements.size() - 1, false, joinAllowed, singularJoinAllowed, idRemovable);
current = currentResult.baseNode;
resultFields = currentResult.addToList(resultFields);
// It can never be a single valued association id reference if the join type is INNER i.e. it is required
singleValuedAssociationNameStartIndex = currentResult.singleValuedAssociationNameIndex;
singleValuedAssociationNameEndIndex = currentResult.singleValuedAssociationNameEndIndex;
if (singleValuedAssociationNameStartIndex != -1) {
if (!mainQuery.jpaProvider.supportsSingleValuedAssociationIdExpressions()) {
if (idRemovable) {
// remove the id part only if we come from a predicate
elementExpr = null;
if (current == null) {
// This is the case when we use a join alias like "alias.id"
// We need to resolve the base since it might not be the root node
AliasInfo a = aliasManager.getAliasInfo(pathElements.get(currentResult.singleValuedAssociationNameIndex).toString());
// We know this can only be a join node alias
current = ((JoinAliasInfo) a).getJoinNode();
resultFields = Collections.emptyList();
}
} else {
// Need a normal join
elementExpr = null;
resultFields.clear();
currentResult = implicitJoin(current, resultFields, pathExpression, fromClause, joinType, currentJoinNode, currentlyResolvingAliases, currentResult.singleValuedAssociationNameIndex, pathElements.size(), false, joinAllowed, singularJoinAllowed, idRemovable);
current = currentResult.baseNode;
resultFields = currentResult.addToList(resultFields);
singleValuedAssociationNameStartIndex = -1;
}
}
}
} else {
// Single element expression like "alias", "relation", "property" or "alias.relation"
currentResult = implicitJoin(current, pathExpression, fromClause, joinType, currentJoinNode, currentlyResolvingAliases, startIndex, pathElements.size() - 1, false, joinAllowed, singularJoinAllowed, idRemovable);
current = currentResult.baseNode;
resultFields = currentResult.addToList(resultFields);
if (idRemovable) {
if (current != null) {
// If there is a "base node" i.e. a current, the expression has 2 elements
if (isSingleValuedAssociationId(current.getNodeType(), elementExpr)) {
// We remove the "id" part
elementExpr = null;
// Treat it like a single valued association id expression
singleValuedAssociationNameStartIndex = singleValuedAssociationNameEndIndex = startIndex - 1;
}
} else {
// There is no base node, this is a expression with 1 element
// Either relative or a direct alias
String elementExpressionString;
if (elementExpr instanceof ArrayExpression) {
elementExpressionString = ((ArrayExpression) elementExpr).getBase().toString();
} else {
elementExpressionString = elementExpr.toString();
}
AliasInfo a = aliasManager.getAliasInfo(elementExpressionString);
if (a == null) {
// If the element expression is an alias, there is nothing to replace
current = getRootNodeOrFail("Could not join path [", expression, "] because it did not use an absolute path but multiple root nodes are available!");
if (isSingleValuedAssociationId(current.getNodeType(), elementExpr)) {
// We replace the "id" part with the alias
elementExpr = new PropertyExpression(current.getAlias());
}
}
}
}
}
JoinResult result;
AliasInfo aliasInfo;
// The case of a simple join alias usage
if (pathElements.size() == 1 && !fromSelectAlias && currentlyResolvingAliases != null && !currentlyResolvingAliases.contains(alias = elementExpr.toString()) && (aliasInfo = aliasManager.getAliasInfoForBottomLevel(alias)) != null) {
// No need to assert the resultFields here since they can't appear anyways if we enter this branch
if (aliasInfo instanceof SelectInfo) {
if (targetTypeName != null) {
throw new IllegalArgumentException("The select alias '" + aliasInfo.getAlias() + "' can not be used for a treat expression!.");
}
// We actually allow usage of select aliases in expressions, but JPA doesn't, so we have to resolve them here
Expression selectExpr = ((SelectInfo) aliasInfo).getExpression();
if (!(selectExpr instanceof PathExpression)) {
throw new RuntimeException("The select expression '" + selectExpr.toString() + "' is not a simple path expression! No idea how to implicit join that.");
}
// join the expression behind a select alias once when it is encountered the first time
if (((PathExpression) selectExpr).getBaseNode() == null) {
implicitJoin(selectExpr, joinAllowed, singularJoinAllowed, objectLeafAllowed, null, fromClause, currentlyResolvingAliases, fromSubquery, true, joinRequired, false);
}
PathExpression selectPathExpr = (PathExpression) selectExpr;
PathReference reference = selectPathExpr.getPathReference();
result = new JoinResult((JoinNode) selectPathExpr.getBaseNode(), Arrays.asList(selectPathExpr.getField()), reference.getType(), -1, -1);
} else {
JoinNode pathJoinNode = ((JoinAliasInfo) aliasInfo).getJoinNode();
if (targetTypeName != null) {
// Treated root path
ManagedType<?> targetType = metamodel.managedType(targetTypeName);
result = new JoinResult(pathJoinNode);
} else {
// Naked join alias usage like in "KEY(joinAlias)"
result = new JoinResult(pathJoinNode);
}
}
} else if (pathElements.size() == 1 && elementExpr instanceof QualifiedExpression) {
QualifiedExpression qualifiedExpression = (QualifiedExpression) elementExpr;
JoinNode baseNode;
if (elementExpr instanceof MapKeyExpression) {
baseNode = joinMapKey((MapKeyExpression) elementExpr, null, fromClause, currentlyResolvingAliases, fromSubquery, fromSelectAlias, true, fetch, true, true);
} else if (elementExpr instanceof ListIndexExpression) {
baseNode = joinListIndex((ListIndexExpression) elementExpr, null, fromClause, currentlyResolvingAliases, fromSubquery, fromSelectAlias, true, fetch, true, true);
} else if (elementExpr instanceof MapEntryExpression) {
baseNode = joinMapEntry((MapEntryExpression) elementExpr, null, fromClause, currentlyResolvingAliases, fromSubquery, fromSelectAlias, true, fetch, true, true);
} else if (elementExpr instanceof MapValueExpression) {
implicitJoin(qualifiedExpression.getPath(), true, singularJoinAllowed, objectLeafAllowed, targetTypeName, fromClause, joinType, null, currentlyResolvingAliases, fromSubquery, fromSelectAlias, joinRequired, false, fetch, false);
baseNode = (JoinNode) qualifiedExpression.getPath().getBaseNode();
} else {
throw new IllegalArgumentException("Unknown qualified expression type: " + elementExpr);
}
result = new JoinResult(baseNode);
} else {
if (singleValuedAssociationNameStartIndex != -1) {
String associationName = new PathExpression(pathElements.subList(singleValuedAssociationNameStartIndex, singleValuedAssociationNameEndIndex + 1)).toString();
AliasInfo singleValuedAssociationRootAliasInfo = null;
JoinTreeNode treeNode;
// } else
if (pathElements.size() == 2) {
// If this path is composed of only two elements, the association name could represent an alias
singleValuedAssociationRootAliasInfo = aliasManager.getAliasInfoForBottomLevel(associationName);
}
if (singleValuedAssociationRootAliasInfo != null) {
JoinNode singleValuedAssociationRoot = ((JoinAliasInfo) singleValuedAssociationRootAliasInfo).getJoinNode();
if (elementExpr != null) {
AttributeHolder attributeHolder = JpaUtils.getAttributeForJoining(metamodel, singleValuedAssociationRoot.getNodeType(), elementExpr, null);
Type<?> type = attributeHolder.getAttributeType();
result = new JoinResult(singleValuedAssociationRoot, Arrays.asList(elementExpr.toString()), type, -1, -1);
} else {
result = new JoinResult(singleValuedAssociationRoot);
}
} else {
if (current == null) {
current = getRootNodeOrFail("Could not join path [", expression, "] because it did not use an absolute path but multiple root nodes are available!");
}
treeNode = current.getNodes().get(associationName);
if (reuseExisting && treeNode != null && treeNode.getDefaultNode() != null) {
if (elementExpr != null) {
Expression restExpression = new PathExpression(pathElements.subList(singleValuedAssociationNameEndIndex + 1, pathElementSize));
String elementString = restExpression.toString();
AttributeHolder attributeHolder = JpaUtils.getAttributeForJoining(metamodel, treeNode.getDefaultNode().getNodeType(), restExpression, null);
Type<?> type = attributeHolder.getAttributeType();
result = new JoinResult(treeNode.getDefaultNode(), Arrays.asList(elementString), type, -1, -1);
} else {
result = new JoinResult(treeNode.getDefaultNode());
}
} else {
if (elementExpr != null) {
Expression restExpression = new PathExpression(pathElements.subList(singleValuedAssociationNameStartIndex, pathElementSize));
String elementString = restExpression.toString();
AttributeHolder attributeHolder = JpaUtils.getAttributeForJoining(metamodel, currentResult.baseNode.getNodeType(), restExpression, null);
Type<?> type = attributeHolder.getAttributeType();
result = new JoinResult(currentResult.baseNode, Arrays.asList(elementString), type, -1, -1);
} else if (metamodel.getManagedType(ExtendedManagedType.class, current.getManagedType()).getAttributes().get(associationName) != null) {
Expression resultExpr = new PathExpression(new PropertyExpression(associationName));
AttributeHolder attributeHolder = JpaUtils.getAttributeForJoining(metamodel, current.getNodeType(), resultExpr, null);
Type<?> type = attributeHolder.getAttributeType();
result = new JoinResult(current, Arrays.asList(associationName), type, -1, -1);
} else {
result = new JoinResult(current);
}
}
}
} else if (elementExpr instanceof ArrayExpression) {
// Element collection case
ArrayExpression arrayExpr = (ArrayExpression) elementExpr;
if (arrayExpr.getBase() instanceof PropertyExpression) {
if (current == null) {
current = getRootNodeOrFail("Could not join path [", expression, "] because it did not use an absolute path but multiple root nodes are available!");
}
}
String joinRelationName = arrayExpr.getBase().toString();
implicitJoinIndex(arrayExpr);
// Find a node by a predicate match
JoinNode matchingNode;
if (pathElements.size() == 1 && (aliasInfo = aliasManager.getAliasInfoForBottomLevel(joinRelationName)) != null) {
// The first node is allowed to be a join alias
if (aliasInfo instanceof SelectInfo) {
throw new IllegalArgumentException("Illegal reference to the select alias '" + joinRelationName + "'");
}
current = ((JoinAliasInfo) aliasInfo).getJoinNode();
generateAndApplyOnPredicate(current, arrayExpr);
} else if ((matchingNode = findNode(current, joinRelationName, arrayExpr)) != null) {
// We found a join node for the same join relation with the same array expression predicate
current = matchingNode;
} else {
String joinAlias = getJoinAlias(arrayExpr);
if (arrayExpr.getBase() instanceof PropertyExpression) {
resultFields.add(joinRelationName);
currentResult = createOrUpdateNode(current, resultFields, targetTypeName, joinAlias, joinType, currentJoinNode, true, false, joinAllowed, singularJoinAllowed);
} else {
joinAlias = aliasManager.generateJoinAlias(joinAlias);
Class<?> entityClass = ((EntityLiteral) arrayExpr.getBase()).getValue();
joinOn(null, rootNodes.get(0).getAlias(), entityClass, joinAlias, JoinType.LEFT, false).end();
currentResult = new JoinResult(((JoinAliasInfo) aliasManager.getAliasInfo(joinAlias)).getJoinNode());
}
current = currentResult.baseNode;
// TODO: Not sure if necessary
if (currentResult.hasField()) {
throw new IllegalArgumentException("The join path [" + pathExpression + "] has a non joinable part [" + currentResult.joinFields() + "]");
}
generateAndApplyOnPredicate(current, arrayExpr);
}
result = new JoinResult(current);
} else if (!pathExpression.isUsedInCollectionFunction()) {
if (current == null) {
current = getRootNodeOrFail("Could not join path [", expression, "] because it did not use an absolute path but multiple root nodes are available!");
}
if (resultFields.isEmpty()) {
result = implicitJoinSingle(current, elementExpr.toString(), targetTypeName, joinType, currentJoinNode, objectLeafAllowed, joinRequired, joinAllowed, singularJoinAllowed);
} else {
resultFields.add(elementExpr.toString());
String attributeName = StringUtils.join(".", resultFields);
// Validates and gets the path type
getPathType(current.getNodeType(), attributeName, pathExpression);
result = implicitJoinSingle(current, attributeName, targetTypeName, joinType, currentJoinNode, objectLeafAllowed, joinRequired, joinAllowed, singularJoinAllowed);
}
} else {
if (current == null) {
current = getRootNodeOrFail("Could not join path [", expression, "] because it did not use an absolute path but multiple root nodes are available!");
}
if (resultFields.isEmpty()) {
String attributeName = elementExpr.toString();
Type<?> type = getPathType(current.getNodeType(), attributeName, pathExpression);
result = new JoinResult(current, Arrays.asList(attributeName), type, -1, -1);
} else {
resultFields.add(elementExpr.toString());
String attributeName = StringUtils.join(".", resultFields);
Type<?> type = getPathType(current.getNodeType(), attributeName, pathExpression);
result = new JoinResult(current, resultFields, type, -1, -1);
}
}
}
if (fetch) {
fetchPath(result.baseNode);
}
// Don't forget to update the clause dependencies, but only for normal attribute accesses, that way paginated queries can prevent joins in certain cases
if (fromClause != null) {
try {
result.baseNode.updateClauseDependencies(fromClause, new LinkedHashSet<JoinNode>());
} catch (IllegalStateException ex) {
throw new IllegalArgumentException("Implicit join in expression '" + expression + "' introduces cyclic join dependency!", ex);
}
}
if (result.isLazy()) {
pathExpression.setPathReference(new LazyPathReference(result.baseNode, result.joinFields(), result.type, joinAllowed));
} else {
pathExpression.setPathReference(new SimplePathReference(result.baseNode, result.joinFields(), result.type));
}
} else if (expression instanceof FunctionExpression) {
FunctionExpression functionExpression = (FunctionExpression) expression;
List<Expression> expressions = functionExpression.getExpressions();
int size = expressions.size();
for (int i = 0; i < size; i++) {
implicitJoin(expressions.get(i), joinAllowed, singularJoinAllowed, objectLeafAllowed, null, fromClause, currentlyResolvingAliases, fromSubquery, fromSelectAlias, joinRequired, false);
}
List<OrderByItem> withinGroup = functionExpression.getWithinGroup();
if (withinGroup != null) {
size = withinGroup.size();
for (int i = 0; i < size; i++) {
implicitJoin(withinGroup.get(i).getExpression(), joinAllowed, singularJoinAllowed, objectLeafAllowed, null, fromClause, currentlyResolvingAliases, fromSubquery, fromSelectAlias, joinRequired, false);
}
}
} else if (expression instanceof MapKeyExpression) {
MapKeyExpression mapKeyExpression = (MapKeyExpression) expression;
joinMapKey(mapKeyExpression, null, fromClause, currentlyResolvingAliases, fromSubquery, fromSelectAlias, joinRequired, fetch, true, true);
} else if (expression instanceof QualifiedExpression) {
implicitJoin(((QualifiedExpression) expression).getPath(), joinAllowed, singularJoinAllowed, objectLeafAllowed, null, fromClause, currentlyResolvingAliases, fromSubquery, fromSelectAlias, joinRequired, false);
} else if (expression instanceof ArrayExpression || expression instanceof GeneralCaseExpression || expression instanceof TreatExpression) {
// NOTE: I haven't found a use case for this yet, so I'd like to throw an exception instead of silently not supporting this
throw new IllegalArgumentException("Unsupported expression for implicit joining found: " + expression);
} else {
// Other expressions don't need handling
}
}
Aggregations