use of com.blazebit.persistence.view.impl.StaticPathCorrelationProvider 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());
}
}
}
}
}
use of com.blazebit.persistence.view.impl.StaticPathCorrelationProvider 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));
}
}
}
use of com.blazebit.persistence.view.impl.StaticPathCorrelationProvider in project blaze-persistence by Blazebit.
the class CorrelatedSubviewJoinTupleTransformerFactory method create.
@Override
public TupleTransformer create(ParameterHolder<?> parameterHolder, Map<String, Object> optionalParameters, EntityViewConfiguration entityViewConfiguration) {
if (!entityViewConfiguration.hasSubFetches(attributePath)) {
return new NullTupleTransformer(template);
}
// For now it's ok, but at some point we will want to support correlated attributes somehow and need to think of a fallback solution here
if (parameterHolder instanceof FullQueryBuilder<?, ?>) {
FullQueryBuilder<?, ?> queryBuilder = (FullQueryBuilder<?, ?>) parameterHolder;
CorrelationProvider provider = correlationProviderFactory.create(parameterHolder, optionalParameters);
JoinCorrelationBuilder correlationBuilder = new JoinCorrelationBuilder(parameterHolder, optionalParameters, queryBuilder, joinBase, correlationAlias, correlationExternalAlias, attributePath, JoinType.LEFT, limiter);
int originalFirstResult = -1;
int originalMaxResults = -1;
if (queryBuilder instanceof LimitBuilder<?>) {
originalFirstResult = ((LimitBuilder<?>) queryBuilder).getFirstResult();
originalMaxResults = ((LimitBuilder<?>) queryBuilder).getMaxResults();
}
ViewJpqlMacro viewJpqlMacro = entityViewConfiguration.getViewJpqlMacro();
EmbeddingViewJpqlMacro embeddingViewJpqlMacro = entityViewConfiguration.getEmbeddingViewJpqlMacro();
String oldViewPath = viewJpqlMacro.getViewPath();
String oldEmbeddingViewPath = embeddingViewJpqlMacro.getEmbeddingViewPath();
// If this uses a static path, we need to avoid setting the embedding view path etc.
if (!(provider instanceof StaticPathCorrelationProvider)) {
viewJpqlMacro.setViewPath(correlationBuilder.getCorrelationAlias());
embeddingViewJpqlMacro.setEmbeddingViewPath(embeddingViewPath);
}
provider.applyCorrelation(correlationBuilder, correlationBasis);
if (queryBuilder instanceof LimitBuilder<?>) {
if (originalFirstResult != ((LimitBuilder<?>) queryBuilder).getFirstResult() || originalMaxResults != ((LimitBuilder<?>) queryBuilder).getMaxResults()) {
throw new IllegalArgumentException("Correlation provider '" + provider + "' wrongly uses setFirstResult() or setMaxResults() on the query builder which might lead to wrong results. Use SELECT fetching with batch size 1 or reformulate the correlation provider to use the limit/offset in a subquery!");
}
}
correlationBuilder.finish();
if (!(provider instanceof StaticPathCorrelationProvider)) {
viewJpqlMacro.setViewPath(oldViewPath);
embeddingViewJpqlMacro.setEmbeddingViewPath(oldEmbeddingViewPath);
}
if (fetches.length != 0) {
for (int i = 0; i < fetches.length; i++) {
queryBuilder.fetch(correlationBuilder.getCorrelationAlias() + "." + fetches[i]);
}
}
ObjectBuilder<Object[]> objectBuilder = template.createObjectBuilder(parameterHolder, optionalParameters, entityViewConfiguration, 0, true, false);
return new CorrelatedSubviewJoinTupleTransformer(template, objectBuilder);
} else {
throw new UnsupportedOperationException("Converting views with correlated attributes isn't supported!");
}
}
Aggregations