Search in sources :

Example 1 with SqmSelectStatement

use of org.hibernate.query.sqm.tree.select.SqmSelectStatement in project hibernate-orm by hibernate.

the class CriteriaEntityGraphTest method buildSqlSelectAst.

private <T> SelectStatement buildSqlSelectAst(Class<T> entityType, RootGraphImplementor<T> entityGraph, GraphSemantic mode, SessionImplementor session) {
    final LoadQueryInfluencers loadQueryInfluencers = new LoadQueryInfluencers(session.getSessionFactory());
    final CriteriaBuilder criteriaBuilder = session.getCriteriaBuilder();
    CriteriaQuery<T> criteriaQuery = criteriaBuilder.createQuery(entityType);
    criteriaQuery.select(criteriaQuery.from(entityType));
    final QueryImplementor<T> query = session.createQuery(criteriaQuery);
    final SqmQueryImplementor<String> hqlQuery = (SqmQueryImplementor<String>) query;
    hqlQuery.applyGraph(entityGraph, mode);
    final SqmSelectStatement<String> sqmStatement = (SqmSelectStatement<String>) hqlQuery.getSqmStatement();
    final StandardSqmTranslator<SelectStatement> sqmConverter = new StandardSqmTranslator<>(sqmStatement, hqlQuery.getQueryOptions(), ((QuerySqmImpl<?>) hqlQuery).getDomainParameterXref(), query.getParameterBindings(), loadQueryInfluencers, session.getSessionFactory(), true);
    final SqmTranslation<SelectStatement> sqmInterpretation = sqmConverter.translate();
    return sqmInterpretation.getSqlAst();
}
Also used : CriteriaBuilder(jakarta.persistence.criteria.CriteriaBuilder) SqmSelectStatement(org.hibernate.query.sqm.tree.select.SqmSelectStatement) LoadQueryInfluencers(org.hibernate.engine.spi.LoadQueryInfluencers) SqmSelectStatement(org.hibernate.query.sqm.tree.select.SqmSelectStatement) SelectStatement(org.hibernate.sql.ast.tree.select.SelectStatement) SqmQueryImplementor(org.hibernate.query.hql.spi.SqmQueryImplementor) StandardSqmTranslator(org.hibernate.query.sqm.sql.internal.StandardSqmTranslator)

Example 2 with SqmSelectStatement

use of org.hibernate.query.sqm.tree.select.SqmSelectStatement in project hibernate-orm by hibernate.

the class SemanticQueryBuilder method visitSetQueryGroup.

@Override
public SqmQueryGroup<Object> visitSetQueryGroup(HqlParser.SetQueryGroupContext ctx) {
    if (creationOptions.useStrictJpaCompliance()) {
        throw new StrictJpaComplianceViolation(StrictJpaComplianceViolation.Type.SET_OPERATIONS);
    }
    final List<ParseTree> children = ctx.children;
    // noinspection unchecked
    final SqmQueryPart<Object> firstQueryPart = (SqmQueryPart<Object>) children.get(0).accept(this);
    SqmQueryGroup<Object> queryGroup;
    if (firstQueryPart instanceof SqmQueryGroup<?>) {
        queryGroup = (SqmQueryGroup<Object>) firstQueryPart;
    } else {
        queryGroup = new SqmQueryGroup<>(firstQueryPart);
    }
    setCurrentQueryPart(queryGroup);
    final int size = children.size();
    final SqmCreationProcessingState firstProcessingState = processingStateStack.pop();
    for (int i = 1; i < size; i += 2) {
        final SetOperator operator = visitSetOperator((HqlParser.SetOperatorContext) children.get(i));
        final HqlParser.OrderedQueryContext simpleQueryCtx = (HqlParser.OrderedQueryContext) children.get(i + 1);
        final List<SqmQueryPart<Object>> queryParts;
        if (queryGroup.getSetOperator() == null || queryGroup.getSetOperator() == operator) {
            queryGroup.setSetOperator(operator);
            queryParts = queryGroup.queryParts();
        } else {
            queryParts = new ArrayList<>(size - (i >> 1));
            queryParts.add(queryGroup);
            queryGroup = new SqmQueryGroup<>(creationContext.getNodeBuilder(), operator, queryParts);
            setCurrentQueryPart(queryGroup);
        }
        final SqmQueryPart<Object> queryPart;
        try {
            processingStateStack.push(new SqmQuerySpecCreationProcessingStateStandardImpl(processingStateStack.getCurrent(), (SqmSelectQuery<?>) firstProcessingState.getProcessingQuery(), this));
            final List<ParseTree> subChildren = simpleQueryCtx.children;
            if (subChildren.get(0) instanceof HqlParser.QueryContext) {
                final SqmQuerySpec<Object> querySpec = new SqmQuerySpec<>(creationContext.getNodeBuilder());
                queryParts.add(querySpec);
                visitQuerySpecExpression((HqlParser.QuerySpecExpressionContext) simpleQueryCtx);
            } else {
                try {
                    final SqmSelectStatement<Object> selectStatement = new SqmSelectStatement<>(creationContext.getNodeBuilder());
                    processingStateStack.push(new SqmQuerySpecCreationProcessingStateStandardImpl(processingStateStack.getCurrent(), selectStatement, this));
                    queryPart = visitNestedQueryExpression((HqlParser.NestedQueryExpressionContext) simpleQueryCtx);
                    queryParts.add(queryPart);
                } finally {
                    processingStateStack.pop();
                }
            }
        } finally {
            processingStateStack.pop();
        }
    }
    processingStateStack.push(firstProcessingState);
    return queryGroup;
}
Also used : SqmCreationProcessingState(org.hibernate.query.hql.spi.SqmCreationProcessingState) SqmQueryGroup(org.hibernate.query.sqm.tree.select.SqmQueryGroup) SqmQuerySpecCreationProcessingStateStandardImpl(org.hibernate.query.sqm.internal.SqmQuerySpecCreationProcessingStateStandardImpl) SetOperator(org.hibernate.query.sqm.SetOperator) SqmSelectQuery(org.hibernate.query.sqm.tree.select.SqmSelectQuery) AbstractSqmSelectQuery(org.hibernate.query.sqm.tree.select.AbstractSqmSelectQuery) SqmSelectStatement(org.hibernate.query.sqm.tree.select.SqmSelectStatement) SqmQueryPart(org.hibernate.query.sqm.tree.select.SqmQueryPart) HqlParser(org.hibernate.grammars.hql.HqlParser) StrictJpaComplianceViolation(org.hibernate.query.sqm.StrictJpaComplianceViolation) SqmQuerySpec(org.hibernate.query.sqm.tree.select.SqmQuerySpec) ParseTree(org.antlr.v4.runtime.tree.ParseTree)

Example 3 with SqmSelectStatement

use of org.hibernate.query.sqm.tree.select.SqmSelectStatement in project hibernate-orm by hibernate.

the class SemanticQueryBuilder method visitSelectStatement.

// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// Top-level statements
@Override
public SqmSelectStatement<R> visitSelectStatement(HqlParser.SelectStatementContext ctx) {
    final HqlParser.QueryExpressionContext queryExpressionContext = ctx.queryExpression();
    final SqmSelectStatement<R> selectStatement = new SqmSelectStatement<>(creationContext.getNodeBuilder());
    parameterCollector = selectStatement;
    processingStateStack.push(new SqmQuerySpecCreationProcessingStateStandardImpl(processingStateStack.getCurrent(), selectStatement, this));
    try {
        queryExpressionContext.accept(this);
    } finally {
        processingStateStack.pop();
    }
    return selectStatement;
}
Also used : SqmSelectStatement(org.hibernate.query.sqm.tree.select.SqmSelectStatement) TIMEZONE_HOUR(org.hibernate.query.sqm.TemporalUnit.TIMEZONE_HOUR) WEEK_OF_YEAR(org.hibernate.query.sqm.TemporalUnit.WEEK_OF_YEAR) DAY_OF_YEAR(org.hibernate.query.sqm.TemporalUnit.DAY_OF_YEAR) IDENTIFIER(org.hibernate.grammars.hql.HqlParser.IDENTIFIER) HqlParser(org.hibernate.grammars.hql.HqlParser) SqmQuerySpecCreationProcessingStateStandardImpl(org.hibernate.query.sqm.internal.SqmQuerySpecCreationProcessingStateStandardImpl)

Example 4 with SqmSelectStatement

use of org.hibernate.query.sqm.tree.select.SqmSelectStatement in project hibernate-orm by hibernate.

the class QuerySqmImpl method doList.

protected List<R> doList() {
    verifySelect();
    getSession().prepareForQueryExecution(requiresTxn(getQueryOptions().getLockOptions().findGreatestLockMode()));
    final SqmSelectStatement<?> sqmStatement = (SqmSelectStatement<?>) getSqmStatement();
    final boolean containsCollectionFetches = sqmStatement.containsCollectionFetches();
    final boolean hasLimit = hasLimit(sqmStatement, getQueryOptions());
    final boolean needsDistinct = containsCollectionFetches && (sqmStatement.usesDistinct() || hasAppliedGraph(getQueryOptions()) || hasLimit);
    final DomainQueryExecutionContext executionContextToUse;
    if (hasLimit && containsCollectionFetches) {
        boolean fail = getSessionFactory().getSessionFactoryOptions().isFailOnPaginationOverCollectionFetchEnabled();
        if (fail) {
            throw new HibernateException("firstResult/maxResults specified with collection fetch. " + "In memory pagination was about to be applied. " + "Failing because 'Fail on pagination over collection fetch' is enabled.");
        } else {
            QueryLogging.QUERY_MESSAGE_LOGGER.firstOrMaxResultsSpecifiedWithCollectionFetch();
        }
        final MutableQueryOptions originalQueryOptions = getQueryOptions();
        final QueryOptions normalizedQueryOptions = omitSqlQueryOptions(originalQueryOptions, true, false);
        if (originalQueryOptions == normalizedQueryOptions) {
            executionContextToUse = this;
        } else {
            executionContextToUse = new DelegatingDomainQueryExecutionContext(this) {

                @Override
                public QueryOptions getQueryOptions() {
                    return normalizedQueryOptions;
                }
            };
        }
    } else {
        executionContextToUse = this;
    }
    final List<R> list = resolveSelectQueryPlan().performList(executionContextToUse);
    if (needsDistinct) {
        int includedCount = -1;
        // NOTE : firstRow is zero-based
        final int first = !hasLimit || getQueryOptions().getLimit().getFirstRow() == null ? getIntegerLiteral(sqmStatement.getOffset(), 0) : getQueryOptions().getLimit().getFirstRow();
        final int max = !hasLimit || getQueryOptions().getLimit().getMaxRows() == null ? getMaxRows(sqmStatement, list.size()) : getQueryOptions().getLimit().getMaxRows();
        final List<R> tmp = new ArrayList<>(list.size());
        final IdentitySet<Object> distinction = new IdentitySet<>(list.size());
        for (final R result : list) {
            if (!distinction.add(result)) {
                continue;
            }
            includedCount++;
            if (includedCount < first) {
                continue;
            }
            tmp.add(result);
            // NOTE : ( max - 1 ) because first is zero-based while max is not...
            if (max >= 0 && (includedCount - first) >= (max - 1)) {
                break;
            }
        }
        return tmp;
    }
    return list;
}
Also used : SqmSelectStatement(org.hibernate.query.sqm.tree.select.SqmSelectStatement) HibernateException(org.hibernate.HibernateException) IdentitySet(org.hibernate.internal.util.collections.IdentitySet) ArrayList(java.util.ArrayList) QueryOptions(org.hibernate.query.spi.QueryOptions) SqlOmittingQueryOptions.omitSqlQueryOptions(org.hibernate.query.spi.SqlOmittingQueryOptions.omitSqlQueryOptions) MutableQueryOptions(org.hibernate.query.spi.MutableQueryOptions) EntityGraphQueryHint(org.hibernate.engine.query.spi.EntityGraphQueryHint) DelegatingDomainQueryExecutionContext(org.hibernate.query.internal.DelegatingDomainQueryExecutionContext) DomainQueryExecutionContext(org.hibernate.query.spi.DomainQueryExecutionContext) MutableQueryOptions(org.hibernate.query.spi.MutableQueryOptions) DelegatingDomainQueryExecutionContext(org.hibernate.query.internal.DelegatingDomainQueryExecutionContext)

Example 5 with SqmSelectStatement

use of org.hibernate.query.sqm.tree.select.SqmSelectStatement in project hibernate-orm by hibernate.

the class SqmSelectionQueryImpl method doList.

protected List<R> doList() {
    getSession().prepareForQueryExecution(requiresTxn(getQueryOptions().getLockOptions().findGreatestLockMode()));
    final SqmSelectStatement<?> sqmStatement = (SqmSelectStatement<?>) getSqmStatement();
    final boolean containsCollectionFetches = sqmStatement.containsCollectionFetches();
    final boolean hasLimit = hasLimit(sqmStatement, getQueryOptions());
    final boolean needsDistinct = containsCollectionFetches && (sqmStatement.usesDistinct() || hasAppliedGraph(getQueryOptions()) || hasLimit);
    final DomainQueryExecutionContext executionContextToUse;
    if (hasLimit && containsCollectionFetches) {
        boolean fail = getSessionFactory().getSessionFactoryOptions().isFailOnPaginationOverCollectionFetchEnabled();
        if (fail) {
            throw new HibernateException("firstResult/maxResults specified with collection fetch. " + "In memory pagination was about to be applied. " + "Failing because 'Fail on pagination over collection fetch' is enabled.");
        } else {
            QueryLogging.QUERY_MESSAGE_LOGGER.firstOrMaxResultsSpecifiedWithCollectionFetch();
        }
        final MutableQueryOptions originalQueryOptions = getQueryOptions();
        final QueryOptions normalizedQueryOptions = omitSqlQueryOptions(originalQueryOptions, true, false);
        if (originalQueryOptions == normalizedQueryOptions) {
            executionContextToUse = this;
        } else {
            executionContextToUse = new DelegatingDomainQueryExecutionContext(this) {

                @Override
                public QueryOptions getQueryOptions() {
                    return normalizedQueryOptions;
                }
            };
        }
    } else {
        executionContextToUse = this;
    }
    final List<R> list = resolveQueryPlan().performList(executionContextToUse);
    if (needsDistinct) {
        int includedCount = -1;
        // NOTE : firstRow is zero-based
        final int first = !hasLimit || getQueryOptions().getLimit().getFirstRow() == null ? getIntegerLiteral(sqmStatement.getOffset(), 0) : getQueryOptions().getLimit().getFirstRow();
        final int max = !hasLimit || getQueryOptions().getLimit().getMaxRows() == null ? getMaxRows(sqmStatement, list.size()) : getQueryOptions().getLimit().getMaxRows();
        final List<R> tmp = new ArrayList<>(list.size());
        final IdentitySet<Object> distinction = new IdentitySet<>(list.size());
        for (final R result : list) {
            if (!distinction.add(result)) {
                continue;
            }
            includedCount++;
            if (includedCount < first) {
                continue;
            }
            tmp.add(result);
            // NOTE : ( max - 1 ) because first is zero-based while max is not...
            if (max >= 0 && (includedCount - first) >= (max - 1)) {
                break;
            }
        }
        return tmp;
    }
    return list;
}
Also used : SqmSelectStatement(org.hibernate.query.sqm.tree.select.SqmSelectStatement) HibernateException(org.hibernate.HibernateException) IdentitySet(org.hibernate.internal.util.collections.IdentitySet) ArrayList(java.util.ArrayList) MutableQueryOptions(org.hibernate.query.spi.MutableQueryOptions) QueryOptions(org.hibernate.query.spi.QueryOptions) SqlOmittingQueryOptions.omitSqlQueryOptions(org.hibernate.query.spi.SqlOmittingQueryOptions.omitSqlQueryOptions) DelegatingDomainQueryExecutionContext(org.hibernate.query.internal.DelegatingDomainQueryExecutionContext) DomainQueryExecutionContext(org.hibernate.query.spi.DomainQueryExecutionContext) MutableQueryOptions(org.hibernate.query.spi.MutableQueryOptions) DelegatingDomainQueryExecutionContext(org.hibernate.query.internal.DelegatingDomainQueryExecutionContext)

Aggregations

SqmSelectStatement (org.hibernate.query.sqm.tree.select.SqmSelectStatement)17 SelectStatement (org.hibernate.sql.ast.tree.select.SelectStatement)9 ArrayList (java.util.ArrayList)4 SqmQueryImplementor (org.hibernate.query.hql.spi.SqmQueryImplementor)4 StandardSqmTranslator (org.hibernate.query.sqm.sql.internal.StandardSqmTranslator)4 TableGroup (org.hibernate.sql.ast.tree.from.TableGroup)4 HibernateException (org.hibernate.HibernateException)3 LoadQueryInfluencers (org.hibernate.engine.spi.LoadQueryInfluencers)3 SessionFactoryImplementor (org.hibernate.engine.spi.SessionFactoryImplementor)3 EntityDomainType (org.hibernate.metamodel.model.domain.EntityDomainType)3 QueryEngine (org.hibernate.query.spi.QueryEngine)3 QueryOptions (org.hibernate.query.spi.QueryOptions)3 SqmQueryPart (org.hibernate.query.sqm.tree.select.SqmQueryPart)3 SqlSelection (org.hibernate.sql.ast.spi.SqlSelection)3 SelectClause (org.hibernate.sql.ast.tree.select.SelectClause)3 JdbcSelect (org.hibernate.sql.exec.spi.JdbcSelect)3 List (java.util.List)2 Map (java.util.Map)2 Session (org.hibernate.Session)2 HqlParser (org.hibernate.grammars.hql.HqlParser)2