Search in sources :

Example 1 with StaticCorrelationProvider

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

use of com.blazebit.persistence.view.impl.StaticCorrelationProvider 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)

Aggregations

SyntaxErrorException (com.blazebit.persistence.parser.expression.SyntaxErrorException)2 CorrelationProviderFactory (com.blazebit.persistence.view.CorrelationProviderFactory)2 ScalarTargetResolvingExpressionVisitor (com.blazebit.persistence.view.impl.ScalarTargetResolvingExpressionVisitor)2 StaticCorrelationProvider (com.blazebit.persistence.view.impl.StaticCorrelationProvider)2 StaticPathCorrelationProvider (com.blazebit.persistence.view.impl.StaticPathCorrelationProvider)2 OrderByItem (com.blazebit.persistence.view.metamodel.OrderByItem)2 Expression (com.blazebit.persistence.parser.expression.Expression)1 NumericLiteral (com.blazebit.persistence.parser.expression.NumericLiteral)1 ParameterExpression (com.blazebit.persistence.parser.expression.ParameterExpression)1 Predicate (com.blazebit.persistence.parser.predicate.Predicate)1 ExtendedManagedType (com.blazebit.persistence.spi.ExtendedManagedType)1 ViewRoot (com.blazebit.persistence.view.metamodel.ViewRoot)1 EntityViewRootMapping (com.blazebit.persistence.view.spi.EntityViewRootMapping)1 PrintWriter (java.io.PrintWriter)1 StringWriter (java.io.StringWriter)1 ArrayList (java.util.ArrayList)1 HashMap (java.util.HashMap)1 HashSet (java.util.HashSet)1 LinkedHashMap (java.util.LinkedHashMap)1 LinkedHashSet (java.util.LinkedHashSet)1