Skip to content

Commit

Permalink
DATAJPA-960 - Fixed alias detection for queries not containing an alias.
Browse files Browse the repository at this point in the history
We're now more lenient against manually defined queries that do not contain aliases when adding order by clauses to them. The alias detection now doesn't accidentally pick up "where" anymore in case no primary alias is declared and the code applying the order by clause only qualifies the expressions created if there actually is an alias in the first place.
  • Loading branch information
odrotbohm committed Sep 7, 2016
1 parent 585ada9 commit 287104c
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 4 deletions.
Expand Up @@ -110,7 +110,7 @@ public abstract class QueryUtils {
builder.append(IDENTIFIER_GROUP); // Entity name, can be qualified (any
builder.append("(?:\\sas)*"); // exclude possible "as" keyword
builder.append("(?:\\s)+"); // at least one space separating
builder.append("(\\w*)"); // the actual alias
builder.append("(?!(?:where))(\\w*)"); // the actual alias

ALIAS_MATCH = compile(builder.toString(), CASE_INSENSITIVE);

Expand Down Expand Up @@ -199,8 +199,7 @@ public static String getQueryString(String template, String entityName) {
* @return
*/
public static String applySorting(String query, Sort sort) {

return applySorting(query, sort, DEFAULT_ALIAS);
return applySorting(query, sort, detectAlias(query));
}

/**
Expand Down Expand Up @@ -259,7 +258,8 @@ private static String getOrderClause(Set<String> joinAliases, String alias, Orde
}
}

String reference = qualifyReference ? String.format("%s.%s", alias, property) : property;
String reference = qualifyReference && StringUtils.hasText(alias) ? String.format("%s.%s", alias, property)
: property;
String wrapped = order.isIgnoreCase() ? String.format("lower(%s)", reference) : reference;

return String.format("%s %s", wrapped, toJpaDirection(order));
Expand Down
Expand Up @@ -352,6 +352,15 @@ public void detectsConstructorExpressionWithLineBreaks() {
assertThat(hasConstructorExpression("select new foo.bar.FooBar(\na.id) from DtoA a "), is(true));
}

/**
* @see DATAJPA-960
*/
@Test
public void doesNotQualifySortIfNoAliasDetected() {
assertThat(applySorting("from mytable where ?1 is null", new Sort("firstname")),
endsWith("order by firstname asc"));
}

private static void assertCountQuery(String originalQuery, String countQuery) {
assertThat(createCountQueryFor(originalQuery), is(countQuery));
}
Expand Down

0 comments on commit 287104c

Please sign in to comment.