Fix count query creation for HQL when using CTE.

Closes #3504
Original pull request #3508
This commit is contained in:
Christoph Strobl
2024-06-13 11:01:16 +02:00
committed by Jens Schauder
parent 59ac57d798
commit 0f6736fc1a
2 changed files with 31 additions and 1 deletions

View File

@@ -93,7 +93,7 @@ class HqlQueryTransformer extends HqlQueryRenderer {
*/
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;

View File

@@ -500,6 +500,36 @@ class HqlQueryTransformerTests {
""");
}
@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() {