Search in sources :

Example 1 with SqmPath

use of org.hibernate.query.sqm.tree.domain.SqmPath in project hibernate-orm by hibernate.

the class SemanticQueryBuilder method visitTreatedNavigablePath.

@Override
public SqmPath<?> visitTreatedNavigablePath(HqlParser.TreatedNavigablePathContext ctx) {
    final DotIdentifierConsumer consumer = dotIdentifierConsumerStack.getCurrent();
    final boolean madeNested;
    if (consumer instanceof QualifiedJoinPathConsumer) {
        final QualifiedJoinPathConsumer qualifiedJoinPathConsumer = (QualifiedJoinPathConsumer) consumer;
        madeNested = !qualifiedJoinPathConsumer.isNested();
        if (madeNested) {
            qualifiedJoinPathConsumer.setNested(true);
        }
    } else {
        madeNested = false;
    }
    consumeManagedTypeReference((HqlParser.PathContext) ctx.getChild(2));
    final String treatTargetName = ctx.getChild(4).getText();
    final String treatTargetEntityName = getCreationContext().getJpaMetamodel().qualifyImportableName(treatTargetName);
    final boolean hasContinuation = ctx.getChildCount() == 7;
    consumer.consumeTreat(treatTargetEntityName, !hasContinuation);
    SqmPath<?> result = (SqmPath<?>) consumer.getConsumedPart();
    if (hasContinuation) {
        if (madeNested) {
            // Reset the nested state before consuming the terminal identifier
            ((QualifiedJoinPathConsumer) consumer).setNested(false);
        }
        final boolean addConsumer = !(consumer instanceof QualifiedJoinPathConsumer);
        if (addConsumer) {
            dotIdentifierConsumerStack.push(new BasicDotIdentifierConsumer(result, this) {

                @Override
                protected void reset() {
                }
            });
        }
        try {
            result = consumeDomainPath((HqlParser.SimplePathContext) ctx.getChild(6).getChild(1));
        } finally {
            if (addConsumer) {
                dotIdentifierConsumerStack.pop();
            }
        }
    }
    return result;
}
Also used : HqlParser(org.hibernate.grammars.hql.HqlParser) DotIdentifierConsumer(org.hibernate.query.hql.spi.DotIdentifierConsumer) SqmPath(org.hibernate.query.sqm.tree.domain.SqmPath)

Example 2 with SqmPath

use of org.hibernate.query.sqm.tree.domain.SqmPath in project hibernate-orm by hibernate.

the class SemanticQueryBuilder method visitInsertStatement.

@Override
public SqmInsertStatement<R> visitInsertStatement(HqlParser.InsertStatementContext ctx) {
    final int dmlTargetIndex;
    if (ctx.getChild(1) instanceof HqlParser.TargetEntityContext) {
        dmlTargetIndex = 1;
    } else {
        dmlTargetIndex = 2;
    }
    final HqlParser.TargetEntityContext dmlTargetContext = (HqlParser.TargetEntityContext) ctx.getChild(dmlTargetIndex);
    final HqlParser.TargetFieldsContext targetFieldsSpecContext = (HqlParser.TargetFieldsContext) ctx.getChild(dmlTargetIndex + 1);
    final SqmRoot<R> root = visitTargetEntity(dmlTargetContext);
    if (root.getReferencedPathSource() instanceof SqmPolymorphicRootDescriptor<?>) {
        throw new SemanticException(String.format("Target type '%s' in insert statement is not an entity", root.getReferencedPathSource().getHibernateEntityName()));
    }
    final HqlParser.QueryExpressionContext queryExpressionContext = ctx.queryExpression();
    if (queryExpressionContext != null) {
        final SqmInsertSelectStatement<R> insertStatement = new SqmInsertSelectStatement<>(root, creationContext.getNodeBuilder());
        parameterCollector = insertStatement;
        final SqmDmlCreationProcessingState processingState = new SqmDmlCreationProcessingState(insertStatement, this);
        processingStateStack.push(processingState);
        try {
            queryExpressionContext.accept(this);
            final SqmCreationProcessingState stateFieldsProcessingState = new SqmCreationProcessingStateImpl(insertStatement, this);
            stateFieldsProcessingState.getPathRegistry().register(root);
            processingStateStack.push(stateFieldsProcessingState);
            try {
                for (HqlParser.SimplePathContext stateFieldCtx : targetFieldsSpecContext.simplePath()) {
                    final SqmPath<?> stateField = (SqmPath<?>) visitSimplePath(stateFieldCtx);
                    // todo : validate each resolved stateField...
                    insertStatement.addInsertTargetStateField(stateField);
                }
            } finally {
                processingStateStack.pop();
            }
            return insertStatement;
        } finally {
            processingStateStack.pop();
        }
    } else {
        final SqmInsertValuesStatement<R> insertStatement = new SqmInsertValuesStatement<>(root, creationContext.getNodeBuilder());
        parameterCollector = insertStatement;
        final SqmDmlCreationProcessingState processingState = new SqmDmlCreationProcessingState(insertStatement, this);
        processingStateStack.push(processingState);
        processingState.getPathRegistry().register(root);
        try {
            final HqlParser.ValuesListContext valuesListContext = ctx.valuesList();
            for (int i = 1; i < valuesListContext.getChildCount(); i += 2) {
                final ParseTree values = valuesListContext.getChild(i);
                final SqmValues sqmValues = new SqmValues();
                for (int j = 1; j < values.getChildCount(); j += 2) {
                    sqmValues.getExpressions().add((SqmExpression<?>) values.getChild(j).accept(this));
                }
                insertStatement.getValuesList().add(sqmValues);
            }
            for (HqlParser.SimplePathContext stateFieldCtx : targetFieldsSpecContext.simplePath()) {
                final SqmPath<?> stateField = (SqmPath<?>) visitSimplePath(stateFieldCtx);
                // todo : validate each resolved stateField...
                insertStatement.addInsertTargetStateField(stateField);
            }
            return insertStatement;
        } finally {
            processingStateStack.pop();
        }
    }
}
Also used : SqmInsertValuesStatement(org.hibernate.query.sqm.tree.insert.SqmInsertValuesStatement) SqmPath(org.hibernate.query.sqm.tree.domain.SqmPath) TIMEZONE_HOUR(org.hibernate.query.sqm.TemporalUnit.TIMEZONE_HOUR) WEEK_OF_YEAR(org.hibernate.query.sqm.TemporalUnit.WEEK_OF_YEAR) DAY_OF_YEAR(org.hibernate.query.sqm.TemporalUnit.DAY_OF_YEAR) IDENTIFIER(org.hibernate.grammars.hql.HqlParser.IDENTIFIER) SqmCreationProcessingState(org.hibernate.query.hql.spi.SqmCreationProcessingState) HqlParser(org.hibernate.grammars.hql.HqlParser) SqmValues(org.hibernate.query.sqm.tree.insert.SqmValues) SqmPolymorphicRootDescriptor(org.hibernate.query.sqm.tree.domain.SqmPolymorphicRootDescriptor) SqmInsertSelectStatement(org.hibernate.query.sqm.tree.insert.SqmInsertSelectStatement) SqmDmlCreationProcessingState(org.hibernate.query.sqm.internal.SqmDmlCreationProcessingState) SqmCreationProcessingStateImpl(org.hibernate.query.sqm.internal.SqmCreationProcessingStateImpl) ParseTree(org.antlr.v4.runtime.tree.ParseTree) SemanticException(org.hibernate.query.SemanticException)

Example 3 with SqmPath

use of org.hibernate.query.sqm.tree.domain.SqmPath in project hibernate-orm by hibernate.

the class SemanticQueryBuilder method visitSelectableNode.

private SqmSelectableNode<?> visitSelectableNode(HqlParser.SelectionContext ctx) {
    final ParseTree subCtx = ctx.getChild(0).getChild(0);
    if (subCtx instanceof HqlParser.ExpressionOrPredicateContext) {
        final SqmExpression<?> sqmExpression = (SqmExpression<?>) subCtx.accept(this);
        if (sqmExpression instanceof SqmPath) {
            final SqmPath<?> sqmPath = (SqmPath<?>) sqmExpression;
            if (sqmPath.getReferencedPathSource() instanceof PluralPersistentAttribute) {
                // - this is not strictly JPA compliant
                if (creationOptions.useStrictJpaCompliance()) {
                    SqmTreeCreationLogger.LOGGER.debugf("Raw selection of plural attribute not supported by JPA: %s.  Use `value(%s)` or `key(%s)` to indicate what part of the collection to select", sqmPath.getAlias(), sqmPath.getAlias(), sqmPath.getAlias());
                }
                final SqmPath<?> elementPath = sqmPath.resolvePathPart(CollectionPart.Nature.ELEMENT.getName(), true, this);
                processingStateStack.getCurrent().getPathRegistry().register(elementPath);
                return elementPath;
            }
        }
        return sqmExpression;
    }
    return (SqmSelectableNode<?>) subCtx.accept(this);
}
Also used : SqmSelectableNode(org.hibernate.query.sqm.tree.select.SqmSelectableNode) SqmExpression(org.hibernate.query.sqm.tree.expression.SqmExpression) PluralPersistentAttribute(org.hibernate.metamodel.model.domain.PluralPersistentAttribute) SqmPath(org.hibernate.query.sqm.tree.domain.SqmPath) ParseTree(org.antlr.v4.runtime.tree.ParseTree)

Example 4 with SqmPath

use of org.hibernate.query.sqm.tree.domain.SqmPath in project hibernate-orm by hibernate.

the class MappingMetamodelImpl method resolveMappingExpressible.

@Override
public MappingModelExpressible<?> resolveMappingExpressible(SqmExpressible<?> sqmExpressible, Function<NavigablePath, TableGroup> tableGroupLocator) {
    if (sqmExpressible instanceof SqmPath) {
        final SqmPath<?> sqmPath = (SqmPath<?>) sqmExpressible;
        final NavigablePath navigablePath = sqmPath.getNavigablePath();
        if (navigablePath.getParent() != null) {
            final TableGroup parentTableGroup = tableGroupLocator.apply(navigablePath.getParent());
            return parentTableGroup.getModelPart().findSubPart(navigablePath.getLocalName(), null);
        }
        return tableGroupLocator.apply(navigablePath.getParent()).getModelPart();
    }
    if (sqmExpressible instanceof BasicType<?>) {
        return (BasicType<?>) sqmExpressible;
    }
    if (sqmExpressible instanceof BasicSqmPathSource<?>) {
        return getTypeConfiguration().getBasicTypeForJavaType(((BasicSqmPathSource<?>) sqmExpressible).getJavaType());
    }
    if (sqmExpressible instanceof SqmFieldLiteral) {
        return getTypeConfiguration().getBasicTypeForJavaType(((SqmFieldLiteral<?>) sqmExpressible).getJavaType());
    }
    if (sqmExpressible instanceof CompositeSqmPathSource) {
        throw new NotYetImplementedFor6Exception("Resolution of embedded-valued SqmExpressible nodes not yet implemented");
    }
    if (sqmExpressible instanceof EmbeddableTypeImpl) {
        return (MappingModelExpressible<?>) sqmExpressible;
    }
    if (sqmExpressible instanceof EntityDomainType<?>) {
        return getEntityDescriptor(((EntityDomainType<?>) sqmExpressible).getHibernateEntityName());
    }
    if (sqmExpressible instanceof TupleType<?>) {
        final MappingModelExpressible<?> mappingModelExpressible = tupleTypeCache.get(sqmExpressible);
        if (mappingModelExpressible != null) {
            return mappingModelExpressible;
        }
        final TupleType<?> tupleType = (TupleType<?>) sqmExpressible;
        final MappingModelExpressible<?>[] components = new MappingModelExpressible<?>[tupleType.componentCount()];
        for (int i = 0; i < components.length; i++) {
            components[i] = resolveMappingExpressible(tupleType.get(i), tableGroupLocator);
        }
        final MappingModelExpressible<?> createdMappingModelExpressible = new TupleMappingModelExpressible(components);
        final MappingModelExpressible<?> existingMappingModelExpressible = tupleTypeCache.putIfAbsent(tupleType, createdMappingModelExpressible);
        return existingMappingModelExpressible == null ? createdMappingModelExpressible : existingMappingModelExpressible;
    }
    return null;
}
Also used : NavigablePath(org.hibernate.query.spi.NavigablePath) TableGroup(org.hibernate.sql.ast.tree.from.TableGroup) BasicType(org.hibernate.type.BasicType) MappingModelExpressible(org.hibernate.metamodel.mapping.MappingModelExpressible) SqmPath(org.hibernate.query.sqm.tree.domain.SqmPath) TupleType(org.hibernate.metamodel.model.domain.TupleType) NotYetImplementedFor6Exception(org.hibernate.NotYetImplementedFor6Exception) EntityDomainType(org.hibernate.metamodel.model.domain.EntityDomainType) SqmFieldLiteral(org.hibernate.query.sqm.tree.expression.SqmFieldLiteral)

Example 5 with SqmPath

use of org.hibernate.query.sqm.tree.domain.SqmPath in project hibernate-orm by hibernate.

the class SelectClauseTests method testBinaryArithmeticExpression.

@Test
public void testBinaryArithmeticExpression() {
    final String query = "select p.numberOfToes + p.numberOfToes as b from Person p";
    final SqmSelectStatement<?> selectStatement = interpretSelect(query);
    final SqmQuerySpec<?> querySpec = selectStatement.getQuerySpec();
    final SqmSelection<?> selection = querySpec.getSelectClause().getSelections().get(0);
    assertThat(querySpec.getFromClause().getRoots().size(), is(1));
    final SqmRoot<?> root = querySpec.getFromClause().getRoots().get(0);
    assertThat(root.getEntityName(), endsWith("Person"));
    assertThat(root.getJoins().size(), is(0));
    SqmBinaryArithmetic expression = (SqmBinaryArithmetic) selection.getSelectableNode();
    SqmPath<?> leftHandOperand = (SqmPath<?>) expression.getLeftHandOperand();
    assertThat(leftHandOperand.getLhs(), sameInstance(root));
    assertThat(leftHandOperand.getReferencedPathSource().getPathName(), is("numberOfToes"));
    // assertThat( leftHandOperand.getFromElement(), nullValue() );
    SqmPath<?> rightHandOperand = (SqmPath<?>) expression.getRightHandOperand();
    assertThat(rightHandOperand.getLhs(), sameInstance(root));
    assertThat(rightHandOperand.getReferencedPathSource().getPathName(), is("numberOfToes"));
// assertThat( leftHandOperand.getFromElement(), nullValue() );
}
Also used : SqmBinaryArithmetic(org.hibernate.query.sqm.tree.expression.SqmBinaryArithmetic) SqmPath(org.hibernate.query.sqm.tree.domain.SqmPath) BaseSqmUnitTest(org.hibernate.orm.test.query.sqm.BaseSqmUnitTest) Test(org.junit.jupiter.api.Test)

Aggregations

SqmPath (org.hibernate.query.sqm.tree.domain.SqmPath)21 DiscriminatorSqmPath (org.hibernate.metamodel.model.domain.internal.DiscriminatorSqmPath)10 SelfInterpretingSqmPath (org.hibernate.query.sqm.sql.internal.SelfInterpretingSqmPath)10 SqmComparisonPredicate (org.hibernate.query.sqm.tree.predicate.SqmComparisonPredicate)6 HashSet (java.util.HashSet)5 Set (java.util.Set)5 SqmPredicate (org.hibernate.query.sqm.tree.predicate.SqmPredicate)5 SqmSelection (org.hibernate.query.sqm.tree.select.SqmSelection)5 AbstractMap (java.util.AbstractMap)4 HashMap (java.util.HashMap)4 IdentityHashMap (java.util.IdentityHashMap)4 LinkedHashMap (java.util.LinkedHashMap)4 Map (java.util.Map)4 SqmLiteral (org.hibernate.query.sqm.tree.expression.SqmLiteral)4 SqmAndPredicate (org.hibernate.query.sqm.tree.predicate.SqmAndPredicate)4 SqmBetweenPredicate (org.hibernate.query.sqm.tree.predicate.SqmBetweenPredicate)4 SqmBooleanExpressionPredicate (org.hibernate.query.sqm.tree.predicate.SqmBooleanExpressionPredicate)4 SqmEmptinessPredicate (org.hibernate.query.sqm.tree.predicate.SqmEmptinessPredicate)4 SqmExistsPredicate (org.hibernate.query.sqm.tree.predicate.SqmExistsPredicate)4 SqmGroupedPredicate (org.hibernate.query.sqm.tree.predicate.SqmGroupedPredicate)4