This is an automated email from the ASF dual-hosted git repository.

borinquenkid pushed a commit to branch feat/sql-text-8.0.x
in repository https://gitbox.apache.org/repos/asf/grails-core.git

commit 383c139df2fda69642e29fc6e91d8cdc96ea5aad
Author: Walter Duque de Estrada <[email protected]>
AuthorDate: Thu Oct 22 14:30:28 2026 -0500

    Hibernate 7: one scanner for the query package, and keep a spaced 
sqlProjection alias and a bracket identifier with an apostrophe working
    
    Fixes #16717. Starts #16616 with its step 0.
    
    Three scanners in org.grails.orm.hibernate.query each decided on their own
    what to skip: HqlQueryContext.indexOfTopLevel and getCommas, 
SqlRestriction's
    placeholder scan, and SqlProjection.splitColumns. Every recent bug of this
    family was a rule mismatch between them (#16597, #16712, #16717).
    
    SqlText now owns the rules once and reads the text once: when an instance is
    created, each character is classified as plain text, quoted text or comment,
    and each plain character gets its parenthesis depth, so every later question
    (indexOfTopLevel, splitTopLevel, countTopLevel, plainIndexes,
    unwrapOuterParentheses, withoutTrailingComments, endsInLineComment) walks 
the
    two arrays and nothing rescans the string. The rules: string literals and
    quoted identifiers with a doubled quote for the quote; in native SQL also
    [bracket identifiers] with ]] and dollar-quoted strings; line and block
    comments; parentheses for a top-level position. The three scanners delegate
    to it, and HqlQueryContext creates one instance per operation instead of
    lowercasing and rescanning for the select, the from and the commas.
    
    The two defects of #16717:
    - A sqlProjection alias with a space broke a count over the projection:
      JpaProjectionAdapter gave a subquery selection a generated alias only when
      it had none, so the derived table of `createCriteria().count { projections
      { sqlProjection ... } }` was rendered as derived1_0(box width), which H2
      rejects. Nothing reads a subquery's selections by alias, so every subquery
      selection now gets a generated one; the main query keeps the caller's 
alias.
    - An apostrophe inside a bracket identifier swallowed the rest of the SQL,
      because quotes were tested before the bracket state. Inside brackets only
      brackets count now.
    
    Two behaviours improve as a side effect: the HQL projection count ignores a
    comma inside a comment or a backquoted identifier, and the HQL keyword 
search
    skips line comments. unwrapOuterParentheses is in place for #16719.
    
    SqlTextSpec holds one table per capability; SqlProjectionSpec and
    HqlQueryContextSpec gain the rows the fix adds; the sqlProjection 
integration
    spec gains the count over a spaced alias, which fails before the fix.
---
 .../orm/hibernate/query/HqlQueryContext.java       | 120 ++-----
 .../orm/hibernate/query/JpaProjectionAdapter.java  |   5 +-
 .../grails/orm/hibernate/query/SqlProjection.java  |  91 +-----
 .../grails/orm/hibernate/query/SqlRestriction.java |  61 +---
 .../org/grails/orm/hibernate/query/SqlText.java    | 349 +++++++++++++++++++++
 ...ibernateCriteriaBuilderSqlProjectionSpec.groovy |  17 +
 .../orm/hibernate/query/HqlQueryContextSpec.groovy |   3 +
 .../orm/hibernate/query/SqlProjectionSpec.groovy   |   2 +
 .../grails/orm/hibernate/query/SqlTextSpec.groovy  | 153 +++++++++
 9 files changed, 555 insertions(+), 246 deletions(-)

diff --git 
a/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/query/HqlQueryContext.java
 
b/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/query/HqlQueryContext.java
index 7d61b4d98a..4f40f3f5a4 100644
--- 
a/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/query/HqlQueryContext.java
+++ 
b/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/query/HqlQueryContext.java
@@ -187,9 +187,10 @@ public record HqlQueryContext(
     static @Nullable String getSingleProjectionClause(CharSequence hql) {
         if (hql == null) return null;
         String s = hql.toString().toLowerCase(Locale.ROOT).trim();
-        int selectIdx = indexOfSelect(s);
+        SqlText lower = SqlText.hql(s);
+        int selectIdx = indexOfSelect(lower);
         if (selectIdx < 0) return null;
-        int fromIdx = indexOfFrom(s, selectIdx);
+        int fromIdx = indexOfFrom(lower, selectIdx);
         return extractSelectClause(s, selectIdx, fromIdx);
     }
 
@@ -214,124 +215,40 @@ public record HqlQueryContext(
      * for a single projection (including DISTINCT x or NEW map(…)), 2 for two 
or more comma-separated
      * top-level projections.
      *
-     * <p>Commas inside parentheses or string literals are ignored.
+     * <p>Commas inside parentheses, string literals, quoted identifiers and 
comments are ignored.
      */
     static int countHqlProjections(CharSequence hql) {
         if (hql == null || hql.isEmpty()) return 0;
         String s = hql.toString().trim();
-        String lower = s.toLowerCase(Locale.ROOT);
+        SqlText lower = SqlText.hql(s.toLowerCase(Locale.ROOT));
         int selectIdx = indexOfSelect(lower);
         if (selectIdx < 0) return 0;
 
         int fromIdx = indexOfFrom(lower, selectIdx);
-        String sel = s.substring(
-                        selectIdx + 
HibernateQueryArgument.HQL_SELECT.value().length(),
-                        fromIdx < 0 ? s.length() : fromIdx)
-                .trim();
-        if (sel.isEmpty()) return 0;
-
-        // Strip leading DISTINCT/ALL
-        String selLower = sel.toLowerCase(Locale.ROOT);
-        if (selLower.startsWith(HibernateQueryArgument.HQL_DISTINCT.value() + 
" "))
-            sel = 
sel.substring(HibernateQueryArgument.HQL_DISTINCT.value().length() + 1)
-                    .trim();
-        else if (selLower.startsWith(HibernateQueryArgument.HQL_ALL.value() + 
" "))
-            sel = 
sel.substring(HibernateQueryArgument.HQL_ALL.value().length() + 1)
-                    .trim();
+        int selStart = selectIdx + 
HibernateQueryArgument.HQL_SELECT.value().length();
+        int selEnd = fromIdx < 0 ? s.length() : fromIdx;
+        if (s.substring(selStart, selEnd).isBlank()) return 0;
 
-        // Count top-level commas, ignoring those inside parens or string 
literals
-        int commas = getCommas(sel);
+        // Count the top-level commas of the select clause in place: a leading 
DISTINCT or ALL holds none
+        int commas = lower.countTopLevel(',', selStart, selEnd);
         return commas == 0 ? 1 : 2;
     }
 
     static int getCommas(String sel) {
-        int depth = 0;
-        int commas = 0;
-        boolean inSingle = false;
-        boolean inDouble = false;
-        int i = 0;
-        while (i < sel.length()) {
-            char c = sel.charAt(i);
-            if (!inDouble && c == '\'') {
-                if (inSingle && i + 1 < sel.length() && sel.charAt(i + 1) == 
'\'') {
-                    // escaped '' — skip next
-                    i++;
-                } else {
-                    inSingle = !inSingle;
-                }
-            } else if (!inSingle && c == '"') {
-                inDouble = !inDouble;
-            } else if (!inSingle && !inDouble) {
-                if (c == '(') {
-                    depth++;
-                } else if (c == ')' && depth > 0) {
-                    depth--;
-                } else if (c == ',' && depth == 0) {
-                    commas++;
-                }
-            }
-            i++;
-        }
-        return commas;
+        return SqlText.hql(sel).countTopLevel(',');
     }
 
     /** Returns the index of the {@code select} of the query itself, not of a 
subquery, or -1 if it has none. */
-    private static int indexOfSelect(String lowerHql) {
-        return indexOfTopLevel(lowerHql, 
HibernateQueryArgument.HQL_SELECT.value() + " ", 0);
+    private static int indexOfSelect(SqlText lowerHql) {
+        return 
lowerHql.indexOfTopLevel(HibernateQueryArgument.HQL_SELECT.value() + " ", 0);
     }
 
     /**
      * Returns the index of the space before the {@code from} of the query 
itself, not of a subquery, at or after
      * {@code fromIndex}, or -1 if it has none.
      */
-    private static int indexOfFrom(String lowerHql, int fromIndex) {
-        return indexOfTopLevel(lowerHql, " " + 
HibernateQueryArgument.HQL_FROM.value() + " ", fromIndex);
-    }
-
-    /**
-     * Returns the index of {@code keyword} in the HQL at or after {@code 
fromIndex}, outside string literals, quoted
-     * identifiers, comments and parentheses. Inside parentheses is a subquery 
or the arguments of a function, and the
-     * {@code select} and {@code from} of a subquery are not those of the 
query. The keyword is matched as written, so
-     * the HQL is passed in lower case.
-     *
-     * @return the index, or -1 if the keyword is not at the top level of the 
HQL
-     */
-    private static int indexOfTopLevel(String hql, String keyword, int 
fromIndex) {
-        int depth = 0;
-        int i = 0;
-        while (i < hql.length()) {
-            char c = hql.charAt(i);
-            if (c == '\'' || c == '"' || c == '`') {
-                i = SqlRestriction.skipQuoted(hql, i, c);
-                continue;
-            }
-            if (hql.startsWith("/*", i)) {
-                int commentEnd = hql.indexOf("*/", i + 2);
-                i = commentEnd < 0 ? hql.length() : commentEnd + 2;
-                continue;
-            }
-            if (c == '(') {
-                depth++;
-            } else if (c == ')' && depth > 0) {
-                depth--;
-            } else if (depth == 0 && i >= fromIndex && hql.startsWith(keyword, 
i) && startsWord(hql, i)) {
-                return i;
-            }
-            i++;
-        }
-        return -1;
-    }
-
-    /**
-     * Returns whether a keyword at {@code index} starts a word, so that 
{@code select} in {@code preselect = 1} or in
-     * {@code b.select} is a part of a name and not the keyword. A keyword 
that starts with a space starts a word.
-     */
-    private static boolean startsWord(String hql, int index) {
-        if (index == 0 || hql.charAt(index) == ' ') {
-            return true;
-        }
-        char previous = hql.charAt(index - 1);
-        return !Character.isJavaIdentifierPart(previous) && previous != '.';
+    private static int indexOfFrom(SqlText lowerHql, int fromIndex) {
+        return lowerHql.indexOfTopLevel(" " + 
HibernateQueryArgument.HQL_FROM.value() + " ", fromIndex);
     }
 
     // ─── HQL normalization 
────────────────────────────────────────────────────
@@ -351,10 +268,11 @@ public record HqlQueryContext(
         if (s.isEmpty()) return s;
 
         String lower = s.toLowerCase();
-        int selectIdx = indexOfSelect(lower);
+        SqlText lowerText = SqlText.hql(lower);
+        int selectIdx = indexOfSelect(lowerText);
         if (selectIdx < 0) return s; // no SELECT clause — nothing to normalize
 
-        int fromIdx = indexOfFrom(lower, selectIdx);
+        int fromIdx = indexOfFrom(lowerText, selectIdx);
         if (fromIdx < 0) return s; // malformed — leave as-is
 
         int selectStart = selectIdx + 
HibernateQueryArgument.HQL_SELECT.value().length() + 1;
@@ -453,7 +371,7 @@ public record HqlQueryContext(
     static @Nullable String getRootAlias(@Nullable String hql) {
         if (hql == null) return null;
         String s = hql.trim();
-        String lower = s.toLowerCase(Locale.ROOT);
+        SqlText lower = SqlText.hql(s.toLowerCase(Locale.ROOT));
         int fromIdx = indexOfFrom(lower, Math.max(indexOfSelect(lower), 0));
         if (fromIdx < 0) return null;
         int cur = fromIdx + HibernateQueryArgument.HQL_FROM.value().length() + 
2;
diff --git 
a/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/query/JpaProjectionAdapter.java
 
b/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/query/JpaProjectionAdapter.java
index 8dd7f4f6dc..36499fadd3 100644
--- 
a/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/query/JpaProjectionAdapter.java
+++ 
b/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/query/JpaProjectionAdapter.java
@@ -64,7 +64,10 @@ public class JpaProjectionAdapter {
         for (Query.Projection p : projections) {
             Selection<?> selection = translator.translate(p);
             if (selection != null) {
-                if (query instanceof Subquery && selection.getAlias() == null) 
{
+                if (query instanceof Subquery) {
+                    // nothing reads a subquery's selections by alias: a count 
selects over the derived table and a
+                    // criterion compares a single expression. A generated 
alias replaces the caller's, which may
+                    // hold characters, such as a space, that the derived 
table's column list cannot carry unquoted
                     selection.alias("col_" + (i++));
                 }
                 selections.add(selection);
diff --git 
a/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/query/SqlProjection.java
 
b/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/query/SqlProjection.java
index 2466924a07..74e2772b42 100644
--- 
a/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/query/SqlProjection.java
+++ 
b/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/query/SqlProjection.java
@@ -45,7 +45,6 @@ public class SqlProjection extends Query.Projection {
     private static final Pattern QUOTED = Pattern.compile("(?s)" + 
QUOTED_IDENTIFIER);
     private static final Pattern TRAILING_ALIAS = Pattern.compile(
             "(?is)^(.*?)\\s+as\\s+(" + QUOTED_IDENTIFIER + "|[\\w$]+)\\s*$");
-    private static final Pattern DOLLAR_QUOTE_TAG = 
Pattern.compile("\\$(?:[A-Za-z_][A-Za-z0-9_]*)?\\$");
 
     private final String sql;
     private final String columnAlias;
@@ -151,98 +150,20 @@ public class SqlProjection extends Query.Projection {
     }
 
     /**
-     * Splits SQL at the commas that separate its columns: those outside 
parentheses, square brackets, string
-     * literals, dollar-quoted strings, quoted identifiers and comments. 
Inside square brackets, which quote an
-     * identifier or hold an array subscript, parentheses are not counted, and 
a doubled closing bracket of the
-     * outermost ones stands for the bracket itself, so {@code [total (cm)]} 
and {@code [a]]b]} are identifiers.
+     * Splits SQL at the commas that separate its columns: those outside 
parentheses, bracket identifiers, string
+     * literals, dollar-quoted strings, quoted identifiers and comments. 
Inside brackets, which quote an identifier or
+     * hold an array subscript, only brackets count, so {@code [box's width]}, 
{@code [total (cm)]} and {@code [a]]b]}
+     * are each one identifier.
      */
     static List<String> splitColumns(String sql) {
-        List<String> columns = new ArrayList<>();
-        int length = sql.length();
-        int depth = 0;
-        int brackets = 0;
-        int start = 0;
-        int i = 0;
-        while (i < length) {
-            char c = sql.charAt(i);
-            if (c == '\'' || c == '"' || c == '`') {
-                i = SqlRestriction.skipQuoted(sql, i, c);
-            } else if (c == '$') {
-                i = skipDollarQuoted(sql, i);
-            } else if (c == '-' && sql.startsWith("--", i)) {
-                i = SqlRestriction.endOfLine(sql, i);
-            } else if (c == '/' && sql.startsWith("/*", i)) {
-                int end = sql.indexOf("*/", i + 2);
-                i = end == -1 ? length : end + 2;
-            } else {
-                if (brackets > 0) {
-                    if (c == '[') {
-                        brackets++;
-                    } else if (c == ']' && brackets == 1 && 
sql.startsWith("]]", i)) {
-                        i++;
-                    } else if (c == ']') {
-                        brackets--;
-                    }
-                } else if (c == '[') {
-                    brackets++;
-                } else if (c == '(') {
-                    depth++;
-                } else if (c == ')') {
-                    depth--;
-                } else if (c == ',' && depth == 0) {
-                    columns.add(sql.substring(start, i).trim());
-                    start = i + 1;
-                }
-                i++;
-            }
-        }
-        columns.add(sql.substring(start).trim());
-        return columns;
-    }
-
-    /**
-     * Returns the index after the dollar-quoted string starting at {@code 
start}, such as {@code $$a,b$$} or
-     * {@code $tag$a,b$tag$}, or the index after the {@code $} if none starts 
there, as in the identifier
-     * {@code a$b} or the parameter {@code $1}.
-     */
-    private static int skipDollarQuoted(String sql, int start) {
-        char previous = start > 0 ? sql.charAt(start - 1) : ' ';
-        Matcher tag = DOLLAR_QUOTE_TAG.matcher(sql).region(start, 
sql.length());
-        if (Character.isLetterOrDigit(previous) || previous == '_' || previous 
== '$' || !tag.lookingAt()) {
-            return start + 1;
-        }
-        int end = sql.indexOf(tag.group(), tag.end());
-        return end == -1 ? sql.length() : end + tag.group().length();
+        return SqlText.sql(sql).splitTopLevel(',');
     }
 
     /**
      * Returns the SQL without the comments and whitespace it ends with.
      */
     private static String withoutTrailingComments(String sql) {
-        int length = sql.length();
-        int end = 0;
-        int i = 0;
-        while (i < length) {
-            char c = sql.charAt(i);
-            if (c == '-' && sql.startsWith("--", i)) {
-                i = SqlRestriction.endOfLine(sql, i);
-            } else if (c == '/' && sql.startsWith("/*", i)) {
-                int close = sql.indexOf("*/", i + 2);
-                i = close == -1 ? length : close + 2;
-            } else {
-                if (c == '\'' || c == '"' || c == '`') {
-                    i = SqlRestriction.skipQuoted(sql, i, c);
-                } else if (c == '$') {
-                    i = skipDollarQuoted(sql, i);
-                } else {
-                    i++;
-                }
-                if (!Character.isWhitespace(c)) {
-                    end = i;
-                }
-            }
-        }
-        return sql.substring(0, end);
+        return SqlText.sql(sql).withoutTrailingComments();
     }
 
     /**
diff --git 
a/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/query/SqlRestriction.java
 
b/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/query/SqlRestriction.java
index 2d692988c8..c9be588a8a 100644
--- 
a/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/query/SqlRestriction.java
+++ 
b/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/query/SqlRestriction.java
@@ -63,9 +63,7 @@ public record SqlRestriction(String sql, List<?> values) 
implements Query.Criter
      * identifier, a line comment or a block comment is not a placeholder.
      */
     static List<Integer> placeholderIndexes(String sql) {
-        List<Integer> placeholders = new ArrayList<>();
-        scan(sql, placeholders);
-        return placeholders;
+        return SqlText.sql(sql).plainIndexes('?');
     }
 
     /**
@@ -73,61 +71,6 @@ public record SqlRestriction(String sql, List<?> values) 
implements Query.Criter
      * line.
      */
     static boolean endsInLineComment(String sql) {
-        return scan(sql, new ArrayList<>());
-    }
-
-    private static boolean scan(String sql, List<Integer> placeholders) {
-        int length = sql.length();
-        int i = 0;
-        while (i < length) {
-            char c = sql.charAt(i);
-            if (c == '\'' || c == '"' || c == '`') {
-                i = skipQuoted(sql, i, c);
-            } else if (c == '-' && sql.startsWith("--", i)) {
-                int end = endOfLine(sql, i);
-                if (end == length) {
-                    return true;
-                }
-                i = end;
-            } else if (c == '/' && sql.startsWith("/*", i)) {
-                int end = sql.indexOf("*/", i + 2);
-                i = end == -1 ? length : end + 2;
-            } else {
-                if (c == '?') {
-                    placeholders.add(i);
-                }
-                i++;
-            }
-        }
-        return false;
-    }
-
-    /**
-     * Returns the index after the quoted text starting at {@code start}, 
where a doubled quote stands for the quote
-     * itself.
-     */
-    static int skipQuoted(String sql, int start, char quote) {
-        int i = start + 1;
-        while (i < sql.length()) {
-            if (sql.charAt(i) == quote) {
-                if (i + 1 < sql.length() && sql.charAt(i + 1) == quote) {
-                    i += 2;
-                    continue;
-                }
-                return i + 1;
-            }
-            i++;
-        }
-        return i;
-    }
-
-    static int endOfLine(String sql, int start) {
-        for (int i = start; i < sql.length(); i++) {
-            char c = sql.charAt(i);
-            if (c == '\n' || c == '\r') {
-                return i;
-            }
-        }
-        return sql.length();
+        return SqlText.sql(sql).endsInLineComment();
     }
 }
diff --git 
a/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/query/SqlText.java
 
b/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/query/SqlText.java
new file mode 100644
index 0000000000..0dce0db48b
--- /dev/null
+++ 
b/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/query/SqlText.java
@@ -0,0 +1,349 @@
+/*
+ *  Licensed to the Apache Software Foundation (ASF) under one
+ *  or more contributor license agreements.  See the NOTICE file
+ *  distributed with this work for additional information
+ *  regarding copyright ownership.  The ASF licenses this file
+ *  to you under the Apache License, Version 2.0 (the
+ *  "License"); you may not use this file except in compliance
+ *  with the License.  You may obtain a copy of the License at
+ *
+ *    https://www.apache.org/licenses/LICENSE-2.0
+ *
+ *  Unless required by applicable law or agreed to in writing,
+ *  software distributed under the License is distributed on an
+ *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ *  KIND, either express or implied.  See the License for the
+ *  specific language governing permissions and limitations
+ *  under the License.
+ */
+
+package org.grails.orm.hibernate.query;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+
+/**
+ * Lexical reading of SQL or HQL text, so that every scanner of this package 
skips the same things the same way:
+ * string literals and quoted identifiers, where a doubled quote stands for 
the quote itself; in native SQL also
+ * {@code [bracket identifiers]}, where {@code ]]} stands for a bracket, and 
{@code $tag$...$tag$} strings; line and
+ * block comments; and parentheses, when a top-level position is asked for. 
The text is read once, when the instance
+ * is created: each character is classified as plain text, quoted text or 
comment, and each plain character carries
+ * its parenthesis depth, so every question asked afterwards walks those two 
arrays and never rescans the text. The
+ * text is scanned, never parsed: this answers where something is, not what it 
means.
+ *
+ * @since 8.0.1
+ */
+final class SqlText {
+
+    /** What a text may hold besides string literals, quoted identifiers and 
comments. */
+    enum Dialect {
+        /** HQL, which has neither bracket identifiers nor dollar-quoted 
strings. */
+        HQL,
+        /** Native SQL, with {@code [bracket identifiers]} and {@code 
$tag$...$tag$} strings. */
+        SQL
+    }
+
+    private static final byte PLAIN = 0;
+    private static final byte QUOTED = 1;
+    private static final byte BLOCK_COMMENT = 2;
+    private static final byte LINE_COMMENT = 3;
+
+    private static final Pattern DOLLAR_QUOTE_TAG = 
Pattern.compile("\\$(?:[A-Za-z_][A-Za-z0-9_]*)?\\$");
+
+    private final String text;
+    private final Dialect dialect;
+    /** The kind of each character: plain text, inside a literal or quoted 
identifier, or inside a comment. */
+    private final byte[] kind;
+    /**
+     * The parenthesis depth of each plain character: the depth a {@code (} 
opens and a {@code )} closes, so the two
+     * parentheses of a pair carry the same depth, and the depth enclosing any 
other character.
+     */
+    private final int[] depth;
+
+    private SqlText(String text, Dialect dialect) {
+        this.text = text;
+        this.dialect = dialect;
+        int length = text.length();
+        this.kind = new byte[length];
+        this.depth = new int[length];
+        int d = 0;
+        int i = 0;
+        while (i < length) {
+            int after = unitEnd(i);
+            if (after > i) {
+                byte unitKind = unitKind(i);
+                for (int j = i; j < after; j++) {
+                    kind[j] = unitKind;
+                }
+                i = after;
+                continue;
+            }
+            char c = text.charAt(i);
+            if (c == '(') {
+                d++;
+                depth[i] = d;
+            } else if (c == ')') {
+                depth[i] = d;
+                if (d > 0) {
+                    d--;
+                }
+            } else {
+                depth[i] = d;
+            }
+            i++;
+        }
+    }
+
+    static SqlText hql(String text) {
+        return new SqlText(text, Dialect.HQL);
+    }
+
+    static SqlText sql(String text) {
+        return new SqlText(text, Dialect.SQL);
+    }
+
+    String text() {
+        return text;
+    }
+
+    int length() {
+        return text.length();
+    }
+
+    /** Returns whether the character at {@code index} is plain text: outside 
every literal, identifier and comment. */
+    boolean isPlain(int index) {
+        return kind[index] == PLAIN;
+    }
+
+    /**
+     * Returns the index of {@code keyword} at or after {@code fromIndex}, 
outside string literals, quoted identifiers,
+     * comments and parentheses, where it starts a word: {@code select} in 
{@code preselect} or in {@code b.select} is
+     * part of a name. A keyword that starts with a space starts a word. The 
keyword is matched as written, so a
+     * case-insensitive search passes the text in lower case.
+     *
+     * @return the index, or -1 when the keyword is not at the top level of 
the text
+     */
+    int indexOfTopLevel(String keyword, int fromIndex) {
+        for (int i = Math.max(fromIndex, 0); i < text.length(); i++) {
+            if (kind[i] == PLAIN && depth[i] == 0 && text.startsWith(keyword, 
i) && startsWord(i)) {
+                return i;
+            }
+        }
+        return -1;
+    }
+
+    /**
+     * Splits the text at the separators outside string literals, quoted 
identifiers, comments and parentheses, and
+     * trims each part. A text without the separator is one part.
+     */
+    List<String> splitTopLevel(char separator) {
+        List<String> parts = new ArrayList<>();
+        int start = 0;
+        for (int i = 0; i < text.length(); i++) {
+            if (isTopLevel(i, separator)) {
+                parts.add(text.substring(start, i).trim());
+                start = i + 1;
+            }
+        }
+        parts.add(text.substring(start).trim());
+        return parts;
+    }
+
+    /** Returns how many times {@code separator} occurs at the top level of 
the whole text. */
+    int countTopLevel(char separator) {
+        return countTopLevel(separator, 0, text.length());
+    }
+
+    /** Returns how many times {@code separator} occurs at the top level 
between {@code from} and {@code to}. */
+    int countTopLevel(char separator, int from, int to) {
+        int count = 0;
+        for (int i = Math.max(from, 0); i < Math.min(to, text.length()); i++) {
+            if (isTopLevel(i, separator)) {
+                count++;
+            }
+        }
+        return count;
+    }
+
+    /** Returns the indexes of {@code c} outside string literals, quoted 
identifiers and comments, at any depth. */
+    List<Integer> plainIndexes(char c) {
+        List<Integer> indexes = new ArrayList<>();
+        for (int i = 0; i < text.length(); i++) {
+            if (kind[i] == PLAIN && text.charAt(i) == c) {
+                indexes.add(i);
+            }
+        }
+        return indexes;
+    }
+
+    /**
+     * Returns the text without parentheses that enclose all of it, however 
many times they are nested, and without
+     * the whitespace around it. A text whose first parenthesis closes before 
its end, such as the parenthesized
+     * branches of a union, is returned as it is, trimmed.
+     */
+    String unwrapOuterParentheses() {
+        int start = 0;
+        int end = text.length() - 1;
+        while (true) {
+            while (start <= end && Character.isWhitespace(text.charAt(start))) 
{
+                start++;
+            }
+            while (end >= start && Character.isWhitespace(text.charAt(end))) {
+                end--;
+            }
+            if (start > end || text.charAt(start) != '(' || kind[start] != 
PLAIN || closingParenthesisOf(start) != end) {
+                break;
+            }
+            start++;
+            end--;
+        }
+        return start > end ? "" : text.substring(start, end + 1);
+    }
+
+    /**
+     * Returns the index of the parenthesis closing the one at {@code open}, 
outside string literals, quoted
+     * identifiers and comments, or -1 when it is not closed.
+     */
+    int closingParenthesisOf(int open) {
+        int target = depth[open];
+        for (int i = open + 1; i < text.length(); i++) {
+            if (kind[i] == PLAIN && text.charAt(i) == ')' && depth[i] == 
target) {
+                return i;
+            }
+        }
+        return -1;
+    }
+
+    /** Returns the text without the comments and whitespace it ends with. */
+    String withoutTrailingComments() {
+        int end = text.length();
+        while (end > 0 && (kind[end - 1] >= BLOCK_COMMENT || (kind[end - 1] == 
PLAIN && Character.isWhitespace(text.charAt(end - 1))))) {
+            end--;
+        }
+        return text.substring(0, end);
+    }
+
+    /** Returns whether the text ends in a line comment, which would comment 
out anything appended on the same line. */
+    boolean endsInLineComment() {
+        return text.length() > 0 && kind[text.length() - 1] == LINE_COMMENT;
+    }
+
+    private boolean isTopLevel(int index, char c) {
+        return kind[index] == PLAIN && depth[index] == 0 && text.charAt(index) 
== c;
+    }
+
+    private boolean startsWord(int index) {
+        if (index == 0 || text.charAt(index) == ' ') {
+            return true;
+        }
+        char previous = text.charAt(index - 1);
+        return !Character.isJavaIdentifierPart(previous) && previous != '.';
+    }
+
+    /**
+     * Returns the index after the string literal, quoted identifier or 
comment that starts at {@code index}, or
+     * {@code index} itself when none starts there and the character is plain 
text.
+     */
+    private int unitEnd(int index) {
+        char c = text.charAt(index);
+        if (c == '\'' || c == '"' || c == '`') {
+            return skipQuoted(index, c);
+        }
+        if (c == '-' && text.startsWith("--", index)) {
+            return endOfLine(index);
+        }
+        if (c == '/' && text.startsWith("/*", index)) {
+            int end = text.indexOf("*/", index + 2);
+            return end == -1 ? text.length() : end + 2;
+        }
+        if (dialect == Dialect.SQL) {
+            if (c == '[') {
+                return skipBracketIdentifier(index);
+            }
+            if (c == '$') {
+                return skipDollarQuoted(index);
+            }
+        }
+        return index;
+    }
+
+    private byte unitKind(int index) {
+        if (text.startsWith("--", index)) {
+            return LINE_COMMENT;
+        }
+        if (text.startsWith("/*", index)) {
+            return BLOCK_COMMENT;
+        }
+        return QUOTED;
+    }
+
+    /** Returns the index after the quoted text starting at {@code start}, 
where a doubled quote stands for the quote. */
+    private int skipQuoted(int start, char quote) {
+        int i = start + 1;
+        while (i < text.length()) {
+            if (text.charAt(i) == quote) {
+                if (i + 1 < text.length() && text.charAt(i + 1) == quote) {
+                    i += 2;
+                    continue;
+                }
+                return i + 1;
+            }
+            i++;
+        }
+        return i;
+    }
+
+    /**
+     * Returns the index after the bracket identifier starting at {@code 
start}. Inside it only brackets count: a
+     * nested {@code [} opens one more level, as in an array subscript, and 
{@code ]]} at the outermost level stands
+     * for a bracket, so {@code [box's width]}, {@code [total (cm)]} and 
{@code [a]]b]} are each one identifier.
+     */
+    private int skipBracketIdentifier(int start) {
+        int brackets = 1;
+        int i = start + 1;
+        while (i < text.length()) {
+            char c = text.charAt(i);
+            if (c == '[') {
+                brackets++;
+            } else if (c == ']') {
+                if (brackets == 1 && text.startsWith("]]", i)) {
+                    i += 2;
+                    continue;
+                }
+                brackets--;
+                if (brackets == 0) {
+                    return i + 1;
+                }
+            }
+            i++;
+        }
+        return i;
+    }
+
+    /**
+     * Returns the index after the dollar-quoted string starting at {@code 
start}, such as {@code $$a,b$$} or
+     * {@code $tag$a,b$tag$}, or {@code start} itself when no string starts 
there, as in the identifier {@code a$b}
+     * or the parameter {@code $1}.
+     */
+    private int skipDollarQuoted(int start) {
+        char previous = start > 0 ? text.charAt(start - 1) : ' ';
+        Matcher tag = DOLLAR_QUOTE_TAG.matcher(text).region(start, 
text.length());
+        if (Character.isLetterOrDigit(previous) || previous == '_' || previous 
== '$' || !tag.lookingAt()) {
+            return start;
+        }
+        int end = text.indexOf(tag.group(), tag.end());
+        return end == -1 ? text.length() : end + tag.group().length();
+    }
+
+    private int endOfLine(int start) {
+        for (int i = start; i < text.length(); i++) {
+            char c = text.charAt(i);
+            if (c == '\n' || c == '\r') {
+                return i;
+            }
+        }
+        return text.length();
+    }
+}
diff --git 
a/grails-data-hibernate7/core/src/test/groovy/grails/orm/HibernateCriteriaBuilderSqlProjectionSpec.groovy
 
b/grails-data-hibernate7/core/src/test/groovy/grails/orm/HibernateCriteriaBuilderSqlProjectionSpec.groovy
index fb0d025f13..523d350da0 100644
--- 
a/grails-data-hibernate7/core/src/test/groovy/grails/orm/HibernateCriteriaBuilderSqlProjectionSpec.groovy
+++ 
b/grails-data-hibernate7/core/src/test/groovy/grails/orm/HibernateCriteriaBuilderSqlProjectionSpec.groovy
@@ -125,6 +125,23 @@ class HibernateCriteriaBuilderSqlProjectionSpec extends 
Specification {
         rows*.toList().sort { it[0] } == [[2, 3L, 24L], [4, 1L, 9L]]
     }
 
+    @Rollback
+    void 'a count over a SQL projection keeps a column alias with a space, 
since the derived table uses generated aliases'() {
+        given:
+        saveBoxes()
+
+        when: "the count selects over the projection, so the projection 
becomes a derived table"
+        Number boxes = SqlProjectionBox.createCriteria().count {
+            projections {
+                sqlProjection 'width * 10 as "box width"', 'box width', INTEGER
+            }
+        }
+
+        then: "the derived table names its column with a generated alias, not 
the caller's, which holds a space"
+        boxes == SqlProjectionBox.count()
+        sqlCapture.statements.any { it.contains('derived1_0(col_0)') }
+    }
+
     @Rollback
     void 'the results are ordered by the alias of a SQL projection'() {
         given:
diff --git 
a/grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/query/HqlQueryContextSpec.groovy
 
b/grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/query/HqlQueryContextSpec.groovy
index 4c66676951..ae3d7d69f5 100644
--- 
a/grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/query/HqlQueryContextSpec.groovy
+++ 
b/grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/query/HqlQueryContextSpec.groovy
@@ -210,6 +210,9 @@ class HqlQueryContextSpec extends Specification {
         "func(a, b), c"                     | 1
         "'a, b', c"                         | 1
         "\"a, b\", c"                       | 1
+        "`a, b`, c"                         | 1
+        "a /* , */, b"                      | 1
+        "a -- ,\n, b"                       | 1
         "a"                                 | 0
     }
 
diff --git 
a/grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/query/SqlProjectionSpec.groovy
 
b/grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/query/SqlProjectionSpec.groovy
index 95e6f97da8..93fbf809a8 100644
--- 
a/grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/query/SqlProjectionSpec.groovy
+++ 
b/grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/query/SqlProjectionSpec.groovy
@@ -46,6 +46,8 @@ class SqlProjectionSpec extends Specification {
         '$$a,b$$, c'                                    | ['$$a,b$$', 'c']
         '$tag$a,$$,b$tag$, c'                           | ['$tag$a,$$,b$tag$', 
'c']
         'a$b, $1'                                       | ['a$b', '$1']
+        "width as [box's width], height as total"       | ["width as [box's 
width]", 'height as total']
+        'width as [a"b], c'                             | ['width as [a"b]', 
'c']
     }
 
     @Unroll
diff --git 
a/grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/query/SqlTextSpec.groovy
 
b/grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/query/SqlTextSpec.groovy
new file mode 100644
index 0000000000..d2f0ac12c6
--- /dev/null
+++ 
b/grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/query/SqlTextSpec.groovy
@@ -0,0 +1,153 @@
+/*
+ *  Licensed to the Apache Software Foundation (ASF) under one
+ *  or more contributor license agreements.  See the NOTICE file
+ *  distributed with this work for additional information
+ *  regarding copyright ownership.  The ASF licenses this file
+ *  to you under the Apache License, Version 2.0 (the
+ *  "License"); you may not use this file except in compliance
+ *  with the License.  You may obtain a copy of the License at
+ *
+ *    https://www.apache.org/licenses/LICENSE-2.0
+ *
+ *  Unless required by applicable law or agreed to in writing,
+ *  software distributed under the License is distributed on an
+ *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ *  KIND, either express or implied.  See the License for the
+ *  specific language governing permissions and limitations
+ *  under the License.
+ */
+package org.grails.orm.hibernate.query
+
+import spock.lang.Specification
+import spock.lang.Unroll
+
+/**
+ * The one table of awkward inputs every scanner of the package is measured 
against: what a string literal, a quoted
+ * or bracket identifier, a dollar-quoted string and a comment hide, and what 
parentheses nest.
+ */
+class SqlTextSpec extends Specification {
+
+    @Unroll
+    void "the SQL #sql splits at the top-level commas into #parts"() {
+        expect:
+        SqlText.sql(sql).splitTopLevel(',' as char) == parts
+
+        where:
+        sql                                       | parts
+        'width'                                   | ['width']
+        'width, sum(height) as total'             | ['width', 'sum(height) as 
total']
+        "coalesce(label, 'a,b'), label"           | ["coalesce(label, 'a,b')", 
'label']
+        "'it''s, not', c"                         | ["'it''s, not'", 'c']
+        '"odd,name", other'                       | ['"odd,name"', 'other']
+        '`odd,name`, other'                       | ['`odd,name`', 'other']
+        "width as [box's width], height as total" | ["width as [box's width]", 
'height as total']
+        'width as [a"b], c'                       | ['width as [a"b]', 'c']
+        'sum(height) as [total (cm)], c'          | ['sum(height) as [total 
(cm)]', 'c']
+        'sum(height) as [a]]b], c'                | ['sum(height) as [a]]b]', 
'c']
+        'arr[f(a, b)], ARRAY[ARRAY[1, 2]], c'     | ['arr[f(a, b)]', 
'ARRAY[ARRAY[1, 2]]', 'c']
+        'a /* b, c */, d'                         | ['a /* b, c */', 'd']
+        'a -- b, c\n, d'                          | ['a -- b, c', 'd']
+        '$$a,b$$, c'                              | ['$$a,b$$', 'c']
+        '$tag$a,$$,b$tag$, c'                     | ['$tag$a,$$,b$tag$', 'c']
+        'a$b, $1'                                 | ['a$b', '$1']
+        'concat(a, concat(b, c)), d'              | ['concat(a, concat(b, 
c))', 'd']
+    }
+
+    void "HQL has no bracket identifiers or dollar quotes, so they are plain 
text there"() {
+        expect:
+        SqlText.hql('a[1, 2], b').splitTopLevel(',' as char) == ['a[1', '2]', 
'b']
+        SqlText.hql('$$a,b$$, c').splitTopLevel(',' as char) == ['$$a', 'b$$', 
'c']
+    }
+
+    @Unroll
+    void "the keyword '#keyword' is found at the top level of '#text' at 
#index"() {
+        expect:
+        SqlText.hql(text).indexOfTopLevel(keyword, 0) == index
+
+        where:
+        text                                                  | keyword  | 
index
+        'select a from B'                                     | 'select '| 0
+        'select a from B'                                     | ' from ' | 8
+        'from B where x in (select y from C)'                 | 'select '| -1
+        "from B where name = 'select '"                       | 'select '| -1
+        'from B where name = "select "'                       | 'select '| -1
+        'from B where name = `select `'                       | 'select '| -1
+        'from B /* select a */ where x = 1'                   | 'select '| -1
+        'from B -- select a\nwhere x = 1'                     | 'select '| -1
+        'from B where preselect = 1'                          | 'select '| -1
+        'from B where b.select = 1'                           | 'select '| -1
+        "from B where name = 'it''s' and 1 = (select count(c) from C) select"  
| 'select' | 61
+        'with x as (select 1) select a from B'                | 'select '| 21
+    }
+
+    void "a search starts at the given index"() {
+        expect:
+        SqlText.hql('select a from B where b in (select c from D) and e = 
1').indexOfTopLevel(' from ', 9) == -1
+        SqlText.hql('select a from B order by a').indexOfTopLevel(' from ', 0) 
== 8
+    }
+
+    @Unroll
+    void "'#text' without parentheses enclosing all of it is '#unwrapped'"() {
+        expect:
+        SqlText.hql(text).unwrapOuterParentheses() == unwrapped
+
+        where:
+        text                                                        | unwrapped
+        'select b from B'                                           | 'select 
b from B'
+        '(select b from B)'                                         | 'select 
b from B'
+        '((select b from B))'                                       | 'select 
b from B'
+        '( select b from B )'                                       | 'select 
b from B'
+        "(select b from B where b.name <> ')')"                     | "select 
b from B where b.name <> ')'"
+        '(/* ignore ) and ( */ select b from B)'                    | '/* 
ignore ) and ( */ select b from B'
+        '(select b from B where b.a in (select a from A))'          | 'select 
b from B where b.a in (select a from A)'
+        '(select b from B) union (select a from A)'                 | '(select 
b from B) union (select a from A)'
+        '(select b from B'                                          | '(select 
b from B'
+        '(select b from B))'                                        | '(select 
b from B))'
+        '()'                                                        | ''
+    }
+
+    @Unroll
+    void "the '?' placeholders of '#sql' are at #indexes"() {
+        expect:
+        SqlText.sql(sql).plainIndexes('?' as char) == indexes
+
+        where:
+        sql                                   | indexes
+        'a = ?'                               | [4]
+        "a = ? and b = '?' and c = ?"         | [4, 26]
+        'a = ? /* ? */ and b = ?'             | [4, 22]
+        'a = ? -- ?\nand b = ?'               | [4, 19]
+        'a = [?] and b = ?'                   | [16]
+        'a = $$?$$ and b = ?'                 | [18]
+        'a = (?)'                             | [5]
+    }
+
+    @Unroll
+    void "'#sql' #description"() {
+        expect:
+        SqlText.sql(sql).endsInLineComment() == ends
+
+        where:
+        sql                      | ends  | description
+        'a = 1 -- done'          | true  | 'ends in a line comment'
+        'a = 1 -- done\n'        | false | 'has its line comment closed by the 
newline'
+        'a = 1 /* done */'       | false | 'ends in a block comment, which is 
closed'
+        "a = '-- not'"           | false | 'has the dashes inside a literal'
+        'a = 1'                  | false | 'has no comment'
+    }
+
+    @Unroll
+    void "'#sql' without its trailing comments is '#expected'"() {
+        expect:
+        SqlText.sql(sql).withoutTrailingComments() == expected
+
+        where:
+        sql                                   | expected
+        'width as w /* a comment */'          | 'width as w'
+        'width as w -- another comment\n'     | 'width as w'
+        'width /* kept */ as w'               | 'width /* kept */ as w'
+        "width as 'w -- not a comment'"       | "width as 'w -- not a comment'"
+        'width as w   '                       | 'width as w'
+    }
+
+}

Reply via email to