Search in sources :

Example 6 with DomainQueryExecutionContext

use of org.hibernate.query.spi.DomainQueryExecutionContext in project hibernate-orm by hibernate.

the class IdSelectionTests method testJoinedSubclassRestrictedOnNonPrimaryRootTable.

@Test
public void testJoinedSubclassRestrictedOnNonPrimaryRootTable(SessionFactoryScope scope) {
    final SqmDeleteStatement<?> sqm = (SqmDeleteStatement<?>) scope.getSessionFactory().getQueryEngine().getHqlTranslator().translate("delete ForeignCustomer where name = :n");
    final DomainParameterXref domainParameterXref = DomainParameterXref.from(sqm);
    final ParameterMetadataImpl parameterMetadata = new ParameterMetadataImpl(domainParameterXref.getQueryParameters());
    final QueryParameterBindingsImpl domainParamBindings = QueryParameterBindingsImpl.from(parameterMetadata, scope.getSessionFactory());
    domainParamBindings.getBinding("n").setBindValue("Acme");
    scope.inTransaction(session -> {
        final DomainQueryExecutionContext executionContext = new TestExecutionContext(session, domainParamBindings);
        MatchingIdSelectionHelper.selectMatchingIds(sqm, domainParameterXref, executionContext);
    });
}
Also used : SqmDeleteStatement(org.hibernate.query.sqm.tree.delete.SqmDeleteStatement) DomainParameterXref(org.hibernate.query.sqm.internal.DomainParameterXref) QueryParameterBindingsImpl(org.hibernate.query.internal.QueryParameterBindingsImpl) ParameterMetadataImpl(org.hibernate.query.internal.ParameterMetadataImpl) DomainQueryExecutionContext(org.hibernate.query.spi.DomainQueryExecutionContext) JoinedInheritanceTest(org.hibernate.orm.test.mapping.inheritance.joined.JoinedInheritanceTest) Test(org.junit.jupiter.api.Test)

Example 7 with DomainQueryExecutionContext

use of org.hibernate.query.spi.DomainQueryExecutionContext in project hibernate-orm by hibernate.

the class RestrictedDeleteExecutionDelegate method execute.

@Override
public int execute(DomainQueryExecutionContext executionContext) {
    final EntityPersister entityDescriptor = sessionFactory.getRuntimeMetamodels().getMappingMetamodel().getEntityDescriptor(sqmDelete.getTarget().getEntityName());
    final String hierarchyRootTableName = ((Joinable) entityDescriptor).getTableName();
    final TableGroup deletingTableGroup = converter.getMutatingTableGroup();
    final TableReference hierarchyRootTableReference = deletingTableGroup.resolveTableReference(deletingTableGroup.getNavigablePath(), hierarchyRootTableName);
    assert hierarchyRootTableReference != null;
    final Map<SqmParameter<?>, List<List<JdbcParameter>>> parameterResolutions;
    final Map<SqmParameter<?>, MappingModelExpressible<?>> paramTypeResolutions;
    if (domainParameterXref.getSqmParameterCount() == 0) {
        parameterResolutions = Collections.emptyMap();
        paramTypeResolutions = Collections.emptyMap();
    } else {
        parameterResolutions = new IdentityHashMap<>();
        paramTypeResolutions = new LinkedHashMap<>();
    }
    // Use the converter to interpret the where-clause.  We do this for 2 reasons:
    // 1) the resolved Predicate is ultimately the base for applying restriction to the deletes
    // 2) we also inspect each ColumnReference that is part of the where-clause to see which
    // table it comes from.  if all of the referenced columns (if any at all) are from the root table
    // we can perform all of the deletes without using an id-table
    final MutableBoolean needsIdTableWrapper = new MutableBoolean(false);
    final Predicate specifiedRestriction = converter.visitWhereClause(sqmDelete.getWhereClause(), columnReference -> {
        if (!hierarchyRootTableReference.getIdentificationVariable().equals(columnReference.getQualifier())) {
            needsIdTableWrapper.setValue(true);
        }
    }, (sqmParameter, mappingType, jdbcParameters) -> {
        parameterResolutions.computeIfAbsent(sqmParameter, k -> new ArrayList<>(1)).add(jdbcParameters);
        paramTypeResolutions.put(sqmParameter, mappingType);
    });
    final PredicateCollector predicateCollector = new PredicateCollector(specifiedRestriction);
    entityDescriptor.applyBaseRestrictions((filterPredicate) -> {
        needsIdTableWrapper.setValue(true);
        predicateCollector.applyPredicate(filterPredicate);
    }, deletingTableGroup, true, executionContext.getSession().getLoadQueryInfluencers().getEnabledFilters(), null, converter);
    converter.pruneTableGroupJoins();
    // We need an id table if we want to delete from an intermediate table to avoid FK violations
    // The intermediate table has a FK to the root table, so we can't delete from the root table first
    // Deleting from the intermediate table first also isn't possible,
    // because that is the source for deletion in other tables, hence we need an id table
    final boolean needsIdTable = needsIdTableWrapper.getValue() || entityDescriptor != entityDescriptor.getRootEntityDescriptor();
    final SqmJdbcExecutionContextAdapter executionContextAdapter = SqmJdbcExecutionContextAdapter.omittingLockingAndPaging(executionContext);
    if (needsIdTable) {
        return executeWithIdTable(predicateCollector.getPredicate(), deletingTableGroup, parameterResolutions, paramTypeResolutions, executionContextAdapter);
    } else {
        return executeWithoutIdTable(predicateCollector.getPredicate(), deletingTableGroup, parameterResolutions, paramTypeResolutions, converter.getSqlExpressionResolver(), executionContextAdapter);
    }
}
Also used : EntityPersister(org.hibernate.persister.entity.EntityPersister) ExecutionContext(org.hibernate.sql.exec.spi.ExecutionContext) EntityPersister(org.hibernate.persister.entity.EntityPersister) PredicateCollector(org.hibernate.sql.ast.tree.predicate.PredicateCollector) Joinable(org.hibernate.persister.entity.Joinable) EntityMappingType(org.hibernate.metamodel.mapping.EntityMappingType) MappingModelHelper(org.hibernate.metamodel.mapping.MappingModelHelper) SqmJdbcExecutionContextAdapter(org.hibernate.query.sqm.internal.SqmJdbcExecutionContextAdapter) ForeignKeyDescriptor(org.hibernate.metamodel.mapping.ForeignKeyDescriptor) SqmUtil(org.hibernate.query.sqm.internal.SqmUtil) Map(java.util.Map) SessionFactoryImplementor(org.hibernate.engine.spi.SessionFactoryImplementor) MutableBoolean(org.hibernate.internal.util.MutableBoolean) InSubQueryPredicate(org.hibernate.sql.ast.tree.predicate.InSubQueryPredicate) SqmDeleteStatement(org.hibernate.query.sqm.tree.delete.SqmDeleteStatement) IdentityHashMap(java.util.IdentityHashMap) Expression(org.hibernate.sql.ast.tree.expression.Expression) SqlExpressionResolver(org.hibernate.sql.ast.spi.SqlExpressionResolver) EntityIdentifierMapping(org.hibernate.metamodel.mapping.EntityIdentifierMapping) LoadQueryInfluencers(org.hibernate.engine.spi.LoadQueryInfluencers) List(java.util.List) SqmMutationStrategyHelper(org.hibernate.query.sqm.mutation.internal.SqmMutationStrategyHelper) SqlTuple(org.hibernate.sql.ast.tree.expression.SqlTuple) SqmParameter(org.hibernate.query.sqm.tree.expression.SqmParameter) QuerySpec(org.hibernate.sql.ast.tree.select.QuerySpec) MappingModelExpressible(org.hibernate.metamodel.mapping.MappingModelExpressible) SelectableConsumer(org.hibernate.metamodel.mapping.SelectableConsumer) SharedSessionContractImplementor(org.hibernate.engine.spi.SharedSessionContractImplementor) QueryOptions(org.hibernate.query.spi.QueryOptions) Logger(org.jboss.logging.Logger) ColumnReference(org.hibernate.sql.ast.tree.expression.ColumnReference) Function(java.util.function.Function) Supplier(java.util.function.Supplier) JdbcParameterBindings(org.hibernate.sql.exec.spi.JdbcParameterBindings) ArrayList(java.util.ArrayList) TableReference(org.hibernate.sql.ast.tree.from.TableReference) LinkedHashMap(java.util.LinkedHashMap) NamedTableReference(org.hibernate.sql.ast.tree.from.NamedTableReference) MultiTableSqmMutationConverter(org.hibernate.query.sqm.mutation.internal.MultiTableSqmMutationConverter) SqmParameterMappingModelResolutionAccess(org.hibernate.query.sqm.spi.SqmParameterMappingModelResolutionAccess) UnionTableReference(org.hibernate.sql.ast.tree.from.UnionTableReference) TemporaryTable(org.hibernate.dialect.temptable.TemporaryTable) DeleteStatement(org.hibernate.sql.ast.tree.delete.DeleteStatement) Predicate(org.hibernate.sql.ast.tree.predicate.Predicate) MutableInteger(org.hibernate.internal.util.MutableInteger) QueryParameterBindings(org.hibernate.query.spi.QueryParameterBindings) JdbcServices(org.hibernate.engine.jdbc.spi.JdbcServices) JdbcDelete(org.hibernate.sql.exec.spi.JdbcDelete) DomainQueryExecutionContext(org.hibernate.query.spi.DomainQueryExecutionContext) Consumer(java.util.function.Consumer) JdbcParameter(org.hibernate.sql.ast.tree.expression.JdbcParameter) DomainParameterXref(org.hibernate.query.sqm.internal.DomainParameterXref) Collections(java.util.Collections) TableGroup(org.hibernate.sql.ast.tree.from.TableGroup) TableGroup(org.hibernate.sql.ast.tree.from.TableGroup) MappingModelExpressible(org.hibernate.metamodel.mapping.MappingModelExpressible) JdbcParameter(org.hibernate.sql.ast.tree.expression.JdbcParameter) MutableBoolean(org.hibernate.internal.util.MutableBoolean) ArrayList(java.util.ArrayList) SqmJdbcExecutionContextAdapter(org.hibernate.query.sqm.internal.SqmJdbcExecutionContextAdapter) InSubQueryPredicate(org.hibernate.sql.ast.tree.predicate.InSubQueryPredicate) Predicate(org.hibernate.sql.ast.tree.predicate.Predicate) TableReference(org.hibernate.sql.ast.tree.from.TableReference) NamedTableReference(org.hibernate.sql.ast.tree.from.NamedTableReference) UnionTableReference(org.hibernate.sql.ast.tree.from.UnionTableReference) PredicateCollector(org.hibernate.sql.ast.tree.predicate.PredicateCollector) Joinable(org.hibernate.persister.entity.Joinable) List(java.util.List) ArrayList(java.util.ArrayList) SqmParameter(org.hibernate.query.sqm.tree.expression.SqmParameter)

Example 8 with DomainQueryExecutionContext

use of org.hibernate.query.spi.DomainQueryExecutionContext in project hibernate-orm by hibernate.

the class TableBasedUpdateHandler method resolveDelegate.

private ExecutionDelegate resolveDelegate(DomainQueryExecutionContext executionContext) {
    final SessionFactoryImplementor sessionFactory = getSessionFactory();
    final MappingMetamodel domainModel = sessionFactory.getRuntimeMetamodels().getMappingMetamodel();
    final EntityPersister entityDescriptor = domainModel.getEntityDescriptor(getSqmDeleteOrUpdateStatement().getTarget().getEntityName());
    final String rootEntityName = entityDescriptor.getRootEntityName();
    final EntityPersister rootEntityDescriptor = domainModel.getEntityDescriptor(rootEntityName);
    final String hierarchyRootTableName = ((Joinable) rootEntityDescriptor).getTableName();
    final MultiTableSqmMutationConverter converterDelegate = new MultiTableSqmMutationConverter(entityDescriptor, getSqmDeleteOrUpdateStatement(), getSqmDeleteOrUpdateStatement().getTarget(), domainParameterXref, executionContext.getQueryOptions(), executionContext.getSession().getLoadQueryInfluencers(), executionContext.getQueryParameterBindings(), sessionFactory);
    final TableGroup updatingTableGroup = converterDelegate.getMutatingTableGroup();
    final TableReference hierarchyRootTableReference = updatingTableGroup.resolveTableReference(updatingTableGroup.getNavigablePath(), hierarchyRootTableName);
    assert hierarchyRootTableReference != null;
    final Map<SqmParameter<?>, List<List<JdbcParameter>>> parameterResolutions;
    if (domainParameterXref.getSqmParameterCount() == 0) {
        parameterResolutions = Collections.emptyMap();
    } else {
        parameterResolutions = new IdentityHashMap<>();
    }
    // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    // visit the set-clause using our special converter, collecting
    // information about the assignments
    final List<Assignment> assignments = new ArrayList<>();
    final Map<SqmParameter<?>, MappingModelExpressible<?>> paramTypeResolutions = new LinkedHashMap<>();
    converterDelegate.visitSetClause(getSqmDeleteOrUpdateStatement().getSetClause(), assignments::add, (sqmParameter, mappingType, jdbcParameters) -> {
        parameterResolutions.computeIfAbsent(sqmParameter, k -> new ArrayList<>(1)).add(jdbcParameters);
        paramTypeResolutions.put(sqmParameter, mappingType);
    });
    converterDelegate.addVersionedAssignment(assignments::add, getSqmDeleteOrUpdateStatement());
    // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    // visit the where-clause using our special converter, collecting information
    // about the restrictions
    final Predicate providedPredicate;
    final SqmWhereClause whereClause = getSqmUpdate().getWhereClause();
    if (whereClause == null || whereClause.getPredicate() == null) {
        providedPredicate = null;
    } else {
        providedPredicate = converterDelegate.visitWhereClause(whereClause, columnReference -> {
        }, (sqmParameter, mappingType, jdbcParameters) -> {
            parameterResolutions.computeIfAbsent(sqmParameter, k -> new ArrayList<>(1)).add(jdbcParameters);
            paramTypeResolutions.put(sqmParameter, mappingType);
        });
        assert providedPredicate != null;
    }
    final PredicateCollector predicateCollector = new PredicateCollector(providedPredicate);
    entityDescriptor.applyBaseRestrictions(predicateCollector::applyPredicate, updatingTableGroup, true, executionContext.getSession().getLoadQueryInfluencers().getEnabledFilters(), null, converterDelegate);
    converterDelegate.pruneTableGroupJoins();
    // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    // cross-reference the TableReference by alias.  The TableGroup already
    // cross-references it by name, bu the ColumnReference only has the alias
    final Map<String, TableReference> tableReferenceByAlias = CollectionHelper.mapOfSize(updatingTableGroup.getTableReferenceJoins().size() + 1);
    collectTableReference(updatingTableGroup.getPrimaryTableReference(), tableReferenceByAlias::put);
    for (int i = 0; i < updatingTableGroup.getTableReferenceJoins().size(); i++) {
        collectTableReference(updatingTableGroup.getTableReferenceJoins().get(i), tableReferenceByAlias::put);
    }
    return new UpdateExecutionDelegate(getSqmUpdate(), converterDelegate, idTable, afterUseAction, sessionUidAccess, domainParameterXref, updatingTableGroup, hierarchyRootTableReference, tableReferenceByAlias, assignments, predicateCollector.getPredicate(), parameterResolutions, paramTypeResolutions, executionContext);
}
Also used : EntityPersister(org.hibernate.persister.entity.EntityPersister) CollectionHelper(org.hibernate.internal.util.collections.CollectionHelper) ExecutionContext(org.hibernate.sql.exec.spi.ExecutionContext) EntityPersister(org.hibernate.persister.entity.EntityPersister) PredicateCollector(org.hibernate.sql.ast.tree.predicate.PredicateCollector) Logger(org.jboss.logging.Logger) Function(java.util.function.Function) Joinable(org.hibernate.persister.entity.Joinable) ArrayList(java.util.ArrayList) SqmJdbcExecutionContextAdapter(org.hibernate.query.sqm.internal.SqmJdbcExecutionContextAdapter) TableReference(org.hibernate.sql.ast.tree.from.TableReference) LinkedHashMap(java.util.LinkedHashMap) MultiTableSqmMutationConverter(org.hibernate.query.sqm.mutation.internal.MultiTableSqmMutationConverter) Map(java.util.Map) BiConsumer(java.util.function.BiConsumer) SqmUpdateStatement(org.hibernate.query.sqm.tree.update.SqmUpdateStatement) TableReferenceJoin(org.hibernate.sql.ast.tree.from.TableReferenceJoin) SessionFactoryImplementor(org.hibernate.engine.spi.SessionFactoryImplementor) Assignment(org.hibernate.sql.ast.tree.update.Assignment) IdentityHashMap(java.util.IdentityHashMap) TemporaryTable(org.hibernate.dialect.temptable.TemporaryTable) Predicate(org.hibernate.sql.ast.tree.predicate.Predicate) DomainQueryExecutionContext(org.hibernate.query.spi.DomainQueryExecutionContext) MappingMetamodel(org.hibernate.metamodel.MappingMetamodel) List(java.util.List) JdbcParameter(org.hibernate.sql.ast.tree.expression.JdbcParameter) SqmWhereClause(org.hibernate.query.sqm.tree.predicate.SqmWhereClause) UpdateHandler(org.hibernate.query.sqm.mutation.internal.UpdateHandler) SqmParameter(org.hibernate.query.sqm.tree.expression.SqmParameter) AbstractMutationHandler(org.hibernate.query.sqm.mutation.spi.AbstractMutationHandler) DomainParameterXref(org.hibernate.query.sqm.internal.DomainParameterXref) Collections(java.util.Collections) MappingModelExpressible(org.hibernate.metamodel.mapping.MappingModelExpressible) TableGroup(org.hibernate.sql.ast.tree.from.TableGroup) SharedSessionContractImplementor(org.hibernate.engine.spi.SharedSessionContractImplementor) MappingModelExpressible(org.hibernate.metamodel.mapping.MappingModelExpressible) ArrayList(java.util.ArrayList) LinkedHashMap(java.util.LinkedHashMap) Predicate(org.hibernate.sql.ast.tree.predicate.Predicate) Assignment(org.hibernate.sql.ast.tree.update.Assignment) TableReference(org.hibernate.sql.ast.tree.from.TableReference) ArrayList(java.util.ArrayList) List(java.util.List) TableGroup(org.hibernate.sql.ast.tree.from.TableGroup) SessionFactoryImplementor(org.hibernate.engine.spi.SessionFactoryImplementor) JdbcParameter(org.hibernate.sql.ast.tree.expression.JdbcParameter) MappingMetamodel(org.hibernate.metamodel.MappingMetamodel) PredicateCollector(org.hibernate.sql.ast.tree.predicate.PredicateCollector) Joinable(org.hibernate.persister.entity.Joinable) SqmWhereClause(org.hibernate.query.sqm.tree.predicate.SqmWhereClause) SqmParameter(org.hibernate.query.sqm.tree.expression.SqmParameter) MultiTableSqmMutationConverter(org.hibernate.query.sqm.mutation.internal.MultiTableSqmMutationConverter)

Example 9 with DomainQueryExecutionContext

use of org.hibernate.query.spi.DomainQueryExecutionContext in project hibernate-orm by hibernate.

the class TableBasedInsertHandler method resolveDelegate.

private ExecutionDelegate resolveDelegate(DomainQueryExecutionContext executionContext) {
    final EntityPersister entityDescriptor = sessionFactory.getRuntimeMetamodels().getMappingMetamodel().getEntityDescriptor(getSqmInsertStatement().getTarget().getEntityName());
    final MultiTableSqmMutationConverter converterDelegate = new MultiTableSqmMutationConverter(entityDescriptor, getSqmInsertStatement(), getSqmInsertStatement().getTarget(), domainParameterXref, executionContext.getQueryOptions(), executionContext.getSession().getLoadQueryInfluencers(), executionContext.getQueryParameterBindings(), sessionFactory);
    final TableGroup insertingTableGroup = converterDelegate.getMutatingTableGroup();
    final Map<SqmParameter<?>, List<List<JdbcParameter>>> parameterResolutions;
    if (domainParameterXref.getSqmParameterCount() == 0) {
        parameterResolutions = Collections.emptyMap();
    } else {
        parameterResolutions = new IdentityHashMap<>();
    }
    // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    // visit the insertion target using our special converter, collecting
    // information about the target paths
    final List<Assignment> targetPathColumns = new ArrayList<>();
    final Map<SqmParameter<?>, MappingModelExpressible<?>> paramTypeResolutions = new LinkedHashMap<>();
    final NamedTableReference entityTableReference = new NamedTableReference(entityTable.getTableExpression(), TemporaryTable.DEFAULT_ALIAS, true, sessionFactory);
    final InsertStatement insertStatement = new InsertStatement(entityTableReference);
    final BaseSqmToSqlAstConverter.AdditionalInsertValues additionalInsertValues = converterDelegate.visitInsertionTargetPaths((assigable, columnReferences) -> {
        insertStatement.addTargetColumnReferences(columnReferences);
        targetPathColumns.add(new Assignment(assigable, (Expression) assigable));
    }, sqmInsertStatement, entityDescriptor, insertingTableGroup, (sqmParameter, mappingType, jdbcParameters) -> {
        parameterResolutions.computeIfAbsent(sqmParameter, k -> new ArrayList<>(1)).add(jdbcParameters);
        paramTypeResolutions.put(sqmParameter, mappingType);
    });
    if (sqmInsertStatement instanceof SqmInsertSelectStatement) {
        final QueryPart queryPart = converterDelegate.visitQueryPart(((SqmInsertSelectStatement<?>) sqmInsertStatement).getSelectQueryPart());
        queryPart.visitQuerySpecs(querySpec -> {
            if (additionalInsertValues.applySelections(querySpec, sessionFactory)) {
                final TemporaryTableColumn rowNumberColumn = entityTable.getColumns().get(entityTable.getColumns().size() - 1);
                final ColumnReference columnReference = new ColumnReference((String) null, rowNumberColumn.getColumnName(), false, null, null, rowNumberColumn.getJdbcMapping(), sessionFactory);
                insertStatement.getTargetColumnReferences().set(insertStatement.getTargetColumnReferences().size() - 1, columnReference);
                targetPathColumns.set(targetPathColumns.size() - 1, new Assignment(columnReference, columnReference));
            } else if (entityDescriptor.getIdentifierGenerator() instanceof OptimizableGenerator) {
                final Optimizer optimizer = ((OptimizableGenerator) entityDescriptor.getIdentifierGenerator()).getOptimizer();
                if (optimizer != null && optimizer.getIncrementSize() > 1) {
                    if (!sessionFactory.getJdbcServices().getDialect().supportsWindowFunctions()) {
                        return;
                    }
                    final TemporaryTableColumn rowNumberColumn = entityTable.getColumns().get(entityTable.getColumns().size() - 1);
                    final ColumnReference columnReference = new ColumnReference((String) null, rowNumberColumn.getColumnName(), false, null, null, rowNumberColumn.getJdbcMapping(), sessionFactory);
                    insertStatement.getTargetColumnReferences().add(columnReference);
                    targetPathColumns.add(new Assignment(columnReference, columnReference));
                    final BasicType<Integer> rowNumberType = sessionFactory.getTypeConfiguration().getBasicTypeForJavaType(Integer.class);
                    querySpec.getSelectClause().addSqlSelection(new SqlSelectionImpl(1, 0, new Over<>(new SelfRenderingFunctionSqlAstExpression("row_number", (appender, args, walker) -> appender.appendSql("row_number()"), Collections.emptyList(), rowNumberType, rowNumberType), Collections.emptyList(), Collections.emptyList())));
                }
            }
        });
        insertStatement.setSourceSelectStatement(queryPart);
    } else {
        // Add the row number column if there is one
        final IdentifierGenerator generator = entityDescriptor.getIdentifierGenerator();
        final BasicType<?> rowNumberType;
        if (generator instanceof OptimizableGenerator) {
            final Optimizer optimizer = ((OptimizableGenerator) generator).getOptimizer();
            if (optimizer != null && optimizer.getIncrementSize() > 1) {
                final TemporaryTableColumn rowNumberColumn = entityTable.getColumns().get(entityTable.getColumns().size() - 1);
                rowNumberType = (BasicType<?>) rowNumberColumn.getJdbcMapping();
                final ColumnReference columnReference = new ColumnReference((String) null, rowNumberColumn.getColumnName(), false, null, null, rowNumberColumn.getJdbcMapping(), sessionFactory);
                insertStatement.getTargetColumnReferences().add(columnReference);
                targetPathColumns.add(new Assignment(columnReference, columnReference));
            } else {
                rowNumberType = null;
            }
        } else {
            rowNumberType = null;
        }
        final List<SqmValues> sqmValuesList = ((SqmInsertValuesStatement<?>) sqmInsertStatement).getValuesList();
        final List<Values> valuesList = new ArrayList<>(sqmValuesList.size());
        for (int i = 0; i < sqmValuesList.size(); i++) {
            final Values values = converterDelegate.visitValues(sqmValuesList.get(i));
            additionalInsertValues.applyValues(values);
            if (rowNumberType != null) {
                values.getExpressions().add(new QueryLiteral<>(i + 1, rowNumberType));
            }
            valuesList.add(values);
        }
        insertStatement.setValuesList(valuesList);
    }
    converterDelegate.pruneTableGroupJoins();
    // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    // cross-reference the TableReference by alias.  The TableGroup already
    // cross-references it by name, but the ColumnReference only has the alias
    final Map<String, TableReference> tableReferenceByAlias = CollectionHelper.mapOfSize(insertingTableGroup.getTableReferenceJoins().size() + 1);
    collectTableReference(insertingTableGroup.getPrimaryTableReference(), tableReferenceByAlias::put);
    for (int i = 0; i < insertingTableGroup.getTableReferenceJoins().size(); i++) {
        collectTableReference(insertingTableGroup.getTableReferenceJoins().get(i), tableReferenceByAlias::put);
    }
    return new InsertExecutionDelegate(sqmInsertStatement, converterDelegate, entityTable, afterUseAction, sessionUidAccess, domainParameterXref, insertingTableGroup, tableReferenceByAlias, targetPathColumns, insertStatement, parameterResolutions, paramTypeResolutions, executionContext);
}
Also used : EntityPersister(org.hibernate.persister.entity.EntityPersister) CollectionHelper(org.hibernate.internal.util.collections.CollectionHelper) ExecutionContext(org.hibernate.sql.exec.spi.ExecutionContext) EntityPersister(org.hibernate.persister.entity.EntityPersister) BasicType(org.hibernate.type.BasicType) Logger(org.jboss.logging.Logger) ColumnReference(org.hibernate.sql.ast.tree.expression.ColumnReference) SqmInsertValuesStatement(org.hibernate.query.sqm.tree.insert.SqmInsertValuesStatement) OptimizableGenerator(org.hibernate.id.OptimizableGenerator) Function(java.util.function.Function) ArrayList(java.util.ArrayList) SqmJdbcExecutionContextAdapter(org.hibernate.query.sqm.internal.SqmJdbcExecutionContextAdapter) TableReference(org.hibernate.sql.ast.tree.from.TableReference) LinkedHashMap(java.util.LinkedHashMap) NamedTableReference(org.hibernate.sql.ast.tree.from.NamedTableReference) MultiTableSqmMutationConverter(org.hibernate.query.sqm.mutation.internal.MultiTableSqmMutationConverter) Map(java.util.Map) BiConsumer(java.util.function.BiConsumer) TableReferenceJoin(org.hibernate.sql.ast.tree.from.TableReferenceJoin) SessionFactoryImplementor(org.hibernate.engine.spi.SessionFactoryImplementor) SqmInsertSelectStatement(org.hibernate.query.sqm.tree.insert.SqmInsertSelectStatement) IdentifierGenerator(org.hibernate.id.IdentifierGenerator) Values(org.hibernate.sql.ast.tree.insert.Values) Assignment(org.hibernate.sql.ast.tree.update.Assignment) IdentityHashMap(java.util.IdentityHashMap) TemporaryTable(org.hibernate.dialect.temptable.TemporaryTable) SelfRenderingFunctionSqlAstExpression(org.hibernate.query.sqm.function.SelfRenderingFunctionSqlAstExpression) Optimizer(org.hibernate.id.enhanced.Optimizer) Expression(org.hibernate.sql.ast.tree.expression.Expression) QueryLiteral(org.hibernate.sql.ast.tree.expression.QueryLiteral) BaseSqmToSqlAstConverter(org.hibernate.query.sqm.sql.BaseSqmToSqlAstConverter) DomainQueryExecutionContext(org.hibernate.query.spi.DomainQueryExecutionContext) InsertHandler(org.hibernate.query.sqm.mutation.internal.InsertHandler) List(java.util.List) JdbcParameter(org.hibernate.sql.ast.tree.expression.JdbcParameter) SqmInsertStatement(org.hibernate.query.sqm.tree.insert.SqmInsertStatement) QueryPart(org.hibernate.sql.ast.tree.select.QueryPart) Over(org.hibernate.sql.ast.tree.expression.Over) SqlSelectionImpl(org.hibernate.sql.results.internal.SqlSelectionImpl) SqmParameter(org.hibernate.query.sqm.tree.expression.SqmParameter) InsertStatement(org.hibernate.sql.ast.tree.insert.InsertStatement) DomainParameterXref(org.hibernate.query.sqm.internal.DomainParameterXref) Collections(java.util.Collections) TemporaryTableColumn(org.hibernate.dialect.temptable.TemporaryTableColumn) MappingModelExpressible(org.hibernate.metamodel.mapping.MappingModelExpressible) TableGroup(org.hibernate.sql.ast.tree.from.TableGroup) SqmValues(org.hibernate.query.sqm.tree.insert.SqmValues) SharedSessionContractImplementor(org.hibernate.engine.spi.SharedSessionContractImplementor) BasicType(org.hibernate.type.BasicType) MappingModelExpressible(org.hibernate.metamodel.mapping.MappingModelExpressible) QueryPart(org.hibernate.sql.ast.tree.select.QueryPart) OptimizableGenerator(org.hibernate.id.OptimizableGenerator) Optimizer(org.hibernate.id.enhanced.Optimizer) ArrayList(java.util.ArrayList) Values(org.hibernate.sql.ast.tree.insert.Values) SqmValues(org.hibernate.query.sqm.tree.insert.SqmValues) TemporaryTableColumn(org.hibernate.dialect.temptable.TemporaryTableColumn) SqmInsertStatement(org.hibernate.query.sqm.tree.insert.SqmInsertStatement) InsertStatement(org.hibernate.sql.ast.tree.insert.InsertStatement) LinkedHashMap(java.util.LinkedHashMap) Assignment(org.hibernate.sql.ast.tree.update.Assignment) TableReference(org.hibernate.sql.ast.tree.from.TableReference) NamedTableReference(org.hibernate.sql.ast.tree.from.NamedTableReference) SqmValues(org.hibernate.query.sqm.tree.insert.SqmValues) ArrayList(java.util.ArrayList) List(java.util.List) SqmInsertSelectStatement(org.hibernate.query.sqm.tree.insert.SqmInsertSelectStatement) BaseSqmToSqlAstConverter(org.hibernate.query.sqm.sql.BaseSqmToSqlAstConverter) TableGroup(org.hibernate.sql.ast.tree.from.TableGroup) NamedTableReference(org.hibernate.sql.ast.tree.from.NamedTableReference) JdbcParameter(org.hibernate.sql.ast.tree.expression.JdbcParameter) SqmInsertValuesStatement(org.hibernate.query.sqm.tree.insert.SqmInsertValuesStatement) SelfRenderingFunctionSqlAstExpression(org.hibernate.query.sqm.function.SelfRenderingFunctionSqlAstExpression) Expression(org.hibernate.sql.ast.tree.expression.Expression) SelfRenderingFunctionSqlAstExpression(org.hibernate.query.sqm.function.SelfRenderingFunctionSqlAstExpression) SqlSelectionImpl(org.hibernate.sql.results.internal.SqlSelectionImpl) SqmParameter(org.hibernate.query.sqm.tree.expression.SqmParameter) MultiTableSqmMutationConverter(org.hibernate.query.sqm.mutation.internal.MultiTableSqmMutationConverter) ColumnReference(org.hibernate.sql.ast.tree.expression.ColumnReference) IdentifierGenerator(org.hibernate.id.IdentifierGenerator)

Example 10 with DomainQueryExecutionContext

use of org.hibernate.query.spi.DomainQueryExecutionContext in project hibernate-orm by hibernate.

the class IdSelectionTests method testSecondaryTableRestrictedOnNonRootTable.

@Test
public void testSecondaryTableRestrictedOnNonRootTable(SessionFactoryScope scope) {
    final SqmDeleteStatement<?> sqm = (SqmDeleteStatement<?>) scope.getSessionFactory().getQueryEngine().getHqlTranslator().translate("delete SimpleEntityWithSecondaryTables where data = :d");
    final DomainParameterXref domainParameterXref = DomainParameterXref.from(sqm);
    final ParameterMetadataImpl parameterMetadata = new ParameterMetadataImpl(domainParameterXref.getQueryParameters());
    final QueryParameterBindingsImpl domainParamBindings = QueryParameterBindingsImpl.from(parameterMetadata, scope.getSessionFactory());
    domainParamBindings.getBinding("d").setBindValue("123");
    scope.inTransaction(session -> {
        final DomainQueryExecutionContext executionContext = new TestExecutionContext(session, domainParamBindings);
        MatchingIdSelectionHelper.selectMatchingIds(sqm, domainParameterXref, executionContext);
    });
}
Also used : SqmDeleteStatement(org.hibernate.query.sqm.tree.delete.SqmDeleteStatement) DomainParameterXref(org.hibernate.query.sqm.internal.DomainParameterXref) QueryParameterBindingsImpl(org.hibernate.query.internal.QueryParameterBindingsImpl) ParameterMetadataImpl(org.hibernate.query.internal.ParameterMetadataImpl) DomainQueryExecutionContext(org.hibernate.query.spi.DomainQueryExecutionContext) JoinedInheritanceTest(org.hibernate.orm.test.mapping.inheritance.joined.JoinedInheritanceTest) Test(org.junit.jupiter.api.Test)

Aggregations

DomainQueryExecutionContext (org.hibernate.query.spi.DomainQueryExecutionContext)13 DomainParameterXref (org.hibernate.query.sqm.internal.DomainParameterXref)9 Test (org.junit.jupiter.api.Test)7 ArrayList (java.util.ArrayList)6 SqmDeleteStatement (org.hibernate.query.sqm.tree.delete.SqmDeleteStatement)6 JoinedInheritanceTest (org.hibernate.orm.test.mapping.inheritance.joined.JoinedInheritanceTest)5 ParameterMetadataImpl (org.hibernate.query.internal.ParameterMetadataImpl)5 QueryParameterBindingsImpl (org.hibernate.query.internal.QueryParameterBindingsImpl)5 Collections (java.util.Collections)4 IdentityHashMap (java.util.IdentityHashMap)4 LinkedHashMap (java.util.LinkedHashMap)4 List (java.util.List)4 Map (java.util.Map)4 TemporaryTable (org.hibernate.dialect.temptable.TemporaryTable)4 SessionFactoryImplementor (org.hibernate.engine.spi.SessionFactoryImplementor)4 MappingModelExpressible (org.hibernate.metamodel.mapping.MappingModelExpressible)4 EntityPersister (org.hibernate.persister.entity.EntityPersister)4 SqmJdbcExecutionContextAdapter (org.hibernate.query.sqm.internal.SqmJdbcExecutionContextAdapter)4 MultiTableSqmMutationConverter (org.hibernate.query.sqm.mutation.internal.MultiTableSqmMutationConverter)4 SqmParameter (org.hibernate.query.sqm.tree.expression.SqmParameter)4