From d28d214ec1c52ffd5e3ba1fc32aa31d5d03c0bac Mon Sep 17 00:00:00 2001 From: Andrea Boriero Date: Wed, 4 Dec 2024 15:09:06 +0100 Subject: [PATCH] HHH-13612 Quoted table name in FROM clause in @Formula gets wrongly qualified with generated alias --- .../main/java/org/hibernate/sql/Template.java | 16 +++++++++++++--- 1 file changed, 13 insertions(+), 3 deletions(-) diff --git a/hibernate-core/src/main/java/org/hibernate/sql/Template.java b/hibernate-core/src/main/java/org/hibernate/sql/Template.java index 23d9e4a8ed..7d242bb8d1 100644 --- a/hibernate-core/src/main/java/org/hibernate/sql/Template.java +++ b/hibernate-core/src/main/java/org/hibernate/sql/Template.java @@ -167,8 +167,11 @@ public final class Template { boolean hasMore = tokens.hasMoreTokens(); String nextToken = hasMore ? tokens.nextToken() : null; + String token = null; + String previousToken; while ( hasMore ) { - String token = nextToken; + previousToken = token; + token = nextToken; String lcToken = token.toLowerCase(Locale.ROOT); hasMore = tokens.hasMoreTokens(); nextToken = hasMore ? tokens.nextToken() : null; @@ -203,7 +206,9 @@ public final class Template { else { isOpenQuote = false; } - if ( isOpenQuote ) { + if ( isOpenQuote + && !inFromClause // don't want to append alias to tokens inside the from clause + && notEndsWithDot( previousToken ) ) { result.append( alias ).append( '.' ); } } @@ -232,7 +237,8 @@ public final class Template { result.append(token); inExtractOrTrim = true; } - else if ( isIdentifier(token) + else if ( !inFromClause // don't want to append alias to tokens inside the from clause + && isIdentifier( token ) && !isFunctionOrKeyword( lcToken, nextToken, dialect, typeConfiguration ) && !isLiteral( lcToken, nextToken, sql, symbols, tokens ) ) { result.append(alias) @@ -268,6 +274,10 @@ public final class Template { return result.toString(); } + private static boolean notEndsWithDot(String token) { + return token == null || !token.endsWith( "." ); + } + private static boolean isLiteral( String lcToken, String next, String sqlWhereString, String symbols, StringTokenizer tokens) {