Skip to content

Commit 9b680e7

Browse files
committed
Added complex function test cases for JSqlParserQueryEnhancer.
The added test cases make sure the new implementation does not have the issue described in spring-projects#2441. Closes spring-projects#2441
1 parent 1de082d commit 9b680e7

File tree

2 files changed

+36
-0
lines changed

2 files changed

+36
-0
lines changed

src/main/java/org/springframework/data/jpa/repository/query/JSqlParserQueryEnhancer.java

+11
Original file line numberDiff line numberDiff line change
@@ -139,6 +139,17 @@ private Set<String> getSelectionAliases(PlainSelect selectBody) {
139139
.collect(Collectors.toSet());
140140
}
141141

142+
/**
143+
* Returns the aliases used inside the selection part in the query.
144+
*
145+
* @return a {@literal Set} containing all found aliases. Guaranteed to be not {@literal null}.
146+
*/
147+
Set<String> getSelectionAliases() {
148+
Select selectStatement = parseSelectStatement(this.query.getQueryString());
149+
PlainSelect selectBody = (PlainSelect) selectStatement.getSelectBody();
150+
return this.getSelectionAliases(selectBody);
151+
}
152+
142153
/**
143154
* Returns the aliases used for {@code join}s.
144155
*

src/test/java/org/springframework/data/jpa/repository/query/QueryEnhancerUnitTests.java

+25
Original file line numberDiff line numberDiff line change
@@ -649,6 +649,31 @@ void detectsJoinAliasesCorrectly(String queryString, List<String> aliases) {
649649

650650
}
651651

652+
@Test // GH-2441
653+
void correctFunctionAliasWithComplexNestedFunctions() {
654+
String queryString = "\nSELECT \nCAST(('{' || string_agg(distinct array_to_string(c.institutes_ids, ','), ',') || '}') AS bigint[]) as institutesIds\nFROM\ncity c";
655+
StringQuery nativeQuery = new StringQuery(queryString, true);
656+
657+
JSqlParserQueryEnhancer queryEnhancer = (JSqlParserQueryEnhancer) getEnhancer(nativeQuery);
658+
659+
assertThat(queryEnhancer.getSelectionAliases()).contains("institutesIds");
660+
}
661+
662+
@Test // GH-2441
663+
void correctApplySortOnComplexNestedFunctionQuery() {
664+
String queryString = "SELECT dd.institutesIds FROM (\n" + " SELECT\n"
665+
+ " CAST(('{' || string_agg(distinct array_to_string(c.institutes_ids, ','), ',') || '}') AS bigint[]) as institutesIds\n"
666+
+ " FROM\n" + " city c\n"
667+
+ " ) dd";
668+
669+
StringQuery nativeQuery = new StringQuery(queryString, true);
670+
671+
QueryEnhancer queryEnhancer = getEnhancer(nativeQuery);
672+
673+
String result = queryEnhancer.applySorting(Sort.by(new Sort.Order(Sort.Direction.ASC, "institutesIds")));
674+
assertThat(result).containsIgnoringCase("order by dd.institutesIds");
675+
}
676+
652677
public static Stream<Arguments> detectsJoinAliasesCorrectlySource() {
653678
return Stream.of( //
654679
Arguments.of("select p from Person p left outer join x.foo b2_$ar", Collections.singletonList("b2_$ar")), //

0 commit comments

Comments
 (0)