use of org.hibernate.sql.ast.tree.expression.QueryLiteral in project hibernate-orm by hibernate.
the class CteInsertHandler method execute.
@Override
public int execute(DomainQueryExecutionContext executionContext) {
final SqmInsertStatement<?> sqmInsertStatement = getSqmStatement();
final SessionFactoryImplementor factory = executionContext.getSession().getFactory();
final EntityPersister entityDescriptor = getEntityDescriptor().getEntityPersister();
final String explicitDmlTargetAlias;
if (sqmInsertStatement.getTarget().getExplicitAlias() == null) {
explicitDmlTargetAlias = "dml_target";
} else {
explicitDmlTargetAlias = sqmInsertStatement.getTarget().getExplicitAlias();
}
final MultiTableSqmMutationConverter sqmConverter = new MultiTableSqmMutationConverter(entityDescriptor, sqmInsertStatement, sqmInsertStatement.getTarget(), explicitDmlTargetAlias, domainParameterXref, executionContext.getQueryOptions(), executionContext.getSession().getLoadQueryInfluencers(), executionContext.getQueryParameterBindings(), factory);
final TableGroup insertingTableGroup = sqmConverter.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 int size = sqmStatement.getInsertionTargetPaths().size();
final List<Map.Entry<SqmCteTableColumn, Assignment>> targetPathColumns = new ArrayList<>(size);
final List<SqmCteTableColumn> targetPathSqmCteColumns = new ArrayList<>(size);
final Map<SqmParameter<?>, MappingModelExpressible<?>> paramTypeResolutions = new LinkedHashMap<>();
final NamedTableReference entityTableReference = new NamedTableReference(cteTable.getCteName(), TemporaryTable.DEFAULT_ALIAS, true, sessionFactory);
final InsertStatement insertStatement = new InsertStatement(entityTableReference);
final BaseSqmToSqlAstConverter.AdditionalInsertValues additionalInsertValues = sqmConverter.visitInsertionTargetPaths((assignable, columnReferences) -> {
// Find a matching cte table column and set that at the current index
for (SqmCteTableColumn column : cteTable.getColumns()) {
if (column.getType() == ((Expression) assignable).getExpressionType()) {
insertStatement.addTargetColumnReferences(columnReferences);
targetPathSqmCteColumns.add(column);
targetPathColumns.add(new AbstractMap.SimpleEntry<>(column, new Assignment(assignable, (Expression) assignable)));
return;
}
}
throw new IllegalStateException("Couldn't find matching cte column for: " + ((Expression) assignable).getExpressionType());
}, sqmInsertStatement, entityDescriptor, insertingTableGroup, (sqmParameter, mappingType, jdbcParameters) -> {
parameterResolutions.computeIfAbsent(sqmParameter, k -> new ArrayList<>(1)).add(jdbcParameters);
paramTypeResolutions.put(sqmParameter, mappingType);
});
final boolean assignsId = targetPathSqmCteColumns.contains(cteTable.getColumns().get(0));
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// Create the statement that represent the source for the entity cte
final Stack<SqlAstProcessingState> processingStateStack = sqmConverter.getProcessingStateStack();
final SqlAstProcessingState oldState = processingStateStack.pop();
final Statement queryStatement;
if (sqmInsertStatement instanceof SqmInsertSelectStatement) {
final QueryPart queryPart = sqmConverter.visitQueryPart(((SqmInsertSelectStatement<?>) sqmInsertStatement).getSelectQueryPart());
queryPart.visitQuerySpecs(querySpec -> {
// in which case we will fill the row_number column instead of the id column
if (additionalInsertValues.applySelections(querySpec, sessionFactory)) {
final SqmCteTableColumn rowNumberColumn = cteTable.getColumns().get(cteTable.getColumns().size() - 1);
final ColumnReference columnReference = new ColumnReference((String) null, rowNumberColumn.getColumnName(), false, null, null, (JdbcMapping) rowNumberColumn.getType(), sessionFactory);
insertStatement.getTargetColumnReferences().set(insertStatement.getTargetColumnReferences().size() - 1, columnReference);
targetPathSqmCteColumns.set(targetPathSqmCteColumns.size() - 1, rowNumberColumn);
}
if (!assignsId && entityDescriptor.getIdentifierGenerator() instanceof PostInsertIdentifierGenerator) {
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())));
}
});
queryStatement = new SelectStatement(queryPart);
} else {
final List<SqmValues> sqmValuesList = ((SqmInsertValuesStatement<?>) sqmInsertStatement).getValuesList();
final List<Values> valuesList = new ArrayList<>(sqmValuesList.size());
for (SqmValues sqmValues : sqmValuesList) {
final Values values = sqmConverter.visitValues(sqmValues);
additionalInsertValues.applyValues(values);
valuesList.add(values);
}
final QuerySpec querySpec = new QuerySpec(true);
final NavigablePath navigablePath = new NavigablePath(entityDescriptor.getRootPathName());
final List<String> columnNames = new ArrayList<>(targetPathColumns.size());
for (Map.Entry<SqmCteTableColumn, Assignment> entry : targetPathColumns) {
for (ColumnReference columnReference : entry.getValue().getAssignable().getColumnReferences()) {
columnNames.add(columnReference.getColumnExpression());
querySpec.getSelectClause().addSqlSelection(new SqlSelectionImpl(1, 0, columnReference));
}
}
final ValuesTableGroup valuesTableGroup = new ValuesTableGroup(navigablePath, entityDescriptor.getEntityPersister(), valuesList, insertingTableGroup.getPrimaryTableReference().getIdentificationVariable(), columnNames, true, factory);
querySpec.getFromClause().addRoot(valuesTableGroup);
queryStatement = new SelectStatement(querySpec);
}
processingStateStack.push(oldState);
sqmConverter.pruneTableGroupJoins();
if (!assignsId && entityDescriptor.getIdentifierGenerator() instanceof PostInsertIdentifierGenerator) {
// Add the row number to the assignments
final SqmCteTableColumn rowNumberColumn = cteTable.getColumns().get(cteTable.getColumns().size() - 1);
final ColumnReference columnReference = new ColumnReference((String) null, rowNumberColumn.getColumnName(), false, null, null, (JdbcMapping) rowNumberColumn.getType(), sessionFactory);
insertStatement.getTargetColumnReferences().add(columnReference);
targetPathSqmCteColumns.add(rowNumberColumn);
}
final CteTable entityCteTable = BaseSqmToSqlAstConverter.createCteTable(getCteTable(), targetPathSqmCteColumns, factory);
// Create the main query spec that will return the count of rows
final QuerySpec querySpec = new QuerySpec(true, 1);
final List<DomainResult<?>> domainResults = new ArrayList<>(1);
final SelectStatement statement = new SelectStatement(querySpec, domainResults);
final CteStatement entityCte;
if (additionalInsertValues.requiresRowNumberIntermediate()) {
final CteTable fullEntityCteTable = BaseSqmToSqlAstConverter.createCteTable(getCteTable(), factory);
final String baseTableName = "base_" + entityCteTable.getTableExpression();
final CteStatement baseEntityCte = new CteStatement(entityCteTable.withName(baseTableName), queryStatement, // The query cte will be reused multiple times
CteMaterialization.MATERIALIZED);
statement.addCteStatement(baseEntityCte);
final CteColumn rowNumberColumn = fullEntityCteTable.getCteColumns().get(fullEntityCteTable.getCteColumns().size() - 1);
final ColumnReference rowNumberColumnReference = new ColumnReference("e", rowNumberColumn.getColumnExpression(), false, null, null, rowNumberColumn.getJdbcMapping(), factory);
final CteColumn idColumn = fullEntityCteTable.getCteColumns().get(0);
final BasicValuedMapping idType = (BasicValuedMapping) idColumn.getJdbcMapping();
final Optimizer optimizer = ((OptimizableGenerator) entityDescriptor.getIdentifierGenerator()).getOptimizer();
final BasicValuedMapping integerType = (BasicValuedMapping) rowNumberColumn.getJdbcMapping();
final Expression rowNumberMinusOneModuloIncrement = new BinaryArithmeticExpression(new BinaryArithmeticExpression(rowNumberColumnReference, BinaryArithmeticOperator.SUBTRACT, new QueryLiteral<>(1, (BasicValuedMapping) rowNumberColumn.getJdbcMapping()), integerType), BinaryArithmeticOperator.MODULO, new QueryLiteral<>(optimizer.getIncrementSize(), integerType), integerType);
// Create the CTE that fetches a new sequence value for the row numbers that need it
{
final QuerySpec rowsWithSequenceQuery = new QuerySpec(true);
rowsWithSequenceQuery.getFromClause().addRoot(new CteTableGroup(new NamedTableReference(baseTableName, "e", false, factory)));
rowsWithSequenceQuery.getSelectClause().addSqlSelection(new SqlSelectionImpl(1, 0, rowNumberColumnReference));
final String fragment = ((BulkInsertionCapableIdentifierGenerator) entityDescriptor.getIdentifierGenerator()).determineBulkInsertionIdentifierGenerationSelectFragment(sessionFactory.getSqlStringGenerationContext());
rowsWithSequenceQuery.getSelectClause().addSqlSelection(new SqlSelectionImpl(2, 1, new SelfRenderingSqlFragmentExpression(fragment)));
rowsWithSequenceQuery.applyPredicate(new ComparisonPredicate(rowNumberMinusOneModuloIncrement, ComparisonOperator.EQUAL, new QueryLiteral<>(0, integerType)));
final CteTable rowsWithSequenceCteTable = new CteTable(ROW_NUMBERS_WITH_SEQUENCE_VALUE, Arrays.asList(rowNumberColumn, idColumn), sessionFactory);
final SelectStatement rowsWithSequenceStatement = new SelectStatement(rowsWithSequenceQuery);
final CteStatement rowsWithSequenceCte = new CteStatement(rowsWithSequenceCteTable, rowsWithSequenceStatement, // The query cte will be reused multiple times
CteMaterialization.MATERIALIZED);
statement.addCteStatement(rowsWithSequenceCte);
}
// Create the CTE that represents the entity cte
{
final QuerySpec entityQuery = new QuerySpec(true);
final NavigablePath navigablePath = new NavigablePath(baseTableName);
final TableGroup baseTableGroup = new TableGroupImpl(navigablePath, null, new NamedTableReference(baseTableName, "e", false, factory), null);
final TableGroup rowsWithSequenceTableGroup = new CteTableGroup(new NamedTableReference(ROW_NUMBERS_WITH_SEQUENCE_VALUE, "t", false, factory));
baseTableGroup.addTableGroupJoin(new TableGroupJoin(rowsWithSequenceTableGroup.getNavigablePath(), SqlAstJoinType.LEFT, rowsWithSequenceTableGroup, new ComparisonPredicate(new BinaryArithmeticExpression(rowNumberColumnReference, BinaryArithmeticOperator.SUBTRACT, rowNumberMinusOneModuloIncrement, integerType), ComparisonOperator.EQUAL, new ColumnReference("t", rowNumberColumn.getColumnExpression(), false, null, null, rowNumberColumn.getJdbcMapping(), factory))));
entityQuery.getFromClause().addRoot(baseTableGroup);
entityQuery.getSelectClause().addSqlSelection(new SqlSelectionImpl(1, 0, new BinaryArithmeticExpression(new ColumnReference("t", idColumn.getColumnExpression(), false, null, null, idColumn.getJdbcMapping(), factory), BinaryArithmeticOperator.ADD, new BinaryArithmeticExpression(rowNumberColumnReference, BinaryArithmeticOperator.SUBTRACT, new ColumnReference("t", rowNumberColumn.getColumnExpression(), false, null, null, rowNumberColumn.getJdbcMapping(), factory), integerType), idType)));
final CteTable finalEntityCteTable;
if (targetPathSqmCteColumns.contains(getCteTable().getColumns().get(0))) {
finalEntityCteTable = entityCteTable;
} else {
targetPathSqmCteColumns.add(0, getCteTable().getColumns().get(0));
finalEntityCteTable = BaseSqmToSqlAstConverter.createCteTable(getCteTable(), targetPathSqmCteColumns, factory);
}
final List<CteColumn> cteColumns = finalEntityCteTable.getCteColumns();
for (int i = 1; i < cteColumns.size(); i++) {
final CteColumn cteColumn = cteColumns.get(i);
entityQuery.getSelectClause().addSqlSelection(new SqlSelectionImpl(i + 1, i, new ColumnReference("e", cteColumn.getColumnExpression(), false, null, null, cteColumn.getJdbcMapping(), factory)));
}
final SelectStatement entityStatement = new SelectStatement(entityQuery);
entityCte = new CteStatement(finalEntityCteTable, entityStatement, // The query cte will be reused multiple times
CteMaterialization.MATERIALIZED);
statement.addCteStatement(entityCte);
}
} else if (!assignsId && entityDescriptor.getIdentifierGenerator() instanceof PostInsertIdentifierGenerator) {
final String baseTableName = "base_" + entityCteTable.getTableExpression();
final CteStatement baseEntityCte = new CteStatement(entityCteTable.withName(baseTableName), queryStatement, // The query cte will be reused multiple times
CteMaterialization.MATERIALIZED);
statement.addCteStatement(baseEntityCte);
targetPathSqmCteColumns.add(0, cteTable.getColumns().get(0));
final CteTable finalEntityCteTable = BaseSqmToSqlAstConverter.createCteTable(getCteTable(), targetPathSqmCteColumns, factory);
final QuerySpec finalQuerySpec = new QuerySpec(true);
final SelectStatement finalQueryStatement = new SelectStatement(finalQuerySpec);
entityCte = new CteStatement(finalEntityCteTable, finalQueryStatement, // The query cte will be reused multiple times
CteMaterialization.MATERIALIZED);
} else {
entityCte = new CteStatement(entityCteTable, queryStatement, // The query cte will be reused multiple times
CteMaterialization.MATERIALIZED);
statement.addCteStatement(entityCte);
}
// Add all CTEs
final String baseInsertCte = addDmlCtes(statement, entityCte, targetPathColumns, assignsId, sqmConverter, parameterResolutions, factory);
final Expression count = createCountStar(factory, sqmConverter);
domainResults.add(new BasicResult(0, null, ((SqlExpressible) count).getJdbcMapping().getJavaTypeDescriptor()));
querySpec.getSelectClause().addSqlSelection(new SqlSelectionImpl(1, 0, count));
querySpec.getFromClause().addRoot(new CteTableGroup(new NamedTableReference(// We want to return the insertion count of the base table
baseInsertCte, CTE_TABLE_IDENTIFIER, false, factory)));
// Execute the statement
final JdbcServices jdbcServices = factory.getJdbcServices();
final SqlAstTranslator<JdbcSelect> translator = jdbcServices.getJdbcEnvironment().getSqlAstTranslatorFactory().buildSelectTranslator(factory, statement);
final JdbcParameterBindings jdbcParameterBindings = SqmUtil.createJdbcParameterBindings(executionContext.getQueryParameterBindings(), domainParameterXref, SqmUtil.generateJdbcParamsXref(domainParameterXref, sqmConverter), factory.getRuntimeMetamodels().getMappingMetamodel(), navigablePath -> sqmConverter.getMutatingTableGroup(), new SqmParameterMappingModelResolutionAccess() {
@Override
@SuppressWarnings("unchecked")
public <T> MappingModelExpressible<T> getResolvedMappingModelType(SqmParameter<T> parameter) {
return (MappingModelExpressible<T>) paramTypeResolutions.get(parameter);
}
}, executionContext.getSession());
final JdbcSelect select = translator.translate(jdbcParameterBindings, executionContext.getQueryOptions());
executionContext.getSession().autoFlushIfRequired(select.getAffectedTableNames());
List<Object> list = jdbcServices.getJdbcSelectExecutor().list(select, jdbcParameterBindings, SqmJdbcExecutionContextAdapter.omittingLockingAndPaging(executionContext), row -> row[0], ListResultsConsumer.UniqueSemantic.NONE);
return ((Number) list.get(0)).intValue();
}
use of org.hibernate.sql.ast.tree.expression.QueryLiteral in project hibernate-orm by hibernate.
the class ExecuteWithTemporaryTableHelper method saveMatchingIdsIntoIdTable.
public static int saveMatchingIdsIntoIdTable(MultiTableSqmMutationConverter sqmConverter, Predicate suppliedPredicate, TemporaryTable idTable, Function<SharedSessionContractImplementor, String> sessionUidAccess, JdbcParameterBindings jdbcParameterBindings, ExecutionContext executionContext) {
final SessionFactoryImplementor factory = executionContext.getSession().getFactory();
final TableGroup mutatingTableGroup = sqmConverter.getMutatingTableGroup();
assert mutatingTableGroup.getModelPart() instanceof EntityMappingType;
final EntityMappingType mutatingEntityDescriptor = (EntityMappingType) mutatingTableGroup.getModelPart();
final NamedTableReference idTableReference = new NamedTableReference(idTable.getTableExpression(), InsertStatement.DEFAULT_ALIAS, false, factory);
final InsertStatement idTableInsert = new InsertStatement(idTableReference);
for (int i = 0; i < idTable.getColumns().size(); i++) {
final TemporaryTableColumn column = idTable.getColumns().get(i);
idTableInsert.addTargetColumnReferences(new ColumnReference(idTableReference, column.getColumnName(), // id columns cannot be formulas and cannot have custom read and write expressions
false, null, null, column.getJdbcMapping(), factory));
}
final QuerySpec matchingIdSelection = new QuerySpec(true, 1);
idTableInsert.setSourceSelectStatement(matchingIdSelection);
matchingIdSelection.getFromClause().addRoot(mutatingTableGroup);
mutatingEntityDescriptor.getIdentifierMapping().forEachSelectable((jdbcPosition, selection) -> {
final TableReference tableReference = mutatingTableGroup.resolveTableReference(mutatingTableGroup.getNavigablePath(), selection.getContainingTableExpression());
matchingIdSelection.getSelectClause().addSqlSelection(new SqlSelectionImpl(jdbcPosition, jdbcPosition + 1, sqmConverter.getSqlExpressionResolver().resolveSqlExpression(SqlExpressionResolver.createColumnReferenceKey(tableReference, selection.getSelectionExpression()), sqlAstProcessingState -> new ColumnReference(tableReference, selection, factory))));
});
if (idTable.getSessionUidColumn() != null) {
final int jdbcPosition = matchingIdSelection.getSelectClause().getSqlSelections().size();
matchingIdSelection.getSelectClause().addSqlSelection(new SqlSelectionImpl(jdbcPosition, jdbcPosition + 1, new QueryLiteral<>(sessionUidAccess.apply(executionContext.getSession()), (BasicValuedMapping) idTable.getSessionUidColumn().getJdbcMapping())));
}
matchingIdSelection.applyPredicate(suppliedPredicate);
return saveIntoTemporaryTable(idTableInsert, jdbcParameterBindings, executionContext);
}
use of org.hibernate.sql.ast.tree.expression.QueryLiteral in project hibernate-orm by hibernate.
the class IntegralTimestampaddFunction method convertedArgument.
private Expression convertedArgument(DurationUnit field, TemporalUnit unit, Expression magnitude) {
final BasicValuedMapping expressionType = (BasicValuedMapping) magnitude.getExpressionType();
final String conversionFactor = field.getUnit().conversionFactor(unit, dialect);
return conversionFactor.isEmpty() ? magnitude : new BinaryArithmeticExpression(magnitude, conversionFactor.charAt(0) == '*' ? BinaryArithmeticOperator.MULTIPLY : BinaryArithmeticOperator.DIVIDE, new QueryLiteral<>(expressionType.getExpressibleJavaType().fromString(conversionFactor.substring(1)), expressionType), expressionType);
}
use of org.hibernate.sql.ast.tree.expression.QueryLiteral in project hibernate-orm by hibernate.
the class SqlFunction method render.
@Override
public void render(SqlAppender sqlAppender, List<? extends SqlAstNode> arguments, SqlAstTranslator<?> walker) {
final QueryLiteral<String> sqlFragmentLiteral = (QueryLiteral<String>) arguments.get(0);
final String sqlFragment = sqlFragmentLiteral.getLiteralValue();
if (arguments.size() != 1) {
int index = 0;
for (int i = 1; i < arguments.size(); i++) {
final SqlAstNode argument = arguments.get(i);
final int paramIndex = sqlFragment.indexOf('?', index);
if (paramIndex == -1) {
throw new IllegalArgumentException("The SQL function passes an argument at index " + i + " but the fragment contains no placeholder for the argument: " + sqlFragment);
}
sqlAppender.append(sqlFragment, index, paramIndex);
argument.accept(walker);
index = paramIndex + 1;
}
} else {
sqlAppender.appendSql(sqlFragment);
}
}
use of org.hibernate.sql.ast.tree.expression.QueryLiteral in project hibernate-orm by hibernate.
the class BaseSqmToSqlAstConverter method resolveGroupOrOrderByExpression.
protected Expression resolveGroupOrOrderByExpression(SqmExpression<?> groupByClauseExpression) {
final int sqmPosition;
if (groupByClauseExpression instanceof SqmAliasedNodeRef) {
final int aliasedNodeOrdinal = ((SqmAliasedNodeRef) groupByClauseExpression).getPosition();
sqmPosition = aliasedNodeOrdinal - 1;
} else if (statement.getQuerySource() == SqmQuerySource.CRITERIA) {
// In JPA Criteria we could be using the same expression object for the group/order by and select item
// We try to find the select item position for this expression here which is not necessarily just an optimization.
// This is vital to enable the support for parameters in these expressions.
// Databases usually don't know if a parameter marker will have the same value as another parameter marker
// and due to that, a database usually complains when seeing something like
// `select ?, count(*) from dual group by ?` saying that there is a missing group by for the first `?`
// To avoid this issue, we determine the position and let the SqlAstTranslator handle the rest.
// Usually it will render `select ?, count(*) from dual group by 1` if supported
// or force rendering the parameter as literal instead so that the database can see the grouping is fine
final SqmQuerySpec<?> querySpec = currentSqmQueryPart.getFirstQuerySpec();
sqmPosition = indexOfExpression(querySpec.getSelectClause().getSelections(), groupByClauseExpression);
} else {
sqmPosition = -1;
}
if (sqmPosition != -1) {
final List<SqlSelection> selections = currentSqlSelectionCollector().getSelections(sqmPosition);
assert selections != null : String.format(Locale.ROOT, "No SqlSelections for SQM position `%s`", sqmPosition);
final List<Expression> expressions = new ArrayList<>(selections.size());
OUTER: for (int i = 0; i < selections.size(); i++) {
final SqlSelection selection = selections.get(i);
// which is, just like the identifier itself, also registered as selection
for (int j = 0; j < i; j++) {
if (selections.get(j) == selection) {
continue OUTER;
}
}
if (currentSqmQueryPart instanceof SqmQueryGroup<?>) {
// Reusing the SqlSelection for query groups would be wrong because the aliases do no exist
// So we have to use a literal expression in a new SqlSelection instance to refer to the position
expressions.add(new SqlSelectionExpression(new SqlSelectionImpl(selection.getJdbcResultSetIndex(), selection.getValuesArrayPosition(), new QueryLiteral<>(selection.getValuesArrayPosition(), basicType(Integer.class)))));
} else {
expressions.add(new SqlSelectionExpression(selection));
}
}
if (expressions.size() == 1) {
return expressions.get(0);
}
return new SqlTuple(expressions, null);
}
return (Expression) groupByClauseExpression.accept(this);
}
Aggregations