Skip to content

Fix alias detection in multi-line queries #2603

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -108,6 +108,7 @@ public abstract class QueryUtils {
Pattern.CASE_INSENSITIVE);

private static final Pattern NO_DIGITS = Pattern.compile("\\D+");
private static final Pattern LINE_BREAK = Pattern.compile("\\R+");

private static final String JOIN = "join\\s+(fetch\\s+)?" + IDENTIFIER + "\\s+(as\\s+)?" + IDENTIFIER_GROUP;
private static final Pattern JOIN_PATTERN = Pattern.compile(JOIN, Pattern.CASE_INSENSITIVE);
Expand Down Expand Up @@ -436,7 +437,7 @@ private static String toJpaDirection(Order order) {
public static String detectAlias(String query) {

String alias = null;
Matcher matcher = ALIAS_MATCH.matcher(removeSubqueries(query));
Matcher matcher = ALIAS_MATCH.matcher(removeSubqueries(removeLinebreaks(query)));
while (matcher.find()) {
alias = matcher.group(2);
}
Expand Down Expand Up @@ -491,6 +492,14 @@ static String removeSubqueries(String query) {
return sb.toString();
}

static String removeLinebreaks(String query) {
if (!StringUtils.hasText(query)) {
return query;
}

return LINE_BREAK.matcher(query).replaceAll(" ");
}

private static Integer findClose(final Integer open, final List<Integer> closes, final List<Boolean> closeMatches) {

for (int i = 0; i < closes.size(); i++) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -140,6 +140,9 @@ void detectsAliasCorrectly() {
assertThat(
detectAlias("from User u where (cast(:e1f2f3ectiveFrom as date) is null) OR :effectiveFrom >= u.createdAt"))
.isEqualTo("u");
assertThat(detectAlias(
"SELECT o\nFROM Order o\nAND EXISTS(SELECT 1\nFROM Vehicle vehicle\nWHERE vehicle.vehicleOrderId = o.id\nAND LOWER(COALESCE(vehicle.make, '')) LIKE :query)"))
.isEqualTo("o"); // GH-2563
}

@Test // GH-2260
Expand Down