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

Open
wants to merge 4 commits into
base: main
Choose a base branch
from
Open
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 @@ -1813,11 +1813,14 @@ public CteContainer visitCteContainer(SqmCteContainer consumer) {
final Collection<SqmCteStatement<?>> sqmCteStatements = consumer.getCteStatements();
cteContainer = new CteContainerImpl( cteContainer );
if ( !sqmCteStatements.isEmpty() ) {
final boolean originalDeduplicateSelectionItems = deduplicateSelectionItems;
deduplicateSelectionItems = false;
currentClauseStack.push( Clause.WITH );
for ( SqmCteStatement<?> sqmCteStatement : sqmCteStatements ) {
visitCteStatement( sqmCteStatement );
}
currentClauseStack.pop();
deduplicateSelectionItems = originalDeduplicateSelectionItems;
// Avoid leaking the processing state from CTEs to upper levels
lastPoppedFromClauseIndex = null;
lastPoppedProcessingState = null;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,6 @@
import org.hibernate.query.sqm.tuple.internal.CteTupleTableGroupProducer;
import org.hibernate.query.sqm.SqmPathSource;
import org.hibernate.query.sqm.tree.select.SqmSelectQuery;
import org.hibernate.query.sqm.tree.select.SqmSelectableNode;
import org.hibernate.sql.ast.spi.FromClauseAccess;
import org.hibernate.sql.ast.spi.SqlSelection;
import org.hibernate.type.BasicType;
Expand All @@ -34,8 +33,8 @@ public class SqmCteTable<T> extends AnonymousTupleType<T> implements JpaCteCrite
private SqmCteTable(
String name,
SqmCteStatement<T> cteStatement,
SqmSelectableNode<?>[] sqmSelectableNodes) {
super( sqmSelectableNodes );
SqmSelectQuery<T> selectStatement) {
super(selectStatement);
this.name = name;
this.cteStatement = cteStatement;
final List<SqmCteTableColumn> columns = new ArrayList<>( componentCount() );
Expand All @@ -49,12 +48,7 @@ public static <X> SqmCteTable<X> createStatementTable(
String name,
SqmCteStatement<X> cteStatement,
SqmSelectQuery<X> selectStatement) {
final SqmSelectableNode<?>[] sqmSelectableNodes = selectStatement.getQueryPart()
.getFirstQuerySpec()
.getSelectClause()
.getSelectionItems()
.toArray( SqmSelectableNode[]::new );
return new SqmCteTable<>( name, cteStatement, sqmSelectableNodes );
return new SqmCteTable<>( name, cteStatement, selectStatement );
}

@Override
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,13 +22,14 @@
import org.hibernate.query.sqm.SqmPathSource;
import org.hibernate.query.sqm.tree.domain.SqmDomainType;
import org.hibernate.query.sqm.tree.domain.SqmPluralPersistentAttribute;
import org.hibernate.query.sqm.tree.select.SqmSelectQuery;
import org.hibernate.query.sqm.tree.select.SqmSelection;
import org.hibernate.query.sqm.tuple.TupleType;
import org.hibernate.query.SemanticException;
import org.hibernate.query.sqm.SqmExpressible;
import org.hibernate.query.sqm.tree.domain.SqmPath;
import org.hibernate.query.sqm.tree.select.SqmSelectClause;
import org.hibernate.query.sqm.tree.select.SqmSelectableNode;
import org.hibernate.query.sqm.tree.select.SqmSubQuery;
import org.hibernate.spi.NavigablePath;
import org.hibernate.sql.ast.spi.FromClauseAccess;
import org.hibernate.sql.ast.spi.SqlSelection;
Expand All @@ -55,26 +56,50 @@ public class AnonymousTupleType<T>
private final String[] componentNames;
private final Map<String, Integer> componentIndexMap;

public AnonymousTupleType(SqmSubQuery<T> subQuery) {
this( extractSqmExpressibles( subQuery ) );
}
public AnonymousTupleType(SqmSelectQuery<T> selectQuery) {
final SqmSelectClause selectClause = selectQuery.getQueryPart()
.getFirstQuerySpec()
.getSelectClause();

public AnonymousTupleType(SqmSelectableNode<?>[] components) {
expressibles = new SqmBindableType<?>[components.length];
componentSourcePaths = new NavigablePath[components.length];
for ( int i = 0; i < components.length; i++ ) {
expressibles[i] = components[i].getNodeType();
if ( components[i] instanceof SqmPath<?> path ) {
componentSourcePaths[i] = path.getNavigablePath();
if ( selectClause == null || selectClause.getSelections().isEmpty() ) {
throw new IllegalArgumentException( "selectQuery has no selection items" );
}
// todo: right now, we "snapshot" the state of the selectQuery when creating this type, but maybe we shouldn't?
// i.e. what if the selectQuery changes later on? Or should we somehow mark the selectQuery to signal,
// that changes to the select clause are invalid after a certain point?

final List<SqmSelection<?>> selections = selectClause.getSelections();
final List<SqmSelectableNode<?>> selectableNodes = new ArrayList<>();
final List<String> aliases = new ArrayList<>();
if ( selections != null ) {
for ( SqmSelection<?> selection : selections ) {
selection.getSelectableNode().visitSubSelectableNodes( selectableNodes::add );

if ( selection.getSelectableNode().isCompoundSelection() ) {
selection.getSelectableNode().visitSubSelectableNodes( node ->
aliases.add( node.getAlias() )
);
}
else {
aliases.add( selection.getAlias() );
}
}
}

final SqmSelectableNode<?>[] components = selectableNodes.toArray(new SqmSelectableNode[0]);

expressibles = new SqmBindableType<?>[components.length];
componentSourcePaths = new NavigablePath[components.length];
componentNames = new String[components.length];
//noinspection unchecked
javaTypeDescriptor = (JavaType<T>) new ObjectArrayJavaType( getTypeDescriptors( components ) );
componentIndexMap = linkedMapOfSize( components.length );
for ( int i = 0; i < components.length; i++ ) {
final SqmSelectableNode<?> component = components[i];
final String alias = component.getAlias();
expressibles[i] = components[i].getNodeType();
if ( components[i] instanceof SqmPath<?> path ) {
componentSourcePaths[i] = path.getNavigablePath();
}
String alias = aliases.get( i );
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 Expand Up @@ -110,17 +135,6 @@ public String getTypeName() {
return SqmDomainType.super.getTypeName();
}

private static SqmSelectableNode<?>[] extractSqmExpressibles(SqmSubQuery<?> subQuery) {
final SqmSelectClause selectClause = subQuery.getQuerySpec().getSelectClause();
if ( selectClause == null || selectClause.getSelectionItems().isEmpty() ) {
throw new IllegalArgumentException( "subquery has no selection items" );
}
// todo: right now, we "snapshot" the state of the subquery when creating this type, but maybe we shouldn't?
// i.e. what if the subquery changes later on? Or should we somehow mark the subquery to signal,
// that changes to the select clause are invalid after a certain point?
return selectClause.getSelectionItems().toArray( SqmSelectableNode[]::new );
}

private static JavaType<?>[] getTypeDescriptors(SqmSelectableNode<?>[] components) {
final JavaType<?>[] typeDescriptors = new JavaType<?>[components.length];
for ( int i = 0; i < components.length; i++ ) {
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 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.DisplayName;
import org.junit.jupiter.api.Test;

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
@DisplayName("Temporary table with same column selected twice, deduplication should be turned off")
void CTE_with_same_column_selected_twice(SessionFactoryScope scope) {
var r = scope.fromSession( session ->
session.createSelectionQuery(
"WITH S0 AS (SELECT foo AS foo, foo AS bar FROM Something) SELECT foo AS foo FROM S0",
String.class ).getSingleResult() );
assertEquals( "a", r );
}

@Test
@DisplayName("Subquery with same column selected twice, deduplication should be turned off")
void CTE_with_same_column_selected_twice_some_aliases_removed(SessionFactoryScope scope) {
var r = scope.fromSession( session ->
session.createSelectionQuery(
"SELECT foo AS foo FROM (SELECT foo AS foo, foo AS foo2 FROM Something)",
String.class ).getSingleResult() );
assertEquals( "a", r );
}

@Test
@DisplayName("Simple query with same column selected twice, deduplication should be turned on")
void simple_query_with_same_column_selected_twice(SessionFactoryScope scope) {
var tuple = scope.fromSession( session ->
session.createSelectionQuery(
"SELECT foo AS foo, foo as bar FROM Something",
Tuple.class ).getSingleResult() );
assertEquals( 2, tuple.getElements().size() );
assertEquals( "a", tuple.get( "foo" ) );
assertEquals( "a", tuple.get( "bar" ) );
}

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