Skip to content

HHH-19396 cannot select the same column twice with different aliases while using cte #10158

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Draft
wants to merge 2 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -1915,6 +1915,11 @@ public QuerySpec visitQuerySpec(SqmQuerySpec<?> sqmQuerySpec) {
final boolean oldInNestedContext = inNestedContext;
inNestedContext = false;

final boolean originalDeduplicateSelectionItems = deduplicateSelectionItems;
sqmQueryPartStack.push( sqmQuerySpec );
// In sub-queries, we can never deduplicate the selection items as that might change semantics
deduplicateSelectionItems = false;

final SqlAstQueryPartProcessingStateImpl processingState;
if ( trackAliasedNodePositions( sqmQuerySpec ) ) {
processingState = new SqlAstQueryPartProcessingStateImpl(
Expand All @@ -1936,10 +1941,6 @@ public QuerySpec visitQuerySpec(SqmQuerySpec<?> sqmQuerySpec) {
);
}

final boolean originalDeduplicateSelectionItems = deduplicateSelectionItems;
sqmQueryPartStack.push( sqmQuerySpec );
// In sub-queries, we can never deduplicate the selection items as that might change semantics
deduplicateSelectionItems = false;
pushProcessingState( processingState );
queryTransformers.push( new ArrayList<>() );

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
import org.hibernate.query.criteria.JpaCteCriteriaAttribute;
import org.hibernate.query.criteria.JpaCteCriteriaType;
import org.hibernate.query.sqm.SqmBindableType;
import org.hibernate.query.sqm.tree.select.SqmSelectClause;
import org.hibernate.query.sqm.tuple.internal.AnonymousTupleSimpleSqmPathSource;
import org.hibernate.query.sqm.tuple.internal.AnonymousTupleType;
import org.hibernate.query.sqm.tuple.internal.CteTupleTableGroupProducer;
Expand All @@ -34,13 +35,14 @@ public class SqmCteTable<T> extends AnonymousTupleType<T> implements JpaCteCrite
private SqmCteTable(
String name,
SqmCteStatement<T> cteStatement,
SqmSelectableNode<?>[] sqmSelectableNodes) {
super( sqmSelectableNodes );
SqmSelectableNode<?>[] sqmSelectableNodes,
List<String> aliases) {
super( sqmSelectableNodes, aliases );
this.name = name;
this.cteStatement = cteStatement;
final List<SqmCteTableColumn> columns = new ArrayList<>( componentCount() );
for ( int i = 0; i < componentCount(); i++ ) {
columns.add( new SqmCteTableColumn( this, getComponentName(i), get(i) ) );
columns.add( new SqmCteTableColumn( this, aliases.get(i), get(i) ) );
}
this.columns = columns;
}
Expand All @@ -49,12 +51,20 @@ public static <X> SqmCteTable<X> createStatementTable(
String name,
SqmCteStatement<X> cteStatement,
SqmSelectQuery<X> selectStatement) {
final SqmSelectableNode<?>[] sqmSelectableNodes = selectStatement.getQueryPart()
final SqmSelectClause selectClause = selectStatement.getQueryPart()
.getFirstQuerySpec()
.getSelectClause()
.getSelectClause();
final SqmSelectableNode<?>[] sqmSelectableNodes = selectClause
.getSelectionItems()
.toArray( SqmSelectableNode[]::new );
return new SqmCteTable<>( name, cteStatement, sqmSelectableNodes );
final var aliases = new ArrayList<String>();
for (final var selection : selectClause.getSelections()) {
final var alias = selection.getAlias();
selection.getSelectableNode().visitSubSelectableNodes( node ->
aliases.add( alias == null ? node.getAlias() : alias )
);
}
return new SqmCteTable<>( name, cteStatement, sqmSelectableNodes, aliases );
}

@Override
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,10 @@ public AnonymousTupleType(SqmSubQuery<T> subQuery) {
}

public AnonymousTupleType(SqmSelectableNode<?>[] components) {
this(components, null);
}

public AnonymousTupleType(SqmSelectableNode<?>[] components, List<String> aliases) {
expressibles = new SqmBindableType<?>[components.length];
componentSourcePaths = new NavigablePath[components.length];
for ( int i = 0; i < components.length; i++ ) {
Expand All @@ -74,7 +78,10 @@ public AnonymousTupleType(SqmSelectableNode<?>[] components) {
componentIndexMap = linkedMapOfSize( components.length );
for ( int i = 0; i < components.length; i++ ) {
final SqmSelectableNode<?> component = components[i];
final String alias = component.getAlias();
String alias = aliases == null ? null : aliases.get( i );
if ( alias == null ) {
alias = component.getAlias();
}
if ( alias == null ) {
throw new SemanticException( "Select item at position " + (i+1) + " in select list has no alias"
+ " (aliases are required in CTEs and in subqueries occurring in from clause)" );
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
/*
* SPDX-License-Identifier: Apache-2.0
* Copyright Red Hat Inc. and Hibernate Authors
*/
package org.hibernate.orm.test.subquery;

import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
import jakarta.persistence.Tuple;
import jakarta.persistence.TupleElement;
import org.hibernate.testing.orm.junit.DomainModel;
import org.hibernate.testing.orm.junit.JiraKey;
import org.hibernate.testing.orm.junit.SessionFactory;
import org.hibernate.testing.orm.junit.SessionFactoryScope;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;

import static java.util.stream.Collectors.toSet;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.jupiter.api.Assertions.assertEquals;

@DomainModel(annotatedClasses = MultipleIdenticalColumnsInSubqueryTest.Something.class)
@SessionFactory
@JiraKey("HHH-19396")
class MultipleIdenticalColumnsInSubqueryTest {

@BeforeEach
void init(SessionFactoryScope scope) {
scope.inTransaction( session -> session.persist( new Something() ) );
}

@AfterEach
void clean(SessionFactoryScope scope) {
scope.inTransaction( session -> session.createMutationQuery( "delete from Something" ).executeUpdate() );
}

@Test
void CTE_with_same_column_selected_twice(SessionFactoryScope scope) {
var r = scope.fromSession( session ->
session.createSelectionQuery(
"WITH S0 AS (SELECT foo AS foo2, foo AS foo FROM Something)" +
"SELECT S0_0.foo AS foo FROM S0 AS S0_0",
String.class ).getSingleResult() );
assertEquals( "a", r );
}

@Test
void CTE_with_same_column_selected_twice_some_aliases_removed(SessionFactoryScope scope) {
var r = scope.fromSession( session ->
session.createSelectionQuery(
"WITH S0 AS (SELECT foo AS foo, foo AS foo2 FROM Something)" +
"SELECT foo AS foo FROM S0",
String.class ).getSingleResult() );
assertEquals( "a", r );
}

@Test
void simple_query_with_same_column_selected_twice(SessionFactoryScope scope) {
var tuple = scope.fromSession( session ->
session.createSelectionQuery(
"SELECT foo AS foo, foo as foo2 FROM Something",
Tuple.class ).getSingleResult() );
assertThat( tuple.getElements().stream().map( TupleElement::getAlias ).collect( toSet() ) )
.containsExactlyInAnyOrder( "foo", "foo2" );
}

@Entity(name = "Something")
static class Something {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String foo = "a";
}
}