Search in sources :

Example 6 with InSubQueryPredicate

use of org.hibernate.sql.ast.tree.predicate.InSubQueryPredicate in project hibernate-orm by hibernate.

the class UpdateExecutionDelegate method updateTable.

private void updateTable(String tableExpression, Supplier<Consumer<SelectableConsumer>> tableKeyColumnVisitationSupplier, QuerySpec idTableSubQuery, ExecutionContext executionContext) {
    final TableReference updatingTableReference = updatingTableGroup.getTableReference(updatingTableGroup.getNavigablePath(), tableExpression, true, true);
    final List<Assignment> assignments = assignmentsByTable.get(updatingTableReference);
    if (assignments == null || assignments.isEmpty()) {
        // no assignments for this table - skip it
        return;
    }
    // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    // create the in-subquery predicate to restrict the updates to just
    // matching ids
    final TableKeyExpressionCollector keyColumnCollector = new TableKeyExpressionCollector(entityDescriptor);
    tableKeyColumnVisitationSupplier.get().accept((columnIndex, selection) -> {
        assert selection.getContainingTableExpression().equals(tableExpression);
        keyColumnCollector.apply(new ColumnReference((String) null, selection, sessionFactory));
    });
    final InSubQueryPredicate idTableSubQueryPredicate = new InSubQueryPredicate(keyColumnCollector.buildKeyExpression(), idTableSubQuery, false);
    // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    // Create the SQL AST and convert it into a JdbcOperation
    final UpdateStatement sqlAst = new UpdateStatement(resolveUnionTableReference(updatingTableReference, tableExpression), assignments, idTableSubQueryPredicate);
    final JdbcServices jdbcServices = sessionFactory.getJdbcServices();
    final JdbcUpdate jdbcUpdate = jdbcServices.getJdbcEnvironment().getSqlAstTranslatorFactory().buildUpdateTranslator(sessionFactory, sqlAst).translate(jdbcParameterBindings, executionContext.getQueryOptions());
    jdbcServices.getJdbcMutationExecutor().execute(jdbcUpdate, jdbcParameterBindings, sql -> executionContext.getSession().getJdbcCoordinator().getStatementPreparer().prepareStatement(sql), (integer, preparedStatement) -> {
    }, executionContext);
}
Also used : Assignment(org.hibernate.sql.ast.tree.update.Assignment) TableReference(org.hibernate.sql.ast.tree.from.TableReference) NamedTableReference(org.hibernate.sql.ast.tree.from.NamedTableReference) UnionTableReference(org.hibernate.sql.ast.tree.from.UnionTableReference) SqmUpdateStatement(org.hibernate.query.sqm.tree.update.SqmUpdateStatement) UpdateStatement(org.hibernate.sql.ast.tree.update.UpdateStatement) JdbcUpdate(org.hibernate.sql.exec.spi.JdbcUpdate) InSubQueryPredicate(org.hibernate.sql.ast.tree.predicate.InSubQueryPredicate) JdbcServices(org.hibernate.engine.jdbc.spi.JdbcServices) ColumnReference(org.hibernate.sql.ast.tree.expression.ColumnReference)

Example 7 with InSubQueryPredicate

use of org.hibernate.sql.ast.tree.predicate.InSubQueryPredicate in project hibernate-orm by hibernate.

the class RestrictedDeleteExecutionDelegate method deleteFromNonRootTableWithoutIdTable.

private int deleteFromNonRootTableWithoutIdTable(NamedTableReference targetTableReference, Supplier<Consumer<SelectableConsumer>> tableKeyColumnVisitationSupplier, SqlExpressionResolver sqlExpressionResolver, TableGroup rootTableGroup, QuerySpec matchingIdSubQuerySpec, JdbcParameterBindings jdbcParameterBindings, ExecutionContext executionContext) {
    assert targetTableReference != null;
    log.tracef("deleteFromNonRootTable - %s", targetTableReference.getTableExpression());
    final NamedTableReference deleteTableReference = new NamedTableReference(targetTableReference.getTableExpression(), DeleteStatement.DEFAULT_ALIAS, true, sessionFactory);
    final Predicate tableDeletePredicate;
    if (matchingIdSubQuerySpec == null) {
        tableDeletePredicate = null;
    } else {
        /*
			 * delete from sub_table
			 * where sub_id in (
			 * 		select root_id from root_table
			 * 		where {predicate}
			 * )
			 */
        /*
			 * Create the `sub_id` reference as the LHS of the in-subquery predicate
			 */
        final List<ColumnReference> deletingTableColumnRefs = new ArrayList<>();
        tableKeyColumnVisitationSupplier.get().accept((columnIndex, selection) -> {
            assert deleteTableReference.getTableReference(selection.getContainingTableExpression()) != null;
            final Expression expression = sqlExpressionResolver.resolveSqlExpression(SqlExpressionResolver.createColumnReferenceKey(deleteTableReference, selection.getSelectionExpression()), sqlAstProcessingState -> new ColumnReference(deleteTableReference, selection, sessionFactory));
            deletingTableColumnRefs.add((ColumnReference) expression);
        });
        final Expression deletingTableColumnRefsExpression;
        if (deletingTableColumnRefs.size() == 1) {
            deletingTableColumnRefsExpression = deletingTableColumnRefs.get(0);
        } else {
            deletingTableColumnRefsExpression = new SqlTuple(deletingTableColumnRefs, entityDescriptor.getIdentifierMapping());
        }
        tableDeletePredicate = new InSubQueryPredicate(deletingTableColumnRefsExpression, matchingIdSubQuerySpec, false);
    }
    final DeleteStatement sqlAstDelete = new DeleteStatement(deleteTableReference, tableDeletePredicate);
    final int rows = executeSqlDelete(sqlAstDelete, jdbcParameterBindings, executionContext);
    log.debugf("deleteFromNonRootTable - `%s` : %s rows", targetTableReference, rows);
    return rows;
}
Also used : NamedTableReference(org.hibernate.sql.ast.tree.from.NamedTableReference) Expression(org.hibernate.sql.ast.tree.expression.Expression) InSubQueryPredicate(org.hibernate.sql.ast.tree.predicate.InSubQueryPredicate) ArrayList(java.util.ArrayList) SqlTuple(org.hibernate.sql.ast.tree.expression.SqlTuple) SqmDeleteStatement(org.hibernate.query.sqm.tree.delete.SqmDeleteStatement) DeleteStatement(org.hibernate.sql.ast.tree.delete.DeleteStatement) InSubQueryPredicate(org.hibernate.sql.ast.tree.predicate.InSubQueryPredicate) Predicate(org.hibernate.sql.ast.tree.predicate.Predicate) ColumnReference(org.hibernate.sql.ast.tree.expression.ColumnReference)

Example 8 with InSubQueryPredicate

use of org.hibernate.sql.ast.tree.predicate.InSubQueryPredicate in project hibernate-orm by hibernate.

the class RestrictedDeleteExecutionDelegate method deleteFromTableUsingIdTable.

private void deleteFromTableUsingIdTable(String tableExpression, Supplier<Consumer<SelectableConsumer>> tableKeyColumnVisitationSupplier, QuerySpec idTableSubQuery, ExecutionContext executionContext) {
    log.tracef("deleteFromTableUsingIdTable - %s", tableExpression);
    final SessionFactoryImplementor factory = executionContext.getSession().getFactory();
    final TableKeyExpressionCollector keyColumnCollector = new TableKeyExpressionCollector(entityDescriptor);
    final NamedTableReference targetTable = new NamedTableReference(tableExpression, DeleteStatement.DEFAULT_ALIAS, true, factory);
    tableKeyColumnVisitationSupplier.get().accept((columnIndex, selection) -> {
        assert selection.getContainingTableExpression().equals(tableExpression);
        assert !selection.isFormula();
        assert selection.getCustomReadExpression() == null;
        assert selection.getCustomWriteExpression() == null;
        keyColumnCollector.apply(new ColumnReference(targetTable, selection, factory));
    });
    final InSubQueryPredicate predicate = new InSubQueryPredicate(keyColumnCollector.buildKeyExpression(), idTableSubQuery, false);
    executeSqlDelete(new DeleteStatement(targetTable, predicate), JdbcParameterBindings.NO_BINDINGS, executionContext);
}
Also used : NamedTableReference(org.hibernate.sql.ast.tree.from.NamedTableReference) SessionFactoryImplementor(org.hibernate.engine.spi.SessionFactoryImplementor) InSubQueryPredicate(org.hibernate.sql.ast.tree.predicate.InSubQueryPredicate) SqmDeleteStatement(org.hibernate.query.sqm.tree.delete.SqmDeleteStatement) DeleteStatement(org.hibernate.sql.ast.tree.delete.DeleteStatement) ColumnReference(org.hibernate.sql.ast.tree.expression.ColumnReference)

Example 9 with InSubQueryPredicate

use of org.hibernate.sql.ast.tree.predicate.InSubQueryPredicate in project hibernate-orm by hibernate.

the class ExpressionReplacementWalker method visitInSubQueryPredicate.

@Override
public void visitInSubQueryPredicate(InSubQueryPredicate inSubQueryPredicate) {
    final Expression testExpression = replaceExpression(inSubQueryPredicate.getTestExpression());
    final QueryPart subQuery = replaceExpression(inSubQueryPredicate.getSubQuery());
    if (testExpression != inSubQueryPredicate.getTestExpression() || subQuery != inSubQueryPredicate.getSubQuery()) {
        returnedNode = new InSubQueryPredicate(testExpression, subQuery, inSubQueryPredicate.isNegated(), inSubQueryPredicate.getExpressionType());
    } else {
        returnedNode = inSubQueryPredicate;
    }
}
Also used : Expression(org.hibernate.sql.ast.tree.expression.Expression) CaseSimpleExpression(org.hibernate.sql.ast.tree.expression.CaseSimpleExpression) BinaryArithmeticExpression(org.hibernate.sql.ast.tree.expression.BinaryArithmeticExpression) SqlSelectionExpression(org.hibernate.sql.ast.tree.expression.SqlSelectionExpression) CaseSearchedExpression(org.hibernate.sql.ast.tree.expression.CaseSearchedExpression) ModifiedSubQueryExpression(org.hibernate.sql.ast.tree.expression.ModifiedSubQueryExpression) SelfRenderingExpression(org.hibernate.sql.ast.tree.expression.SelfRenderingExpression) QueryPart(org.hibernate.sql.ast.tree.select.QueryPart) InSubQueryPredicate(org.hibernate.sql.ast.tree.predicate.InSubQueryPredicate)

Example 10 with InSubQueryPredicate

use of org.hibernate.sql.ast.tree.predicate.InSubQueryPredicate in project hibernate-orm by hibernate.

the class LoaderSelectBuilder method applySubSelectRestriction.

private void applySubSelectRestriction(QuerySpec querySpec, NavigablePath rootNavigablePath, TableGroup rootTableGroup, SubselectFetch subselect, LoaderSqlAstCreationState sqlAstCreationState) {
    final SqlAstCreationContext sqlAstCreationContext = sqlAstCreationState.getCreationContext();
    final SessionFactoryImplementor sessionFactory = sqlAstCreationContext.getSessionFactory();
    assert loadable instanceof PluralAttributeMapping;
    final PluralAttributeMapping attributeMapping = (PluralAttributeMapping) loadable;
    final ForeignKeyDescriptor fkDescriptor = attributeMapping.getKeyDescriptor();
    final NavigablePath navigablePath = rootNavigablePath.append(attributeMapping.getAttributeName());
    final Expression fkExpression;
    final int jdbcTypeCount = fkDescriptor.getJdbcTypeCount();
    if (jdbcTypeCount == 1) {
        assert fkDescriptor instanceof SimpleForeignKeyDescriptor;
        final SimpleForeignKeyDescriptor simpleFkDescriptor = (SimpleForeignKeyDescriptor) fkDescriptor;
        final TableReference tableReference = rootTableGroup.resolveTableReference(navigablePath, simpleFkDescriptor.getContainingTableExpression());
        fkExpression = sqlAstCreationState.getSqlExpressionResolver().resolveSqlExpression(createColumnReferenceKey(tableReference, simpleFkDescriptor.getSelectionExpression()), sqlAstProcessingState -> new ColumnReference(tableReference, simpleFkDescriptor.getSelectionExpression(), false, null, null, simpleFkDescriptor.getJdbcMapping(), this.creationContext.getSessionFactory()));
    } else {
        final List<ColumnReference> columnReferences = new ArrayList<>(jdbcTypeCount);
        fkDescriptor.forEachSelectable((columnIndex, selection) -> {
            final TableReference tableReference = rootTableGroup.resolveTableReference(navigablePath, selection.getContainingTableExpression());
            columnReferences.add((ColumnReference) sqlAstCreationState.getSqlExpressionResolver().resolveSqlExpression(createColumnReferenceKey(tableReference, selection.getSelectionExpression()), sqlAstProcessingState -> new ColumnReference(tableReference, selection, this.creationContext.getSessionFactory())));
        });
        fkExpression = new SqlTuple(columnReferences, fkDescriptor);
    }
    querySpec.applyPredicate(new InSubQueryPredicate(fkExpression, generateSubSelect(attributeMapping, rootTableGroup, subselect, jdbcTypeCount, sqlAstCreationState, sessionFactory), false));
}
Also used : Arrays(java.util.Arrays) CollectionFetch(org.hibernate.sql.results.graph.collection.internal.CollectionFetch) CollectionDomainResult(org.hibernate.sql.results.graph.collection.internal.CollectionDomainResult) GraphSemantic(org.hibernate.graph.GraphSemantic) ResultsHelper.attributeName(org.hibernate.query.results.ResultsHelper.attributeName) TableGroupJoin(org.hibernate.sql.ast.tree.from.TableGroupJoin) CascadingAction(org.hibernate.engine.spi.CascadingAction) EntityValuedModelPart(org.hibernate.metamodel.mapping.EntityValuedModelPart) EntityResultImpl(org.hibernate.sql.results.graph.entity.internal.EntityResultImpl) SqlAstCreationContext(org.hibernate.sql.ast.spi.SqlAstCreationContext) BagSemantics(org.hibernate.collection.spi.BagSemantics) FetchableContainer(org.hibernate.sql.results.graph.FetchableContainer) PluralAttributeMapping(org.hibernate.metamodel.mapping.PluralAttributeMapping) ComparisonPredicate(org.hibernate.sql.ast.tree.predicate.ComparisonPredicate) BiDirectionalFetch(org.hibernate.sql.results.graph.BiDirectionalFetch) ForeignKeyDescriptor(org.hibernate.metamodel.mapping.ForeignKeyDescriptor) Map(java.util.Map) FetchProfile(org.hibernate.engine.profile.FetchProfile) JdbcParameterImpl(org.hibernate.sql.exec.internal.JdbcParameterImpl) ComparisonOperator(org.hibernate.query.sqm.ComparisonOperator) SessionFactoryImplementor(org.hibernate.engine.spi.SessionFactoryImplementor) CollectionPart(org.hibernate.metamodel.mapping.CollectionPart) EntityValuedFetchable(org.hibernate.sql.results.graph.entity.EntityValuedFetchable) InSubQueryPredicate(org.hibernate.sql.ast.tree.predicate.InSubQueryPredicate) Fetchable(org.hibernate.sql.results.graph.Fetchable) TableGroupJoinProducer(org.hibernate.sql.ast.tree.from.TableGroupJoinProducer) LockOptions(org.hibernate.LockOptions) NavigablePath(org.hibernate.query.spi.NavigablePath) AliasCollector(org.hibernate.sql.ast.spi.AliasCollector) DomainResult(org.hibernate.sql.results.graph.DomainResult) Expression(org.hibernate.sql.ast.tree.expression.Expression) OrderByFragment(org.hibernate.metamodel.mapping.ordering.OrderByFragment) SimpleFromClauseAccessImpl(org.hibernate.sql.ast.spi.SimpleFromClauseAccessImpl) SqlExpressionResolver(org.hibernate.sql.ast.spi.SqlExpressionResolver) Objects(java.util.Objects) EntityIdentifierMapping(org.hibernate.metamodel.mapping.EntityIdentifierMapping) SelectStatement(org.hibernate.sql.ast.tree.select.SelectStatement) LoadQueryInfluencers(org.hibernate.engine.spi.LoadQueryInfluencers) List(java.util.List) CascadeStyle(org.hibernate.engine.spi.CascadeStyle) SqlTuple(org.hibernate.sql.ast.tree.expression.SqlTuple) QuerySpec(org.hibernate.sql.ast.tree.select.QuerySpec) SubselectFetch(org.hibernate.engine.spi.SubselectFetch) SimpleForeignKeyDescriptor(org.hibernate.metamodel.mapping.internal.SimpleForeignKeyDescriptor) EmbeddedAttributeMapping(org.hibernate.metamodel.mapping.internal.EmbeddedAttributeMapping) SqlExpressionResolver.createColumnReferenceKey(org.hibernate.sql.ast.spi.SqlExpressionResolver.createColumnReferenceKey) FetchParent(org.hibernate.sql.results.graph.FetchParent) BasicValuedModelPart(org.hibernate.metamodel.mapping.BasicValuedModelPart) InListPredicate(org.hibernate.sql.ast.tree.predicate.InListPredicate) Logger(org.jboss.logging.Logger) ColumnReference(org.hibernate.sql.ast.tree.expression.ColumnReference) ArrayList(java.util.ArrayList) RootGraphImplementor(org.hibernate.graph.spi.RootGraphImplementor) TableReference(org.hibernate.sql.ast.tree.from.TableReference) ModelPart(org.hibernate.metamodel.mapping.ModelPart) Loader(org.hibernate.loader.ast.spi.Loader) BiConsumer(java.util.function.BiConsumer) EntityIdentifierNavigablePath(org.hibernate.query.sqm.spi.EntityIdentifierNavigablePath) SqlAliasBaseManager(org.hibernate.sql.ast.spi.SqlAliasBaseManager) SqlAstCreationState(org.hibernate.sql.ast.spi.SqlAstCreationState) FetchTiming(org.hibernate.engine.FetchTiming) Loadable(org.hibernate.loader.ast.spi.Loadable) Fetch(org.hibernate.sql.results.graph.Fetch) Consumer(java.util.function.Consumer) Restrictable(org.hibernate.metamodel.mapping.Restrictable) EntityGraphTraversalState(org.hibernate.sql.results.graph.EntityGraphTraversalState) FetchStyle(org.hibernate.engine.FetchStyle) StandardEntityGraphTraversalStateImpl(org.hibernate.sql.results.internal.StandardEntityGraphTraversalStateImpl) AbstractMap(java.util.AbstractMap) JdbcParameter(org.hibernate.sql.ast.tree.expression.JdbcParameter) FromClauseAccess(org.hibernate.sql.ast.spi.FromClauseAccess) QueryPart(org.hibernate.sql.ast.tree.select.QueryPart) SqlAstJoinType(org.hibernate.sql.ast.SqlAstJoinType) NaturalIdMapping(org.hibernate.metamodel.mapping.NaturalIdMapping) SqlSelectionImpl(org.hibernate.sql.results.internal.SqlSelectionImpl) NonAggregatedIdentifierMapping(org.hibernate.metamodel.mapping.NonAggregatedIdentifierMapping) AttributeMapping(org.hibernate.metamodel.mapping.AttributeMapping) Collections(java.util.Collections) TableGroup(org.hibernate.sql.ast.tree.from.TableGroup) EffectiveEntityGraph(org.hibernate.engine.spi.EffectiveEntityGraph) PluralTableGroup(org.hibernate.sql.ast.tree.from.PluralTableGroup) NavigablePath(org.hibernate.query.spi.NavigablePath) EntityIdentifierNavigablePath(org.hibernate.query.sqm.spi.EntityIdentifierNavigablePath) SessionFactoryImplementor(org.hibernate.engine.spi.SessionFactoryImplementor) InSubQueryPredicate(org.hibernate.sql.ast.tree.predicate.InSubQueryPredicate) PluralAttributeMapping(org.hibernate.metamodel.mapping.PluralAttributeMapping) ArrayList(java.util.ArrayList) TableReference(org.hibernate.sql.ast.tree.from.TableReference) SqlAstCreationContext(org.hibernate.sql.ast.spi.SqlAstCreationContext) Expression(org.hibernate.sql.ast.tree.expression.Expression) ForeignKeyDescriptor(org.hibernate.metamodel.mapping.ForeignKeyDescriptor) SimpleForeignKeyDescriptor(org.hibernate.metamodel.mapping.internal.SimpleForeignKeyDescriptor) SqlTuple(org.hibernate.sql.ast.tree.expression.SqlTuple) SimpleForeignKeyDescriptor(org.hibernate.metamodel.mapping.internal.SimpleForeignKeyDescriptor) ColumnReference(org.hibernate.sql.ast.tree.expression.ColumnReference)

Aggregations

InSubQueryPredicate (org.hibernate.sql.ast.tree.predicate.InSubQueryPredicate)10 Expression (org.hibernate.sql.ast.tree.expression.Expression)6 ColumnReference (org.hibernate.sql.ast.tree.expression.ColumnReference)5 NamedTableReference (org.hibernate.sql.ast.tree.from.NamedTableReference)5 QuerySpec (org.hibernate.sql.ast.tree.select.QuerySpec)5 ForeignKeyDescriptor (org.hibernate.metamodel.mapping.ForeignKeyDescriptor)4 SessionFactoryImplementor (org.hibernate.engine.spi.SessionFactoryImplementor)3 EntityIdentifierMapping (org.hibernate.metamodel.mapping.EntityIdentifierMapping)3 SqlTuple (org.hibernate.sql.ast.tree.expression.SqlTuple)3 ArrayList (java.util.ArrayList)2 JdbcServices (org.hibernate.engine.jdbc.spi.JdbcServices)2 CollectionPart (org.hibernate.metamodel.mapping.CollectionPart)2 MappingModelExpressible (org.hibernate.metamodel.mapping.MappingModelExpressible)2 SqmParameterMappingModelResolutionAccess (org.hibernate.query.sqm.spi.SqmParameterMappingModelResolutionAccess)2 SqmDeleteStatement (org.hibernate.query.sqm.tree.delete.SqmDeleteStatement)2 SqmExpression (org.hibernate.query.sqm.tree.expression.SqmExpression)2 DeleteStatement (org.hibernate.sql.ast.tree.delete.DeleteStatement)2 TableReference (org.hibernate.sql.ast.tree.from.TableReference)2 QueryPart (org.hibernate.sql.ast.tree.select.QueryPart)2 JdbcParameterBindings (org.hibernate.sql.exec.spi.JdbcParameterBindings)2