use of com.blazebit.persistence.parser.expression.Subquery 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));
}
}
}
}
}
use of com.blazebit.persistence.parser.expression.Subquery in project blaze-persistence by Blazebit.
the class SelectManager method wrapPlainParameters.
public void wrapPlainParameters() {
boolean needsCastParameters = queryBuilder.mainQuery.dbmsDialect.needsCastParameters();
for (int i = 0; i < selectInfos.size(); i++) {
SelectInfo selectInfo = selectInfos.get(i);
final Expression expression = selectInfo.getExpression();
if (expression instanceof ParameterExpression) {
String parameterName = ((ParameterExpression) expression).getName();
ParameterManager.ParameterImpl<?> parameter = parameterManager.getParameter(parameterName);
Object boundValue = parameter.getValue();
Class<?> elementType;
if (parameter.getParameterType() == null) {
if (boundValue == null) {
throw new IllegalArgumentException("Can't use the parameter with name '" + parameterName + "' as plain SELECT item with a null value!");
}
ParameterManager.ParameterValue parameterValue = parameter.getParameterValue();
if (parameterValue == null) {
elementType = boundValue.getClass();
} else {
elementType = parameterValue.getValueType();
}
} else {
elementType = parameter.getParameterType();
}
if (BasicCastTypes.TYPES.contains(elementType) && needsCastParameters) {
// We also need a cast for parameter expressions except in the SET clause
List<Expression> arguments = new ArrayList<>(2);
arguments.add(expression);
arguments.add(new StringLiteral(mainQuery.dbmsDialect.getSqlType(elementType)));
selectInfo.set(new FunctionExpression("CAST_" + elementType.getSimpleName(), arguments, expression));
} else {
final EntityMetamodelImpl.AttributeExample attributeExample = mainQuery.metamodel.getBasicTypeExampleAttributes().get(elementType);
if (attributeExample == null) {
throw new IllegalArgumentException("Can't use the parameter with name '" + parameterName + "', type '" + elementType.getName() + "' and value '" + boundValue + "' as plain SELECT item because there is no example attribute with that type in the JPA model providing the SQL type!");
}
List<Expression> arguments = new ArrayList<>(2);
arguments.add(new SubqueryExpression(new Subquery() {
@Override
public String getQueryString() {
return attributeExample.getExampleJpql() + expression;
}
}));
if (needsCastParameters && attributeExample.getAttribute().getColumnTypes().length != 0) {
arguments.add(new StringLiteral(attributeExample.getAttribute().getColumnTypes()[0]));
}
selectInfo.set(new FunctionExpression(ParamFunction.FUNCTION_NAME, arguments, expression));
}
}
}
}
use of com.blazebit.persistence.parser.expression.Subquery in project blaze-persistence by Blazebit.
the class SelectManager method addJpqlFunctionProcessor.
private void addJpqlFunctionProcessor(Expression expr, int index) {
if (expr instanceof FunctionExpression) {
String functionName = ((FunctionExpression) expr).getFunctionName().toLowerCase();
JpqlFunction jpqlFunction = mainQuery.cbf.getRegisteredFunctions().get(functionName);
if (jpqlFunction instanceof JpqlFunctionProcessor<?>) {
jpqlFunctionProcessors.put(index, (JpqlFunctionProcessor<?>) jpqlFunction);
if ("to_multiset".equals(functionName)) {
Subquery subquery = ((SubqueryExpression) ((FunctionExpression) expr).getExpressions().get(0)).getSubquery();
if (subquery instanceof SubqueryInternalBuilder<?>) {
SubqueryInternalBuilder<?> subqueryInternalBuilder = (SubqueryInternalBuilder<?>) subquery;
jpqlFunctionProcessors.put(index, new NestedToMultisetJpqlFunctionProcessor((JpqlFunctionProcessor<?>) jpqlFunction, subqueryInternalBuilder.getJpqlFunctionProcessors(), subqueryInternalBuilder.getSelectExpressions()));
}
}
}
} else if (expr instanceof SubqueryExpression) {
Subquery subquery = ((SubqueryExpression) expr).getSubquery();
if (subquery instanceof SubqueryInternalBuilder<?>) {
SubqueryInternalBuilder<?> subqueryInternalBuilder = (SubqueryInternalBuilder<?>) subquery;
if (!subqueryInternalBuilder.getJpqlFunctionProcessors().isEmpty()) {
jpqlFunctionProcessors.put(index, subqueryInternalBuilder.getJpqlFunctionProcessors().get(0));
}
}
}
}
use of com.blazebit.persistence.parser.expression.Subquery in project blaze-persistence by Blazebit.
the class SizeTransformationVisitor method generateSubquery.
private SubqueryExpression generateSubquery(PathExpression sizeArg) {
JoinNode sizeArgJoin = (JoinNode) sizeArg.getBaseNode();
final Type<?> nodeType = sizeArgJoin.getNodeType();
if (!(nodeType instanceof EntityType<?>)) {
throw new IllegalArgumentException("Size on a collection owned by a non-entity type is not supported yet: " + sizeArg);
}
final EntityType<?> startType = (EntityType<?>) nodeType;
Subquery countSubquery = (Subquery) subqueryInitFactory.createSubqueryInitiator(null, new SubqueryBuilderListenerImpl<>(), false, getClause()).from(sizeArg.getPathReference().toString()).select("COUNT(*)");
for (SingularAttribute<?, ?> idAttribute : JpaMetamodelUtils.getIdAttributes(startType)) {
String groupByExprString = sizeArgJoin.getAlias() + "." + idAttribute.getName();
ResolvedExpression groupByExpr = new ResolvedExpression(groupByExprString, null);
Set<ClauseType> clauseTypes = subqueryGroupBys.get(groupByExpr);
if (clauseTypes == null) {
List<PathElementExpression> pathElementExpressions = new ArrayList<>(2);
pathElementExpressions.add(new PropertyExpression(sizeArgJoin.getAlias()));
pathElementExpressions.add(new PropertyExpression(idAttribute.getName()));
PathExpression pathExpression = new PathExpression(pathElementExpressions);
pathExpression.setPathReference(new SimplePathReference(sizeArgJoin, idAttribute.getName(), metamodel.type(JpaMetamodelUtils.resolveFieldClass(startType.getJavaType(), idAttribute))));
groupByExpr = new ResolvedExpression(groupByExprString, pathExpression);
subqueryGroupBys.put(groupByExpr, EnumSet.of(clause));
} else {
clauseTypes.add(clause);
}
}
return new SubqueryExpression(countSubquery);
}
use of com.blazebit.persistence.parser.expression.Subquery in project blaze-persistence by Blazebit.
the class ToMultisetFunction method process.
@Override
public Object process(CharSequence result, List<Object> arguments) {
SubqueryExpression subqueryExpression = (SubqueryExpression) arguments.get(0);
Subquery subquery = subqueryExpression.getSubquery();
String[] fields;
if (subquery instanceof SubqueryInternalBuilder<?>) {
fields = createFields(((SubqueryInternalBuilder<?>) subquery).getSelectExpressions().size());
} else {
throw new IllegalArgumentException("Can't handle: " + subquery);
}
if (toJsonFunction == null) {
return toXmlFunction.process(result, fields);
} else {
return toJsonFunction.process(result, fields);
}
}
Aggregations