Skip to content

Commit

Permalink
Fix count query creation for HQL when using CTE.
Browse files Browse the repository at this point in the history
Closes spring-projects#3504
Original pull request spring-projects#3508
  • Loading branch information
christophstrobl authored and schauder committed Jun 13, 2024
1 parent 59ac57d commit 0f6736f
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 1 deletion.
Original file line number Diff line number Diff line change
Expand Up @@ -93,7 +93,7 @@ public boolean hasConstructorExpression() {
*/
private static boolean isSubquery(ParserRuleContext ctx) {

if (ctx instanceof HqlParser.SubqueryContext) {
if (ctx instanceof HqlParser.SubqueryContext || ctx instanceof HqlParser.CteContext) {
return true;
} else if (ctx instanceof HqlParser.SelectStatementContext) {
return false;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -500,6 +500,36 @@ select count(user) from User user
""");
}

@Test // GH-3504
void createCountWithCteShouldWork() {

String countQuery = createCountQueryFor("""
WITH maxId AS(select max(sr.snapshot.id) snapshotId from SnapshotReference sr
where sr.id.selectionId = ?1 and sr.enabled
group by sr.userId)
select sr from maxId m join SnapshotReference sr on sr.snapshot.id = m.snapshotId
""");

assertThat(countQuery).startsWith("WITH maxId AS(select max(sr.snapshot.id) snapshotId from SnapshotReference sr")
.endsWith("select count(m) from maxId m join SnapshotReference sr on sr.snapshot.id = m.snapshotId");
}

@Test // GH-3504
void createSortedQueryWithCteShouldWork() {

String sortedQuery = createQueryFor("""
WITH maxId AS(select max(sr.snapshot.id) snapshotId from SnapshotReference sr
where sr.id.selectionId = ?1 and sr.enabled
group by sr.userId)
select sr from maxId m join SnapshotReference sr on sr.snapshot.id = m.snapshotId
""", Sort.by("sr.snapshot"));

assertThat(sortedQuery).startsWith(
"WITH maxId AS(select max(sr.snapshot.id) snapshotId from SnapshotReference sr where sr.id.selectionId = ?1 and sr.enabled group by sr.userId )")
.endsWith(
"select sr from maxId m join SnapshotReference sr on sr.snapshot.id = m.snapshotId order by sr.snapshot asc");
}

@Test
void createCountQuerySupportsLineBreaksInSelectClause() {

Expand Down

0 comments on commit 0f6736f

Please sign in to comment.