Search in sources :

Example 36 with Expression

use of org.hibernate.sql.ast.tree.expression.Expression in project hibernate-orm by hibernate.

the class CountFunction method render.

@Override
public void render(SqlAppender sqlAppender, List<? extends SqlAstNode> sqlAstArguments, Predicate filter, SqlAstTranslator<?> translator) {
    final boolean caseWrapper = filter != null && !translator.supportsFilterClause();
    final SqlAstNode arg = sqlAstArguments.get(0);
    sqlAppender.appendSql("count(");
    final SqlTuple tuple;
    if (arg instanceof Distinct) {
        sqlAppender.appendSql("distinct ");
        final Expression distinctArg = ((Distinct) arg).getExpression();
        if ((tuple = SqlTupleContainer.getSqlTuple(distinctArg)) != null) {
            final List<? extends Expression> expressions = tuple.getExpressions();
            // Single element tuple
            if (expressions.size() == 1) {
                renderSimpleArgument(sqlAppender, filter, translator, caseWrapper, expressions.get(0));
            } else // Emulate tuple distinct count
            if (!dialect.supportsTupleDistinctCounts()) {
                // count(distinct coalesce(nullif(coalesce(col1 || '', '\0'), ''), '\01') || '\0' || coalesce(nullif(coalesce(col2 || '', '\0'), ''), '\02'))
                if (caseWrapper) {
                    translator.getCurrentClauseStack().push(Clause.WHERE);
                    sqlAppender.appendSql("case when ");
                    filter.accept(translator);
                    sqlAppender.appendSql(" then ");
                    translator.getCurrentClauseStack().pop();
                }
                if (castDistinctStringConcat) {
                    sqlAppender.appendSql("cast(");
                }
                sqlAppender.appendSql("coalesce(nullif(coalesce(");
                boolean needsConcat = renderCastedArgument(sqlAppender, translator, expressions.get(0));
                int argumentNumber = 1;
                for (int i = 1; i < expressions.size(); i++, argumentNumber++) {
                    if (needsConcat) {
                        // Concat with empty string to get implicit conversion
                        sqlAppender.appendSql(concatOperator);
                        sqlAppender.appendSql("''");
                    }
                    sqlAppender.appendSql(",'\\0'),''),'\\0");
                    sqlAppender.appendSql(argumentNumber);
                    sqlAppender.appendSql("')");
                    sqlAppender.appendSql(concatOperator);
                    sqlAppender.appendSql("'\\0'");
                    sqlAppender.appendSql(concatOperator);
                    sqlAppender.appendSql("coalesce(nullif(coalesce(");
                    needsConcat = renderCastedArgument(sqlAppender, translator, expressions.get(i));
                }
                if (needsConcat) {
                    // Concat with empty string to get implicit conversion
                    sqlAppender.appendSql(concatOperator);
                    sqlAppender.appendSql("''");
                }
                sqlAppender.appendSql(",'\\0'),''),'\\0");
                sqlAppender.appendSql(argumentNumber);
                sqlAppender.appendSql("')");
                if (castDistinctStringConcat) {
                    sqlAppender.appendSql(" as ");
                    sqlAppender.appendSql(concatArgumentCastType);
                    sqlAppender.appendSql(')');
                }
                if (caseWrapper) {
                    sqlAppender.appendSql(" else null end");
                }
            } else {
                renderTupleCountSupported(sqlAppender, filter, translator, caseWrapper, tuple, expressions, dialect.requiresParensForTupleDistinctCounts());
            }
        } else {
            renderSimpleArgument(sqlAppender, filter, translator, caseWrapper, distinctArg);
        }
    } else {
        if (canReplaceWithStar(arg, translator)) {
            renderSimpleArgument(sqlAppender, filter, translator, caseWrapper, Star.INSTANCE);
        } else if ((tuple = SqlTupleContainer.getSqlTuple(arg)) != null) {
            final List<? extends Expression> expressions = tuple.getExpressions();
            // Single element tuple
            if (expressions.size() == 1) {
                renderSimpleArgument(sqlAppender, filter, translator, caseWrapper, expressions.get(0));
            } else // Emulate the tuple count with a case when expression
            if (!dialect.supportsTupleCounts()) {
                sqlAppender.appendSql("case when ");
                if (caseWrapper) {
                    translator.getCurrentClauseStack().push(Clause.WHERE);
                    filter.accept(translator);
                    translator.getCurrentClauseStack().pop();
                    sqlAppender.appendSql(" and ");
                }
                translator.render(expressions.get(0), defaultArgumentRenderingMode);
                sqlAppender.appendSql(" is not null");
                for (int i = 1; i < expressions.size(); i++) {
                    sqlAppender.appendSql(" and ");
                    translator.render(expressions.get(i), defaultArgumentRenderingMode);
                    sqlAppender.appendSql(" is not null");
                }
                sqlAppender.appendSql(" then 1 else null end");
            } else // Tuple counts are supported
            {
                renderTupleCountSupported(sqlAppender, filter, translator, caseWrapper, tuple, expressions, dialect.requiresParensForTupleCounts());
            }
        } else {
            renderSimpleArgument(sqlAppender, filter, translator, caseWrapper, arg);
        }
    }
    sqlAppender.appendSql(')');
    if (filter != null && !caseWrapper) {
        translator.getCurrentClauseStack().push(Clause.WHERE);
        sqlAppender.appendSql(" filter (where ");
        filter.accept(translator);
        sqlAppender.appendSql(')');
        translator.getCurrentClauseStack().pop();
    }
}
Also used : Distinct(org.hibernate.sql.ast.tree.expression.Distinct) Expression(org.hibernate.sql.ast.tree.expression.Expression) FunctionExpression(org.hibernate.sql.ast.tree.expression.FunctionExpression) SqlTuple(org.hibernate.sql.ast.tree.expression.SqlTuple) List(java.util.List) SqlAstNode(org.hibernate.sql.ast.tree.SqlAstNode)

Example 37 with Expression

use of org.hibernate.sql.ast.tree.expression.Expression in project hibernate-orm by hibernate.

the class AvgFunction method render.

@Override
public void render(SqlAppender sqlAppender, List<? extends SqlAstNode> sqlAstArguments, Predicate filter, SqlAstTranslator<?> translator) {
    final boolean caseWrapper = filter != null && !translator.supportsFilterClause();
    sqlAppender.appendSql("avg(");
    final Expression arg;
    if (sqlAstArguments.get(0) instanceof Distinct) {
        sqlAppender.appendSql("distinct ");
        arg = ((Distinct) sqlAstArguments.get(0)).getExpression();
    } else {
        arg = (Expression) sqlAstArguments.get(0);
    }
    if (caseWrapper) {
        translator.getCurrentClauseStack().push(Clause.WHERE);
        sqlAppender.appendSql("case when ");
        filter.accept(translator);
        translator.getCurrentClauseStack().pop();
        sqlAppender.appendSql(" then ");
        renderArgument(sqlAppender, translator, arg);
        sqlAppender.appendSql(" else null end)");
    } else {
        renderArgument(sqlAppender, translator, arg);
        sqlAppender.appendSql(')');
        if (filter != null) {
            translator.getCurrentClauseStack().push(Clause.WHERE);
            sqlAppender.appendSql(" filter (where ");
            filter.accept(translator);
            sqlAppender.appendSql(')');
            translator.getCurrentClauseStack().pop();
        }
    }
}
Also used : Distinct(org.hibernate.sql.ast.tree.expression.Distinct) Expression(org.hibernate.sql.ast.tree.expression.Expression)

Example 38 with Expression

use of org.hibernate.sql.ast.tree.expression.Expression in project hibernate-orm by hibernate.

the class ListaggFunction method render.

@Override
public void render(SqlAppender sqlAppender, List<? extends SqlAstNode> sqlAstArguments, Predicate filter, List<SortSpecification> withinGroup, SqlAstTranslator<?> translator) {
    final boolean caseWrapper = filter != null && !translator.supportsFilterClause();
    sqlAppender.appendSql("listagg(");
    final SqlAstNode firstArg = sqlAstArguments.get(0);
    final Expression arg;
    if (firstArg instanceof Distinct) {
        sqlAppender.appendSql("distinct ");
        arg = ((Distinct) firstArg).getExpression();
    } else {
        arg = (Expression) firstArg;
    }
    if (caseWrapper) {
        sqlAppender.appendSql("case when ");
        translator.getCurrentClauseStack().push(Clause.WHERE);
        filter.accept(translator);
        translator.getCurrentClauseStack().pop();
        sqlAppender.appendSql(" then ");
        arg.accept(translator);
        sqlAppender.appendSql(" else null end");
    } else {
        arg.accept(translator);
    }
    if (sqlAstArguments.size() != 1) {
        sqlAppender.appendSql(',');
        sqlAstArguments.get(1).accept(translator);
    }
    sqlAppender.appendSql(')');
    if (withinGroup != null && !withinGroup.isEmpty()) {
        translator.getCurrentClauseStack().push(Clause.WITHIN_GROUP);
        sqlAppender.appendSql(" within group (order by ");
        withinGroup.get(0).accept(translator);
        for (int i = 1; i < withinGroup.size(); i++) {
            sqlAppender.appendSql(',');
            withinGroup.get(i).accept(translator);
        }
        sqlAppender.appendSql(')');
        translator.getCurrentClauseStack().pop();
    } else if (emptyWithinReplacement != null) {
        sqlAppender.appendSql(' ');
        sqlAppender.appendSql(emptyWithinReplacement);
    }
    if (!caseWrapper && filter != null) {
        translator.getCurrentClauseStack().push(Clause.WHERE);
        sqlAppender.appendSql(" filter (where ");
        filter.accept(translator);
        sqlAppender.appendSql(')');
        translator.getCurrentClauseStack().pop();
    }
}
Also used : Distinct(org.hibernate.sql.ast.tree.expression.Distinct) Expression(org.hibernate.sql.ast.tree.expression.Expression) SqlAstNode(org.hibernate.sql.ast.tree.SqlAstNode)

Example 39 with Expression

use of org.hibernate.sql.ast.tree.expression.Expression in project hibernate-orm by hibernate.

the class SQLServerFormatEmulation method render.

@Override
public void render(SqlAppender sqlAppender, List<? extends SqlAstNode> arguments, SqlAstTranslator<?> walker) {
    final Expression datetime = (Expression) arguments.get(0);
    final boolean isTime = TypeConfiguration.getSqlTemporalType(datetime.getExpressionType()) == TemporalType.TIME;
    final Format format = (Format) arguments.get(1);
    sqlAppender.appendSql("format(");
    if (isTime) {
        sqlAppender.appendSql("cast(");
        datetime.accept(walker);
        sqlAppender.appendSql(" as datetime)");
    } else {
        datetime.accept(walker);
    }
    sqlAppender.appendSql(",'");
    dialect.appendDatetimeFormat(sqlAppender, format.getFormat());
    sqlAppender.appendSql("')");
}
Also used : Format(org.hibernate.sql.ast.tree.expression.Format) Expression(org.hibernate.sql.ast.tree.expression.Expression)

Example 40 with Expression

use of org.hibernate.sql.ast.tree.expression.Expression in project hibernate-orm by hibernate.

the class EntityValuedPathInterpretation method from.

public static <T> EntityValuedPathInterpretation<T> from(NavigablePath navigablePath, TableGroup tableGroup, ModelPart resultModelPart, EntityValuedModelPart mapping, EntityValuedModelPart treatedMapping, SqmToSqlAstConverter sqlAstCreationState) {
    final SqlExpressionResolver sqlExprResolver = sqlAstCreationState.getSqlExpressionResolver();
    final SessionFactoryImplementor sessionFactory = sqlAstCreationState.getCreationContext().getSessionFactory();
    final Expression sqlExpression;
    if (resultModelPart == null) {
        final EntityMappingType entityMappingType = mapping.getEntityMappingType();
        final EntityIdentifierMapping identifierMapping = entityMappingType.getIdentifierMapping();
        final EntityDiscriminatorMapping discriminatorMapping = entityMappingType.getDiscriminatorMapping();
        final List<Expression> expressions = new ArrayList<>(entityMappingType.getJdbcTypeCount() + identifierMapping.getJdbcTypeCount() + (discriminatorMapping == null ? 0 : 1));
        final TableGroup parentTableGroup = tableGroup;
        final SelectableConsumer selectableConsumer = (selectionIndex, selectableMapping) -> {
            final TableReference tableReference = parentTableGroup.resolveTableReference(navigablePath, selectableMapping.getContainingTableExpression(), false);
            expressions.add(sqlExprResolver.resolveSqlExpression(createColumnReferenceKey(tableReference, selectableMapping.getSelectionExpression()), processingState -> new ColumnReference(tableReference, selectableMapping, sessionFactory)));
        };
        identifierMapping.forEachSelectable(selectableConsumer);
        if (discriminatorMapping != null) {
            discriminatorMapping.forEachSelectable(selectableConsumer);
        }
        entityMappingType.forEachSelectable(selectableConsumer);
        sqlExpression = new SqlTuple(expressions, entityMappingType);
    } else {
        if (resultModelPart instanceof BasicValuedModelPart) {
            final BasicValuedModelPart basicValuedModelPart = (BasicValuedModelPart) resultModelPart;
            final TableReference tableReference = tableGroup.resolveTableReference(navigablePath, basicValuedModelPart.getContainingTableExpression());
            sqlExpression = sqlExprResolver.resolveSqlExpression(createColumnReferenceKey(tableReference, basicValuedModelPart.getSelectionExpression()), processingState -> new ColumnReference(tableReference, basicValuedModelPart, sessionFactory));
        } else {
            final List<Expression> expressions = new ArrayList<>(resultModelPart.getJdbcTypeCount());
            resultModelPart.forEachSelectable((selectionIndex, selectableMapping) -> {
                final TableReference tableReference = tableGroup.resolveTableReference(navigablePath, selectableMapping.getContainingTableExpression());
                expressions.add(sqlExprResolver.resolveSqlExpression(createColumnReferenceKey(tableReference, selectableMapping.getSelectionExpression()), processingState -> new ColumnReference(tableReference, selectableMapping, sessionFactory)));
            });
            sqlExpression = new SqlTuple(expressions, resultModelPart);
        }
    }
    return new EntityValuedPathInterpretation<>(sqlExpression, navigablePath, tableGroup, treatedMapping);
}
Also used : BasicValuedModelPart(org.hibernate.metamodel.mapping.BasicValuedModelPart) DomainResultCreationState(org.hibernate.sql.results.graph.DomainResultCreationState) SqlTupleContainer(org.hibernate.sql.ast.tree.expression.SqlTupleContainer) ColumnReference(org.hibernate.sql.ast.tree.expression.ColumnReference) EntityValuedModelPart(org.hibernate.metamodel.mapping.EntityValuedModelPart) EntityMappingType(org.hibernate.metamodel.mapping.EntityMappingType) ArrayList(java.util.ArrayList) TableReference(org.hibernate.sql.ast.tree.from.TableReference) ModelPart(org.hibernate.metamodel.mapping.ModelPart) EntityAssociationMapping(org.hibernate.metamodel.mapping.EntityAssociationMapping) ToOneAttributeMapping(org.hibernate.metamodel.mapping.internal.ToOneAttributeMapping) SessionFactoryImplementor(org.hibernate.engine.spi.SessionFactoryImplementor) Assignable(org.hibernate.sql.ast.tree.update.Assignable) NavigablePath(org.hibernate.query.spi.NavigablePath) SqmEntityValuedSimplePath(org.hibernate.query.sqm.tree.domain.SqmEntityValuedSimplePath) Expression(org.hibernate.sql.ast.tree.expression.Expression) EntityDiscriminatorMapping(org.hibernate.metamodel.mapping.EntityDiscriminatorMapping) SqmToSqlAstConverter(org.hibernate.query.sqm.sql.SqmToSqlAstConverter) SqlAstWalker(org.hibernate.sql.ast.SqlAstWalker) SqlExpressionResolver(org.hibernate.sql.ast.spi.SqlExpressionResolver) Consumer(java.util.function.Consumer) EntityIdentifierMapping(org.hibernate.metamodel.mapping.EntityIdentifierMapping) List(java.util.List) SqlTuple(org.hibernate.sql.ast.tree.expression.SqlTuple) Collections(java.util.Collections) MappingModelExpressible(org.hibernate.metamodel.mapping.MappingModelExpressible) SelectableConsumer(org.hibernate.metamodel.mapping.SelectableConsumer) TableGroup(org.hibernate.sql.ast.tree.from.TableGroup) SqlExpressionResolver.createColumnReferenceKey(org.hibernate.sql.ast.spi.SqlExpressionResolver.createColumnReferenceKey) TableGroup(org.hibernate.sql.ast.tree.from.TableGroup) BasicValuedModelPart(org.hibernate.metamodel.mapping.BasicValuedModelPart) SelectableConsumer(org.hibernate.metamodel.mapping.SelectableConsumer) SessionFactoryImplementor(org.hibernate.engine.spi.SessionFactoryImplementor) ArrayList(java.util.ArrayList) EntityDiscriminatorMapping(org.hibernate.metamodel.mapping.EntityDiscriminatorMapping) TableReference(org.hibernate.sql.ast.tree.from.TableReference) SqlExpressionResolver(org.hibernate.sql.ast.spi.SqlExpressionResolver) Expression(org.hibernate.sql.ast.tree.expression.Expression) EntityIdentifierMapping(org.hibernate.metamodel.mapping.EntityIdentifierMapping) SqlTuple(org.hibernate.sql.ast.tree.expression.SqlTuple) EntityMappingType(org.hibernate.metamodel.mapping.EntityMappingType) ColumnReference(org.hibernate.sql.ast.tree.expression.ColumnReference)

Aggregations

Expression (org.hibernate.sql.ast.tree.expression.Expression)130 CaseSearchedExpression (org.hibernate.sql.ast.tree.expression.CaseSearchedExpression)68 CaseSimpleExpression (org.hibernate.sql.ast.tree.expression.CaseSimpleExpression)67 BinaryArithmeticExpression (org.hibernate.sql.ast.tree.expression.BinaryArithmeticExpression)62 SqlSelectionExpression (org.hibernate.sql.ast.tree.expression.SqlSelectionExpression)57 ModifiedSubQueryExpression (org.hibernate.sql.ast.tree.expression.ModifiedSubQueryExpression)54 SelfRenderingExpression (org.hibernate.sql.ast.tree.expression.SelfRenderingExpression)54 ColumnReference (org.hibernate.sql.ast.tree.expression.ColumnReference)42 SelfRenderingFunctionSqlAstExpression (org.hibernate.query.sqm.function.SelfRenderingFunctionSqlAstExpression)37 SqlTuple (org.hibernate.sql.ast.tree.expression.SqlTuple)35 SqmExpression (org.hibernate.query.sqm.tree.expression.SqmExpression)34 SelfRenderingSqlFragmentExpression (org.hibernate.sql.ast.tree.expression.SelfRenderingSqlFragmentExpression)33 SelfRenderingAggregateFunctionSqlAstExpression (org.hibernate.query.sqm.function.SelfRenderingAggregateFunctionSqlAstExpression)32 ArrayList (java.util.ArrayList)31 SqmModifiedSubQueryExpression (org.hibernate.query.sqm.tree.expression.SqmModifiedSubQueryExpression)31 TableGroup (org.hibernate.sql.ast.tree.from.TableGroup)28 TableReference (org.hibernate.sql.ast.tree.from.TableReference)25 SessionFactoryImplementor (org.hibernate.engine.spi.SessionFactoryImplementor)23 ComparisonPredicate (org.hibernate.sql.ast.tree.predicate.ComparisonPredicate)23 NavigablePath (org.hibernate.query.spi.NavigablePath)21