Search in sources :

Example 1 with ParameterExpression

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

the class JoinVisitor method rewriteToAssociationParam.

private boolean rewriteToAssociationParam(ParameterValueTransformer tranformer, Expression expression) {
    if (!(expression instanceof ParameterExpression)) {
        return false;
    }
    ParameterExpression parameterExpression = (ParameterExpression) expression;
    ParameterManager.ParameterImpl<Object> param = (ParameterManager.ParameterImpl<Object>) parameterManager.getParameter(parameterExpression.getName());
    param.setTransformer(tranformer);
    return true;
}
Also used : ParameterExpression(com.blazebit.persistence.parser.expression.ParameterExpression)

Example 2 with ParameterExpression

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

the class JpaUtils method expandBindings.

public static void expandBindings(Map<String, Integer> bindingMap, Map<String, String> columnBindingMap, Map<String, ExtendedAttribute<?, ?>> attributeEntries, ClauseType clause, AbstractCommonQueryBuilder<?, ?, ?, ?, ?> queryBuilder, String keyFunctionExpression, boolean enableElementCollectionIdCutoff) {
    SelectManager<?> selectManager = queryBuilder.selectManager;
    JoinManager joinManager = queryBuilder.joinManager;
    ParameterManager parameterManager = queryBuilder.parameterManager;
    JpaProvider jpaProvider = queryBuilder.mainQuery.jpaProvider;
    EntityMetamodelImpl metamodel = queryBuilder.mainQuery.metamodel;
    boolean requiresNullCast = queryBuilder.mainQuery.dbmsDialect.requiresNullCast();
    boolean needsCastParameters = queryBuilder.mainQuery.dbmsDialect.needsCastParameters();
    JpaMetamodelAccessor jpaMetamodelAccessor = jpaProvider.getJpaMetamodelAccessor();
    boolean needsElementCollectionIdCutoff = enableElementCollectionIdCutoff && jpaProvider.needsElementCollectionIdCutoff();
    final Queue<String> attributeQueue = new ArrayDeque<>(bindingMap.keySet());
    while (!attributeQueue.isEmpty()) {
        final String attributeName = attributeQueue.remove();
        Integer tupleIndex = bindingMap.get(attributeName);
        Class<?> elementType;
        String columnType;
        boolean splitExpression;
        ExtendedAttribute<?, ?> attributeEntry = attributeEntries.get(attributeName);
        if (attributeEntry == null) {
            if (!attributeName.equalsIgnoreCase(keyFunctionExpression)) {
                continue;
            }
            String realAttributeName = attributeName.substring(attributeName.indexOf('(') + 1, attributeName.length() - 1);
            attributeEntry = attributeEntries.get(realAttributeName);
            if (attributeEntry.getAttribute() instanceof ListAttribute<?, ?>) {
                elementType = Integer.class;
                columnType = queryBuilder.mainQuery.dbmsDialect.getSqlType(Integer.class);
            } else {
                MapAttribute<?, ?, ?> mapAttribute = (MapAttribute<?, ?, ?>) attributeEntry.getAttribute();
                elementType = mapAttribute.getKeyJavaType();
                columnType = attributeEntry.getJoinTable() != null && attributeEntry.getJoinTable().getKeyColumnTypes() != null && attributeEntry.getJoinTable().getKeyColumnTypes().size() == 1 ? attributeEntry.getJoinTable().getKeyColumnTypes().values().iterator().next() : null;
            }
            splitExpression = false;
        } else {
            elementType = attributeEntry.getElementClass();
            columnType = attributeEntry.getColumnTypes().length == 0 ? null : attributeEntry.getColumnTypes()[0];
            final List<Attribute<?, ?>> attributePath = attributeEntry.getAttributePath();
            final Attribute<?, ?> lastAttribute = attributePath.get(attributePath.size() - 1);
            splitExpression = lastAttribute.getPersistentAttributeType() == Attribute.PersistentAttributeType.EMBEDDED;
            if (!splitExpression) {
                if ((clause != ClauseType.SET || jpaProvider.supportsUpdateSetAssociationId()) && jpaMetamodelAccessor.isJoinable(lastAttribute) && !isBasicElementType(lastAttribute)) {
                    splitExpression = true;
                    if (needsElementCollectionIdCutoff) {
                        OUTER: for (int i = 0; i < attributePath.size() - 1; i++) {
                            Attribute<?, ?> attribute = attributePath.get(i);
                            if (attribute.getPersistentAttributeType() == Attribute.PersistentAttributeType.ELEMENT_COLLECTION) {
                                // This is a special case, when an embeddable is between an element collection and the association, we still need to split the expression
                                for (int j = i + 1; j < attributePath.size() - 1; j++) {
                                    attribute = attributePath.get(j);
                                    if (attribute.getPersistentAttributeType() == Attribute.PersistentAttributeType.EMBEDDED) {
                                        break OUTER;
                                    }
                                }
                                splitExpression = false;
                                break;
                            }
                        }
                    }
                }
            }
        }
        SelectInfo selectInfo = selectManager.getSelectInfos().get(tupleIndex);
        final Expression selectExpression = selectInfo.getExpression();
        if (splitExpression) {
            // TODO: Maybe also allow Treat, Case-When, Array?
            if (selectExpression instanceof NullExpression) {
                final Collection<String> embeddedPropertyNames = getEmbeddedPropertyPaths(attributeEntries, attributeName, needsElementCollectionIdCutoff, false);
                if (embeddedPropertyNames.size() > 0) {
                    selectManager.getSelectInfos().remove(tupleIndex.intValue());
                    bindingMap.remove(attributeName);
                    // We are going to insert the expanded attributes as new select items and shift existing ones
                    int delta = embeddedPropertyNames.size() - 1;
                    if (delta > 0) {
                        for (Map.Entry<String, Integer> entry : bindingMap.entrySet()) {
                            if (entry.getValue() > tupleIndex) {
                                entry.setValue(entry.getValue() + delta);
                            }
                        }
                    }
                    int offset = 0;
                    for (String embeddedPropertyName : embeddedPropertyNames) {
                        String nestedAttributePath = attributeName + "." + embeddedPropertyName;
                        ExtendedAttribute<?, ?> nestedAttributeEntry = attributeEntries.get(nestedAttributePath);
                        // Process the nested attribute path recursively
                        attributeQueue.add(nestedAttributePath);
                        // Replace this binding in the binding map, additional selects need an updated index
                        bindingMap.put(nestedAttributePath, tupleIndex + offset);
                        selectManager.select(offset == 0 ? selectExpression : selectExpression.copy(ExpressionCopyContext.EMPTY), null, tupleIndex + offset);
                        if (columnBindingMap != null) {
                            for (String column : nestedAttributeEntry.getColumnNames()) {
                                columnBindingMap.put(column, nestedAttributePath);
                            }
                        }
                        offset++;
                    }
                }
            } else if (selectExpression instanceof PathExpression) {
                boolean firstBinding = true;
                final Collection<String> embeddedPropertyNames = getEmbeddedPropertyPaths(attributeEntries, attributeName, needsElementCollectionIdCutoff, false);
                PathExpression baseExpression = embeddedPropertyNames.size() > 1 ? ((PathExpression) selectExpression).copy(ExpressionCopyContext.EMPTY) : ((PathExpression) selectExpression);
                joinManager.implicitJoin(baseExpression, true, true, true, null, ClauseType.SELECT, new HashSet<String>(), false, false, false, false);
                if (elementType != baseExpression.getPathReference().getType().getJavaType()) {
                    throw new IllegalStateException("An association should be bound to its association type and not its identifier type");
                }
                if (embeddedPropertyNames.size() > 0) {
                    bindingMap.remove(attributeName);
                    // We are going to insert the expanded attributes as new select items and shift existing ones
                    int delta = embeddedPropertyNames.size() - 1;
                    if (delta > 0) {
                        for (Map.Entry<String, Integer> entry : bindingMap.entrySet()) {
                            if (entry.getValue() > tupleIndex) {
                                entry.setValue(entry.getValue() + delta);
                            }
                        }
                    }
                    int offset = 0;
                    for (String embeddedPropertyName : embeddedPropertyNames) {
                        PathExpression pathExpression = firstBinding ? ((PathExpression) selectExpression) : baseExpression.copy(ExpressionCopyContext.EMPTY);
                        for (String propertyNamePart : embeddedPropertyName.split("\\.")) {
                            pathExpression.getExpressions().add(new PropertyExpression(propertyNamePart));
                        }
                        String nestedAttributePath = attributeName + "." + embeddedPropertyName;
                        ExtendedAttribute<?, ?> nestedAttributeEntry = attributeEntries.get(nestedAttributePath);
                        // Process the nested attribute path recursively
                        attributeQueue.add(nestedAttributePath);
                        // Replace this binding in the binding map, additional selects need an updated index
                        bindingMap.put(nestedAttributePath, firstBinding ? tupleIndex : tupleIndex + offset);
                        if (!firstBinding) {
                            selectManager.select(pathExpression, null, tupleIndex + offset);
                        } else {
                            firstBinding = false;
                        }
                        if (columnBindingMap != null) {
                            for (String column : nestedAttributeEntry.getColumnNames()) {
                                columnBindingMap.put(column, nestedAttributePath);
                            }
                        }
                        offset++;
                    }
                }
            } else if (selectExpression instanceof ParameterExpression) {
                final Collection<String> embeddedPropertyNames = getEmbeddedPropertyPaths(attributeEntries, attributeName, jpaProvider.needsElementCollectionIdCutoff(), false);
                if (embeddedPropertyNames.size() > 0) {
                    ParameterExpression parameterExpression = (ParameterExpression) selectExpression;
                    String parameterName = parameterExpression.getName();
                    Map<String, List<String>> parameterAccessPaths = new HashMap<>(embeddedPropertyNames.size());
                    ParameterValueTransformer tranformer = parameterManager.getParameter(parameterName).getTransformer();
                    if (tranformer instanceof SplittingParameterTransformer) {
                        for (String name : ((SplittingParameterTransformer) tranformer).getParameterNames()) {
                            parameterManager.unregisterParameterName(name, clause, queryBuilder);
                        }
                    }
                    selectManager.getSelectInfos().remove(tupleIndex.intValue());
                    bindingMap.remove(attributeName);
                    // We are going to insert the expanded attributes as new select items and shift existing ones
                    int delta = embeddedPropertyNames.size() - 1;
                    if (delta > 0) {
                        for (Map.Entry<String, Integer> entry : bindingMap.entrySet()) {
                            if (entry.getValue() > tupleIndex) {
                                entry.setValue(entry.getValue() + delta);
                            }
                        }
                    }
                    int offset = 0;
                    for (String embeddedPropertyName : embeddedPropertyNames) {
                        String subParamName = "_" + parameterName + "_" + embeddedPropertyName.replace('.', '_');
                        parameterManager.registerParameterName(subParamName, false, clause, queryBuilder);
                        parameterAccessPaths.put(subParamName, Arrays.asList(embeddedPropertyName.split("\\.")));
                        String nestedAttributePath = attributeName + "." + embeddedPropertyName;
                        ExtendedAttribute<?, ?> nestedAttributeEntry = attributeEntries.get(nestedAttributePath);
                        // Process the nested attribute path recursively
                        attributeQueue.add(nestedAttributePath);
                        // Replace this binding in the binding map, additional selects need an updated index
                        bindingMap.put(nestedAttributePath, tupleIndex + offset);
                        selectManager.select(new ParameterExpression(subParamName), null, tupleIndex + offset);
                        if (columnBindingMap != null) {
                            for (String column : nestedAttributeEntry.getColumnNames()) {
                                columnBindingMap.put(column, nestedAttributePath);
                            }
                        }
                        offset++;
                    }
                    parameterManager.getParameter(parameterName).setTransformer(new SplittingParameterTransformer(parameterManager, metamodel, elementType, parameterAccessPaths));
                }
            } else {
                throw new IllegalArgumentException("Illegal expression '" + selectExpression.toString() + "' for binding relation '" + attributeName + "'!");
            }
        } else if (requiresNullCast && selectExpression instanceof NullExpression) {
            if (BasicCastTypes.TYPES.contains(elementType) && queryBuilder.statementType != DbmsStatementType.INSERT) {
                // We also need a cast for parameter expressions except in the SET clause
                List<Expression> arguments = new ArrayList<>(2);
                arguments.add(selectExpression);
                if (columnType != null) {
                    arguments.add(new StringLiteral(columnType));
                }
                selectInfo.set(new FunctionExpression("CAST_" + elementType.getSimpleName(), arguments, selectExpression));
            } else {
                final EntityMetamodelImpl.AttributeExample attributeExample = metamodel.getBasicTypeExampleAttributes().get(elementType);
                if (attributeExample != null) {
                    List<Expression> arguments = new ArrayList<>(2);
                    arguments.add(new SubqueryExpression(new Subquery() {

                        @Override
                        public String getQueryString() {
                            return attributeExample.getExampleJpql() + selectExpression;
                        }
                    }));
                    if (queryBuilder.statementType != DbmsStatementType.INSERT && needsCastParameters) {
                        arguments.add(new StringLiteral(attributeExample.getAttribute().getColumnTypes()[0]));
                    }
                    selectInfo.set(new FunctionExpression(NullfnFunction.FUNCTION_NAME, arguments, selectExpression));
                }
            }
        } else if (selectExpression instanceof ParameterExpression && clause != ClauseType.SET) {
            if (BasicCastTypes.TYPES.contains(elementType) && queryBuilder.statementType != DbmsStatementType.INSERT) {
                // We also need a cast for parameter expressions except in the SET clause
                List<Expression> arguments = new ArrayList<>(2);
                arguments.add(selectExpression);
                if (columnType != null) {
                    arguments.add(new StringLiteral(columnType));
                }
                selectInfo.set(new FunctionExpression("CAST_" + elementType.getSimpleName(), arguments, selectExpression));
            } else {
                final EntityMetamodelImpl.AttributeExample attributeExample = metamodel.getBasicTypeExampleAttributes().get(elementType);
                if (attributeExample != null) {
                    List<Expression> arguments = new ArrayList<>(2);
                    arguments.add(new SubqueryExpression(new Subquery() {

                        @Override
                        public String getQueryString() {
                            return attributeExample.getExampleJpql() + selectExpression;
                        }
                    }));
                    if (queryBuilder.statementType != DbmsStatementType.INSERT && needsCastParameters) {
                        arguments.add(new StringLiteral(attributeExample.getAttribute().getColumnTypes()[0]));
                    }
                    selectInfo.set(new FunctionExpression(ParamFunction.FUNCTION_NAME, arguments, selectExpression));
                }
            }
        }
    }
}
Also used : HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) PathExpression(com.blazebit.persistence.parser.expression.PathExpression) ArrayList(java.util.ArrayList) List(java.util.List) HashSet(java.util.HashSet) ExtendedAttribute(com.blazebit.persistence.spi.ExtendedAttribute) JpaMetamodelAccessor(com.blazebit.persistence.spi.JpaMetamodelAccessor) NullExpression(com.blazebit.persistence.parser.expression.NullExpression) MapAttribute(javax.persistence.metamodel.MapAttribute) StringLiteral(com.blazebit.persistence.parser.expression.StringLiteral) Collection(java.util.Collection) HashMap(java.util.HashMap) Map(java.util.Map) MapAttribute(javax.persistence.metamodel.MapAttribute) Attribute(javax.persistence.metamodel.Attribute) PluralAttribute(javax.persistence.metamodel.PluralAttribute) ExtendedAttribute(com.blazebit.persistence.spi.ExtendedAttribute) ListAttribute(javax.persistence.metamodel.ListAttribute) Subquery(com.blazebit.persistence.parser.expression.Subquery) SubqueryExpression(com.blazebit.persistence.parser.expression.SubqueryExpression) FunctionExpression(com.blazebit.persistence.parser.expression.FunctionExpression) PropertyExpression(com.blazebit.persistence.parser.expression.PropertyExpression) JpaProvider(com.blazebit.persistence.spi.JpaProvider) ArrayDeque(java.util.ArrayDeque) Expression(com.blazebit.persistence.parser.expression.Expression) QualifiedExpression(com.blazebit.persistence.parser.expression.QualifiedExpression) TreatExpression(com.blazebit.persistence.parser.expression.TreatExpression) ParameterExpression(com.blazebit.persistence.parser.expression.ParameterExpression) PathExpression(com.blazebit.persistence.parser.expression.PathExpression) PropertyExpression(com.blazebit.persistence.parser.expression.PropertyExpression) ArrayExpression(com.blazebit.persistence.parser.expression.ArrayExpression) NullExpression(com.blazebit.persistence.parser.expression.NullExpression) FunctionExpression(com.blazebit.persistence.parser.expression.FunctionExpression) SubqueryExpression(com.blazebit.persistence.parser.expression.SubqueryExpression) ParameterExpression(com.blazebit.persistence.parser.expression.ParameterExpression) ListAttribute(javax.persistence.metamodel.ListAttribute)

Example 3 with ParameterExpression

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

the class JoinManager method getJoinAlias.

private String getJoinAlias(ArrayExpression expr) {
    StringBuilder sb = new StringBuilder(expr.getBase().toString());
    Expression indexExpr = expr.getIndex();
    if (indexExpr instanceof ParameterExpression) {
        ParameterExpression indexParamExpr = (ParameterExpression) indexExpr;
        sb.append('_');
        sb.append(indexParamExpr.getName());
    } else if (indexExpr instanceof NumericLiteral) {
        sb.append('_');
        sb.append(((NumericLiteral) indexExpr).getValue());
    } else if (indexExpr instanceof StringLiteral) {
        sb.append('_');
        sb.append(((StringLiteral) indexExpr).getValue());
    } else {
        sb.append('_');
        String indexStringExpr = indexExpr.toString();
        for (int i = 0; i < indexStringExpr.length(); i++) {
            final char c = indexStringExpr.charAt(i);
            if (Character.isJavaIdentifierPart(c)) {
                sb.append(c);
            } else {
                sb.append('_');
            }
        }
    }
    return sb.toString();
}
Also used : NumericLiteral(com.blazebit.persistence.parser.expression.NumericLiteral) StringLiteral(com.blazebit.persistence.parser.expression.StringLiteral) ListIndexExpression(com.blazebit.persistence.parser.expression.ListIndexExpression) Expression(com.blazebit.persistence.parser.expression.Expression) QualifiedExpression(com.blazebit.persistence.parser.expression.QualifiedExpression) TreatExpression(com.blazebit.persistence.parser.expression.TreatExpression) ParameterExpression(com.blazebit.persistence.parser.expression.ParameterExpression) PathExpression(com.blazebit.persistence.parser.expression.PathExpression) PropertyExpression(com.blazebit.persistence.parser.expression.PropertyExpression) ArrayExpression(com.blazebit.persistence.parser.expression.ArrayExpression) FunctionExpression(com.blazebit.persistence.parser.expression.FunctionExpression) SubqueryExpression(com.blazebit.persistence.parser.expression.SubqueryExpression) PathElementExpression(com.blazebit.persistence.parser.expression.PathElementExpression) GeneralCaseExpression(com.blazebit.persistence.parser.expression.GeneralCaseExpression) MapEntryExpression(com.blazebit.persistence.parser.expression.MapEntryExpression) MapValueExpression(com.blazebit.persistence.parser.expression.MapValueExpression) MapKeyExpression(com.blazebit.persistence.parser.expression.MapKeyExpression) ParameterExpression(com.blazebit.persistence.parser.expression.ParameterExpression)

Example 4 with ParameterExpression

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

the class ResolvingQueryGenerator method visit.

@Override
public void visit(InPredicate predicate) {
    boolean quantifiedPredicate = this.quantifiedPredicate;
    this.quantifiedPredicate = true;
    if (predicate.getRight().size() == 1 && jpaProvider.needsAssociationToIdRewriteInOnClause() && clauseType == ClauseType.JOIN) {
        Expression right = predicate.getRight().get(0);
        if (right instanceof ParameterExpression) {
            ParameterExpression parameterExpression = (ParameterExpression) right;
            @SuppressWarnings("unchecked") Type<?> associationType = getAssociationType(predicate.getLeft(), right);
            // If the association type is a entity type, we transform it
            if (associationType instanceof EntityType<?>) {
                renderEquality(predicate.getLeft(), right, predicate.isNegated(), PredicateQuantifier.ONE);
            } else {
                super.visit(predicate);
            }
        } else if (right instanceof PathExpression) {
            renderEquality(predicate.getLeft(), right, predicate.isNegated(), PredicateQuantifier.ONE);
        } else {
            super.visit(predicate);
        }
    } else {
        super.visit(predicate);
    }
    this.quantifiedPredicate = quantifiedPredicate;
}
Also used : EntityType(javax.persistence.metamodel.EntityType) PathExpression(com.blazebit.persistence.parser.expression.PathExpression) ListIndexExpression(com.blazebit.persistence.parser.expression.ListIndexExpression) Expression(com.blazebit.persistence.parser.expression.Expression) QualifiedExpression(com.blazebit.persistence.parser.expression.QualifiedExpression) TreatExpression(com.blazebit.persistence.parser.expression.TreatExpression) ParameterExpression(com.blazebit.persistence.parser.expression.ParameterExpression) ArithmeticExpression(com.blazebit.persistence.parser.expression.ArithmeticExpression) PathExpression(com.blazebit.persistence.parser.expression.PathExpression) AggregateExpression(com.blazebit.persistence.parser.expression.AggregateExpression) ArrayExpression(com.blazebit.persistence.parser.expression.ArrayExpression) FunctionExpression(com.blazebit.persistence.parser.expression.FunctionExpression) SubqueryExpression(com.blazebit.persistence.parser.expression.SubqueryExpression) MapValueExpression(com.blazebit.persistence.parser.expression.MapValueExpression) NullExpression(com.blazebit.persistence.parser.expression.NullExpression) MapKeyExpression(com.blazebit.persistence.parser.expression.MapKeyExpression) ParameterExpression(com.blazebit.persistence.parser.expression.ParameterExpression)

Example 5 with ParameterExpression

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

the class ResolvingQueryGenerator method rewriteToIdParam.

private void rewriteToIdParam(Expression expression) {
    if (!(expression instanceof ParameterExpression)) {
        return;
    }
    ParameterExpression parameterExpression = (ParameterExpression) expression;
    ParameterManager.ParameterImpl<Object> param = (ParameterManager.ParameterImpl<Object>) parameterManager.getParameter(parameterExpression.getName());
    param.setTransformer(parameterTransformerFactory.getToIdTransformer());
}
Also used : ParameterExpression(com.blazebit.persistence.parser.expression.ParameterExpression)

Aggregations

ParameterExpression (com.blazebit.persistence.parser.expression.ParameterExpression)15 Expression (com.blazebit.persistence.parser.expression.Expression)9 PathExpression (com.blazebit.persistence.parser.expression.PathExpression)9 FunctionExpression (com.blazebit.persistence.parser.expression.FunctionExpression)8 MapKeyExpression (com.blazebit.persistence.parser.expression.MapKeyExpression)8 SubqueryExpression (com.blazebit.persistence.parser.expression.SubqueryExpression)8 ListIndexExpression (com.blazebit.persistence.parser.expression.ListIndexExpression)7 PropertyExpression (com.blazebit.persistence.parser.expression.PropertyExpression)7 TreatExpression (com.blazebit.persistence.parser.expression.TreatExpression)7 ArrayExpression (com.blazebit.persistence.parser.expression.ArrayExpression)6 MapValueExpression (com.blazebit.persistence.parser.expression.MapValueExpression)6 NullExpression (com.blazebit.persistence.parser.expression.NullExpression)5 AggregateExpression (com.blazebit.persistence.parser.expression.AggregateExpression)4 PathElementExpression (com.blazebit.persistence.parser.expression.PathElementExpression)4 QualifiedExpression (com.blazebit.persistence.parser.expression.QualifiedExpression)4 HashMap (java.util.HashMap)4 ArithmeticExpression (com.blazebit.persistence.parser.expression.ArithmeticExpression)3 MapEntryExpression (com.blazebit.persistence.parser.expression.MapEntryExpression)3 NumericLiteral (com.blazebit.persistence.parser.expression.NumericLiteral)3 StringLiteral (com.blazebit.persistence.parser.expression.StringLiteral)3