use of com.blazebit.persistence.impl.query.CTENode in project blaze-persistence by Blazebit.
the class PaginatedCriteriaBuilderImpl method getIdQuery.
private TypedQuery<Object[]> getIdQuery(String idQueryString, boolean normalQueryMode, Set<JoinNode> keyRestrictedLeftJoins, List<JoinNode> entityFunctions) {
if (normalQueryMode && isEmpty(keyRestrictedLeftJoins, ID_QUERY_CLAUSE_EXCLUSIONS)) {
TypedQuery<Object[]> idQuery = em.createQuery(idQueryString, Object[].class);
if (isCacheable()) {
mainQuery.jpaProvider.setCacheable(idQuery);
}
if (firstResult < maximumCount && withCountQuery && withInlineCountQuery && maximumCount != Long.MAX_VALUE) {
parameterManager.parameterizeQuery(idQuery, getDualNodeAlias());
idQuery.setParameter(getDualNodeAlias() + "_value_0", 0L);
} else {
parameterManager.parameterizeQuery(idQuery);
}
return parameterManager.getCriteriaNameMapping() == null ? idQuery : new TypedQueryWrapper<>(idQuery, parameterManager.getCriteriaNameMapping());
}
TypedQuery<Object[]> baseQuery = em.createQuery(idQueryString, Object[].class);
Set<String> parameterListNames = parameterManager.getParameterListNames(baseQuery);
List<String> keyRestrictedLeftJoinAliases = getKeyRestrictedLeftJoinAliases(baseQuery, keyRestrictedLeftJoins, ID_QUERY_CLAUSE_EXCLUSIONS);
List<EntityFunctionNode> entityFunctionNodes = getEntityFunctionNodes(baseQuery, entityFunctions);
boolean shouldRenderCteNodes = renderCteNodes(false);
List<CTENode> ctes = shouldRenderCteNodes ? getCteNodes(false) : Collections.EMPTY_LIST;
QuerySpecification querySpecification = new CustomQuerySpecification(this, baseQuery, parameterManager.getParameterImpls(), parameterListNames, null, null, keyRestrictedLeftJoinAliases, entityFunctionNodes, mainQuery.cteManager.isRecursive(), ctes, shouldRenderCteNodes, mainQuery.getQueryConfiguration().isQueryPlanCacheEnabled(), null);
CustomSQLTypedQuery<Object[]> idQuery = new CustomSQLTypedQuery<Object[]>(querySpecification, baseQuery, parameterManager.getCriteriaNameMapping(), parameterManager.getTransformers(), parameterManager.getValuesParameters(), parameterManager.getValuesBinders());
if (firstResult < maximumCount && withCountQuery && withInlineCountQuery && maximumCount != Long.MAX_VALUE) {
parameterManager.parameterizeQuery(idQuery, getDualNodeAlias());
idQuery.setParameter(getDualNodeAlias() + "_value_0", 0L);
} else {
parameterManager.parameterizeQuery(idQuery);
}
return idQuery;
}
use of com.blazebit.persistence.impl.query.CTENode in project blaze-persistence by Blazebit.
the class AbstractCommonQueryBuilder method getCteNodes.
protected List<CTENode> getCteNodes(boolean isSubquery) {
List<CTENode> cteNodes = new ArrayList<CTENode>();
// NOTE: Delete statements could cause CTEs to be generated for the cascading deletes
if (!isMainQuery || isSubquery || !mainQuery.dbmsDialect.supportsWithClause() || !mainQuery.cteManager.hasCtes() && statementType != DbmsStatementType.DELETE || statementType != DbmsStatementType.SELECT && !mainQuery.dbmsDialect.supportsWithClauseInModificationQuery()) {
return cteNodes;
}
StringBuilder sb = new StringBuilder();
for (CTEInfo cteInfo : mainQuery.cteManager.getCtes()) {
if (!cteInfo.inline) {
// Build queries and add as participating queries
Map<DbmsModificationState, String> modificationStates = cteInfo.nonRecursiveCriteriaBuilder.getModificationStates(explicitVersionEntities);
Query nonRecursiveQuery = cteInfo.nonRecursiveCriteriaBuilder.getQuery(modificationStates);
QuerySpecification<?> nonRecursiveQuerySpecification = getQuerySpecification(nonRecursiveQuery);
Map<String, String> nonRecursiveTableNameRemappings = null;
if (nonRecursiveQuery instanceof CustomSQLQuery) {
// EntityAlias -> CteName
nonRecursiveTableNameRemappings = cteInfo.nonRecursiveCriteriaBuilder.getModificationStateRelatedTableNameRemappings(explicitVersionEntities);
}
Query recursiveQuery;
QuerySpecification<?> recursiveQuerySpecification = null;
Map<String, String> recursiveTableNameRemappings = null;
if (cteInfo.recursive) {
modificationStates = cteInfo.nonRecursiveCriteriaBuilder.getModificationStates(explicitVersionEntities);
recursiveQuery = cteInfo.recursiveCriteriaBuilder.getQuery(modificationStates);
if (!mainQuery.dbmsDialect.supportsJoinsInRecursiveCte() && cteInfo.recursiveCriteriaBuilder.joinManager.hasNonEmulatableJoins()) {
throw new IllegalStateException("The dbms dialect does not support joins in the recursive part of a CTE!");
}
recursiveQuerySpecification = getQuerySpecification(recursiveQuery);
if (recursiveQuery instanceof CustomSQLQuery) {
// EntityAlias -> CteName
recursiveTableNameRemappings = cteInfo.recursiveCriteriaBuilder.getModificationStateRelatedTableNameRemappings(explicitVersionEntities);
}
}
String cteName = cteInfo.cteType.getName();
final List<String> columnNames = cteInfo.columnNames;
String head;
String[] aliases;
if (mainQuery.dbmsDialect.supportsWithClauseHead()) {
sb.setLength(0);
sb.append(cteName);
sb.append('(');
for (int i = 0; i < columnNames.size(); i++) {
String column = columnNames.get(i);
if (i != 0) {
sb.append(", ");
}
sb.append(column);
}
sb.append(')');
head = sb.toString();
aliases = null;
} else {
sb.setLength(0);
sb.append(cteName);
List<String> list = new ArrayList<>(columnNames.size());
for (int i = 0; i < columnNames.size(); i++) {
String[] columns = mainQuery.metamodel.getManagedType(ExtendedManagedType.class, cteInfo.cteType.getJavaType()).getAttribute(columnNames.get(i)).getColumnNames();
for (String column : columns) {
list.add(column);
}
}
head = sb.toString();
aliases = list.toArray(new String[list.size()]);
}
String nonRecursiveWithClauseSuffix = null;
if (!cteInfo.recursive && !mainQuery.dbmsDialect.supportsNonRecursiveWithClause()) {
sb.setLength(0);
sb.append(" UNION ALL ");
sb.append("SELECT ");
sb.append("NULL");
for (int i = 1; i < columnNames.size(); i++) {
sb.append(", ");
sb.append("NULL");
}
sb.append(" FROM DUAL WHERE 1=0");
nonRecursiveWithClauseSuffix = sb.toString();
}
cteNodes.add(new CTENode(cteInfo.name, cteInfo.cteType.getName(), head, aliases, cteInfo.unionAll, nonRecursiveQuerySpecification, recursiveQuerySpecification, nonRecursiveTableNameRemappings, recursiveTableNameRemappings, nonRecursiveWithClauseSuffix));
}
}
return cteNodes;
}
use of com.blazebit.persistence.impl.query.CTENode in project blaze-persistence by Blazebit.
the class AbstractCommonQueryBuilder method getTypedQuery.
protected TypedQuery<QueryResultType> getTypedQuery(StringBuilder lateralSb, JoinNode lateralJoinNode) {
// NOTE: This must happen first because it generates implicit joins
String baseQueryString = getBaseQueryStringWithCheck(lateralSb, lateralJoinNode);
// We can only use the query directly if we have no ctes, entity functions or hibernate bugs
Set<JoinNode> keyRestrictedLeftJoins = getKeyRestrictedLeftJoins();
final boolean needsSqlReplacement = isMainQuery && mainQuery.cteManager.hasCtes() || joinManager.hasEntityFunctions() || !keyRestrictedLeftJoins.isEmpty() || !isMainQuery && hasLimit();
if (!needsSqlReplacement) {
TypedQuery<QueryResultType> query = (TypedQuery<QueryResultType>) em.createQuery(baseQueryString, selectManager.getExpectedQueryResultType());
if (firstResult != 0) {
query.setFirstResult(firstResult);
}
if (maxResults != Integer.MAX_VALUE) {
query.setMaxResults(maxResults);
}
if (isCacheable()) {
mainQuery.jpaProvider.setCacheable(query);
}
parameterManager.parameterizeQuery(query);
return applyObjectBuilder(query);
}
TypedQuery<QueryResultType> baseQuery = (TypedQuery<QueryResultType>) em.createQuery(baseQueryString, selectManager.getExpectedQueryResultType());
if (isCacheable()) {
mainQuery.jpaProvider.setCacheable(baseQuery);
}
Set<String> parameterListNames = parameterManager.getParameterListNames(baseQuery);
String limit = null;
String offset = null;
// The main query will handle that separately
if (!isMainQuery && lateralSb == null) {
if (firstResult != 0) {
offset = Integer.toString(firstResult);
}
if (maxResults != Integer.MAX_VALUE) {
limit = Integer.toString(maxResults);
}
}
List<String> keyRestrictedLeftJoinAliases = getKeyRestrictedLeftJoinAliases(baseQuery, keyRestrictedLeftJoins, Collections.<ClauseType>emptySet());
List<EntityFunctionNode> entityFunctionNodes = getEntityFunctionNodes(baseQuery);
boolean shouldRenderCteNodes = lateralSb == null && renderCteNodes(false);
List<CTENode> ctes = shouldRenderCteNodes ? getCteNodes(false) : Collections.<CTENode>emptyList();
QuerySpecification querySpecification = new CustomQuerySpecification(this, baseQuery, parameterManager.getParameterImpls(), parameterListNames, limit, offset, keyRestrictedLeftJoinAliases, entityFunctionNodes, mainQuery.cteManager.isRecursive(), ctes, shouldRenderCteNodes, mainQuery.getQueryConfiguration().isQueryPlanCacheEnabled(), null);
TypedQuery<QueryResultType> query = new CustomSQLTypedQuery<QueryResultType>(querySpecification, baseQuery, parameterManager.getCriteriaNameMapping(), parameterManager.getTransformers(), parameterManager.getValuesParameters(), parameterManager.getValuesBinders());
// The main query will use the native mechanism for limit/offset
if (isMainQuery && lateralSb == null) {
if (firstResult != 0) {
query.setFirstResult(firstResult);
}
if (maxResults != Integer.MAX_VALUE) {
query.setMaxResults(maxResults);
}
}
parameterManager.parameterizeQuery(query);
return applyObjectBuilder(query);
}
use of com.blazebit.persistence.impl.query.CTENode in project blaze-persistence by Blazebit.
the class AbstractDeleteCollectionCriteriaBuilder method getQuerySpecification.
private <R> QuerySpecification getQuerySpecification(Query baseQuery, Query exampleQuery, String[] returningColumns, ReturningObjectBuilder<R> objectBuilder, Map<DbmsModificationState, String> includedModificationStates) {
Set<String> parameterListNames = parameterManager.getParameterListNames(baseQuery);
boolean isEmbedded = this instanceof ReturningBuilder;
boolean shouldRenderCteNodes = renderCteNodes(isEmbedded);
List<CTENode> ctes = shouldRenderCteNodes ? getCteNodes(isEmbedded) : Collections.EMPTY_LIST;
// Prepare a Map<EntityAlias.idColumnName, CollectionAlias.idColumnName>
// This is used to replace references to id columns properly in the final sql query
ExtendedQuerySupport extendedQuerySupport = getService(ExtendedQuerySupport.class);
String sql = extendedQuerySupport.getSql(em, baseQuery);
String ownerAlias = extendedQuerySupport.getSqlAlias(em, baseQuery, entityAlias);
String targetAlias = extendedQuerySupport.getSqlAlias(em, baseQuery, JoinManager.COLLECTION_DML_BASE_QUERY_ALIAS);
JoinTable joinTable = collectionAttribute.getJoinTable();
if (joinTable == null) {
throw new IllegalStateException("Deleting inverse collections is not supported!");
}
int joinTableIndex = SqlUtils.indexOfTableName(sql, joinTable.getTableName());
String collectionAlias = SqlUtils.extractAlias(sql, joinTableIndex + joinTable.getTableName().length());
String tableToDelete = joinTable.getTableName();
String tablePrefix = mainQuery.dbmsDialect.getDeleteJoinStyle() == DeleteJoinStyle.FROM ? collectionAlias : tableToDelete;
Map<String, String> columnExpressionRemappings = new HashMap<>(joinTable.getIdColumnMappings().size());
List<String> joinTableIdColumns = new ArrayList<>();
if (joinTable.getKeyColumnMappings() != null) {
for (Map.Entry<String, String> entry : joinTable.getKeyColumnMappings().entrySet()) {
joinTableIdColumns.add(entry.getKey());
columnExpressionRemappings.put(CollectionDmlSupportFunction.FUNCTION_NAME + "(" + collectionAlias + "." + entry.getValue() + ")", tablePrefix + "." + entry.getKey());
}
}
String[] discriminatorColumnCheck = mainQuery.jpaProvider.getDiscriminatorColumnCheck(entityType);
if (discriminatorColumnCheck != null) {
columnExpressionRemappings.put(ownerAlias + "." + discriminatorColumnCheck[0] + "=" + discriminatorColumnCheck[1], "1=1");
}
for (Map.Entry<String, String> entry : joinTable.getIdColumnMappings().entrySet()) {
joinTableIdColumns.add(entry.getKey());
columnExpressionRemappings.put(CollectionDmlSupportFunction.FUNCTION_NAME + "(" + ownerAlias + "." + entry.getValue() + ")", tablePrefix + "." + entry.getKey());
}
for (Map.Entry<String, String> entry : joinTable.getTargetColumnMappings().entrySet()) {
columnExpressionRemappings.put(CollectionDmlSupportFunction.FUNCTION_NAME + "(" + targetAlias + "." + entry.getValue() + ")", tablePrefix + "." + entry.getKey());
}
// If the id attribute is an embedded type, there is the possibility that row value expressions are used which we need to handle as well
Set<SingularAttribute<?, ?>> idAttributes = JpaMetamodelUtils.getIdAttributes(entityType);
if (idAttributes.size() == 1 && idAttributes.iterator().next().getType() instanceof ManagedType<?>) {
StringBuilder leftSb = new StringBuilder();
StringBuilder rightSb = new StringBuilder();
leftSb.append(CollectionDmlSupportFunction.FUNCTION_NAME).append("((");
rightSb.append("(");
for (Map.Entry<String, String> entry : joinTable.getIdColumnMappings().entrySet()) {
leftSb.append(ownerAlias).append('.').append(entry.getValue()).append(", ");
rightSb.append(tablePrefix).append('.').append(entry.getKey()).append(',');
}
leftSb.setLength(leftSb.length() - 2);
leftSb.append("))");
rightSb.setCharAt(rightSb.length() - 1, ')');
columnExpressionRemappings.put(leftSb.toString(), rightSb.toString());
}
return new CollectionDeleteModificationQuerySpecification(this, baseQuery, exampleQuery, parameterManager.getParameterImpls(), parameterListNames, mainQuery.cteManager.isRecursive(), ctes, shouldRenderCteNodes, isEmbedded, returningColumns, objectBuilder, includedModificationStates, returningAttributeBindingMap, mainQuery.getQueryConfiguration().isQueryPlanCacheEnabled(), tableToDelete, collectionAlias, joinTableIdColumns.toArray(new String[0]), false, getDeleteExampleQuery(), columnExpressionRemappings);
}
use of com.blazebit.persistence.impl.query.CTENode in project blaze-persistence by Blazebit.
the class AbstractFullQueryBuilder method getCountQuery.
protected TypedQuery<Long> getCountQuery(String countQueryString, boolean useCountWrapper) {
// We can only use the query directly if we have no ctes, entity functions or hibernate bugs
Set<JoinNode> keyRestrictedLeftJoins = getKeyRestrictedLeftJoins();
Set<JoinNode> alwaysIncludedNodes = getIdentifierExpressionsToUseNonRootJoinNodes();
List<JoinNode> entityFunctions = null;
boolean normalQueryMode = !useCountWrapper && (!isMainQuery || (!mainQuery.cteManager.hasCtes() && (entityFunctions = joinManager.getEntityFunctions(COUNT_QUERY_GROUP_BY_CLAUSE_EXCLUSIONS, true, alwaysIncludedNodes)).isEmpty() && keyRestrictedLeftJoins.isEmpty()));
Collection<Parameter<?>> parameters;
Map<String, String> valuesParameters;
Map<String, ValuesParameterBinder> valuesBinders;
JoinNode dualNode = null;
if (cachedMaximumCount == Long.MAX_VALUE) {
if (normalQueryMode && isEmpty(keyRestrictedLeftJoins, COUNT_QUERY_CLAUSE_EXCLUSIONS)) {
TypedQuery<Long> countQuery = em.createQuery(countQueryString, Long.class);
if (isCacheable()) {
mainQuery.jpaProvider.setCacheable(countQuery);
}
parameterManager.parameterizeQuery(countQuery);
return parameterManager.getCriteriaNameMapping() == null ? countQuery : new TypedQueryWrapper<>(countQuery, parameterManager.getCriteriaNameMapping());
}
parameters = (Collection<Parameter<?>>) (Collection<?>) parameterManager.getParameterImpls();
valuesParameters = parameterManager.getValuesParameters();
valuesBinders = parameterManager.getValuesBinders();
} else {
parameters = new ArrayList<>(parameterManager.getParameters());
valuesParameters = new HashMap<>(parameterManager.getValuesParameters());
valuesBinders = parameterManager.getValuesBinders();
dualNode = createDualNode();
entityFunctions = new ArrayList<>();
entityFunctions.add(dualNode);
String valueParameterName = dualNode.getAlias() + "_value_0";
String[][] parameterNames = new String[1][1];
parameterNames[0][0] = valueParameterName;
ParameterManager.ValuesParameterWrapper valuesParameterWrapper = new ParameterManager.ValuesParameterWrapper(dualNode.getJavaType(), parameterNames, new AttributeAccessor[1]);
parameters.add(new ParameterManager.ParameterImpl<Object>(dualNode.getAlias(), false, null, null, valuesParameterWrapper));
valuesParameters.put(valueParameterName, dualNode.getAlias());
valuesBinders.put(dualNode.getAlias(), valuesParameterWrapper.getBinder());
}
if (entityFunctions == null) {
entityFunctions = joinManager.getEntityFunctions(COUNT_QUERY_GROUP_BY_CLAUSE_EXCLUSIONS, true, alwaysIncludedNodes);
}
Query baseQuery = em.createQuery(countQueryString);
Set<String> parameterListNames = parameterManager.getParameterListNames(baseQuery);
String limit = null;
String offset = null;
if (firstResult != 0) {
offset = Integer.toString(firstResult);
}
if (maxResults != Integer.MAX_VALUE) {
limit = Integer.toString(maxResults);
}
List<String> keyRestrictedLeftJoinAliases = getKeyRestrictedLeftJoinAliases(baseQuery, keyRestrictedLeftJoins, COUNT_QUERY_CLAUSE_EXCLUSIONS);
List<EntityFunctionNode> entityFunctionNodes;
if (dualNode == null) {
entityFunctionNodes = getEntityFunctionNodes(baseQuery, entityFunctions);
} else {
entityFunctionNodes = getEntityFunctionNodes(baseQuery, entityFunctions, Collections.<JoinNode>emptyList(), false);
}
boolean shouldRenderCteNodes = renderCteNodes(false);
List<CTENode> ctes = shouldRenderCteNodes ? getCteNodes(false) : Collections.EMPTY_LIST;
QuerySpecification querySpecification = new CustomQuerySpecification(this, baseQuery, parameters, parameterListNames, limit, offset, keyRestrictedLeftJoinAliases, entityFunctionNodes, mainQuery.cteManager.isRecursive(), ctes, shouldRenderCteNodes, mainQuery.getQueryConfiguration().isQueryPlanCacheEnabled(), useCountWrapper ? getCountExampleQuery() : null);
CustomSQLTypedQuery<Long> countQuery = new CustomSQLTypedQuery<>(querySpecification, baseQuery, parameterManager.getCriteriaNameMapping(), parameterManager.getTransformers(), valuesParameters, valuesBinders);
if (dualNode == null) {
parameterManager.parameterizeQuery(countQuery);
} else {
parameterManager.parameterizeQuery(countQuery, dualNode.getAlias());
countQuery.setParameter(dualNode.getAlias(), Collections.singleton(0L));
}
return countQuery;
}
Aggregations