Search in sources :

Example 26 with Expression

use of org.hibernate.sql.ast.tree.expression.Expression in project hibernate-orm by hibernate.

the class AbstractCteMutationHandler method createIdSubQueryPredicate.

protected Predicate createIdSubQueryPredicate(List<? extends Expression> lhsExpressions, CteStatement idSelectCte, ModelPart fkModelPart, SessionFactoryImplementor factory) {
    final NamedTableReference idSelectTableReference = new NamedTableReference(idSelectCte.getCteTable().getTableExpression(), CTE_TABLE_IDENTIFIER, false, factory);
    final Junction predicate = new Junction(Junction.Nature.CONJUNCTION);
    final List<CteColumn> cteColumns = idSelectCte.getCteTable().getCteColumns();
    final int size = lhsExpressions.size();
    final QuerySpec subQuery = new QuerySpec(false, 1);
    subQuery.getFromClause().addRoot(new CteTableGroup(idSelectTableReference));
    final SelectClause subQuerySelectClause = subQuery.getSelectClause();
    if (fkModelPart == null) {
        for (int i = 0; i < size; i++) {
            final CteColumn cteColumn = cteColumns.get(i);
            subQuerySelectClause.addSqlSelection(new SqlSelectionImpl(i + 1, i, new ColumnReference(idSelectTableReference, cteColumn.getColumnExpression(), cteColumn.getJdbcMapping(), factory)));
        }
    } else {
        fkModelPart.forEachSelectable((selectionIndex, selectableMapping) -> {
            subQuerySelectClause.addSqlSelection(new SqlSelectionImpl(selectionIndex + 1, selectionIndex, new ColumnReference(idSelectTableReference, selectableMapping.getSelectionExpression(), selectableMapping.getJdbcMapping(), factory)));
        });
    }
    final Expression lhs;
    if (lhsExpressions.size() == 1) {
        lhs = lhsExpressions.get(0);
    } else {
        lhs = new SqlTuple(lhsExpressions, null);
    }
    predicate.add(new InSubQueryPredicate(lhs, subQuery, false));
    return predicate;
}
Also used : CteColumn(org.hibernate.sql.ast.tree.cte.CteColumn) SelectClause(org.hibernate.sql.ast.tree.select.SelectClause) NamedTableReference(org.hibernate.sql.ast.tree.from.NamedTableReference) InSubQueryPredicate(org.hibernate.sql.ast.tree.predicate.InSubQueryPredicate) CteTableGroup(org.hibernate.sql.ast.tree.cte.CteTableGroup) SqmExpression(org.hibernate.query.sqm.tree.expression.SqmExpression) Expression(org.hibernate.sql.ast.tree.expression.Expression) SqlTuple(org.hibernate.sql.ast.tree.expression.SqlTuple) Junction(org.hibernate.sql.ast.tree.predicate.Junction) SqlSelectionImpl(org.hibernate.sql.results.internal.SqlSelectionImpl) QuerySpec(org.hibernate.sql.ast.tree.select.QuerySpec) ColumnReference(org.hibernate.sql.ast.tree.expression.ColumnReference)

Example 27 with Expression

use of org.hibernate.sql.ast.tree.expression.Expression in project hibernate-orm by hibernate.

the class SimpleDeleteQueryPlan method executeUpdate.

@Override
public int executeUpdate(DomainQueryExecutionContext executionContext) {
    BulkOperationCleanupAction.schedule(executionContext.getSession(), sqmDelete);
    final SharedSessionContractImplementor session = executionContext.getSession();
    final SessionFactoryImplementor factory = session.getFactory();
    final JdbcServices jdbcServices = factory.getJdbcServices();
    SqlAstTranslator<JdbcDelete> deleteTranslator = null;
    if (jdbcDelete == null) {
        deleteTranslator = createDeleteTranslator(executionContext);
    }
    final JdbcParameterBindings jdbcParameterBindings = SqmUtil.createJdbcParameterBindings(executionContext.getQueryParameterBindings(), domainParameterXref, jdbcParamsXref, factory.getRuntimeMetamodels().getMappingMetamodel(), sqmInterpretation.getFromClauseAccess()::findTableGroup, new SqmParameterMappingModelResolutionAccess() {

        @Override
        @SuppressWarnings("unchecked")
        public <T> MappingModelExpressible<T> getResolvedMappingModelType(SqmParameter<T> parameter) {
            return (MappingModelExpressible<T>) sqmInterpretation.getSqmParameterMappingModelTypeResolutions().get(parameter);
        }
    }, session);
    if (jdbcDelete != null && !jdbcDelete.isCompatibleWith(jdbcParameterBindings, executionContext.getQueryOptions())) {
        deleteTranslator = createDeleteTranslator(executionContext);
    }
    if (deleteTranslator != null) {
        jdbcDelete = deleteTranslator.translate(jdbcParameterBindings, executionContext.getQueryOptions());
    } else {
        jdbcDelete.bindFilterJdbcParameters(jdbcParameterBindings);
    }
    final boolean missingRestriction = sqmDelete.getWhereClause() == null || sqmDelete.getWhereClause().getPredicate() == null;
    if (missingRestriction) {
        assert domainParameterXref.getSqmParameterCount() == 0;
        assert jdbcParamsXref.isEmpty();
    }
    final SqmJdbcExecutionContextAdapter executionContextAdapter = SqmJdbcExecutionContextAdapter.usingLockingAndPaging(executionContext);
    SqmMutationStrategyHelper.cleanUpCollectionTables(entityDescriptor, (tableReference, attributeMapping) -> {
        if (missingRestriction) {
            return null;
        }
        final ForeignKeyDescriptor fkDescriptor = attributeMapping.getKeyDescriptor();
        final Expression fkColumnExpression = MappingModelHelper.buildColumnReferenceExpression(fkDescriptor.getKeyPart(), null, factory);
        final QuerySpec matchingIdSubQuery = new QuerySpec(false);
        final MutatingTableReferenceGroupWrapper tableGroup = new MutatingTableReferenceGroupWrapper(new NavigablePath(attributeMapping.getRootPathName()), attributeMapping, sqmInterpretation.getSqlAst().getTargetTable());
        final Expression fkTargetColumnExpression = MappingModelHelper.buildColumnReferenceExpression(tableGroup, fkDescriptor.getTargetPart(), sqmInterpretation.getSqlExpressionResolver(), factory);
        matchingIdSubQuery.getSelectClause().addSqlSelection(new SqlSelectionImpl(1, 0, fkTargetColumnExpression));
        matchingIdSubQuery.getFromClause().addRoot(tableGroup);
        matchingIdSubQuery.applyPredicate(sqmInterpretation.getSqlAst().getRestriction());
        return new InSubQueryPredicate(fkColumnExpression, matchingIdSubQuery, false);
    }, (missingRestriction ? JdbcParameterBindings.NO_BINDINGS : jdbcParameterBindings), executionContextAdapter);
    return jdbcServices.getJdbcMutationExecutor().execute(jdbcDelete, jdbcParameterBindings, sql -> session.getJdbcCoordinator().getStatementPreparer().prepareStatement(sql), (integer, preparedStatement) -> {
    }, executionContextAdapter);
}
Also used : MutatingTableReferenceGroupWrapper(org.hibernate.sql.ast.tree.from.MutatingTableReferenceGroupWrapper) NavigablePath(org.hibernate.query.spi.NavigablePath) SqmParameterMappingModelResolutionAccess(org.hibernate.query.sqm.spi.SqmParameterMappingModelResolutionAccess) MappingModelExpressible(org.hibernate.metamodel.mapping.MappingModelExpressible) SessionFactoryImplementor(org.hibernate.engine.spi.SessionFactoryImplementor) InSubQueryPredicate(org.hibernate.sql.ast.tree.predicate.InSubQueryPredicate) SharedSessionContractImplementor(org.hibernate.engine.spi.SharedSessionContractImplementor) JdbcServices(org.hibernate.engine.jdbc.spi.JdbcServices) Expression(org.hibernate.sql.ast.tree.expression.Expression) ForeignKeyDescriptor(org.hibernate.metamodel.mapping.ForeignKeyDescriptor) SqlSelectionImpl(org.hibernate.sql.results.internal.SqlSelectionImpl) JdbcDelete(org.hibernate.sql.exec.spi.JdbcDelete) QuerySpec(org.hibernate.sql.ast.tree.select.QuerySpec) JdbcParameterBindings(org.hibernate.sql.exec.spi.JdbcParameterBindings)

Example 28 with Expression

use of org.hibernate.sql.ast.tree.expression.Expression in project hibernate-orm by hibernate.

the class MatchingIdSelectionHelper method generateMatchingIdSelectQuery.

/**
 * @asciidoc
 *
 * Generates a query-spec for selecting all ids matching the restriction defined as part
 * of the user's update/delete query.  This query-spec is generally used:
 *
 * 		* to select all the matching ids via JDBC - see {@link MatchingIdSelectionHelper#selectMatchingIds}
 * 		* as a sub-query restriction to insert rows into an "id table"
 */
public static QuerySpec generateMatchingIdSelectQuery(EntityMappingType targetEntityDescriptor, SqmDeleteOrUpdateStatement sqmStatement, DomainParameterXref domainParameterXref, Predicate restriction, MultiTableSqmMutationConverter sqmConverter, SessionFactoryImplementor sessionFactory) {
    final EntityDomainType entityDomainType = sqmStatement.getTarget().getModel();
    if (log.isTraceEnabled()) {
        log.tracef("Starting generation of entity-id SQM selection - %s", entityDomainType.getHibernateEntityName());
    }
    final QuerySpec idSelectionQuery = new QuerySpec(true, 1);
    final TableGroup mutatingTableGroup = sqmConverter.getMutatingTableGroup();
    idSelectionQuery.getFromClause().addRoot(mutatingTableGroup);
    targetEntityDescriptor.getIdentifierMapping().forEachSelectable((position, selection) -> {
        final TableReference tableReference = mutatingTableGroup.resolveTableReference(mutatingTableGroup.getNavigablePath(), selection.getContainingTableExpression());
        final Expression expression = sqmConverter.getSqlExpressionResolver().resolveSqlExpression(SqlExpressionResolver.createColumnReferenceKey(tableReference, selection.getSelectionExpression()), sqlAstProcessingState -> new ColumnReference(tableReference, selection, sessionFactory));
        idSelectionQuery.getSelectClause().addSqlSelection(new SqlSelectionImpl(position, position + 1, expression));
    });
    idSelectionQuery.applyPredicate(restriction);
    return idSelectionQuery;
}
Also used : TableReference(org.hibernate.sql.ast.tree.from.TableReference) TableGroup(org.hibernate.sql.ast.tree.from.TableGroup) Expression(org.hibernate.sql.ast.tree.expression.Expression) SqlSelectionImpl(org.hibernate.sql.results.internal.SqlSelectionImpl) EntityDomainType(org.hibernate.metamodel.model.domain.EntityDomainType) QuerySpec(org.hibernate.sql.ast.tree.select.QuerySpec) ColumnReference(org.hibernate.sql.ast.tree.expression.ColumnReference)

Example 29 with Expression

use of org.hibernate.sql.ast.tree.expression.Expression in project hibernate-orm by hibernate.

the class SybaseASESqlAstTranslator method visitAnsiCaseSearchedExpression.

// Sybase ASE does not allow CASE expressions where all result arms contain plain parameters.
// At least one result arm must provide some type context for inference,
// so we cast the first result arm if we encounter this condition
@Override
protected void visitAnsiCaseSearchedExpression(CaseSearchedExpression caseSearchedExpression, Consumer<Expression> resultRenderer) {
    if (getParameterRenderingMode() == SqlAstNodeRenderingMode.DEFAULT && areAllResultsParameters(caseSearchedExpression)) {
        final List<CaseSearchedExpression.WhenFragment> whenFragments = caseSearchedExpression.getWhenFragments();
        final Expression firstResult = whenFragments.get(0).getResult();
        super.visitAnsiCaseSearchedExpression(caseSearchedExpression, e -> {
            if (e == firstResult) {
                renderCasted(e);
            } else {
                resultRenderer.accept(e);
            }
        });
    } else {
        super.visitAnsiCaseSearchedExpression(caseSearchedExpression, resultRenderer);
    }
}
Also used : Expression(org.hibernate.sql.ast.tree.expression.Expression) CaseSimpleExpression(org.hibernate.sql.ast.tree.expression.CaseSimpleExpression) CaseSearchedExpression(org.hibernate.sql.ast.tree.expression.CaseSearchedExpression)

Example 30 with Expression

use of org.hibernate.sql.ast.tree.expression.Expression in project hibernate-orm by hibernate.

the class SybaseSqlAstTranslator method visitAnsiCaseSearchedExpression.

// Sybase does not allow CASE expressions where all result arms contain plain parameters.
// At least one result arm must provide some type context for inference,
// so we cast the first result arm if we encounter this condition
@Override
protected void visitAnsiCaseSearchedExpression(CaseSearchedExpression caseSearchedExpression, Consumer<Expression> resultRenderer) {
    if (getParameterRenderingMode() == SqlAstNodeRenderingMode.DEFAULT && areAllResultsParameters(caseSearchedExpression)) {
        final List<CaseSearchedExpression.WhenFragment> whenFragments = caseSearchedExpression.getWhenFragments();
        final Expression firstResult = whenFragments.get(0).getResult();
        super.visitAnsiCaseSearchedExpression(caseSearchedExpression, e -> {
            if (e == firstResult) {
                renderCasted(e);
            } else {
                resultRenderer.accept(e);
            }
        });
    } else {
        super.visitAnsiCaseSearchedExpression(caseSearchedExpression, resultRenderer);
    }
}
Also used : Expression(org.hibernate.sql.ast.tree.expression.Expression) CaseSimpleExpression(org.hibernate.sql.ast.tree.expression.CaseSimpleExpression) CaseSearchedExpression(org.hibernate.sql.ast.tree.expression.CaseSearchedExpression)

Aggregations

Expression (org.hibernate.sql.ast.tree.expression.Expression)130 CaseSearchedExpression (org.hibernate.sql.ast.tree.expression.CaseSearchedExpression)68 CaseSimpleExpression (org.hibernate.sql.ast.tree.expression.CaseSimpleExpression)67 BinaryArithmeticExpression (org.hibernate.sql.ast.tree.expression.BinaryArithmeticExpression)62 SqlSelectionExpression (org.hibernate.sql.ast.tree.expression.SqlSelectionExpression)57 ModifiedSubQueryExpression (org.hibernate.sql.ast.tree.expression.ModifiedSubQueryExpression)54 SelfRenderingExpression (org.hibernate.sql.ast.tree.expression.SelfRenderingExpression)54 ColumnReference (org.hibernate.sql.ast.tree.expression.ColumnReference)42 SelfRenderingFunctionSqlAstExpression (org.hibernate.query.sqm.function.SelfRenderingFunctionSqlAstExpression)37 SqlTuple (org.hibernate.sql.ast.tree.expression.SqlTuple)35 SqmExpression (org.hibernate.query.sqm.tree.expression.SqmExpression)34 SelfRenderingSqlFragmentExpression (org.hibernate.sql.ast.tree.expression.SelfRenderingSqlFragmentExpression)33 SelfRenderingAggregateFunctionSqlAstExpression (org.hibernate.query.sqm.function.SelfRenderingAggregateFunctionSqlAstExpression)32 ArrayList (java.util.ArrayList)31 SqmModifiedSubQueryExpression (org.hibernate.query.sqm.tree.expression.SqmModifiedSubQueryExpression)31 TableGroup (org.hibernate.sql.ast.tree.from.TableGroup)28 TableReference (org.hibernate.sql.ast.tree.from.TableReference)25 SessionFactoryImplementor (org.hibernate.engine.spi.SessionFactoryImplementor)23 ComparisonPredicate (org.hibernate.sql.ast.tree.predicate.ComparisonPredicate)23 NavigablePath (org.hibernate.query.spi.NavigablePath)21