Search in sources :

Example 1 with AliasReplacementVisitor

use of com.blazebit.persistence.parser.AliasReplacementVisitor in project blaze-persistence by Blazebit.

the class JoinManager method generateAndApplyOnPredicate.

private void generateAndApplyOnPredicate(JoinNode joinNode, ArrayExpression arrayExpr) {
    PathExpression joinAliasPathExpression = new PathExpression(new PropertyExpression(joinNode.getAlias()));
    arrayExpr.getIndex().accept(new AliasReplacementVisitor(joinAliasPathExpression, ArrayExpression.ELEMENT_NAME));
    Predicate filterPredicate = getArrayExpressionPredicate(joinNode, arrayExpr);
    // Array expression predicates get a different root, normal expressions not
    ClauseType fromClause = joinVisitor.getFromClause();
    JoinNode currentJoinNode = joinVisitor.getCurrentJoinNode();
    CompoundPredicate currentPred = joinNode.getOnPredicate();
    boolean newPredicate = false;
    if (currentPred != null) {
        // Only add the predicate if it isn't contained yet
        if (!findPredicate(currentPred, filterPredicate, joinNode.getAlias())) {
            currentPred.getChildren().add(filterPredicate);
            newPredicate = true;
        }
    } else {
        CompoundPredicate onAndPredicate = new CompoundPredicate(CompoundPredicate.BooleanOperator.AND);
        onAndPredicate.getChildren().add(filterPredicate);
        joinNode.setOnPredicate(onAndPredicate);
        newPredicate = true;
    }
    try {
        joinVisitor.setFromClause(ClauseType.JOIN);
        joinVisitor.setCurrentJoinNode(joinNode);
        if (arrayExpr.getIndex() instanceof Predicate) {
            JoinNode oldRootNode = rootNode;
            try {
                rootNode = joinNode;
                joinNode.accept(joinVisitor);
            } finally {
                rootNode = oldRootNode;
            }
        } else {
            arrayExpr.getIndex().accept(joinVisitor);
        }
    } finally {
        joinVisitor.setFromClause(fromClause);
        joinVisitor.setCurrentJoinNode(currentJoinNode);
    }
    if (newPredicate) {
        joinNode.registerDependencies();
        joinNode.updateClauseDependencies(ClauseType.JOIN, new LinkedHashSet<JoinNode>());
    }
}
Also used : AliasReplacementVisitor(com.blazebit.persistence.parser.AliasReplacementVisitor) PathExpression(com.blazebit.persistence.parser.expression.PathExpression) PropertyExpression(com.blazebit.persistence.parser.expression.PropertyExpression) CompoundPredicate(com.blazebit.persistence.parser.predicate.CompoundPredicate) EqPredicate(com.blazebit.persistence.parser.predicate.EqPredicate) Predicate(com.blazebit.persistence.parser.predicate.Predicate) CompoundPredicate(com.blazebit.persistence.parser.predicate.CompoundPredicate)

Example 2 with AliasReplacementVisitor

use of com.blazebit.persistence.parser.AliasReplacementVisitor in project blaze-persistence by Blazebit.

the class AbstractAttribute method checkAttribute.

public void checkAttribute(ManagedType<?> managedType, MetamodelBuildingContext context) {
    Class<?> expressionType = getJavaType();
    Class<?> keyType = null;
    Class<?> elementType = null;
    ManagedType<?> elementManagedType;
    javax.persistence.metamodel.Attribute<?, ?> elementAttribute;
    if (possibleTargetTypes.size() != 1) {
        if (getElementType() instanceof ManagedViewType<?>) {
            elementManagedType = context.getEntityMetamodel().getManagedType(((ManagedViewType<?>) getElementType()).getEntityClass());
        } else {
            elementManagedType = context.getEntityMetamodel().getManagedType(getElementType().getJavaType());
        }
        elementAttribute = null;
    } else {
        elementManagedType = context.getEntityMetamodel().getManagedType(possibleTargetTypes.get(0).getLeafBaseValueClass());
        elementAttribute = possibleTargetTypes.get(0).getLeafMethod();
    }
    ScalarTargetResolvingExpressionVisitor visitor = new ScalarTargetResolvingExpressionVisitor(elementManagedType, elementAttribute, context.getEntityMetamodel(), context.getJpqlFunctions(), declaringType.getEntityViewRootTypes());
    if (fetches.length != 0) {
        if (context.getEntityMetamodel().getManagedType(getElementType().getJavaType()) == null) {
            context.addError("Specifying fetches for non-entity attribute type [" + Arrays.toString(fetches) + "] at the " + getLocation() + " is not allowed!");
        } else {
            for (int i = 0; i < fetches.length; i++) {
                final String fetch = fetches[i];
                final String errorLocation;
                if (fetches.length == 1) {
                    errorLocation = "the fetch expression";
                } else {
                    errorLocation = "the " + (i + 1) + ". fetch expression";
                }
                visitor.clear();
                try {
                    // Validate the fetch expression parses
                    context.getExpressionFactory().createPathExpression(fetch).accept(visitor);
                } catch (SyntaxErrorException ex) {
                    try {
                        context.getExpressionFactory().createSimpleExpression(fetch, false, false, true);
                        // The used expression is not usable for fetches
                        context.addError("Invalid fetch expression '" + fetch + "' of the " + getLocation() + ". Simplify the fetch expression to a simple path expression. Encountered error: " + ex.getMessage());
                    } catch (SyntaxErrorException ex2) {
                        // This is a real syntax error
                        context.addError("Syntax error in " + errorLocation + " '" + fetch + "' of the " + getLocation() + ": " + ex.getMessage());
                    }
                } catch (IllegalArgumentException ex) {
                    context.addError("An error occurred while trying to resolve the " + errorLocation + " '" + fetch + "' of the " + getLocation() + ": " + ex.getMessage());
                }
            }
        }
    }
    if (limitExpression != null) {
        try {
            Expression inItemExpression = context.getTypeValidationExpressionFactory().createInItemExpression(limitExpression);
            if (!(inItemExpression instanceof ParameterExpression) && !(inItemExpression instanceof NumericLiteral) || inItemExpression instanceof NumericLiteral && ((NumericLiteral) inItemExpression).getNumericType() != NumericType.INTEGER) {
                context.addError("Syntax error in the limit expression '" + limitExpression + "' of the " + getLocation() + ": The expression must be a integer literal or a parameter expression");
            }
        } catch (SyntaxErrorException ex) {
            context.addError("Syntax error in the limit expression '" + limitExpression + "' of the " + getLocation() + ": " + ex.getMessage());
        } catch (IllegalArgumentException ex) {
            context.addError("An error occurred while trying to resolve the limit expression '" + limitExpression + "' of the " + getLocation() + ": " + ex.getMessage());
        }
        try {
            Expression inItemExpression = context.getTypeValidationExpressionFactory().createInItemExpression(offsetExpression);
            if (!(inItemExpression instanceof ParameterExpression) && !(inItemExpression instanceof NumericLiteral) || inItemExpression instanceof NumericLiteral && ((NumericLiteral) inItemExpression).getNumericType() != NumericType.INTEGER) {
                context.addError("Syntax error in the offset expression '" + offsetExpression + "' of the " + getLocation() + ": The expression must be a integer literal or a parameter expression");
            }
        } catch (SyntaxErrorException ex) {
            context.addError("Syntax error in the offset expression '" + offsetExpression + "' of the " + getLocation() + ": " + ex.getMessage());
        } catch (IllegalArgumentException ex) {
            context.addError("An error occurred while trying to resolve the offset expression '" + offsetExpression + "' of the " + getLocation() + ": " + ex.getMessage());
        }
        for (int i = 0; i < orderByItems.size(); i++) {
            OrderByItem orderByItem = orderByItems.get(i);
            String expression = orderByItem.getExpression();
            try {
                visitor.clear();
                context.getTypeValidationExpressionFactory().createSimpleExpression(expression, false, false, true).accept(visitor);
            } catch (SyntaxErrorException ex) {
                context.addError("Syntax error in the " + (i + 1) + "th order by expression '" + expression + "' of the " + getLocation() + ": " + ex.getMessage());
            } catch (IllegalArgumentException ex) {
                context.addError("An error occurred while trying to resolve the " + (i + 1) + "th order by expression '" + expression + "' of the " + getLocation() + ": " + ex.getMessage());
            }
        }
    }
    if (fetchStrategy == FetchStrategy.MULTISET) {
        if (getElementType() instanceof ManagedViewTypeImplementor<?> && ((ManagedViewTypeImplementor<?>) getElementType()).hasJpaManagedAttributes()) {
            context.addError("Using the MULTISET fetch strategy is not allowed when the subview contains attributes with entity types. MULTISET at the " + getLocation() + " is not allowed!");
        } else if (getElementType() instanceof BasicTypeImpl<?> && ((BasicTypeImpl<?>) getElementType()).isJpaManaged()) {
            context.addError("Using the MULTISET fetch strategy is not allowed with entity types. MULTISET at the " + getLocation() + " is not allowed!");
        }
    }
    Expression indexExpression = null;
    if (isCollection()) {
        elementType = getElementType().getJavaType();
        if (!isUpdatable()) {
            // Updatable collection attributes are specially handled in the type compatibility check
            if (isIndexed()) {
                if (getCollectionType() == PluralAttribute.CollectionType.MAP) {
                    expressionType = Collection.class;
                    keyType = getKeyType().getJavaType();
                } else {
                    expressionType = Collection.class;
                    keyType = Integer.class;
                }
            } else {
                // We can assign e.g. a Set to a List, so let's use the common supertype
                expressionType = Collection.class;
            }
        }
        if (isIndexed()) {
            if (getCollectionType() == PluralAttribute.CollectionType.MAP) {
                indexExpression = getKeyMappingExpression();
                String[] keyFetches = getKeyFetches();
                if (keyFetches.length != 0) {
                    ManagedType<?> managedKeyType = context.getEntityMetamodel().getManagedType(getKeyType().getJavaType());
                    if (managedKeyType == null) {
                        context.addError("Specifying key fetches for non-entity attribute key type [" + Arrays.toString(keyFetches) + "] at the " + getLocation() + " is not allowed!");
                    } else {
                        ScalarTargetResolvingExpressionVisitor keyVisitor = new ScalarTargetResolvingExpressionVisitor(managedKeyType, context.getEntityMetamodel(), context.getJpqlFunctions(), declaringType.getEntityViewRootTypes());
                        for (int i = 0; i < keyFetches.length; i++) {
                            final String fetch = keyFetches[i];
                            final String errorLocation;
                            if (keyFetches.length == 1) {
                                errorLocation = "the key fetch expression";
                            } else {
                                errorLocation = "the " + (i + 1) + ". key fetch expression";
                            }
                            keyVisitor.clear();
                            try {
                                // Validate the fetch expression parses
                                context.getExpressionFactory().createPathExpression(fetch).accept(keyVisitor);
                            } catch (SyntaxErrorException ex) {
                                try {
                                    context.getExpressionFactory().createSimpleExpression(fetch, false, false, true);
                                    // The used expression is not usable for fetches
                                    context.addError("Invalid key fetch expression '" + fetch + "' of the " + getLocation() + ". Simplify the key fetch expression to a simple path expression. Encountered error: " + ex.getMessage());
                                } catch (SyntaxErrorException ex2) {
                                    // This is a real syntax error
                                    context.addError("Syntax error in " + errorLocation + " '" + fetch + "' of the " + getLocation() + ": " + ex.getMessage());
                                }
                            } catch (IllegalArgumentException ex) {
                                context.addError("An error occurred while trying to resolve the " + errorLocation + " '" + fetch + "' of the " + getLocation() + ": " + ex.getMessage());
                            }
                        }
                    }
                }
            } else {
                indexExpression = getMappingIndexExpression();
            }
        }
    }
    if (isSubview()) {
        ManagedViewTypeImplementor<?> subviewType = (ManagedViewTypeImplementor<?>) getElementType();
        if (isCollection()) {
            elementType = subviewType.getEntityClass();
        } else {
            expressionType = subviewType.getEntityClass();
        }
    } else {
        // If we determined, that the java type is a basic type, let's double check if the user didn't do something wrong
        Class<?> elementJavaType = getElementType().getJavaType();
        if ((elementJavaType.getModifiers() & Modifier.ABSTRACT) != 0) {
            // If the element type has an entity view annotation, although it is considered basic, we throw an error as this means, the view was probably not registered
            if (!isQueryParameter() && AnnotationUtils.findAnnotation(elementJavaType, EntityView.class) != null && getElementType().getConvertedType() == null) {
                context.addError("The element type '" + elementJavaType.getName() + "' is considered basic although the class is annotated with @EntityView. Add a type converter or add the java class to the entity view configuration! Problematic attribute " + getLocation());
            }
        }
    }
    if (isKeySubview()) {
        keyType = ((ManagedViewTypeImplementor<?>) getKeyType()).getEntityClass();
    }
    if (keyType != null) {
        validateTypesCompatible(possibleIndexTargetTypes, keyType, null, isUpdatable(), true, context, ExpressionLocation.MAPPING_INDEX, getLocation());
    }
    if (isCorrelated()) {
        // Validate that resolving "correlationBasis" on "managedType" is valid
        validateTypesCompatible(managedType, correlationBasisExpression, Object.class, null, false, true, declaringType.getEntityViewRootTypes(), context, ExpressionLocation.CORRELATION_BASIS, getLocation());
        if (correlated != null) {
            // Validate that resolving "correlationResult" on "correlated" is compatible with "expressionType" and "elementType"
            validateTypesCompatible(possibleTargetTypes, expressionType, elementType, false, !isCollection(), context, ExpressionLocation.CORRELATION_RESULT, getLocation());
            Predicate correlationPredicate = getCorrelationPredicate();
            if (correlationPredicate != null) {
                ExpressionFactory ef = context.getTypeValidationExpressionFactory();
                // First we need to prefix the correlation basis expression with an alias because we use that in the predicate
                PrefixingQueryGenerator prefixingQueryGenerator = new PrefixingQueryGenerator(ef, correlationKeyAlias, null, null, declaringType.getEntityViewRootTypes().keySet(), false, false);
                prefixingQueryGenerator.setQueryBuffer(new StringBuilder());
                correlationBasisExpression.accept(prefixingQueryGenerator);
                // Next we replace the plain alias usage with the prefixed correlation basis expression
                AliasReplacementVisitor aliasReplacementVisitor = new AliasReplacementVisitor(ef.createSimpleExpression(prefixingQueryGenerator.getQueryBuffer().toString()), correlationKeyAlias);
                correlationPredicate = correlationPredicate.copy(ExpressionCopyContext.EMPTY);
                correlationPredicate.accept(aliasReplacementVisitor);
                // Finally we validate that the expression
                try {
                    Map<String, javax.persistence.metamodel.Type<?>> rootTypes = new HashMap<>(declaringType.getEntityViewRootTypes());
                    rootTypes.put(correlationKeyAlias, managedType);
                    ScalarTargetResolvingExpressionVisitor correlationVisitor = new ScalarTargetResolvingExpressionVisitor(correlated, context.getEntityMetamodel(), context.getJpqlFunctions(), rootTypes);
                    correlationPredicate.accept(correlationVisitor);
                } catch (SyntaxErrorException ex) {
                    context.addError("Syntax error in the condition expression '" + correlationPredicate + "' of the " + getLocation() + ": " + ex.getMessage());
                } catch (IllegalArgumentException ex) {
                    context.addError("An error occurred while trying to resolve the condition expression '" + correlationPredicate + "' of the " + getLocation() + ": " + ex.getMessage());
                }
            }
        }
    } else if (isSubquery()) {
        if (subqueryExpression != null && !subqueryExpression.isEmpty()) {
            // If a converter is applied, we already know that there was a type match with the underlying type
            if (getElementType().getConvertedType() == null) {
                validateTypesCompatible(possibleTargetTypes, expressionType, elementType, false, !isCollection(), context, ExpressionLocation.SUBQUERY_EXPRESSION, getLocation());
            }
        }
    } else if (!isQueryParameter()) {
        // Forcing singular via @MappingSingular
        if (!isCollection() && (Collection.class.isAssignableFrom(expressionType) || Map.class.isAssignableFrom(expressionType))) {
            Class<?>[] typeArguments = getTypeArguments();
            elementType = typeArguments[typeArguments.length - 1];
        }
        // If a converter is applied, we already know that there was a type match with the underlying type
        if (getElementType().getConvertedType() == null) {
            // Validate that resolving "mapping" on "managedType" is compatible with "expressionType" and "elementType"
            validateTypesCompatible(possibleTargetTypes, expressionType, elementType, isUpdatable(), !isCollection(), context, ExpressionLocation.MAPPING, getLocation());
        }
        if (isMutable() && (declaringType.isUpdatable() || declaringType.isCreatable())) {
            UpdatableExpressionVisitor updatableVisitor = new UpdatableExpressionVisitor(context.getEntityMetamodel(), managedType.getJavaType(), isUpdatable(), declaringType.getEntityViewRootTypes());
            try {
                // NOTE: Not supporting "this" here because it doesn't make sense to have an updatable mapping that refers to this
                // The only thing that might be interesting is supporting "this" when we support cascading as properties could be nested
                // But not sure yet if the embeddable attributes would then be modeled as "updatable".
                // I guess these attributes are not "updatable" but that probably depends on the decision regarding collections as they have a similar problem
                // A collection itself might not be "updatable" but it's elements could be. This is roughly the same problem
                mappingExpression.accept(updatableVisitor);
                Map<javax.persistence.metamodel.Attribute<?, ?>, javax.persistence.metamodel.Type<?>> possibleTargets = updatableVisitor.getPossibleTargets();
                if (possibleTargets.size() > 1) {
                    context.addError("Multiple possible target type for the mapping in the " + getLocation() + ": " + possibleTargets);
                }
                // TODO: maybe allow to override this per-attribute?
                if (isDisallowOwnedUpdatableSubview()) {
                    for (Type<?> updateCascadeAllowedSubtype : getUpdateCascadeAllowedSubtypes()) {
                        ManagedViewType<?> managedViewType = (ManagedViewType<?>) updateCascadeAllowedSubtype;
                        if (managedViewType.isUpdatable()) {
                            context.addError("Invalid use of @UpdatableEntityView type '" + managedViewType.getJavaType().getName() + "' for the " + getLocation() + ". Consider using a read-only view type instead or use @AllowUpdatableEntityViews! " + "For further information on this topic, please consult the documentation https://persistence.blazebit.com/documentation/entity-view/manual/en_US/index.html#updatable-mappings-subview");
                        }
                    }
                }
            } catch (IllegalArgumentException ex) {
                context.addError("There is an error for the " + getLocation() + ": " + ex.getMessage());
            }
            if (isUpdatable()) {
                if (isCollection() && getElementCollectionType() != null) {
                    context.addError("The use of a multi-collection i.e. List<Collection<?>> or Map<?, Collection<?>> at the " + getLocation() + " is unsupported for updatable collections!");
                }
            }
            if ((isUpdatable() || isKeySubview() && ((ManagedViewTypeImplementor<?>) getKeyType()).isUpdatable()) && indexExpression != null) {
                boolean invalid;
                if (getCollectionType() == PluralAttribute.CollectionType.MAP) {
                    invalid = !(indexExpression instanceof MapKeyExpression) || !"this".equals(((MapKeyExpression) indexExpression).getPath().getPath());
                } else {
                    invalid = !(indexExpression instanceof ListIndexExpression) || !"this".equals(((ListIndexExpression) indexExpression).getPath().getPath());
                }
                if (invalid) {
                    context.addError("The @MappingIndex at the " + getLocation() + " is a complex mapping and can thus not be updatable!");
                }
            }
        }
    }
}
Also used : NumericLiteral(com.blazebit.persistence.parser.expression.NumericLiteral) HashMap(java.util.HashMap) MapAttribute(javax.persistence.metamodel.MapAttribute) PluralAttribute(com.blazebit.persistence.view.metamodel.PluralAttribute) ExtendedAttribute(com.blazebit.persistence.spi.ExtendedAttribute) ListAttribute(javax.persistence.metamodel.ListAttribute) Attribute(com.blazebit.persistence.view.metamodel.Attribute) Predicate(com.blazebit.persistence.parser.predicate.Predicate) AliasReplacementVisitor(com.blazebit.persistence.parser.AliasReplacementVisitor) MapKeyExpression(com.blazebit.persistence.parser.expression.MapKeyExpression) OrderByItem(com.blazebit.persistence.view.metamodel.OrderByItem) ListIndexExpression(com.blazebit.persistence.parser.expression.ListIndexExpression) UpdatableExpressionVisitor(com.blazebit.persistence.view.impl.UpdatableExpressionVisitor) ManagedViewType(com.blazebit.persistence.view.metamodel.ManagedViewType) ExpressionFactory(com.blazebit.persistence.parser.expression.ExpressionFactory) EntityView(com.blazebit.persistence.view.EntityView) SyntaxErrorException(com.blazebit.persistence.parser.expression.SyntaxErrorException) ScalarTargetResolvingExpressionVisitor(com.blazebit.persistence.view.impl.ScalarTargetResolvingExpressionVisitor) TargetType(com.blazebit.persistence.view.impl.ScalarTargetResolvingExpressionVisitor.TargetType) NumericType(com.blazebit.persistence.parser.expression.NumericType) ManagedType(javax.persistence.metamodel.ManagedType) Type(com.blazebit.persistence.view.metamodel.Type) ExtendedManagedType(com.blazebit.persistence.spi.ExtendedManagedType) ManagedViewType(com.blazebit.persistence.view.metamodel.ManagedViewType) ViewType(com.blazebit.persistence.view.metamodel.ViewType) ListIndexExpression(com.blazebit.persistence.parser.expression.ListIndexExpression) Expression(com.blazebit.persistence.parser.expression.Expression) ParameterExpression(com.blazebit.persistence.parser.expression.ParameterExpression) PathExpression(com.blazebit.persistence.parser.expression.PathExpression) PropertyExpression(com.blazebit.persistence.parser.expression.PropertyExpression) NullExpression(com.blazebit.persistence.parser.expression.NullExpression) MapKeyExpression(com.blazebit.persistence.parser.expression.MapKeyExpression) ParameterExpression(com.blazebit.persistence.parser.expression.ParameterExpression) Collection(java.util.Collection) PrefixingQueryGenerator(com.blazebit.persistence.view.impl.PrefixingQueryGenerator) Map(java.util.Map) HashMap(java.util.HashMap)

Example 3 with AliasReplacementVisitor

use of com.blazebit.persistence.parser.AliasReplacementVisitor in project blaze-persistence by Blazebit.

the class AbstractCommonQueryBuilder method inlineSelectAlias.

void inlineSelectAlias(String selectAlias, Expression expression) {
    final AliasReplacementVisitor aliasReplacementVisitor = new AliasReplacementVisitor(expression, selectAlias);
    ExpressionModifierVisitor<ExpressionModifier> expressionModifierVisitor = new ExpressionModifierVisitor<ExpressionModifier>() {

        @Override
        public void visit(ExpressionModifier expressionModifier, ClauseType clauseType) {
            Expression expr = expressionModifier.get();
            Expression newExpr = expr.accept(aliasReplacementVisitor);
            if (expr != newExpr) {
                expressionModifier.set(newExpr);
            }
        }
    };
    joinManager.apply(expressionModifierVisitor);
    selectManager.apply(expressionModifierVisitor);
    whereManager.apply(expressionModifierVisitor);
    havingManager.apply(expressionModifierVisitor);
    groupByManager.apply(expressionModifierVisitor);
    orderByManager.apply(expressionModifierVisitor);
}
Also used : AliasReplacementVisitor(com.blazebit.persistence.parser.AliasReplacementVisitor) ParameterExpression(javax.persistence.criteria.ParameterExpression) ArrayExpression(com.blazebit.persistence.parser.expression.ArrayExpression) FunctionExpression(com.blazebit.persistence.parser.expression.FunctionExpression) PathElementExpression(com.blazebit.persistence.parser.expression.PathElementExpression) Expression(com.blazebit.persistence.parser.expression.Expression) PathExpression(com.blazebit.persistence.parser.expression.PathExpression) PropertyExpression(com.blazebit.persistence.parser.expression.PropertyExpression) SubqueryExpression(com.blazebit.persistence.parser.expression.SubqueryExpression) ExpressionModifier(com.blazebit.persistence.parser.expression.modifier.ExpressionModifier) ExpressionModifierVisitor(com.blazebit.persistence.impl.transform.ExpressionModifierVisitor)

Example 4 with AliasReplacementVisitor

use of com.blazebit.persistence.parser.AliasReplacementVisitor in project blaze-persistence by Blazebit.

the class MetamodelBuildingContextImpl method getPossibleTargetTypes.

@Override
public List<ScalarTargetResolvingExpressionVisitor.TargetType> getPossibleTargetTypes(Class<?> entityClass, Attribute<?, ?> rootAttribute, Annotation mapping, Map<String, javax.persistence.metamodel.Type<?>> rootTypes) {
    ManagedType<?> managedType = entityMetamodel.getManagedType(entityClass);
    String expression;
    if (mapping instanceof Mapping) {
        expression = ((Mapping) mapping).value();
    } else if (mapping instanceof IdMapping) {
        expression = ((IdMapping) mapping).value();
    } else if (mapping instanceof MappingIndex) {
        expression = ((MappingIndex) mapping).value();
    } else if (mapping instanceof MappingCorrelatedSimple) {
        MappingCorrelatedSimple m = (MappingCorrelatedSimple) mapping;
        managedType = entityMetamodel.getManagedType(m.correlated());
        expression = m.correlationResult();
        // Correlation result is the correlated type, so the possible target type is the managed type
        if (expression.isEmpty()) {
            return Collections.<ScalarTargetResolvingExpressionVisitor.TargetType>singletonList(new ScalarTargetResolvingExpressionVisitor.TargetTypeImpl(false, null, managedType.getJavaType(), null, null));
        }
    } else if (mapping instanceof MappingCorrelated) {
        MappingCorrelated m = (MappingCorrelated) mapping;
        CorrelationProviderFactory correlationProviderFactory = CorrelationProviderHelper.getFactory(m.correlator());
        ScalarTargetResolvingExpressionVisitor resolver = new ScalarTargetResolvingExpressionVisitor(entityClass, getEntityMetamodel(), getJpqlFunctions(), rootTypes);
        javax.persistence.metamodel.Type<?> type = TypeExtractingCorrelationBuilder.extractType(correlationProviderFactory, "_alias", this, resolver);
        if (type == null) {
            // We can't determine the managed type
            return Collections.emptyList();
        }
        managedType = (ManagedType<?>) type;
        expression = m.correlationResult();
        // Correlation result is the correlated type, so the possible target type is the managed type
        if (expression.isEmpty()) {
            return Collections.<ScalarTargetResolvingExpressionVisitor.TargetType>singletonList(new ScalarTargetResolvingExpressionVisitor.TargetTypeImpl(false, null, managedType.getJavaType(), null, null));
        }
    } else if (mapping instanceof MappingSubquery) {
        MappingSubquery mappingSubquery = (MappingSubquery) mapping;
        if (!mappingSubquery.expression().isEmpty()) {
            Expression simpleExpression = typeValidationExpressionFactory.createSimpleExpression(((MappingSubquery) mapping).expression(), false, true, false);
            AliasReplacementVisitor aliasReplacementVisitor = new AliasReplacementVisitor(NullExpression.INSTANCE, mappingSubquery.subqueryAlias());
            simpleExpression.accept(aliasReplacementVisitor);
            ScalarTargetResolvingExpressionVisitor visitor = new ScalarTargetResolvingExpressionVisitor(entityClass, entityMetamodel, jpqlFunctions, rootTypes);
            simpleExpression.accept(visitor);
            return visitor.getPossibleTargetTypes();
        }
        // We can't determine the managed type
        return Collections.emptyList();
    } else {
        // There is no entity model type for other mappings
        return Collections.emptyList();
    }
    // Don't bother with empty expressions or missing managed type, let the validation process handle this
    if (expression.isEmpty() || managedType == null) {
        return Collections.emptyList();
    }
    expression = AbstractAttribute.stripThisFromMapping(expression);
    // The result is "THIS" apparently, so the possible target type is the managed type
    if (expression.isEmpty()) {
        Class<?> leafBaseClass = managedType.getJavaType();
        Class<?> leafBaseKeyClass = null;
        Class<?> leafBaseValueClass = null;
        if (rootAttribute instanceof PluralAttribute<?, ?, ?>) {
            leafBaseClass = rootAttribute.getJavaType();
            leafBaseValueClass = ((PluralAttribute<?, ?, ?>) rootAttribute).getElementType().getJavaType();
            if (rootAttribute instanceof MapAttribute<?, ?, ?>) {
                leafBaseKeyClass = ((MapAttribute<?, ?, ?>) rootAttribute).getKeyJavaType();
            }
        } else if (rootAttribute instanceof SingularAttribute<?, ?>) {
            leafBaseClass = rootAttribute.getJavaType();
        }
        return Collections.<ScalarTargetResolvingExpressionVisitor.TargetType>singletonList(new ScalarTargetResolvingExpressionVisitor.TargetTypeImpl(leafBaseValueClass != null, rootAttribute, leafBaseClass, leafBaseKeyClass, leafBaseValueClass));
    }
    Expression simpleExpression = typeValidationExpressionFactory.createSimpleExpression(expression, false, false, true);
    if (simpleExpression instanceof EntityLiteral) {
        // This is a special case where the mapping i.e. attribute name matches an entity name
        try {
            Attribute<?, ?> attribute = managedType.getAttribute(expression);
            return Collections.<ScalarTargetResolvingExpressionVisitor.TargetType>singletonList(new ScalarTargetResolvingExpressionVisitor.TargetTypeImpl(false, attribute, attribute.getJavaType(), null, attribute.getJavaType()));
        } catch (IllegalArgumentException ex) {
        // Apparently it's not an attribute, so let it run through
        }
    }
    ScalarTargetResolvingExpressionVisitor visitor = new ScalarTargetResolvingExpressionVisitor(managedType, rootAttribute, entityMetamodel, jpqlFunctions, rootTypes);
    simpleExpression.accept(visitor);
    return visitor.getPossibleTargetTypes();
}
Also used : EntityLiteral(com.blazebit.persistence.parser.expression.EntityLiteral) Mapping(com.blazebit.persistence.view.Mapping) IdMapping(com.blazebit.persistence.view.IdMapping) MappingSubquery(com.blazebit.persistence.view.MappingSubquery) IdMapping(com.blazebit.persistence.view.IdMapping) AliasReplacementVisitor(com.blazebit.persistence.parser.AliasReplacementVisitor) CorrelationProviderFactory(com.blazebit.persistence.view.CorrelationProviderFactory) MappingCorrelated(com.blazebit.persistence.view.MappingCorrelated) PluralAttribute(javax.persistence.metamodel.PluralAttribute) MappingIndex(com.blazebit.persistence.view.MappingIndex) ScalarTargetResolvingExpressionVisitor(com.blazebit.persistence.view.impl.ScalarTargetResolvingExpressionVisitor) MapAttribute(javax.persistence.metamodel.MapAttribute) MappingCorrelatedSimple(com.blazebit.persistence.view.MappingCorrelatedSimple) Expression(com.blazebit.persistence.parser.expression.Expression) NullExpression(com.blazebit.persistence.parser.expression.NullExpression)

Aggregations

AliasReplacementVisitor (com.blazebit.persistence.parser.AliasReplacementVisitor)4 Expression (com.blazebit.persistence.parser.expression.Expression)3 PathExpression (com.blazebit.persistence.parser.expression.PathExpression)3 PropertyExpression (com.blazebit.persistence.parser.expression.PropertyExpression)3 NullExpression (com.blazebit.persistence.parser.expression.NullExpression)2 Predicate (com.blazebit.persistence.parser.predicate.Predicate)2 ScalarTargetResolvingExpressionVisitor (com.blazebit.persistence.view.impl.ScalarTargetResolvingExpressionVisitor)2 ExpressionModifierVisitor (com.blazebit.persistence.impl.transform.ExpressionModifierVisitor)1 ArrayExpression (com.blazebit.persistence.parser.expression.ArrayExpression)1 EntityLiteral (com.blazebit.persistence.parser.expression.EntityLiteral)1 ExpressionFactory (com.blazebit.persistence.parser.expression.ExpressionFactory)1 FunctionExpression (com.blazebit.persistence.parser.expression.FunctionExpression)1 ListIndexExpression (com.blazebit.persistence.parser.expression.ListIndexExpression)1 MapKeyExpression (com.blazebit.persistence.parser.expression.MapKeyExpression)1 NumericLiteral (com.blazebit.persistence.parser.expression.NumericLiteral)1 NumericType (com.blazebit.persistence.parser.expression.NumericType)1 ParameterExpression (com.blazebit.persistence.parser.expression.ParameterExpression)1 PathElementExpression (com.blazebit.persistence.parser.expression.PathElementExpression)1 SubqueryExpression (com.blazebit.persistence.parser.expression.SubqueryExpression)1 SyntaxErrorException (com.blazebit.persistence.parser.expression.SyntaxErrorException)1