Search in sources :

Example 1 with ComparisonPredicate

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

the class EmbeddedForeignKeyDescriptor method isSimpleJoinPredicate.

@Override
public boolean isSimpleJoinPredicate(Predicate predicate) {
    if (!(predicate instanceof Junction)) {
        return false;
    }
    final Junction junction = (Junction) predicate;
    if (junction.getNature() != Junction.Nature.CONJUNCTION) {
        return false;
    }
    final List<Predicate> predicates = junction.getPredicates();
    if (predicates.size() != keySelectableMappings.getJdbcTypeCount()) {
        return false;
    }
    Boolean lhsIsKey = null;
    for (int i = 0; i < predicates.size(); i++) {
        final Predicate p = predicates.get(i);
        if (!(p instanceof ComparisonPredicate)) {
            return false;
        }
        final ComparisonPredicate comparisonPredicate = (ComparisonPredicate) p;
        if (comparisonPredicate.getOperator() != ComparisonOperator.EQUAL) {
            return false;
        }
        final Expression lhsExpr = comparisonPredicate.getLeftHandExpression();
        final Expression rhsExpr = comparisonPredicate.getRightHandExpression();
        if (!(lhsExpr instanceof ColumnReference) || !(rhsExpr instanceof ColumnReference)) {
            return false;
        }
        final ColumnReference lhs = (ColumnReference) lhsExpr;
        final ColumnReference rhs = (ColumnReference) rhsExpr;
        if (lhsIsKey == null) {
            final String keyExpression = keySelectableMappings.getSelectable(i).getSelectionExpression();
            final String targetExpression = targetSelectableMappings.getSelectable(i).getSelectionExpression();
            if (keyExpression.equals(targetExpression)) {
                if (!lhs.getColumnExpression().equals(keyExpression) || !rhs.getColumnExpression().equals(keyExpression)) {
                    return false;
                }
            } else {
                if (keyExpression.equals(lhs.getColumnExpression())) {
                    if (!targetExpression.equals(rhs.getColumnExpression())) {
                        return false;
                    }
                    lhsIsKey = true;
                } else if (keyExpression.equals(rhs.getColumnExpression())) {
                    if (!targetExpression.equals(lhs.getColumnExpression())) {
                        return false;
                    }
                    lhsIsKey = false;
                } else {
                    return false;
                }
            }
        } else {
            final String lhsSelectionExpression;
            final String rhsSelectionExpression;
            if (lhsIsKey) {
                lhsSelectionExpression = keySelectableMappings.getSelectable(i).getSelectionExpression();
                rhsSelectionExpression = targetSelectableMappings.getSelectable(i).getSelectionExpression();
            } else {
                lhsSelectionExpression = targetSelectableMappings.getSelectable(i).getSelectionExpression();
                rhsSelectionExpression = keySelectableMappings.getSelectable(i).getSelectionExpression();
            }
            if (!lhs.getColumnExpression().equals(lhsSelectionExpression) || !rhs.getColumnExpression().equals(rhsSelectionExpression)) {
                return false;
            }
        }
    }
    return true;
}
Also used : Expression(org.hibernate.sql.ast.tree.expression.Expression) Junction(org.hibernate.sql.ast.tree.predicate.Junction) ComparisonPredicate(org.hibernate.sql.ast.tree.predicate.ComparisonPredicate) ComparisonPredicate(org.hibernate.sql.ast.tree.predicate.ComparisonPredicate) Predicate(org.hibernate.sql.ast.tree.predicate.Predicate) ColumnReference(org.hibernate.sql.ast.tree.expression.ColumnReference)

Example 2 with ComparisonPredicate

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

the class SimpleForeignKeyDescriptor method isSimpleJoinPredicate.

@Override
public boolean isSimpleJoinPredicate(Predicate predicate) {
    if (!(predicate instanceof ComparisonPredicate)) {
        return false;
    }
    final ComparisonPredicate comparisonPredicate = (ComparisonPredicate) predicate;
    if (comparisonPredicate.getOperator() != ComparisonOperator.EQUAL) {
        return false;
    }
    final Expression lhsExpr = comparisonPredicate.getLeftHandExpression();
    final Expression rhsExpr = comparisonPredicate.getRightHandExpression();
    if (!(lhsExpr instanceof ColumnReference) || !(rhsExpr instanceof ColumnReference)) {
        return false;
    }
    final String lhs = ((ColumnReference) lhsExpr).getColumnExpression();
    final String rhs = ((ColumnReference) rhsExpr).getColumnExpression();
    final String keyExpression = keySide.getModelPart().getSelectionExpression();
    final String targetExpression = targetSide.getModelPart().getSelectionExpression();
    return (lhs.equals(keyExpression) && rhs.equals(targetExpression)) || (lhs.equals(targetExpression) && rhs.equals(keyExpression));
}
Also used : Expression(org.hibernate.sql.ast.tree.expression.Expression) ComparisonPredicate(org.hibernate.sql.ast.tree.predicate.ComparisonPredicate) ColumnReference(org.hibernate.sql.ast.tree.expression.ColumnReference)

Example 3 with ComparisonPredicate

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

the class LoaderSelectBuilder method applyRestriction.

private void applyRestriction(QuerySpec rootQuerySpec, NavigablePath rootNavigablePath, TableGroup rootTableGroup, ModelPart modelPart, int numberColumns, Consumer<JdbcParameter> jdbcParameterConsumer, LoaderSqlAstCreationState sqlAstCreationState) {
    final SqlExpressionResolver sqlExpressionResolver = sqlAstCreationState.getSqlExpressionResolver();
    final NavigablePath navigablePath = rootNavigablePath.append(modelPart.getNavigableRole().getNavigableName());
    if (numberColumns == 1) {
        modelPart.forEachSelectable((columnIndex, selection) -> {
            final TableReference tableReference = rootTableGroup.resolveTableReference(navigablePath, selection.getContainingTableExpression());
            final ColumnReference columnRef = (ColumnReference) sqlExpressionResolver.resolveSqlExpression(createColumnReferenceKey(tableReference, selection.getSelectionExpression()), p -> new ColumnReference(tableReference, selection, creationContext.getSessionFactory()));
            if (numberOfKeysToLoad == 1) {
                final JdbcParameter jdbcParameter = new JdbcParameterImpl(selection.getJdbcMapping());
                jdbcParameterConsumer.accept(jdbcParameter);
                rootQuerySpec.applyPredicate(new ComparisonPredicate(columnRef, ComparisonOperator.EQUAL, jdbcParameter));
            } else {
                final InListPredicate predicate = new InListPredicate(columnRef);
                for (int i = 0; i < numberOfKeysToLoad; i++) {
                    for (int j = 0; j < numberColumns; j++) {
                        final JdbcParameter jdbcParameter = new JdbcParameterImpl(columnRef.getJdbcMapping());
                        jdbcParameterConsumer.accept(jdbcParameter);
                        predicate.addExpression(jdbcParameter);
                    }
                }
                rootQuerySpec.applyPredicate(predicate);
            }
        });
    } else {
        final List<ColumnReference> columnReferences = new ArrayList<>(numberColumns);
        modelPart.forEachSelectable((columnIndex, selection) -> {
            final TableReference tableReference = rootTableGroup.resolveTableReference(navigablePath, selection.getContainingTableExpression());
            columnReferences.add((ColumnReference) sqlExpressionResolver.resolveSqlExpression(createColumnReferenceKey(tableReference, selection.getSelectionExpression()), p -> new ColumnReference(tableReference, selection, creationContext.getSessionFactory())));
        });
        final SqlTuple tuple = new SqlTuple(columnReferences, modelPart);
        final InListPredicate predicate = new InListPredicate(tuple);
        for (int i = 0; i < numberOfKeysToLoad; i++) {
            final List<JdbcParameter> tupleParams = new ArrayList<>(numberColumns);
            for (int j = 0; j < numberColumns; j++) {
                final ColumnReference columnReference = columnReferences.get(j);
                final JdbcParameter jdbcParameter = new JdbcParameterImpl(columnReference.getJdbcMapping());
                jdbcParameterConsumer.accept(jdbcParameter);
                tupleParams.add(jdbcParameter);
            }
            final SqlTuple paramTuple = new SqlTuple(tupleParams, modelPart);
            predicate.addExpression(paramTuple);
        }
        rootQuerySpec.applyPredicate(predicate);
    }
}
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) JdbcParameter(org.hibernate.sql.ast.tree.expression.JdbcParameter) ArrayList(java.util.ArrayList) InListPredicate(org.hibernate.sql.ast.tree.predicate.InListPredicate) ComparisonPredicate(org.hibernate.sql.ast.tree.predicate.ComparisonPredicate) TableReference(org.hibernate.sql.ast.tree.from.TableReference) SqlExpressionResolver(org.hibernate.sql.ast.spi.SqlExpressionResolver) SqlTuple(org.hibernate.sql.ast.tree.expression.SqlTuple) JdbcParameterImpl(org.hibernate.sql.exec.internal.JdbcParameterImpl) ColumnReference(org.hibernate.sql.ast.tree.expression.ColumnReference)

Example 4 with ComparisonPredicate

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

the class SimpleNaturalIdLoader method applyNaturalIdRestriction.

@Override
protected void applyNaturalIdRestriction(Object bindValue, TableGroup rootTableGroup, Consumer<Predicate> predicateConsumer, BiConsumer<JdbcParameter, JdbcParameterBinding> jdbcParameterConsumer, LoaderSqlAstCreationState sqlAstCreationState, SharedSessionContractImplementor session) {
    if (bindValue == null) {
        naturalIdMapping().getAttribute().forEachSelectable((index, selectable) -> {
            final Expression columnReference = resolveColumnReference(rootTableGroup, selectable, sqlAstCreationState.getSqlExpressionResolver(), session.getFactory());
            predicateConsumer.accept(new NullnessPredicate(columnReference));
        });
    } else {
        naturalIdMapping().getAttribute().breakDownJdbcValues(bindValue, (jdbcValue, jdbcValueMapping) -> {
            final Expression columnReference = resolveColumnReference(rootTableGroup, jdbcValueMapping, sqlAstCreationState.getSqlExpressionResolver(), session.getFactory());
            if (jdbcValue == null) {
                predicateConsumer.accept(new NullnessPredicate(columnReference));
            } else {
                final JdbcParameter jdbcParameter = new JdbcParameterImpl(jdbcValueMapping.getJdbcMapping());
                final ComparisonPredicate predicate = new ComparisonPredicate(columnReference, ComparisonOperator.EQUAL, jdbcParameter);
                predicateConsumer.accept(predicate);
                jdbcParameterConsumer.accept(jdbcParameter, new JdbcParameterBindingImpl(jdbcValueMapping.getJdbcMapping(), jdbcValue));
            }
        }, session);
    }
}
Also used : Expression(org.hibernate.sql.ast.tree.expression.Expression) JdbcParameter(org.hibernate.sql.ast.tree.expression.JdbcParameter) JdbcParameterBindingImpl(org.hibernate.sql.exec.internal.JdbcParameterBindingImpl) NullnessPredicate(org.hibernate.sql.ast.tree.predicate.NullnessPredicate) JdbcParameterImpl(org.hibernate.sql.exec.internal.JdbcParameterImpl) ComparisonPredicate(org.hibernate.sql.ast.tree.predicate.ComparisonPredicate)

Example 5 with ComparisonPredicate

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

the class CteInsertHandler method addDmlCtes.

protected String addDmlCtes(CteContainer statement, CteStatement queryCte, List<Map.Entry<SqmCteTableColumn, Assignment>> assignments, boolean assignsId, MultiTableSqmMutationConverter sqmConverter, Map<SqmParameter<?>, List<List<JdbcParameter>>> parameterResolutions, SessionFactoryImplementor factory) {
    final TableGroup updatingTableGroup = sqmConverter.getMutatingTableGroup();
    final EntityMappingType entityDescriptor = getEntityDescriptor();
    final EntityPersister entityPersister = entityDescriptor.getEntityPersister();
    final String rootEntityName = entityPersister.getRootEntityName();
    final EntityPersister rootEntityDescriptor = factory.getRuntimeMetamodels().getMappingMetamodel().getEntityDescriptor(rootEntityName);
    final String hierarchyRootTableName = ((Joinable) rootEntityDescriptor).getTableName();
    final TableReference hierarchyRootTableReference = updatingTableGroup.resolveTableReference(updatingTableGroup.getNavigablePath(), hierarchyRootTableName);
    assert hierarchyRootTableReference != null;
    // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    // 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(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);
    }
    final Map<TableReference, List<Map.Entry<SqmCteTableColumn, Assignment>>> assignmentsByTable = CollectionHelper.mapOfSize(updatingTableGroup.getTableReferenceJoins().size() + 1);
    for (int i = 0; i < assignments.size(); i++) {
        final Map.Entry<SqmCteTableColumn, Assignment> entry = assignments.get(i);
        final Assignment assignment = entry.getValue();
        final List<ColumnReference> assignmentColumnRefs = assignment.getAssignable().getColumnReferences();
        TableReference assignmentTableReference = null;
        for (int c = 0; c < assignmentColumnRefs.size(); c++) {
            final ColumnReference columnReference = assignmentColumnRefs.get(c);
            final TableReference tableReference = resolveTableReference(columnReference, updatingTableGroup, tableReferenceByAlias);
            // TODO: this could be fixed by introducing joins to DML statements
            if (assignmentTableReference != null && !assignmentTableReference.equals(tableReference)) {
                throw new IllegalStateException("Assignment referred to columns from multiple tables");
            }
            assignmentTableReference = tableReference;
        }
        assert assignmentTableReference != null;
        List<Map.Entry<SqmCteTableColumn, Assignment>> assignmentsForTable = assignmentsByTable.get(assignmentTableReference);
        if (assignmentsForTable == null) {
            assignmentsForTable = new ArrayList<>();
            assignmentsByTable.put(assignmentTableReference, assignmentsForTable);
        }
        assignmentsForTable.add(entry);
    }
    // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    // Add the root insert as cte
    final AbstractEntityPersister persister = (AbstractEntityPersister) entityDescriptor.getEntityPersister();
    final String rootTableName = persister.getTableName(0);
    final TableReference rootTableReference = updatingTableGroup.getTableReference(updatingTableGroup.getNavigablePath(), rootTableName, true, true);
    final IdentifierGenerator identifierGenerator = entityDescriptor.getEntityPersister().getIdentifierGenerator();
    final List<Map.Entry<SqmCteTableColumn, Assignment>> tableAssignments = assignmentsByTable.get(rootTableReference);
    if ((tableAssignments == null || tableAssignments.isEmpty()) && !(identifierGenerator instanceof PostInsertIdentifierGenerator)) {
        throw new IllegalStateException("There must be at least a single root table assignment");
    }
    final int tableSpan = persister.getTableSpan();
    final String[] rootKeyColumns = persister.getKeyColumns(0);
    final List<CteColumn> keyCteColumns = queryCte.getCteTable().getCteColumns().subList(0, rootKeyColumns.length);
    for (int i = 0; i < tableSpan; i++) {
        final String tableExpression = persister.getTableName(i);
        final TableReference updatingTableReference = updatingTableGroup.getTableReference(updatingTableGroup.getNavigablePath(), tableExpression, true, true);
        final List<Map.Entry<SqmCteTableColumn, Assignment>> assignmentList = assignmentsByTable.get(updatingTableReference);
        final NamedTableReference dmlTableReference = resolveUnionTableReference(updatingTableReference, tableExpression);
        final String[] keyColumns = persister.getKeyColumns(i);
        final List<ColumnReference> returningColumnReferences = new ArrayList<>(keyColumns.length + (assignmentList == null ? 0 : assignmentList.size()));
        final List<ColumnReference> insertColumnReferences;
        final QuerySpec insertSelectSpec = new QuerySpec(true);
        CteStatement finalCteStatement = null;
        final CteTable dmlResultCte;
        if (i == 0 && !assignsId && identifierGenerator instanceof PostInsertIdentifierGenerator) {
            // Special handling for identity generation
            final String baseTableName = "base_" + queryCte.getCteTable().getTableExpression();
            insertSelectSpec.getFromClause().addRoot(new CteTableGroup(new NamedTableReference(baseTableName, "e", false, factory)));
            final CteColumn rowNumberColumn = queryCte.getCteTable().getCteColumns().get(queryCte.getCteTable().getCteColumns().size() - 1);
            final ColumnReference rowNumberColumnReference = new ColumnReference("e", rowNumberColumn.getColumnExpression(), false, null, null, rowNumberColumn.getJdbcMapping(), factory);
            // Insert in the same order as the original tuples came
            insertSelectSpec.addSortSpecification(new SortSpecification(rowNumberColumnReference, SortOrder.ASCENDING));
            final List<CteColumn> returningColumns = new ArrayList<>(keyCteColumns.size() + 1);
            returningColumns.addAll(keyCteColumns);
            dmlResultCte = new CteTable(getCteTableName(tableExpression, "base_"), returningColumns, factory);
            for (int j = 0; j < keyColumns.length; j++) {
                returningColumnReferences.add(new ColumnReference(dmlTableReference, keyColumns[j], false, null, null, null, factory));
            }
            insertColumnReferences = Collections.emptyList();
            final SelectStatement queryStatement = (SelectStatement) queryCte.getCteDefinition();
            final QuerySpec querySpec = queryStatement.getQuerySpec();
            final NavigablePath navigablePath = new NavigablePath(baseTableName);
            final TableGroup baseTableGroup = new TableGroupImpl(navigablePath, null, new NamedTableReference(baseTableName, "e", false, factory), null);
            final TableGroup rootInsertCteTableGroup = new CteTableGroup(new NamedTableReference(getCteTableName(tableExpression), "t", false, factory));
            baseTableGroup.addTableGroupJoin(new TableGroupJoin(rootInsertCteTableGroup.getNavigablePath(), SqlAstJoinType.INNER, rootInsertCteTableGroup, new ComparisonPredicate(rowNumberColumnReference, ComparisonOperator.EQUAL, new ColumnReference("t", rowNumberColumn.getColumnExpression(), false, null, null, rowNumberColumn.getJdbcMapping(), factory))));
            querySpec.getFromClause().addRoot(baseTableGroup);
            final List<CteColumn> cteColumns = queryCte.getCteTable().getCteColumns();
            // The id column in this case comes from the dml CTE
            final CteColumn idCteColumn = cteColumns.get(0);
            querySpec.getSelectClause().addSqlSelection(new SqlSelectionImpl(1, 0, new ColumnReference("t", idCteColumn.getColumnExpression(), false, null, null, idCteColumn.getJdbcMapping(), factory)));
            // The other columns come from the base CTE
            for (int j = 1; j < cteColumns.size(); j++) {
                final CteColumn cteColumn = cteColumns.get(j);
                querySpec.getSelectClause().addSqlSelection(new SqlSelectionImpl(1, 0, new ColumnReference("e", cteColumn.getColumnExpression(), false, null, null, cteColumn.getJdbcMapping(), factory)));
            }
            // Now build the final CTE statement
            final List<CteColumn> finalReturningColumns = new ArrayList<>(keyCteColumns.size() + 1);
            finalReturningColumns.addAll(keyCteColumns);
            finalReturningColumns.add(rowNumberColumn);
            final CteTable finalResultCte = new CteTable(getCteTableName(tableExpression), finalReturningColumns, factory);
            final QuerySpec finalResultQuery = new QuerySpec(true);
            finalResultQuery.getFromClause().addRoot(new CteTableGroup(new NamedTableReference(dmlResultCte.getTableExpression(), "e", false, factory)));
            // The id column in this case comes from the dml CTE
            final ColumnReference idColumnReference = new ColumnReference("e", idCteColumn.getColumnExpression(), false, null, null, idCteColumn.getJdbcMapping(), factory);
            finalResultQuery.getSelectClause().addSqlSelection(new SqlSelectionImpl(1, 0, idColumnReference));
            final BasicType<Integer> rowNumberType = sessionFactory.getTypeConfiguration().getBasicTypeForJavaType(Integer.class);
            finalResultQuery.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())));
            finalResultQuery.addSortSpecification(new SortSpecification(idColumnReference, SortOrder.ASCENDING));
            final SelectStatement finalResultStatement = new SelectStatement(finalResultQuery);
            finalCteStatement = new CteStatement(finalResultCte, finalResultStatement);
        } else {
            insertSelectSpec.getFromClause().addRoot(new CteTableGroup(new NamedTableReference(queryCte.getCteTable().getTableExpression(), "e", false, factory)));
            dmlResultCte = new CteTable(getCteTableName(tableExpression), keyCteColumns, factory);
            for (int j = 0; j < keyColumns.length; j++) {
                returningColumnReferences.add(new ColumnReference(dmlTableReference, keyColumns[j], false, null, null, null, factory));
                insertSelectSpec.getSelectClause().addSqlSelection(new SqlSelectionImpl(1, 0, new ColumnReference("e", rootKeyColumns[j], false, null, null, null, factory)));
            }
            insertColumnReferences = returningColumnReferences;
        }
        final InsertStatement dmlStatement = new InsertStatement(dmlTableReference, returningColumnReferences);
        dmlStatement.addTargetColumnReferences(insertColumnReferences);
        if (assignmentList != null) {
            for (Map.Entry<SqmCteTableColumn, Assignment> entry : assignmentList) {
                final Assignment assignment = entry.getValue();
                // Skip the id mapping here as we handled that already
                if (assignment.getAssignedValue().getExpressionType() instanceof EntityIdentifierMapping) {
                    continue;
                }
                final List<ColumnReference> assignmentReferences = assignment.getAssignable().getColumnReferences();
                dmlStatement.addTargetColumnReferences(assignmentReferences);
                final int size = assignmentReferences.size();
                for (int j = 0; j < size; j++) {
                    final ColumnReference columnReference = assignmentReferences.get(j);
                    final String columnName = size > 1 ? entry.getKey().getColumnName() + '_' + i : entry.getKey().getColumnName();
                    insertSelectSpec.getSelectClause().addSqlSelection(new SqlSelectionImpl(1, 0, new ColumnReference("e", columnName, columnReference.isColumnExpressionFormula(), null, null, columnReference.getJdbcMapping(), factory)));
                }
            }
        }
        dmlStatement.setSourceSelectStatement(insertSelectSpec);
        statement.addCteStatement(new CteStatement(dmlResultCte, dmlStatement));
        if (finalCteStatement != null) {
            statement.addCteStatement(finalCteStatement);
        }
        if (i == 0 && !assignsId && identifierGenerator instanceof PostInsertIdentifierGenerator) {
            // Special handling for identity generation
            statement.addCteStatement(queryCte);
        }
    }
    return getCteTableName(rootTableName);
}
Also used : EntityPersister(org.hibernate.persister.entity.EntityPersister) AbstractEntityPersister(org.hibernate.persister.entity.AbstractEntityPersister) CteColumn(org.hibernate.sql.ast.tree.cte.CteColumn) CollectionHelper(org.hibernate.internal.util.collections.CollectionHelper) Arrays(java.util.Arrays) EntityPersister(org.hibernate.persister.entity.EntityPersister) Statement(org.hibernate.sql.ast.tree.Statement) SqlExpressible(org.hibernate.metamodel.mapping.SqlExpressible) BasicType(org.hibernate.type.BasicType) SqmCteTable(org.hibernate.query.sqm.tree.cte.SqmCteTable) SqmInsertValuesStatement(org.hibernate.query.sqm.tree.insert.SqmInsertValuesStatement) TableGroupJoin(org.hibernate.sql.ast.tree.from.TableGroupJoin) CteStatement(org.hibernate.sql.ast.tree.cte.CteStatement) Joinable(org.hibernate.persister.entity.Joinable) EntityMappingType(org.hibernate.metamodel.mapping.EntityMappingType) SqmExpression(org.hibernate.query.sqm.tree.expression.SqmExpression) Identifier(org.hibernate.boot.model.naming.Identifier) SqmJdbcExecutionContextAdapter(org.hibernate.query.sqm.internal.SqmJdbcExecutionContextAdapter) ComparisonPredicate(org.hibernate.sql.ast.tree.predicate.ComparisonPredicate) SqmUtil(org.hibernate.query.sqm.internal.SqmUtil) PostInsertIdentifierGenerator(org.hibernate.id.PostInsertIdentifierGenerator) Map(java.util.Map) ComparisonOperator(org.hibernate.query.sqm.ComparisonOperator) 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) Assignment(org.hibernate.sql.ast.tree.update.Assignment) IdentityHashMap(java.util.IdentityHashMap) SelfRenderingSqlFragmentExpression(org.hibernate.sql.ast.tree.expression.SelfRenderingSqlFragmentExpression) SelfRenderingFunctionSqlAstExpression(org.hibernate.query.sqm.function.SelfRenderingFunctionSqlAstExpression) TypeConfiguration(org.hibernate.type.spi.TypeConfiguration) Optimizer(org.hibernate.id.enhanced.Optimizer) NavigablePath(org.hibernate.query.spi.NavigablePath) DomainResult(org.hibernate.sql.results.graph.DomainResult) BasicValuedMapping(org.hibernate.metamodel.mapping.BasicValuedMapping) Expression(org.hibernate.sql.ast.tree.expression.Expression) BaseSqmToSqlAstConverter(org.hibernate.query.sqm.sql.BaseSqmToSqlAstConverter) BasicResult(org.hibernate.sql.results.graph.basic.BasicResult) SqlAstProcessingState(org.hibernate.sql.ast.spi.SqlAstProcessingState) EntityIdentifierMapping(org.hibernate.metamodel.mapping.EntityIdentifierMapping) SelectStatement(org.hibernate.sql.ast.tree.select.SelectStatement) InsertHandler(org.hibernate.query.sqm.mutation.internal.InsertHandler) List(java.util.List) Over(org.hibernate.sql.ast.tree.expression.Over) SqmParameter(org.hibernate.query.sqm.tree.expression.SqmParameter) AbstractEntityPersister(org.hibernate.persister.entity.AbstractEntityPersister) InsertStatement(org.hibernate.sql.ast.tree.insert.InsertStatement) QuerySpec(org.hibernate.sql.ast.tree.select.QuerySpec) MappingModelExpressible(org.hibernate.metamodel.mapping.MappingModelExpressible) TableGroupImpl(org.hibernate.query.results.TableGroupImpl) JdbcMapping(org.hibernate.metamodel.mapping.JdbcMapping) CteContainer(org.hibernate.sql.ast.tree.cte.CteContainer) CteMaterialization(org.hibernate.sql.ast.tree.cte.CteMaterialization) ColumnReference(org.hibernate.sql.ast.tree.expression.ColumnReference) OptimizableGenerator(org.hibernate.id.OptimizableGenerator) SemanticException(org.hibernate.query.SemanticException) SortOrder(org.hibernate.query.sqm.SortOrder) JdbcParameterBindings(org.hibernate.sql.exec.spi.JdbcParameterBindings) SortSpecification(org.hibernate.sql.ast.tree.select.SortSpecification) ArrayList(java.util.ArrayList) TableReference(org.hibernate.sql.ast.tree.from.TableReference) LinkedHashMap(java.util.LinkedHashMap) CteTable(org.hibernate.sql.ast.tree.cte.CteTable) NamedTableReference(org.hibernate.sql.ast.tree.from.NamedTableReference) MultiTableSqmMutationConverter(org.hibernate.query.sqm.mutation.internal.MultiTableSqmMutationConverter) SqmParameterMappingModelResolutionAccess(org.hibernate.query.sqm.spi.SqmParameterMappingModelResolutionAccess) CteColumn(org.hibernate.sql.ast.tree.cte.CteColumn) UnionTableReference(org.hibernate.sql.ast.tree.from.UnionTableReference) BiConsumer(java.util.function.BiConsumer) BinaryArithmeticExpression(org.hibernate.sql.ast.tree.expression.BinaryArithmeticExpression) BinaryArithmeticOperator(org.hibernate.query.sqm.BinaryArithmeticOperator) ValuesTableGroup(org.hibernate.sql.ast.tree.from.ValuesTableGroup) Values(org.hibernate.sql.ast.tree.insert.Values) BulkInsertionCapableIdentifierGenerator(org.hibernate.id.BulkInsertionCapableIdentifierGenerator) TemporaryTable(org.hibernate.dialect.temptable.TemporaryTable) ListResultsConsumer(org.hibernate.sql.results.spi.ListResultsConsumer) SqmStar(org.hibernate.query.sqm.tree.expression.SqmStar) CteTableGroup(org.hibernate.sql.ast.tree.cte.CteTableGroup) SqlAstTranslator(org.hibernate.sql.ast.SqlAstTranslator) JdbcServices(org.hibernate.engine.jdbc.spi.JdbcServices) QueryLiteral(org.hibernate.sql.ast.tree.expression.QueryLiteral) DomainQueryExecutionContext(org.hibernate.query.spi.DomainQueryExecutionContext) SqmCteTableColumn(org.hibernate.query.sqm.tree.cte.SqmCteTableColumn) AbstractMap(java.util.AbstractMap) JdbcParameter(org.hibernate.sql.ast.tree.expression.JdbcParameter) SqmInsertStatement(org.hibernate.query.sqm.tree.insert.SqmInsertStatement) QueryPart(org.hibernate.sql.ast.tree.select.QueryPart) SqlAstJoinType(org.hibernate.sql.ast.SqlAstJoinType) SqlSelectionImpl(org.hibernate.sql.results.internal.SqlSelectionImpl) Stack(org.hibernate.internal.util.collections.Stack) DomainParameterXref(org.hibernate.query.sqm.internal.DomainParameterXref) Collections(java.util.Collections) TableGroup(org.hibernate.sql.ast.tree.from.TableGroup) JdbcSelect(org.hibernate.sql.exec.spi.JdbcSelect) SqmValues(org.hibernate.query.sqm.tree.insert.SqmValues) NavigablePath(org.hibernate.query.spi.NavigablePath) ArrayList(java.util.ArrayList) ComparisonPredicate(org.hibernate.sql.ast.tree.predicate.ComparisonPredicate) InsertStatement(org.hibernate.sql.ast.tree.insert.InsertStatement) SqmInsertStatement(org.hibernate.query.sqm.tree.insert.SqmInsertStatement) Assignment(org.hibernate.sql.ast.tree.update.Assignment) TableGroupJoin(org.hibernate.sql.ast.tree.from.TableGroupJoin) SqmInsertSelectStatement(org.hibernate.query.sqm.tree.insert.SqmInsertSelectStatement) SelectStatement(org.hibernate.sql.ast.tree.select.SelectStatement) Over(org.hibernate.sql.ast.tree.expression.Over) TableReference(org.hibernate.sql.ast.tree.from.TableReference) NamedTableReference(org.hibernate.sql.ast.tree.from.NamedTableReference) UnionTableReference(org.hibernate.sql.ast.tree.from.UnionTableReference) SqmCteTable(org.hibernate.query.sqm.tree.cte.SqmCteTable) CteTable(org.hibernate.sql.ast.tree.cte.CteTable) CteStatement(org.hibernate.sql.ast.tree.cte.CteStatement) List(java.util.List) ArrayList(java.util.ArrayList) TableGroupImpl(org.hibernate.query.results.TableGroupImpl) EntityMappingType(org.hibernate.metamodel.mapping.EntityMappingType) ValuesTableGroup(org.hibernate.sql.ast.tree.from.ValuesTableGroup) CteTableGroup(org.hibernate.sql.ast.tree.cte.CteTableGroup) TableGroup(org.hibernate.sql.ast.tree.from.TableGroup) NamedTableReference(org.hibernate.sql.ast.tree.from.NamedTableReference) PostInsertIdentifierGenerator(org.hibernate.id.PostInsertIdentifierGenerator) CteTableGroup(org.hibernate.sql.ast.tree.cte.CteTableGroup) SqmCteTableColumn(org.hibernate.query.sqm.tree.cte.SqmCteTableColumn) SortSpecification(org.hibernate.sql.ast.tree.select.SortSpecification) Joinable(org.hibernate.persister.entity.Joinable) SelfRenderingFunctionSqlAstExpression(org.hibernate.query.sqm.function.SelfRenderingFunctionSqlAstExpression) EntityIdentifierMapping(org.hibernate.metamodel.mapping.EntityIdentifierMapping) SqlSelectionImpl(org.hibernate.sql.results.internal.SqlSelectionImpl) QuerySpec(org.hibernate.sql.ast.tree.select.QuerySpec) Map(java.util.Map) IdentityHashMap(java.util.IdentityHashMap) LinkedHashMap(java.util.LinkedHashMap) AbstractMap(java.util.AbstractMap) AbstractEntityPersister(org.hibernate.persister.entity.AbstractEntityPersister) ColumnReference(org.hibernate.sql.ast.tree.expression.ColumnReference) PostInsertIdentifierGenerator(org.hibernate.id.PostInsertIdentifierGenerator) IdentifierGenerator(org.hibernate.id.IdentifierGenerator) BulkInsertionCapableIdentifierGenerator(org.hibernate.id.BulkInsertionCapableIdentifierGenerator)

Aggregations

ComparisonPredicate (org.hibernate.sql.ast.tree.predicate.ComparisonPredicate)17 Expression (org.hibernate.sql.ast.tree.expression.Expression)14 ColumnReference (org.hibernate.sql.ast.tree.expression.ColumnReference)12 ArrayList (java.util.ArrayList)9 ComparisonOperator (org.hibernate.query.sqm.ComparisonOperator)7 JdbcParameter (org.hibernate.sql.ast.tree.expression.JdbcParameter)7 QuerySpec (org.hibernate.sql.ast.tree.select.QuerySpec)7 SessionFactoryImplementor (org.hibernate.engine.spi.SessionFactoryImplementor)6 SqlSelectionImpl (org.hibernate.sql.results.internal.SqlSelectionImpl)6 Collections (java.util.Collections)5 List (java.util.List)5 Map (java.util.Map)5 EntityIdentifierMapping (org.hibernate.metamodel.mapping.EntityIdentifierMapping)5 NavigablePath (org.hibernate.query.spi.NavigablePath)4 BinaryArithmeticExpression (org.hibernate.sql.ast.tree.expression.BinaryArithmeticExpression)4 CaseSearchedExpression (org.hibernate.sql.ast.tree.expression.CaseSearchedExpression)4 CaseSimpleExpression (org.hibernate.sql.ast.tree.expression.CaseSimpleExpression)4 ModifiedSubQueryExpression (org.hibernate.sql.ast.tree.expression.ModifiedSubQueryExpression)4 SelfRenderingExpression (org.hibernate.sql.ast.tree.expression.SelfRenderingExpression)4 SqlSelectionExpression (org.hibernate.sql.ast.tree.expression.SqlSelectionExpression)4