Search in sources :

Example 1 with DeleteStatement

use of org.hibernate.sql.ast.tree.delete.DeleteStatement in project hibernate-orm by hibernate.

the class AbstractSqlAstTranslator method translate.

@Override
public T translate(JdbcParameterBindings jdbcParameterBindings, QueryOptions queryOptions) {
    try {
        this.jdbcParameterBindings = jdbcParameterBindings;
        this.lockOptions = queryOptions.getLockOptions().makeCopy();
        this.limit = queryOptions.getLimit() == null ? null : queryOptions.getLimit().makeCopy();
        final JdbcOperation jdbcOperation;
        if (statement instanceof DeleteStatement) {
            jdbcOperation = translateDelete((DeleteStatement) statement);
        } else if (statement instanceof UpdateStatement) {
            jdbcOperation = translateUpdate((UpdateStatement) statement);
        } else if (statement instanceof InsertStatement) {
            jdbcOperation = translateInsert((InsertStatement) statement);
        } else if (statement instanceof SelectStatement) {
            jdbcOperation = translateSelect((SelectStatement) statement);
        } else {
            throw new IllegalArgumentException("Unexpected statement!");
        }
        if (jdbcParameterBindings != null && CollectionHelper.isNotEmpty(getFilterJdbcParameters())) {
            for (FilterJdbcParameter filterJdbcParameter : getFilterJdbcParameters()) {
                jdbcParameterBindings.addBinding(filterJdbcParameter.getParameter(), filterJdbcParameter.getBinding());
            }
        }
        return (T) jdbcOperation;
    } finally {
        cleanup();
    }
}
Also used : SelectStatement(org.hibernate.sql.ast.tree.select.SelectStatement) UpdateStatement(org.hibernate.sql.ast.tree.update.UpdateStatement) JdbcOperation(org.hibernate.sql.exec.spi.JdbcOperation) DeleteStatement(org.hibernate.sql.ast.tree.delete.DeleteStatement) FilterJdbcParameter(org.hibernate.internal.FilterJdbcParameter) InsertStatement(org.hibernate.sql.ast.tree.insert.InsertStatement)

Example 2 with DeleteStatement

use of org.hibernate.sql.ast.tree.delete.DeleteStatement in project hibernate-orm by hibernate.

the class CteDeleteHandler method addDmlCtes.

@Override
protected void addDmlCtes(CteContainer statement, CteStatement idSelectCte, MultiTableSqmMutationConverter sqmConverter, Map<SqmParameter, List<JdbcParameter>> parameterResolutions, SessionFactoryImplementor factory) {
    final TableGroup updatingTableGroup = sqmConverter.getMutatingTableGroup();
    final SelectStatement idSelectStatement = (SelectStatement) idSelectCte.getCteDefinition();
    sqmConverter.getProcessingStateStack().push(new SqlAstQueryPartProcessingStateImpl(idSelectStatement.getQuerySpec(), sqmConverter.getCurrentProcessingState(), sqmConverter.getSqlAstCreationState(), sqmConverter.getCurrentClauseStack()::getCurrent, false));
    getEntityDescriptor().visitSubTypeAttributeMappings(attribute -> {
        if (attribute instanceof PluralAttributeMapping) {
            final PluralAttributeMapping pluralAttribute = (PluralAttributeMapping) attribute;
            if (pluralAttribute.getSeparateCollectionTable() != null) {
                // Ensure that the FK target columns are available
                final boolean useFkTarget = !(pluralAttribute.getKeyDescriptor().getTargetPart() instanceof EntityIdentifierMapping);
                if (useFkTarget) {
                    final TableGroup mutatingTableGroup = sqmConverter.getMutatingTableGroup();
                    pluralAttribute.getKeyDescriptor().getTargetPart().applySqlSelections(mutatingTableGroup.getNavigablePath(), mutatingTableGroup, sqmConverter, (selection, jdbcMapping) -> {
                        idSelectStatement.getDomainResultDescriptors().add(new BasicResult<>(selection.getValuesArrayPosition(), null, jdbcMapping.getJavaTypeDescriptor()));
                    });
                }
                // this collection has a separate collection table, meaning it is one of:
                // 1) element-collection
                // 2) many-to-many
                // 3) one-to many using a dedicated join-table
                // 
                // in all of these cases, we should clean up the matching rows in the
                // collection table
                final String tableExpression = pluralAttribute.getSeparateCollectionTable();
                final CteTable dmlResultCte = new CteTable(getCteTableName(pluralAttribute), idSelectCte.getCteTable().getCteColumns(), factory);
                final NamedTableReference dmlTableReference = new NamedTableReference(tableExpression, DeleteStatement.DEFAULT_ALIAS, true, factory);
                final List<ColumnReference> columnReferences = new ArrayList<>(idSelectCte.getCteTable().getCteColumns().size());
                pluralAttribute.getKeyDescriptor().visitKeySelectables((index, selectable) -> columnReferences.add(new ColumnReference(dmlTableReference, selectable, factory)));
                final MutationStatement dmlStatement = new DeleteStatement(dmlTableReference, createIdSubQueryPredicate(columnReferences, idSelectCte, useFkTarget ? pluralAttribute.getKeyDescriptor().getTargetPart() : null, factory), columnReferences);
                statement.addCteStatement(new CteStatement(dmlResultCte, dmlStatement));
            }
        }
    });
    sqmConverter.getProcessingStateStack().pop();
    getEntityDescriptor().visitConstraintOrderedTables((tableExpression, tableColumnsVisitationSupplier) -> {
        final CteTable dmlResultCte = new CteTable(getCteTableName(tableExpression), idSelectCte.getCteTable().getCteColumns(), factory);
        final TableReference updatingTableReference = updatingTableGroup.getTableReference(updatingTableGroup.getNavigablePath(), tableExpression, true, true);
        final NamedTableReference dmlTableReference = resolveUnionTableReference(updatingTableReference, tableExpression);
        final List<ColumnReference> columnReferences = new ArrayList<>(idSelectCte.getCteTable().getCteColumns().size());
        tableColumnsVisitationSupplier.get().accept((index, selectable) -> columnReferences.add(new ColumnReference(dmlTableReference, selectable, factory)));
        final MutationStatement dmlStatement = new DeleteStatement(dmlTableReference, createIdSubQueryPredicate(columnReferences, idSelectCte, factory), columnReferences);
        statement.addCteStatement(new CteStatement(dmlResultCte, dmlStatement));
    });
}
Also used : TableGroup(org.hibernate.sql.ast.tree.from.TableGroup) NamedTableReference(org.hibernate.sql.ast.tree.from.NamedTableReference) PluralAttributeMapping(org.hibernate.metamodel.mapping.PluralAttributeMapping) ArrayList(java.util.ArrayList) SqmDeleteStatement(org.hibernate.query.sqm.tree.delete.SqmDeleteStatement) DeleteStatement(org.hibernate.sql.ast.tree.delete.DeleteStatement) SelectStatement(org.hibernate.sql.ast.tree.select.SelectStatement) SqlAstQueryPartProcessingStateImpl(org.hibernate.query.sqm.sql.internal.SqlAstQueryPartProcessingStateImpl) SqmCteTable(org.hibernate.query.sqm.tree.cte.SqmCteTable) CteTable(org.hibernate.sql.ast.tree.cte.CteTable) MutationStatement(org.hibernate.sql.ast.tree.MutationStatement) TableReference(org.hibernate.sql.ast.tree.from.TableReference) NamedTableReference(org.hibernate.sql.ast.tree.from.NamedTableReference) EntityIdentifierMapping(org.hibernate.metamodel.mapping.EntityIdentifierMapping) CteStatement(org.hibernate.sql.ast.tree.cte.CteStatement) ColumnReference(org.hibernate.sql.ast.tree.expression.ColumnReference)

Example 3 with DeleteStatement

use of org.hibernate.sql.ast.tree.delete.DeleteStatement in project hibernate-orm by hibernate.

the class InlineDeleteHandler method executeDelete.

private void executeDelete(String targetTableExpression, EntityMappingType entityDescriptor, Supplier<Consumer<SelectableConsumer>> tableKeyColumnsVisitationSupplier, List<Object> ids, int valueIndex, ModelPart valueModelPart, JdbcParameterBindings jdbcParameterBindings, DomainQueryExecutionContext executionContext) {
    final NamedTableReference targetTableReference = new NamedTableReference(targetTableExpression, DeleteStatement.DEFAULT_ALIAS, false, sessionFactory);
    final SqmJdbcExecutionContextAdapter executionContextAdapter = SqmJdbcExecutionContextAdapter.omittingLockingAndPaging(executionContext);
    final Predicate matchingIdsPredicate = matchingIdsPredicateProducer.produceRestriction(ids, entityDescriptor, valueIndex, valueModelPart, targetTableReference, tableKeyColumnsVisitationSupplier, executionContextAdapter);
    final DeleteStatement deleteStatement = new DeleteStatement(targetTableReference, matchingIdsPredicate);
    final JdbcDelete jdbcOperation = sqlAstTranslatorFactory.buildDeleteTranslator(sessionFactory, deleteStatement).translate(jdbcParameterBindings, executionContext.getQueryOptions());
    jdbcMutationExecutor.execute(jdbcOperation, jdbcParameterBindings, this::prepareQueryStatement, (integer, preparedStatement) -> {
    }, executionContextAdapter);
}
Also used : NamedTableReference(org.hibernate.sql.ast.tree.from.NamedTableReference) JdbcDelete(org.hibernate.sql.exec.spi.JdbcDelete) SqmDeleteStatement(org.hibernate.query.sqm.tree.delete.SqmDeleteStatement) DeleteStatement(org.hibernate.sql.ast.tree.delete.DeleteStatement) SqmJdbcExecutionContextAdapter(org.hibernate.query.sqm.internal.SqmJdbcExecutionContextAdapter) Predicate(org.hibernate.sql.ast.tree.predicate.Predicate)

Example 4 with DeleteStatement

use of org.hibernate.sql.ast.tree.delete.DeleteStatement in project hibernate-orm by hibernate.

the class SimpleDeleteQueryPlan method createDeleteTranslator.

private SqlAstTranslator<JdbcDelete> createDeleteTranslator(DomainQueryExecutionContext executionContext) {
    final SessionFactoryImplementor factory = executionContext.getSession().getFactory();
    final QueryEngine queryEngine = factory.getQueryEngine();
    final SqmTranslatorFactory translatorFactory = queryEngine.getSqmTranslatorFactory();
    final SqmTranslator<DeleteStatement> translator = translatorFactory.createSimpleDeleteTranslator(sqmDelete, executionContext.getQueryOptions(), domainParameterXref, executionContext.getQueryParameterBindings(), executionContext.getSession().getLoadQueryInfluencers(), factory);
    sqmInterpretation = translator.translate();
    this.jdbcParamsXref = SqmUtil.generateJdbcParamsXref(domainParameterXref, sqmInterpretation::getJdbcParamsBySqmParam);
    return factory.getJdbcServices().getJdbcEnvironment().getSqlAstTranslatorFactory().buildDeleteTranslator(factory, sqmInterpretation.getSqlAst());
}
Also used : SessionFactoryImplementor(org.hibernate.engine.spi.SessionFactoryImplementor) QueryEngine(org.hibernate.query.spi.QueryEngine) SqmDeleteStatement(org.hibernate.query.sqm.tree.delete.SqmDeleteStatement) DeleteStatement(org.hibernate.sql.ast.tree.delete.DeleteStatement) SqmTranslatorFactory(org.hibernate.query.sqm.sql.SqmTranslatorFactory)

Example 5 with DeleteStatement

use of org.hibernate.sql.ast.tree.delete.DeleteStatement in project hibernate-orm by hibernate.

the class BaseSqmToSqlAstConverter method visitDeleteStatement.

// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// Delete statement
@Override
public DeleteStatement visitDeleteStatement(SqmDeleteStatement<?> statement) {
    final CteContainer cteContainer = this.visitCteContainer(statement);
    final String entityName = statement.getTarget().getEntityName();
    final EntityPersister entityDescriptor = creationContext.getSessionFactory().getRuntimeMetamodels().getMappingMetamodel().getEntityDescriptor(entityName);
    assert entityDescriptor != null;
    pushProcessingState(new SqlAstProcessingStateImpl(getCurrentProcessingState(), this, getCurrentClauseStack()::getCurrent));
    try {
        final NavigablePath rootPath = statement.getTarget().getNavigablePath();
        final TableGroup rootTableGroup = entityDescriptor.createRootTableGroup(true, rootPath, statement.getRoot().getAlias(), () -> predicate -> additionalRestrictions = SqlAstTreeHelper.combinePredicates(additionalRestrictions, predicate), this, getCreationContext());
        getFromClauseAccess().registerTableGroup(rootPath, rootTableGroup);
        if (!rootTableGroup.getTableReferenceJoins().isEmpty()) {
            throw new HibernateException("Not expecting multiple table references for an SQM DELETE");
        }
        FilterHelper.applyBaseRestrictions((filterPredicate) -> additionalRestrictions = filterPredicate, entityDescriptor, rootTableGroup, AbstractSqlAstTranslator.rendersTableReferenceAlias(Clause.DELETE), getLoadQueryInfluencers(), this);
        Predicate suppliedPredicate = null;
        final SqmWhereClause whereClause = statement.getWhereClause();
        if (whereClause != null) {
            suppliedPredicate = visitWhereClause(whereClause.getPredicate());
        }
        return new DeleteStatement(cteContainer, (NamedTableReference) rootTableGroup.getPrimaryTableReference(), SqlAstTreeHelper.combinePredicates(suppliedPredicate, additionalRestrictions), Collections.emptyList());
    } finally {
        popProcessingStateStack();
    }
}
Also used : EntityPersister(org.hibernate.persister.entity.EntityPersister) SingleTableEntityPersister(org.hibernate.persister.entity.SingleTableEntityPersister) AbstractEntityPersister(org.hibernate.persister.entity.AbstractEntityPersister) SqmCteContainer(org.hibernate.query.sqm.tree.cte.SqmCteContainer) CteContainer(org.hibernate.sql.ast.tree.cte.CteContainer) NavigablePath(org.hibernate.query.spi.NavigablePath) VirtualTableGroup(org.hibernate.sql.ast.tree.from.VirtualTableGroup) LazyTableGroup(org.hibernate.sql.ast.tree.from.LazyTableGroup) TableGroup(org.hibernate.sql.ast.tree.from.TableGroup) CorrelatedTableGroup(org.hibernate.sql.ast.tree.from.CorrelatedTableGroup) CorrelatedPluralTableGroup(org.hibernate.sql.ast.tree.from.CorrelatedPluralTableGroup) PluralTableGroup(org.hibernate.sql.ast.tree.from.PluralTableGroup) QueryPartTableGroup(org.hibernate.sql.ast.tree.from.QueryPartTableGroup) HibernateException(org.hibernate.HibernateException) SqmWhereClause(org.hibernate.query.sqm.tree.predicate.SqmWhereClause) SqlAstProcessingStateImpl(org.hibernate.query.sqm.sql.internal.SqlAstProcessingStateImpl) DeleteStatement(org.hibernate.sql.ast.tree.delete.DeleteStatement) SqmDeleteStatement(org.hibernate.query.sqm.tree.delete.SqmDeleteStatement) InSubQueryPredicate(org.hibernate.sql.ast.tree.predicate.InSubQueryPredicate) SqmBooleanExpressionPredicate(org.hibernate.query.sqm.tree.predicate.SqmBooleanExpressionPredicate) SelfRenderingPredicate(org.hibernate.sql.ast.tree.predicate.SelfRenderingPredicate) NegatedPredicate(org.hibernate.sql.ast.tree.predicate.NegatedPredicate) LikePredicate(org.hibernate.sql.ast.tree.predicate.LikePredicate) BetweenPredicate(org.hibernate.sql.ast.tree.predicate.BetweenPredicate) SqmPredicate(org.hibernate.query.sqm.tree.predicate.SqmPredicate) SqmNegatedPredicate(org.hibernate.query.sqm.tree.predicate.SqmNegatedPredicate) ExistsPredicate(org.hibernate.sql.ast.tree.predicate.ExistsPredicate) SqmAndPredicate(org.hibernate.query.sqm.tree.predicate.SqmAndPredicate) SqmMemberOfPredicate(org.hibernate.query.sqm.tree.predicate.SqmMemberOfPredicate) SqmLikePredicate(org.hibernate.query.sqm.tree.predicate.SqmLikePredicate) SqmExistsPredicate(org.hibernate.query.sqm.tree.predicate.SqmExistsPredicate) SqmOrPredicate(org.hibernate.query.sqm.tree.predicate.SqmOrPredicate) SqmNullnessPredicate(org.hibernate.query.sqm.tree.predicate.SqmNullnessPredicate) SqmComparisonPredicate(org.hibernate.query.sqm.tree.predicate.SqmComparisonPredicate) SqmGroupedPredicate(org.hibernate.query.sqm.tree.predicate.SqmGroupedPredicate) SqmInListPredicate(org.hibernate.query.sqm.tree.predicate.SqmInListPredicate) ComparisonPredicate(org.hibernate.sql.ast.tree.predicate.ComparisonPredicate) NullnessPredicate(org.hibernate.sql.ast.tree.predicate.NullnessPredicate) SqmBetweenPredicate(org.hibernate.query.sqm.tree.predicate.SqmBetweenPredicate) GroupedPredicate(org.hibernate.sql.ast.tree.predicate.GroupedPredicate) BooleanExpressionPredicate(org.hibernate.sql.ast.tree.predicate.BooleanExpressionPredicate) InListPredicate(org.hibernate.sql.ast.tree.predicate.InListPredicate) SqmInSubQueryPredicate(org.hibernate.query.sqm.tree.predicate.SqmInSubQueryPredicate) SqmEmptinessPredicate(org.hibernate.query.sqm.tree.predicate.SqmEmptinessPredicate) Predicate(org.hibernate.sql.ast.tree.predicate.Predicate)

Aggregations

DeleteStatement (org.hibernate.sql.ast.tree.delete.DeleteStatement)9 SqmDeleteStatement (org.hibernate.query.sqm.tree.delete.SqmDeleteStatement)6 NamedTableReference (org.hibernate.sql.ast.tree.from.NamedTableReference)5 SessionFactoryImplementor (org.hibernate.engine.spi.SessionFactoryImplementor)3 Predicate (org.hibernate.sql.ast.tree.predicate.Predicate)3 SelectStatement (org.hibernate.sql.ast.tree.select.SelectStatement)3 ArrayList (java.util.ArrayList)2 ColumnReference (org.hibernate.sql.ast.tree.expression.ColumnReference)2 TableGroup (org.hibernate.sql.ast.tree.from.TableGroup)2 InSubQueryPredicate (org.hibernate.sql.ast.tree.predicate.InSubQueryPredicate)2 HibernateException (org.hibernate.HibernateException)1 JdbcServices (org.hibernate.engine.jdbc.spi.JdbcServices)1 FilterJdbcParameter (org.hibernate.internal.FilterJdbcParameter)1 EntityIdentifierMapping (org.hibernate.metamodel.mapping.EntityIdentifierMapping)1 PluralAttributeMapping (org.hibernate.metamodel.mapping.PluralAttributeMapping)1 AbstractEntityPersister (org.hibernate.persister.entity.AbstractEntityPersister)1 EntityPersister (org.hibernate.persister.entity.EntityPersister)1 SingleTableEntityPersister (org.hibernate.persister.entity.SingleTableEntityPersister)1 NavigablePath (org.hibernate.query.spi.NavigablePath)1 QueryEngine (org.hibernate.query.spi.QueryEngine)1