Skip to content

Commit 0f6736f

Browse files
christophstroblschauder
authored andcommitted
Fix count query creation for HQL when using CTE.
Closes #3504 Original pull request #3508
1 parent 59ac57d commit 0f6736f

File tree

2 files changed

+31
-1
lines changed

2 files changed

+31
-1
lines changed

spring-data-jpa/src/main/java/org/springframework/data/jpa/repository/query/HqlQueryTransformer.java

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -93,7 +93,7 @@ public boolean hasConstructorExpression() {
9393
*/
9494
private static boolean isSubquery(ParserRuleContext ctx) {
9595

96-
if (ctx instanceof HqlParser.SubqueryContext) {
96+
if (ctx instanceof HqlParser.SubqueryContext || ctx instanceof HqlParser.CteContext) {
9797
return true;
9898
} else if (ctx instanceof HqlParser.SelectStatementContext) {
9999
return false;

spring-data-jpa/src/test/java/org/springframework/data/jpa/repository/query/HqlQueryTransformerTests.java

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -500,6 +500,36 @@ select count(user) from User user
500500
""");
501501
}
502502

503+
@Test // GH-3504
504+
void createCountWithCteShouldWork() {
505+
506+
String countQuery = createCountQueryFor("""
507+
WITH maxId AS(select max(sr.snapshot.id) snapshotId from SnapshotReference sr
508+
where sr.id.selectionId = ?1 and sr.enabled
509+
group by sr.userId)
510+
select sr from maxId m join SnapshotReference sr on sr.snapshot.id = m.snapshotId
511+
""");
512+
513+
assertThat(countQuery).startsWith("WITH maxId AS(select max(sr.snapshot.id) snapshotId from SnapshotReference sr")
514+
.endsWith("select count(m) from maxId m join SnapshotReference sr on sr.snapshot.id = m.snapshotId");
515+
}
516+
517+
@Test // GH-3504
518+
void createSortedQueryWithCteShouldWork() {
519+
520+
String sortedQuery = createQueryFor("""
521+
WITH maxId AS(select max(sr.snapshot.id) snapshotId from SnapshotReference sr
522+
where sr.id.selectionId = ?1 and sr.enabled
523+
group by sr.userId)
524+
select sr from maxId m join SnapshotReference sr on sr.snapshot.id = m.snapshotId
525+
""", Sort.by("sr.snapshot"));
526+
527+
assertThat(sortedQuery).startsWith(
528+
"WITH maxId AS(select max(sr.snapshot.id) snapshotId from SnapshotReference sr where sr.id.selectionId = ?1 and sr.enabled group by sr.userId )")
529+
.endsWith(
530+
"select sr from maxId m join SnapshotReference sr on sr.snapshot.id = m.snapshotId order by sr.snapshot asc");
531+
}
532+
503533
@Test
504534
void createCountQuerySupportsLineBreaksInSelectClause() {
505535

0 commit comments

Comments
 (0)