Search in sources :

Example 1 with OrderByItem

use of com.blazebit.persistence.view.metamodel.OrderByItem 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 2 with OrderByItem

use of com.blazebit.persistence.view.metamodel.OrderByItem in project blaze-persistence by Blazebit.

the class ManagedViewTypeImpl method checkAttributes.

@Override
public void checkAttributes(MetamodelBuildingContext context) {
    if (inheritanceMapping != null) {
        ScalarTargetResolvingExpressionVisitor visitor = new ScalarTargetResolvingExpressionVisitor(jpaManagedType, context.getEntityMetamodel(), context.getJpqlFunctions(), viewRootTypes);
        try {
            context.getExpressionFactory().createBooleanExpression(inheritanceMapping, false).accept(visitor);
        } catch (RuntimeException ex) {
            context.addError("Invalid inheritance mapping expression '" + inheritanceMapping + "' on the entity view " + javaType.getName() + ". Encountered error: " + ex.getMessage());
        }
    }
    // Ensure that a plural entity attribute is not used multiple times in different plural entity view attributes
    // If it were used multiple times, the second collection would not receive all expected elements, because both are based on the same join
    // and the first collection will already cause a "fold" of the results for materializing the collection in the entity view
    // We could theoretically try to defer the "fold" action, but the current model makes this pretty hard. The obvious workaround is to map a plural subview attribute
    // and put all mappings into that. This will guarantee that the "fold" action only happens after all properties have been processed
    Map<String, List<String>> collectionMappings = new HashMap<>();
    Map<String, List<String>> collectionMappingSingulars = new HashMap<>();
    for (AbstractMethodAttribute<? super X, ?> attribute : attributes.values()) {
        attribute.checkAttribute(jpaManagedType, context);
        for (Map.Entry<String, Boolean> entry : attribute.getCollectionJoinMappings(jpaManagedType, context).entrySet()) {
            if (entry.getValue()) {
                List<String> locations = collectionMappingSingulars.get(entry.getKey());
                if (locations == null) {
                    locations = new ArrayList<>(2);
                    collectionMappingSingulars.put(entry.getKey(), locations);
                }
                locations.add("Attribute '" + attribute.getName() + "' in entity view '" + javaType.getName() + "'");
            } else {
                List<String> locations = collectionMappings.get(entry.getKey());
                if (locations == null) {
                    locations = new ArrayList<>(2);
                    collectionMappings.put(entry.getKey(), locations);
                }
                locations.add("Attribute '" + attribute.getName() + "' in entity view '" + javaType.getName() + "'");
            }
        }
    }
    if (!constructorIndex.isEmpty()) {
        for (MappingConstructorImpl<X> constructor : constructorIndex.values()) {
            Map<String, List<String>> constructorCollectionMappings = new HashMap<>();
            for (Map.Entry<String, List<String>> entry : collectionMappings.entrySet()) {
                constructorCollectionMappings.put(entry.getKey(), new ArrayList<>(entry.getValue()));
            }
            constructor.checkParameters(jpaManagedType, constructorCollectionMappings, collectionMappingSingulars, context);
            reportCollectionMappingErrors(context, collectionMappings, collectionMappingSingulars);
        }
    } else {
        reportCollectionMappingErrors(context, collectionMappings, collectionMappingSingulars);
    }
    for (ViewRoot viewRoot : viewRoots) {
        if (viewRoot.getType() != null) {
            String location = "entity view root with the name '" + viewRoot.getName() + "' on type '" + javaType.getName() + "'";
            ScalarTargetResolvingExpressionVisitor visitor = new ScalarTargetResolvingExpressionVisitor((ManagedType<?>) viewRoot.getType(), context.getEntityMetamodel(), context.getJpqlFunctions(), viewRootTypes);
            String[] fetches = viewRoot.getFetches();
            if (fetches.length != 0) {
                if (!(viewRoot.getType() instanceof ManagedType<?>)) {
                    context.addError("Specifying fetches for non-entity attribute type [" + Arrays.toString(fetches) + "] at the " + location + " 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 " + location + ". 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 " + location + ": " + ex.getMessage());
                            }
                        } catch (IllegalArgumentException ex) {
                            context.addError("An error occurred while trying to resolve the " + errorLocation + " '" + fetch + "' of the " + location + ": " + ex.getMessage());
                        }
                    }
                }
            }
            String limitExpression = viewRoot.getLimitExpression();
            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 " + location + ": 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 " + location + ": " + ex.getMessage());
                } catch (IllegalArgumentException ex) {
                    context.addError("An error occurred while trying to resolve the limit expression '" + limitExpression + "' of the " + location + ": " + ex.getMessage());
                }
                String offsetExpression = viewRoot.getOffsetExpression();
                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 " + location + ": 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 " + location + ": " + ex.getMessage());
                } catch (IllegalArgumentException ex) {
                    context.addError("An error occurred while trying to resolve the offset expression '" + offsetExpression + "' of the " + location + ": " + ex.getMessage());
                }
                List<OrderByItem> orderByItems = viewRoot.getOrderByItems();
                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 " + location + ": " + ex.getMessage());
                    } catch (IllegalArgumentException ex) {
                        context.addError("An error occurred while trying to resolve the " + (i + 1) + "th order by expression '" + expression + "' of the " + location + ": " + ex.getMessage());
                    }
                }
            }
            CorrelationProviderFactory correlationProviderFactory = viewRoot.getCorrelationProviderFactory();
            Predicate correlationPredicate = null;
            if (correlationProviderFactory instanceof StaticCorrelationProvider) {
                correlationPredicate = ((StaticCorrelationProvider) correlationProviderFactory).getCorrelationPredicate();
            } else if (correlationProviderFactory instanceof StaticPathCorrelationProvider) {
                correlationPredicate = ((StaticPathCorrelationProvider) correlationProviderFactory).getCorrelationPredicate();
                String correlationPath = ((StaticPathCorrelationProvider) correlationProviderFactory).getCorrelationPath();
                try {
                    ScalarTargetResolvingExpressionVisitor correlationPathVisitor = new ScalarTargetResolvingExpressionVisitor(getJpaManagedType(), context.getEntityMetamodel(), context.getJpqlFunctions(), viewRootTypes);
                    context.getTypeValidationExpressionFactory().createSimpleExpression(correlationPath, false, false, true).accept(correlationPathVisitor);
                } catch (SyntaxErrorException ex) {
                    context.addError("Syntax error in the expression '" + correlationPath + "' of the " + location + ": " + ex.getMessage());
                } catch (IllegalArgumentException ex) {
                    context.addError("An error occurred while trying to resolve the expression '" + correlationPath + "' of the " + location + ": " + ex.getMessage());
                }
            }
            if (correlationPredicate != null) {
                try {
                    visitor.clear();
                    correlationPredicate.accept(visitor);
                } catch (SyntaxErrorException ex) {
                    context.addError("Syntax error in the condition expression '" + correlationPredicate + "' of the " + location + ": " + ex.getMessage());
                } catch (IllegalArgumentException ex) {
                    context.addError("An error occurred while trying to resolve the condition expression '" + correlationPredicate + "' of the " + location + ": " + ex.getMessage());
                }
            }
        }
    }
}
Also used : NumericLiteral(com.blazebit.persistence.parser.expression.NumericLiteral) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) Predicate(com.blazebit.persistence.parser.predicate.Predicate) OrderByItem(com.blazebit.persistence.view.metamodel.OrderByItem) CorrelationProviderFactory(com.blazebit.persistence.view.CorrelationProviderFactory) List(java.util.List) ArrayList(java.util.ArrayList) ManagedType(javax.persistence.metamodel.ManagedType) ExtendedManagedType(com.blazebit.persistence.spi.ExtendedManagedType) ViewRoot(com.blazebit.persistence.view.metamodel.ViewRoot) SyntaxErrorException(com.blazebit.persistence.parser.expression.SyntaxErrorException) ScalarTargetResolvingExpressionVisitor(com.blazebit.persistence.view.impl.ScalarTargetResolvingExpressionVisitor) Expression(com.blazebit.persistence.parser.expression.Expression) ParameterExpression(com.blazebit.persistence.parser.expression.ParameterExpression) ParameterExpression(com.blazebit.persistence.parser.expression.ParameterExpression) StaticPathCorrelationProvider(com.blazebit.persistence.view.impl.StaticPathCorrelationProvider) Map(java.util.Map) NavigableMap(java.util.NavigableMap) SortedMap(java.util.SortedMap) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) TreeMap(java.util.TreeMap) StaticCorrelationProvider(com.blazebit.persistence.view.impl.StaticCorrelationProvider)

Example 3 with OrderByItem

use of com.blazebit.persistence.view.metamodel.OrderByItem in project blaze-persistence by Blazebit.

the class ManagedViewTypeImpl method createLimiter.

@Override
public Limiter createLimiter(ExpressionFactory expressionFactory, String prefix, String limitExpression, String offsetExpression, List<OrderByItem> orderByItems) {
    if (limitExpression != null) {
        List<OrderByItem> items;
        if (orderByItems.isEmpty()) {
            items = Collections.emptyList();
        } else {
            PrefixingQueryGenerator prefixingQueryGenerator = new PrefixingQueryGenerator(expressionFactory, prefix, null, null, getEntityViewRootTypes().keySet(), true, false);
            StringBuilder sb = new StringBuilder();
            prefixingQueryGenerator.setQueryBuffer(sb);
            items = new ArrayList<>(orderByItems.size());
            for (int i = 0; i < orderByItems.size(); i++) {
                OrderByItem orderByItem = orderByItems.get(i);
                Expression expr = expressionFactory.createSimpleExpression(orderByItem.getExpression(), false, false, true);
                sb.setLength(0);
                expr.accept(prefixingQueryGenerator);
                items.add(new OrderByItem(sb.toString(), orderByItem.isAscending(), orderByItem.isNullsFirst()));
            }
        }
        return new Limiter(limitExpression, offsetExpression, items);
    }
    return null;
}
Also used : OrderByItem(com.blazebit.persistence.view.metamodel.OrderByItem) Expression(com.blazebit.persistence.parser.expression.Expression) ParameterExpression(com.blazebit.persistence.parser.expression.ParameterExpression) PrefixingQueryGenerator(com.blazebit.persistence.view.impl.PrefixingQueryGenerator) Limiter(com.blazebit.persistence.view.impl.objectbuilder.Limiter)

Example 4 with OrderByItem

use of com.blazebit.persistence.view.metamodel.OrderByItem in project blaze-persistence by Blazebit.

the class ViewMappingImpl method initViewRoots.

private void initViewRoots(MetamodelBuildingContext context) {
    if (entityViewRoots == null || entityViewRoots.isEmpty()) {
        this.viewRoots = Collections.emptySet();
        this.viewRootTypes = Collections.emptyMap();
    } else {
        this.viewRoots = new LinkedHashSet<>(entityViewRoots.size());
        this.viewRootTypes = new HashMap<>(entityViewRoots.size());
        Set<String> rootAliases = new HashSet<>(entityViewRoots.size());
        for (EntityViewRootMapping entityViewRoot : entityViewRoots) {
            rootAliases.add(entityViewRoot.getName());
        }
        for (EntityViewRootMapping entityViewRoot : entityViewRoots) {
            String viewRootName = entityViewRoot.getName();
            Class<?> entityClass = entityViewRoot.getManagedTypeClass();
            String joinExpression = entityViewRoot.getJoinExpression();
            Class<? extends CorrelationProvider> correlationProvider = entityViewRoot.getCorrelationProvider();
            CorrelationProviderFactory correlationProviderFactory = null;
            javax.persistence.metamodel.Type<?> type = null;
            String conditionExpression = entityViewRoot.getConditionExpression();
            if (entityClass != null) {
                if (joinExpression != null || correlationProvider != null) {
                    context.addError("Illegal entity view root mapping '" + viewRootName + "' at the class '" + entityViewClass.getName() + "'! Only one of the attributes entity, expression or correlator may be used!");
                }
                if (conditionExpression == null) {
                    context.addError("Illegal entity view root mapping '" + viewRootName + "' at the class '" + entityViewClass.getName() + "'! When using the entity attribute, a condition expression is required!");
                } else {
                    correlationProviderFactory = new StaticCorrelationProvider(entityClass, viewRootName, conditionExpression, createPredicate(conditionExpression, context, viewRootName), rootAliases);
                }
            } else if (joinExpression != null) {
                if (correlationProvider != null) {
                    context.addError("Illegal entity view root mapping '" + viewRootName + "' at the class '" + entityViewClass.getName() + "'! Only one of the attributes entity, expression or correlator may be used!");
                }
                if (conditionExpression == null) {
                    correlationProviderFactory = new StaticPathCorrelationProvider(joinExpression, viewRootName, "1=1", createPredicate("1=1", context, viewRootName), rootAliases);
                } else {
                    correlationProviderFactory = new StaticPathCorrelationProvider(joinExpression, viewRootName, conditionExpression, createPredicate(conditionExpression, context, viewRootName), rootAliases);
                }
            } else if (correlationProvider != null) {
                if (conditionExpression != null) {
                    context.addError("Illegal entity view root mapping '" + viewRootName + "' at the class '" + entityViewClass.getName() + "'! When using the correlator attribute, using a condition expression is illegal!");
                }
                correlationProviderFactory = CorrelationProviderHelper.getFactory(correlationProvider);
            } else {
                context.addError("Illegal entity view root mapping '" + viewRootName + "' at the class '" + entityViewClass.getName() + "'! One of the attributes entity, expression or correlator must be used for a valid entity view root definition!");
            }
            String limitExpression;
            String offsetExpression;
            List<OrderByItem> orderByItems;
            if (entityViewRoot.getLimitExpression() == null || entityViewRoot.getLimitExpression().isEmpty()) {
                limitExpression = null;
                offsetExpression = null;
                orderByItems = Collections.emptyList();
            } else {
                limitExpression = entityViewRoot.getLimitExpression();
                offsetExpression = entityViewRoot.getOffsetExpression();
                if (offsetExpression == null || offsetExpression.isEmpty()) {
                    offsetExpression = "0";
                }
                List<String> orderByItemExpressions = entityViewRoot.getOrderByItems();
                orderByItems = AbstractAttribute.parseOrderByItems(orderByItemExpressions);
            }
            try {
                type = TypeExtractingCorrelationBuilder.extractType(correlationProviderFactory, viewRootName, context, new ScalarTargetResolvingExpressionVisitor(getManagedType(context), context.getEntityMetamodel(), context.getJpqlFunctions(), viewRootTypes));
            } catch (Exception ex) {
                StringWriter sw = new StringWriter();
                sw.append("Illegal entity view root mapping '").append(viewRootName).append("' at the class '").append(entityViewClass.getName()).append("'! The given entity class is not a valid managed type:\n");
                ex.printStackTrace(new PrintWriter(sw));
                context.addError(sw.toString());
            }
            viewRootTypes.put(viewRootName, type);
            viewRoots.add(new ViewRootImpl(viewRootName, type, correlationProviderFactory, correlationProvider, entityViewRoot.getJoinType(), entityViewRoot.getFetches(), orderByItems, limitExpression, offsetExpression));
        }
    }
}
Also used : ScalarTargetResolvingExpressionVisitor(com.blazebit.persistence.view.impl.ScalarTargetResolvingExpressionVisitor) SyntaxErrorException(com.blazebit.persistence.parser.expression.SyntaxErrorException) OrderByItem(com.blazebit.persistence.view.metamodel.OrderByItem) CorrelationProviderFactory(com.blazebit.persistence.view.CorrelationProviderFactory) StringWriter(java.io.StringWriter) StaticPathCorrelationProvider(com.blazebit.persistence.view.impl.StaticPathCorrelationProvider) EntityViewRootMapping(com.blazebit.persistence.view.spi.EntityViewRootMapping) StaticCorrelationProvider(com.blazebit.persistence.view.impl.StaticCorrelationProvider) HashSet(java.util.HashSet) LinkedHashSet(java.util.LinkedHashSet) PrintWriter(java.io.PrintWriter)

Example 5 with OrderByItem

use of com.blazebit.persistence.view.metamodel.OrderByItem in project blaze-persistence by Blazebit.

the class Limiter method apply.

public <T extends LimitBuilder<?> & OrderByBuilder<?>> void apply(ParameterHolder<?> parameterHolder, Map<String, Object> optionalParameters, T builder) {
    Integer limitValue = this.limitValue;
    if (limitValue == null) {
        limitValue = (Integer) optionalParameters.get(limitParameter);
        if (limitValue == null) {
            limitValue = (Integer) parameterHolder.getParameterValue(limitParameter);
        }
        if (limitValue == null) {
            return;
        }
    }
    for (OrderByItem orderByItem : orderByItems) {
        builder.orderBy(orderByItem.getExpression(), orderByItem.isAscending(), orderByItem.isNullsFirst());
    }
    builder.setMaxResults(limitValue);
    Integer offsetValue = this.offsetValue;
    if (offsetValue == null) {
        offsetValue = (Integer) optionalParameters.get(offsetParameter);
        if (offsetValue == null) {
            offsetValue = (Integer) parameterHolder.getParameterValue(offsetParameter);
        }
    }
    if (offsetValue != null) {
        builder.setFirstResult(offsetValue);
    }
}
Also used : OrderByItem(com.blazebit.persistence.view.metamodel.OrderByItem)

Aggregations

OrderByItem (com.blazebit.persistence.view.metamodel.OrderByItem)6 Expression (com.blazebit.persistence.parser.expression.Expression)3 ParameterExpression (com.blazebit.persistence.parser.expression.ParameterExpression)3 SyntaxErrorException (com.blazebit.persistence.parser.expression.SyntaxErrorException)3 ScalarTargetResolvingExpressionVisitor (com.blazebit.persistence.view.impl.ScalarTargetResolvingExpressionVisitor)3 NumericLiteral (com.blazebit.persistence.parser.expression.NumericLiteral)2 Predicate (com.blazebit.persistence.parser.predicate.Predicate)2 ExtendedManagedType (com.blazebit.persistence.spi.ExtendedManagedType)2 CorrelationProviderFactory (com.blazebit.persistence.view.CorrelationProviderFactory)2 PrefixingQueryGenerator (com.blazebit.persistence.view.impl.PrefixingQueryGenerator)2 StaticCorrelationProvider (com.blazebit.persistence.view.impl.StaticCorrelationProvider)2 StaticPathCorrelationProvider (com.blazebit.persistence.view.impl.StaticPathCorrelationProvider)2 ArrayList (java.util.ArrayList)2 HashMap (java.util.HashMap)2 Map (java.util.Map)2 ManagedType (javax.persistence.metamodel.ManagedType)2 AliasReplacementVisitor (com.blazebit.persistence.parser.AliasReplacementVisitor)1 ExpressionFactory (com.blazebit.persistence.parser.expression.ExpressionFactory)1 ListIndexExpression (com.blazebit.persistence.parser.expression.ListIndexExpression)1 MapKeyExpression (com.blazebit.persistence.parser.expression.MapKeyExpression)1