You are viewing a plain text version of this content. The canonical link for it is here.
Posted to reviews@spark.apache.org by "pan3793 (via GitHub)" <gi...@apache.org> on 2026/03/23 05:47:04 UTC

[PR] [SPARK-48338][SQL] `spark-sql` cli correctly handles SQL Scripting compound blocks [spark]

pan3793 opened a new pull request, #54946:
URL: https://github.com/apache/spark/pull/54946

   <!--
   Thanks for sending a pull request!  Here are some tips for you:
     1. If this is your first time, please read our contributor guidelines: https://spark.apache.org/contributing.html
     2. Ensure you have added or run the appropriate tests for your PR: https://spark.apache.org/developer-tools.html
     3. If the PR is unfinished, add '[WIP]' in your PR title, e.g., '[WIP][SPARK-XXXX] Your PR title ...'.
     4. Be sure to keep the PR description updated to reflect all changes.
     5. Please write your PR title to summarize what this PR proposes.
     6. If possible, provide a concise example to reproduce the issue for a faster review.
     7. If you want to add a new configuration, please read the guideline first for naming configurations in
        'core/src/main/scala/org/apache/spark/internal/config/ConfigEntry.scala'.
     8. If you want to add or modify an error type or message, please read the guideline first in
        'common/utils/src/main/resources/error/README.md'.
   -->
   
   ### What changes were proposed in this pull request?
   <!--
   Please clarify what changes you are proposing. The purpose of this section is to outline the changes and how this PR fixes the issue. 
   If possible, please consider writing useful notes for better and faster reviews in your PR. See the examples below.
     1. If you refactor some codes with changing classes, showing the class hierarchy will help reviewers.
     2. If you fix some SQL features, you can provide some references of other DBMSes.
     3. If there is design documentation, please add the link.
     4. If there is a discussion in the mailing list, please add the link.
   -->
   The `spark-sql` cli now correctly handles SQL Scripting compound blocks (e.g., `BEGIN...END`, `IF...END IF`, `WHILE...DO...END WHILE`, `CASE...END CASE`) by tracking block nesting depth during input processing.
   
     Changes:
     - Added `SqlScriptBlockTracker` class in the companion object that tracks SQL Scripting block depth by scanning keyword tokens (`BEGIN`, `END`, `CASE`, `IF`, `DO`, `LOOP`, `REPEAT`) while correctly handling decorative suffixes after `END` (e.g., `END IF`, `END CASE`).
     - Updated `splitSemiColon` to use `SqlScriptBlockTracker` so semicolons inside compound blocks are not treated as statement boundaries.
     - Updated the interactive input loop to call `sqlScriptingBlockDepth` and continue accumulating input when the user is still inside an open scripting block.
   
   ### Why are the changes needed?
   <!--
   Please clarify why the changes are needed. For instance,
     1. If you propose a new API, clarify the use case for a new API.
     2. If you fix a bug, you can clarify why it is a bug.
   -->
   The `spark-sql` CLI uses semicolons to determine statement boundaries, both for splitting multi-statement input (`splitSemiColon`) and for deciding when to execute in interactive mode (line ends with `;`). SQL Scripting compound blocks use semicolons as internal statement terminators (e.g., `BEGIN SELECT 1; SELECT 2; END;`), so the CLI incorrectly splits or prematurely executes incomplete blocks.
   
   For example, in interactive mode:
   ```
   spark-sql> BEGIN
            >   SELECT 1;   <-- CLI fires here with incomplete "BEGIN\n  SELECT 1;"
   ```
   
   After this change, the CLI waits until the block is fully closed (`END;`) before executing.
   
   ### Does this PR introduce _any_ user-facing change?
   <!--
   Note that it means *any* user-facing change including all aspects such as new features, bug fixes, or other behavior changes. Documentation-only updates are not considered user-facing changes.
   
   If yes, please clarify the previous behavior and the change this PR proposes - provide the console output, description and/or an example to show the behavior difference if possible.
   If possible, please also clarify if this is a user-facing change compared to the released Spark versions or within the unreleased branches such as master.
   If no, write 'No'.
   -->
   Yes. The `spark-sql` CLI now correctly accepts multi-line SQL Scripting blocks in both interactive mode and file/`-e` mode without prematurely splitting or executing them.
   
   ### How was this patch tested?
   <!--
   If tests were added, say they were added here. Please make sure to add some test cases that check the changes thoroughly including negative and positive cases if possible.
   If it was tested in a way different from regular unit tests, please clarify how you tested step by step, ideally copy and paste-able, so that other reviewers can test and check, and descendants can verify in the future.
   If tests were not added, please describe why they were not added and/or why it was difficult to add.
   If benchmark tests were added, please run the benchmarks in GitHub Actions for the consistent environment, and the instructions could accord to: https://spark.apache.org/developer-tools.html#github-workflow-benchmarks.
   -->
   New UTs are added in `CliSuite.scala`
   
   With additional playing with `spark-sql`:
   ```
   $ build/sbt -Phive,hive-thriftserver clean package
   $ SPARK_PREPEND_CLASSES=true bin/spark-sql 
   spark-sql (default)> SELECT current_timestamp();
   2026-03-23 13:46:37.797724
   Time taken: 0.033 seconds, Fetched 1 row(s)
   spark-sql (default)> BEGIN
                      >   DECLARE counter INT DEFAULT 1;
                      >   DECLARE total INT DEFAULT 0;
                      > 
                      >   WHILE counter <= 5 DO
                      >     SET total = total + counter;
                      >     SET counter = counter + 1;
                      >   END WHILE;
                      > 
                      >   SELECT total AS sum_of_first_five;
                      > END;
   15
   Time taken: 0.363 seconds, Fetched 1 row(s)
   spark-sql (default)> SELECT current_timestamp();
   2026-03-23 13:46:38.303671
   Time taken: 0.028 seconds, Fetched 1 row(s)
   spark-sql (default)> 
   ```
   
   ### Was this patch authored or co-authored using generative AI tooling?
   <!--
   If generative AI tooling has been used in the process of authoring this patch, please include the
   phrase: 'Generated-by: ' followed by the name of the tool and its version.
   If no, write 'No'.
   Please refer to the [ASF Generative Tooling Guidance](https://www.apache.org/legal/generative-tooling.html) for details.
   -->
   Generated-by: Claude Code (Claude Sonnet 4.6), OpenCode (MiMo V2 Pro)


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


Re: [PR] [SPARK-56147][SQL] `spark-sql` cli correctly handles SQL Scripting compound blocks [spark]

Posted by "cloud-fan (via GitHub)" <gi...@apache.org>.
cloud-fan commented on code in PR #54946:
URL: https://github.com/apache/spark/pull/54946#discussion_r3050478780


##########
sql/hive-thriftserver/src/main/scala/org/apache/spark/sql/hive/thriftserver/SparkSQLCLIDriver.scala:
##########
@@ -374,6 +385,131 @@ private[hive] object SparkSQLCLIDriver extends Logging {
     }
     Array[Completer](propCompleter, customCompleter)
   }
+
+  private final val END_SUFFIX_KEYWORDS =
+    Set("IF", "CASE", "FOR", "WHILE", "LOOP", "REPEAT")
+
+  /**
+   * Tracks SQL Scripting block nesting depth by processing SQL keyword tokens.
+   *
+   * Call [[processChar]] for each character that is outside quoted strings and comments.
+   * Call [[clearWordBuffer]] when entering a quoted string or comment mid-word.
+   * Call [[flush]] after the last character to finalize any pending token.
+   * Read [[depth]] to obtain the current block nesting level.
+   *
+   * Depth tracking rules:
+   *   - BEGIN                                      -> depth++
+   *   - CASE / IF (not `IF(`) / DO / LOOP / REPEAT -> depth++ only when depth > 0
+   *   - Every END keyword                          -> depth-- (when depth > 0)
+   *   - Keywords immediately following END (IF, CASE, FOR, WHILE, LOOP, REPEAT) are
+   *     decorative suffixes (e.g. "END IF") and do NOT change the depth.
+   */
+  private[hive] class SqlScriptBlockTracker {
+    var depth: Int = 0
+    private val wordBuf = new StringBuilder()
+    private var prevWord: String = ""
+
+    private def isWordChar(c: Char): Boolean = c.isLetterOrDigit || c == '_'
+
+    /** Feed a single character that is known to be outside any quote or comment. */
+    def processChar(c: Char): Unit = {
+      if (isWordChar(c)) {
+        wordBuf.append(c)
+      } else if (wordBuf.nonEmpty) {
+        onWordEnd(wordBuf.toString, c)
+        wordBuf.clear()
+      }
+    }
+
+    /** Discard a partially accumulated word (e.g. when entering a quote/comment). */
+    def clearWordBuffer(): Unit = wordBuf.clear()
+
+    /** Flush any remaining word at the end of the input. */
+    def flush(): Unit = {
+      if (wordBuf.nonEmpty) {
+        onWordEnd(wordBuf.toString, ' ')
+        wordBuf.clear()
+      }
+    }
+
+    private def onWordEnd(word: String, nextChar: Char): Unit = {
+      val upper = word.toUpperCase(Locale.ROOT)
+      if (prevWord == "END" && END_SUFFIX_KEYWORDS.contains(upper)) {
+        // Decorative suffix after END (e.g. "END IF") -- do not change depth.
+        prevWord = upper
+        return
+      }
+      prevWord = upper
+      upper match {
+        case "BEGIN" => depth += 1
+        case "END" if depth > 0 => depth -= 1
+        case "CASE" if depth > 0 => depth += 1
+        case "IF" if depth > 0 && nextChar != '(' => depth += 1
+        case "DO" if depth > 0 => depth += 1
+        case "LOOP" if depth > 0 => depth += 1
+        case "REPEAT" if depth > 0 => depth += 1
+        case _ =>
+      }
+    }
+  }
+
+  /**
+   * Computes the SQL scripting block depth of the given SQL text.
+   * Returns 0 when the text is not inside any scripting block, > 0 when still open.
+   */
+  private[hive] def sqlScriptingBlockDepth(text: String): Int = {
+    var insideSingleQuote = false
+    var insideDoubleQuote = false
+    var insideSimpleComment = false
+    var bracketedCommentLevel = 0
+    var escape = false
+    var leavingBracketedComment = false
+    val tracker = new SqlScriptBlockTracker()
+
+    def insideBracketedComment: Boolean = bracketedCommentLevel > 0
+    def insideComment: Boolean = insideSimpleComment || insideBracketedComment
+    def insideAnyQuote: Boolean = insideSingleQuote || insideDoubleQuote
+
+    for (index <- 0 until text.length) {
+      if (leavingBracketedComment) {
+        bracketedCommentLevel -= 1
+        leavingBracketedComment = false
+      }
+
+      val c = text.charAt(index)
+
+      if (!insideComment && !insideAnyQuote) {
+        tracker.processChar(c)
+      } else if (tracker.depth >= 0) {

Review Comment:
   `tracker.depth >= 0` is always true since depth is only decremented when `> 0`. Simplify to `else`:
   ```suggestion
         } else {
   ```



##########
sql/hive-thriftserver/src/main/scala/org/apache/spark/sql/hive/thriftserver/SparkSQLCLIDriver.scala:
##########
@@ -374,6 +385,131 @@ private[hive] object SparkSQLCLIDriver extends Logging {
     }
     Array[Completer](propCompleter, customCompleter)
   }
+
+  private final val END_SUFFIX_KEYWORDS =
+    Set("IF", "CASE", "FOR", "WHILE", "LOOP", "REPEAT")
+
+  /**
+   * Tracks SQL Scripting block nesting depth by processing SQL keyword tokens.
+   *
+   * Call [[processChar]] for each character that is outside quoted strings and comments.
+   * Call [[clearWordBuffer]] when entering a quoted string or comment mid-word.
+   * Call [[flush]] after the last character to finalize any pending token.
+   * Read [[depth]] to obtain the current block nesting level.
+   *
+   * Depth tracking rules:
+   *   - BEGIN                                      -> depth++
+   *   - CASE / IF (not `IF(`) / DO / LOOP / REPEAT -> depth++ only when depth > 0
+   *   - Every END keyword                          -> depth-- (when depth > 0)
+   *   - Keywords immediately following END (IF, CASE, FOR, WHILE, LOOP, REPEAT) are
+   *     decorative suffixes (e.g. "END IF") and do NOT change the depth.
+   */
+  private[hive] class SqlScriptBlockTracker {
+    var depth: Int = 0
+    private val wordBuf = new StringBuilder()
+    private var prevWord: String = ""
+
+    private def isWordChar(c: Char): Boolean = c.isLetterOrDigit || c == '_'
+
+    /** Feed a single character that is known to be outside any quote or comment. */
+    def processChar(c: Char): Unit = {
+      if (isWordChar(c)) {
+        wordBuf.append(c)
+      } else if (wordBuf.nonEmpty) {
+        onWordEnd(wordBuf.toString, c)
+        wordBuf.clear()
+      }
+    }
+
+    /** Discard a partially accumulated word (e.g. when entering a quote/comment). */
+    def clearWordBuffer(): Unit = wordBuf.clear()
+
+    /** Flush any remaining word at the end of the input. */
+    def flush(): Unit = {
+      if (wordBuf.nonEmpty) {
+        onWordEnd(wordBuf.toString, ' ')
+        wordBuf.clear()
+      }
+    }
+
+    private def onWordEnd(word: String, nextChar: Char): Unit = {
+      val upper = word.toUpperCase(Locale.ROOT)
+      if (prevWord == "END" && END_SUFFIX_KEYWORDS.contains(upper)) {
+        // Decorative suffix after END (e.g. "END IF") -- do not change depth.
+        prevWord = upper
+        return
+      }
+      prevWord = upper
+      upper match {
+        case "BEGIN" => depth += 1

Review Comment:
   `BEGIN` is in Spark's `nonReserved` grammar list, meaning it can appear as a regular identifier — e.g., `SELECT begin FROM t;` is valid Spark SQL. Since the tracker unconditionally increments depth on `BEGIN`, this would cause the interactive CLI to enter continuation mode (waiting for `END;`) instead of executing the statement.
   
   In practice this is rare since `begin` is an unusual identifier choice, but it could confuse users. One mitigation: only treat `BEGIN` as a block opener when it appears at a statement boundary (start of input, or right after a semicolon-split point). Would this be worth addressing?



##########
sql/hive-thriftserver/src/main/scala/org/apache/spark/sql/hive/thriftserver/SparkSQLCLIDriver.scala:
##########
@@ -374,6 +385,131 @@ private[hive] object SparkSQLCLIDriver extends Logging {
     }
     Array[Completer](propCompleter, customCompleter)
   }
+
+  private final val END_SUFFIX_KEYWORDS =
+    Set("IF", "CASE", "FOR", "WHILE", "LOOP", "REPEAT")
+
+  /**
+   * Tracks SQL Scripting block nesting depth by processing SQL keyword tokens.
+   *
+   * Call [[processChar]] for each character that is outside quoted strings and comments.
+   * Call [[clearWordBuffer]] when entering a quoted string or comment mid-word.
+   * Call [[flush]] after the last character to finalize any pending token.
+   * Read [[depth]] to obtain the current block nesting level.
+   *
+   * Depth tracking rules:
+   *   - BEGIN                                      -> depth++
+   *   - CASE / IF (not `IF(`) / DO / LOOP / REPEAT -> depth++ only when depth > 0
+   *   - Every END keyword                          -> depth-- (when depth > 0)
+   *   - Keywords immediately following END (IF, CASE, FOR, WHILE, LOOP, REPEAT) are
+   *     decorative suffixes (e.g. "END IF") and do NOT change the depth.
+   */
+  private[hive] class SqlScriptBlockTracker {
+    var depth: Int = 0
+    private val wordBuf = new StringBuilder()
+    private var prevWord: String = ""
+
+    private def isWordChar(c: Char): Boolean = c.isLetterOrDigit || c == '_'
+
+    /** Feed a single character that is known to be outside any quote or comment. */
+    def processChar(c: Char): Unit = {
+      if (isWordChar(c)) {
+        wordBuf.append(c)
+      } else if (wordBuf.nonEmpty) {
+        onWordEnd(wordBuf.toString, c)
+        wordBuf.clear()
+      }
+    }
+
+    /** Discard a partially accumulated word (e.g. when entering a quote/comment). */
+    def clearWordBuffer(): Unit = wordBuf.clear()
+
+    /** Flush any remaining word at the end of the input. */
+    def flush(): Unit = {
+      if (wordBuf.nonEmpty) {
+        onWordEnd(wordBuf.toString, ' ')
+        wordBuf.clear()
+      }
+    }
+
+    private def onWordEnd(word: String, nextChar: Char): Unit = {
+      val upper = word.toUpperCase(Locale.ROOT)
+      if (prevWord == "END" && END_SUFFIX_KEYWORDS.contains(upper)) {
+        // Decorative suffix after END (e.g. "END IF") -- do not change depth.
+        prevWord = upper
+        return
+      }
+      prevWord = upper
+      upper match {
+        case "BEGIN" => depth += 1
+        case "END" if depth > 0 => depth -= 1
+        case "CASE" if depth > 0 => depth += 1
+        case "IF" if depth > 0 && nextChar != '(' => depth += 1
+        case "DO" if depth > 0 => depth += 1
+        case "LOOP" if depth > 0 => depth += 1
+        case "REPEAT" if depth > 0 => depth += 1
+        case _ =>
+      }
+    }
+  }
+
+  /**
+   * Computes the SQL scripting block depth of the given SQL text.
+   * Returns 0 when the text is not inside any scripting block, > 0 when still open.
+   */
+  private[hive] def sqlScriptingBlockDepth(text: String): Int = {

Review Comment:
   The quote/comment/escape scanning in this method (~lines 460-512) is nearly identical to the scanning in `splitSemiColon` (~lines 762-866) — both track `insideSingleQuote`, `insideDoubleQuote`, `insideSimpleComment`, `bracketedCommentLevel`, `escape`, `leavingBracketedComment` with the same toggle logic, and both feed characters to a `SqlScriptBlockTracker`.
   
   Consider extracting the common scanning loop so both callers can share it. For example, a helper method that takes a text and a callback/visitor could iterate character-by-character with the quote/comment state machine, letting `sqlScriptingBlockDepth` just read the tracker's depth, and `splitSemiColon` handle semicolons and substring extraction. This would eliminate the duplication and ensure both paths stay in sync when future changes arise (e.g., adding backtick-quoted identifier support).



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


Re: [PR] [SPARK-56147][SQL] Use parser-based SQL splitter in `spark-sql` CLI [spark]

Posted by "pan3793 (via GitHub)" <gi...@apache.org>.
pan3793 commented on code in PR #54946:
URL: https://github.com/apache/spark/pull/54946#discussion_r3469321803


##########
sql/core/src/main/scala/org/apache/spark/sql/execution/SparkSqlParser.scala:
##########
@@ -103,6 +103,22 @@ class SparkSqlParser extends AbstractSqlParser {
     parseInternal(command, None)(toResult)
   }
 
+  /**
+   * Split a SQL string into individual statements after expanding any `${...}`
+   * variable references. Variable substitution has to happen *before* splitting
+   * because a substituted value may itself contain `;`, comments, or
+   * `BEGIN ... END` structure that affect statement boundaries.
+   *
+   * Parameter substitution is intentionally NOT applied here: the splitter
+   * runs at the top level of an interactive session / batch input, where there
+   * is no parameter context bound. If a caller does have a parameter context,
+   * they should pre-substitute the input and call this with the result.
+   */
+  override def splitStatements(sqlText: String): SqlStatementSplitResult = {
+    val variableSubstituted = substitutor.substitute(sqlText)

Review Comment:
   new algorithm:
   
   **Placeholder-validation hybrid for `${...}` variable substitution** — Spark SQL allows `SET key=value; SELECT '${key}'` so that `${key}` is substituted using the value set by an earlier statement in the same batch. Substituting `${...}` up-front (before splitting) breaks this ordering, and also breaks block boundaries when the substituted value lands inside a `BEGIN ... END` whose variable was set by a `SET` outside the block. Instead, the splitter accepts an optional `validationPreprocess: String => String` callback that `SparkSqlParser` uses to replace `${...}` with a constant placeholder identifier _for the parser's validation only_. The emitted `SqlStatement` text is always the **original** input, so the variable references survive into the emitted statement and are substituted for real at execution time after earlier `SET`s have run.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


Re: [PR] [SPARK-56147][SQL] Use parser-based SQL splitter in `spark-sql` CLI [spark]

Posted by "pan3793 (via GitHub)" <gi...@apache.org>.
pan3793 commented on code in PR #54946:
URL: https://github.com/apache/spark/pull/54946#discussion_r3550200432


##########
sql/hive-thriftserver/src/main/scala/org/apache/spark/sql/hive/thriftserver/SparkSQLCLIDriver.scala:
##########
@@ -255,30 +262,57 @@ private[hive] object SparkSQLCLIDriver extends Logging {
     def continuedPromptWithDBSpaces: String = continuedPrompt + ReflectionUtils.invokeStatic(
       classOf[CliDriver], "spacesForString", classOf[String] -> currentDB)
 
+    val sqlParser = SparkSQLEnv.sparkSession.sessionState.sqlParser
     var currentPrompt = promptWithCurrentDB
     var line = reader.readLine(currentPrompt + "> ")
 
     while (line != null) {
       // SPARK-55198: call line.trim to also skip comment line with leading whitespaces,
       // this keeps the behavior align with HIVE-8396
       if (!line.trim.startsWith("--")) {
-        if (prefix.nonEmpty) {
-          prefix += '\n'
-        }
-
-        if (line.trim().endsWith(";") && !line.trim().endsWith("\\;")) {
-          line = prefix + line
-          ret = cli.processLine(line, true)
-          prefix = ""
-          currentPrompt = promptWithCurrentDB
+        val trimmed = line.trim
+        if (trimmed.endsWith(";") && !trimmed.endsWith("\\;")) {
+          // The line ends with `;` (and not the Hive-compat `\;` continuation
+          // escape) -- the user signaled end of statement. Ask the splitter
+          // to split the accumulated buffer into statements. The splitter
+          // correctly handles `;` inside quoted strings, comments, and SQL
+          // scripting compound blocks (`BEGIN ... END`).
+          val candidate = if (buffer.isEmpty) line else buffer + "\n" + line

Review Comment:
   thanks, added a UT as suggested: `SPARK-56147: interactive BEGIN ... END block buffers across lines and runs as a single statement`



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


Re: [PR] [SPARK-56147][SQL] `spark-sql` cli correctly handles SQL Scripting compound blocks [spark]

Posted by "pan3793 (via GitHub)" <gi...@apache.org>.
pan3793 commented on PR #54946:
URL: https://github.com/apache/spark/pull/54946#issuecomment-4124925933

   cc @davidm-db @MaxGekk could you please take a look?


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


Re: [PR] [SPARK-56147][SQL] Use parser-based SQL splitter in `spark-sql` CLI [spark]

Posted by "pan3793 (via GitHub)" <gi...@apache.org>.
pan3793 commented on code in PR #54946:
URL: https://github.com/apache/spark/pull/54946#discussion_r3469283599


##########
sql/hive-thriftserver/src/main/scala/org/apache/spark/sql/hive/thriftserver/SparkSQLCLIDriver.scala:
##########
@@ -255,30 +258,44 @@ private[hive] object SparkSQLCLIDriver extends Logging {
     def continuedPromptWithDBSpaces: String = continuedPrompt + ReflectionUtils.invokeStatic(
       classOf[CliDriver], "spacesForString", classOf[String] -> currentDB)
 
+    val sqlParser = SparkSQLEnv.sparkSession.sessionState.sqlParser
     var currentPrompt = promptWithCurrentDB
     var line = reader.readLine(currentPrompt + "> ")
 
     while (line != null) {
       // SPARK-55198: call line.trim to also skip comment line with leading whitespaces,
       // this keeps the behavior align with HIVE-8396
       if (!line.trim.startsWith("--")) {
-        if (prefix.nonEmpty) {
-          prefix += '\n'
-        }
-
-        if (line.trim().endsWith(";") && !line.trim().endsWith("\\;")) {
-          line = prefix + line
-          ret = cli.processLine(line, true)
-          prefix = ""
-          currentPrompt = promptWithCurrentDB
-        } else {
-          prefix = prefix + line
-          currentPrompt = continuedPromptWithDBSpaces
+        val candidate = if (buffer.isEmpty) line else buffer + "\n" + line

Review Comment:
   restored original behavior, and added a new test in `CliSuite` - `SPARK-56147: \; at end of line is a Hive-compat line continuation marker`. 



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


Re: [PR] [SPARK-56147][SQL] Use parser-based SQL splitter in `spark-sql` CLI [spark]

Posted by "cloud-fan (via GitHub)" <gi...@apache.org>.
cloud-fan commented on code in PR #54946:
URL: https://github.com/apache/spark/pull/54946#discussion_r3548159950


##########
sql/hive-thriftserver/src/main/scala/org/apache/spark/sql/hive/thriftserver/SparkSQLCLIDriver.scala:
##########
@@ -255,30 +262,57 @@ private[hive] object SparkSQLCLIDriver extends Logging {
     def continuedPromptWithDBSpaces: String = continuedPrompt + ReflectionUtils.invokeStatic(
       classOf[CliDriver], "spacesForString", classOf[String] -> currentDB)
 
+    val sqlParser = SparkSQLEnv.sparkSession.sessionState.sqlParser
     var currentPrompt = promptWithCurrentDB
     var line = reader.readLine(currentPrompt + "> ")
 
     while (line != null) {
       // SPARK-55198: call line.trim to also skip comment line with leading whitespaces,
       // this keeps the behavior align with HIVE-8396
       if (!line.trim.startsWith("--")) {
-        if (prefix.nonEmpty) {
-          prefix += '\n'
-        }
-
-        if (line.trim().endsWith(";") && !line.trim().endsWith("\\;")) {
-          line = prefix + line
-          ret = cli.processLine(line, true)
-          prefix = ""
-          currentPrompt = promptWithCurrentDB
+        val trimmed = line.trim
+        if (trimmed.endsWith(";") && !trimmed.endsWith("\\;")) {
+          // The line ends with `;` (and not the Hive-compat `\;` continuation
+          // escape) -- the user signaled end of statement. Ask the splitter
+          // to split the accumulated buffer into statements. The splitter
+          // correctly handles `;` inside quoted strings, comments, and SQL
+          // scripting compound blocks (`BEGIN ... END`).
+          val candidate = if (buffer.isEmpty) line else buffer + "\n" + line

Review Comment:
   The headline user-facing change is that interactive `spark-sql> BEGIN ... END;` now buffers across the continuation prompt instead of firing early, but no `CliSuite` test drives this path. Every scripting/comment test uses `-e`/`-f` batch mode or single-line input, and `SqlStatementSplitterSuite` exercises the splitter in isolation — so this loop (`:268-308`), which consumes `splitResult.partialStatement` and decides continue-prompt vs. flush, is only covered end-to-end for the `\;` case. The `WHILE ... END WHILE` session in the PR description is exactly what has no regression test.
   
   Consider a `runCliWithin` case feeding a multi-line block line-by-line (like the existing SPARK-33100/37471 multi-line comment tests) and asserting the block executes as one statement rather than firing at an internal `;`. Non-blocking.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


Re: [PR] [SPARK-56147][SQL] Use parser-based SQL splitter in `spark-sql` CLI [spark]

Posted by "pan3793 (via GitHub)" <gi...@apache.org>.
pan3793 commented on PR #54946:
URL: https://github.com/apache/spark/pull/54946#issuecomment-4931425416

   **Merge Summary:**
   - merged into master https://github.com/apache/spark/commit/49c2637d4fa9cc49ee63903e94fd226db65c065a
   - merged into branch-4.x https://github.com/apache/spark/commit/62b7327c06b83d75c1cdd05a66a2cdd738f555f7
   
   *Posted by `merge_spark_pr.py`*


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


Re: [PR] [SPARK-56147][SQL] Use parser-based SQL splitter in `spark-sql` CLI [spark]

Posted by "pan3793 (via GitHub)" <gi...@apache.org>.
pan3793 closed pull request #54946: [SPARK-56147][SQL] Use parser-based SQL splitter in `spark-sql` CLI
URL: https://github.com/apache/spark/pull/54946


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


Re: [PR] [SPARK-56147][SQL] `spark-sql` cli correctly handles SQL Scripting compound blocks [spark]

Posted by "pan3793 (via GitHub)" <gi...@apache.org>.
pan3793 commented on code in PR #54946:
URL: https://github.com/apache/spark/pull/54946#discussion_r3051058103


##########
sql/hive-thriftserver/src/main/scala/org/apache/spark/sql/hive/thriftserver/SparkSQLCLIDriver.scala:
##########
@@ -374,6 +385,131 @@ private[hive] object SparkSQLCLIDriver extends Logging {
     }
     Array[Completer](propCompleter, customCompleter)
   }
+
+  private final val END_SUFFIX_KEYWORDS =
+    Set("IF", "CASE", "FOR", "WHILE", "LOOP", "REPEAT")
+
+  /**
+   * Tracks SQL Scripting block nesting depth by processing SQL keyword tokens.
+   *
+   * Call [[processChar]] for each character that is outside quoted strings and comments.
+   * Call [[clearWordBuffer]] when entering a quoted string or comment mid-word.
+   * Call [[flush]] after the last character to finalize any pending token.
+   * Read [[depth]] to obtain the current block nesting level.
+   *
+   * Depth tracking rules:
+   *   - BEGIN                                      -> depth++
+   *   - CASE / IF (not `IF(`) / DO / LOOP / REPEAT -> depth++ only when depth > 0
+   *   - Every END keyword                          -> depth-- (when depth > 0)
+   *   - Keywords immediately following END (IF, CASE, FOR, WHILE, LOOP, REPEAT) are
+   *     decorative suffixes (e.g. "END IF") and do NOT change the depth.
+   */
+  private[hive] class SqlScriptBlockTracker {
+    var depth: Int = 0
+    private val wordBuf = new StringBuilder()
+    private var prevWord: String = ""
+
+    private def isWordChar(c: Char): Boolean = c.isLetterOrDigit || c == '_'
+
+    /** Feed a single character that is known to be outside any quote or comment. */
+    def processChar(c: Char): Unit = {
+      if (isWordChar(c)) {
+        wordBuf.append(c)
+      } else if (wordBuf.nonEmpty) {
+        onWordEnd(wordBuf.toString, c)
+        wordBuf.clear()
+      }
+    }
+
+    /** Discard a partially accumulated word (e.g. when entering a quote/comment). */
+    def clearWordBuffer(): Unit = wordBuf.clear()
+
+    /** Flush any remaining word at the end of the input. */
+    def flush(): Unit = {
+      if (wordBuf.nonEmpty) {
+        onWordEnd(wordBuf.toString, ' ')
+        wordBuf.clear()
+      }
+    }
+
+    private def onWordEnd(word: String, nextChar: Char): Unit = {
+      val upper = word.toUpperCase(Locale.ROOT)
+      if (prevWord == "END" && END_SUFFIX_KEYWORDS.contains(upper)) {
+        // Decorative suffix after END (e.g. "END IF") -- do not change depth.
+        prevWord = upper
+        return
+      }
+      prevWord = upper
+      upper match {
+        case "BEGIN" => depth += 1

Review Comment:
   Second thought, this might be a more complex problem. For example, suppose Spark SQL will be extended to support `CREATE PROCEDURE` SQL syntax like Databricks SQL. In this case, `BEGIN` is in the middle of the statement, so it's hard to determine the statement boundary ...
   
   https://docs.databricks.com/aws/en/sql/language-manual/sql-ref-syntax-ddl-create-procedure
   ```
   CREATE PROCEDURE procedure_name AS
   BEGIN
     ...
   END
   ```



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


Re: [PR] [SPARK-56147][SQL] `spark-sql` cli correctly handles SQL Scripting compound blocks [spark]

Posted by "pan3793 (via GitHub)" <gi...@apache.org>.
pan3793 commented on code in PR #54946:
URL: https://github.com/apache/spark/pull/54946#discussion_r3050526436


##########
sql/hive-thriftserver/src/main/scala/org/apache/spark/sql/hive/thriftserver/SparkSQLCLIDriver.scala:
##########
@@ -374,6 +385,131 @@ private[hive] object SparkSQLCLIDriver extends Logging {
     }
     Array[Completer](propCompleter, customCompleter)
   }
+
+  private final val END_SUFFIX_KEYWORDS =
+    Set("IF", "CASE", "FOR", "WHILE", "LOOP", "REPEAT")
+
+  /**
+   * Tracks SQL Scripting block nesting depth by processing SQL keyword tokens.
+   *
+   * Call [[processChar]] for each character that is outside quoted strings and comments.
+   * Call [[clearWordBuffer]] when entering a quoted string or comment mid-word.
+   * Call [[flush]] after the last character to finalize any pending token.
+   * Read [[depth]] to obtain the current block nesting level.
+   *
+   * Depth tracking rules:
+   *   - BEGIN                                      -> depth++
+   *   - CASE / IF (not `IF(`) / DO / LOOP / REPEAT -> depth++ only when depth > 0
+   *   - Every END keyword                          -> depth-- (when depth > 0)
+   *   - Keywords immediately following END (IF, CASE, FOR, WHILE, LOOP, REPEAT) are
+   *     decorative suffixes (e.g. "END IF") and do NOT change the depth.
+   */
+  private[hive] class SqlScriptBlockTracker {
+    var depth: Int = 0
+    private val wordBuf = new StringBuilder()
+    private var prevWord: String = ""
+
+    private def isWordChar(c: Char): Boolean = c.isLetterOrDigit || c == '_'
+
+    /** Feed a single character that is known to be outside any quote or comment. */
+    def processChar(c: Char): Unit = {
+      if (isWordChar(c)) {
+        wordBuf.append(c)
+      } else if (wordBuf.nonEmpty) {
+        onWordEnd(wordBuf.toString, c)
+        wordBuf.clear()
+      }
+    }
+
+    /** Discard a partially accumulated word (e.g. when entering a quote/comment). */
+    def clearWordBuffer(): Unit = wordBuf.clear()
+
+    /** Flush any remaining word at the end of the input. */
+    def flush(): Unit = {
+      if (wordBuf.nonEmpty) {
+        onWordEnd(wordBuf.toString, ' ')
+        wordBuf.clear()
+      }
+    }
+
+    private def onWordEnd(word: String, nextChar: Char): Unit = {
+      val upper = word.toUpperCase(Locale.ROOT)
+      if (prevWord == "END" && END_SUFFIX_KEYWORDS.contains(upper)) {
+        // Decorative suffix after END (e.g. "END IF") -- do not change depth.
+        prevWord = upper
+        return
+      }
+      prevWord = upper
+      upper match {
+        case "BEGIN" => depth += 1

Review Comment:
   this is a good catch! ~~and the suggested approach also sgtm~~



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


Re: [PR] [SPARK-56147][SQL] `spark-sql` cli correctly handles SQL Scripting compound blocks [spark]

Posted by "pan3793 (via GitHub)" <gi...@apache.org>.
pan3793 commented on code in PR #54946:
URL: https://github.com/apache/spark/pull/54946#discussion_r3464962993


##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/parser/ParserInterface.scala:
##########
@@ -80,4 +80,24 @@ trait ParserInterface extends DataTypeParserInterface {
    */
   @throws[ParseException]("Text cannot be parsed to routine parameters")
   def parseRoutineParam(sqlText: String): StructType
+
+  /**
+   * Split a SQL string into individual statements at `;` boundaries.
+   *
+   * Designed for tooling such as the `spark-sql` CLI that needs to feed multiple
+   * statements to the parser one at a time, while correctly handling quoted
+   * strings, single-line and bracketed comments, and SQL scripting compound blocks
+   * (`BEGIN ... END`) so that semicolons inside them do not split the surrounding
+   * statement.
+   *
+   * The method is fault-tolerant: it does not throw on incomplete or malformed
+   * input. Trailing text that does not yet form a complete statement is returned
+   * in [[SqlStatementSplitResult.partialStatement]] so callers can buffer it and
+   * read more input.
+   *
+   * Implementations are expected to apply the same input preprocessing (variable
+   * substitution, etc.) as their `parsePlan` so that the splitter sees the same
+   * stream of tokens the parser would.
+   */
+  def splitStatements(sqlText: String): SqlStatementSplitResult

Review Comment:
   the current `SqlStatementSplitter.split` only covers simple extended SQL syntax; if the plugin extends complex SQL syntax, for example, 
   
   ```
   CREATE PROCEDURE procedure_name AS
   BEGIN
     ...
   END
   ```
   
   it still requires that the plugin implement its own splitter



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


Re: [PR] [SPARK-56147][SQL] `spark-sql` cli correctly handles SQL Scripting compound blocks [spark]

Posted by "pan3793 (via GitHub)" <gi...@apache.org>.
pan3793 commented on code in PR #54946:
URL: https://github.com/apache/spark/pull/54946#discussion_r3050526436


##########
sql/hive-thriftserver/src/main/scala/org/apache/spark/sql/hive/thriftserver/SparkSQLCLIDriver.scala:
##########
@@ -374,6 +385,131 @@ private[hive] object SparkSQLCLIDriver extends Logging {
     }
     Array[Completer](propCompleter, customCompleter)
   }
+
+  private final val END_SUFFIX_KEYWORDS =
+    Set("IF", "CASE", "FOR", "WHILE", "LOOP", "REPEAT")
+
+  /**
+   * Tracks SQL Scripting block nesting depth by processing SQL keyword tokens.
+   *
+   * Call [[processChar]] for each character that is outside quoted strings and comments.
+   * Call [[clearWordBuffer]] when entering a quoted string or comment mid-word.
+   * Call [[flush]] after the last character to finalize any pending token.
+   * Read [[depth]] to obtain the current block nesting level.
+   *
+   * Depth tracking rules:
+   *   - BEGIN                                      -> depth++
+   *   - CASE / IF (not `IF(`) / DO / LOOP / REPEAT -> depth++ only when depth > 0
+   *   - Every END keyword                          -> depth-- (when depth > 0)
+   *   - Keywords immediately following END (IF, CASE, FOR, WHILE, LOOP, REPEAT) are
+   *     decorative suffixes (e.g. "END IF") and do NOT change the depth.
+   */
+  private[hive] class SqlScriptBlockTracker {
+    var depth: Int = 0
+    private val wordBuf = new StringBuilder()
+    private var prevWord: String = ""
+
+    private def isWordChar(c: Char): Boolean = c.isLetterOrDigit || c == '_'
+
+    /** Feed a single character that is known to be outside any quote or comment. */
+    def processChar(c: Char): Unit = {
+      if (isWordChar(c)) {
+        wordBuf.append(c)
+      } else if (wordBuf.nonEmpty) {
+        onWordEnd(wordBuf.toString, c)
+        wordBuf.clear()
+      }
+    }
+
+    /** Discard a partially accumulated word (e.g. when entering a quote/comment). */
+    def clearWordBuffer(): Unit = wordBuf.clear()
+
+    /** Flush any remaining word at the end of the input. */
+    def flush(): Unit = {
+      if (wordBuf.nonEmpty) {
+        onWordEnd(wordBuf.toString, ' ')
+        wordBuf.clear()
+      }
+    }
+
+    private def onWordEnd(word: String, nextChar: Char): Unit = {
+      val upper = word.toUpperCase(Locale.ROOT)
+      if (prevWord == "END" && END_SUFFIX_KEYWORDS.contains(upper)) {
+        // Decorative suffix after END (e.g. "END IF") -- do not change depth.
+        prevWord = upper
+        return
+      }
+      prevWord = upper
+      upper match {
+        case "BEGIN" => depth += 1

Review Comment:
   this is a good catch! and the suggested approach also sgtm



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


Re: [PR] [SPARK-56147][SQL] `spark-sql` cli correctly handles SQL Scripting compound blocks [spark]

Posted by "pan3793 (via GitHub)" <gi...@apache.org>.
pan3793 commented on code in PR #54946:
URL: https://github.com/apache/spark/pull/54946#discussion_r3464947022


##########
sql/core/src/main/scala/org/apache/spark/sql/execution/SparkSqlParser.scala:
##########
@@ -103,6 +103,22 @@ class SparkSqlParser extends AbstractSqlParser {
     parseInternal(command, None)(toResult)
   }
 
+  /**
+   * Split a SQL string into individual statements after expanding any `${...}`
+   * variable references. Variable substitution has to happen *before* splitting
+   * because a substituted value may itself contain `;`, comments, or
+   * `BEGIN ... END` structure that affect statement boundaries.
+   *
+   * Parameter substitution is intentionally NOT applied here: the splitter
+   * runs at the top level of an interactive session / batch input, where there
+   * is no parameter context bound. If a caller does have a parameter context,
+   * they should pre-substitute the input and call this with the result.
+   */
+  override def splitStatements(sqlText: String): SqlStatementSplitResult = {
+    val variableSubstituted = substitutor.substitute(sqlText)

Review Comment:
   > Suggest splitting the raw text ...
   
   this causes problems, because `${...}` is illeage syntax for antlr parser ...



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


Re: [PR] [SPARK-56147][SQL] Use parser-based SQL splitter in `spark-sql` CLI [spark]

Posted by "pan3793 (via GitHub)" <gi...@apache.org>.
pan3793 commented on PR #54946:
URL: https://github.com/apache/spark/pull/54946#issuecomment-4931419190

   the last commit only modifies the comment and test, CI passes, merging to master/4.x


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


Re: [PR] [SPARK-48338][SQL] `spark-sql` cli correctly handles SQL Scripting compound blocks [spark]

Posted by "pan3793 (via GitHub)" <gi...@apache.org>.
pan3793 commented on PR #54946:
URL: https://github.com/apache/spark/pull/54946#issuecomment-4108906136

   cc @srielau @cloud-fan, could you please take a look?


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


Re: [PR] [SPARK-56147][SQL] Use parser-based SQL splitter in `spark-sql` CLI [spark]

Posted by "pan3793 (via GitHub)" <gi...@apache.org>.
pan3793 commented on code in PR #54946:
URL: https://github.com/apache/spark/pull/54946#discussion_r3469307493


##########
sql/core/src/test/scala/org/apache/spark/sql/execution/SparkSqlParserSuite.scala:
##########
@@ -1206,4 +1206,31 @@ class SparkSqlParserSuite extends AnalysisTest with SharedSparkSession {
     parser.parsePlan(
       "SELECT CAST(null AS STRUCT<>), CAST(null AS MAP<STRING, ARRAY<INT>>), 2 >> 1")
   }
+
+  test("splitStatements applies variable substitution before splitting") {

Review Comment:
   this is an invalid case and has been removed - I misunderstood the current variable substitution mechanism, updated the code to return the raw statement instead of the preprocessed one. 



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


Re: [PR] [SPARK-56147][SQL] Use parser-based SQL splitter in `spark-sql` CLI [spark]

Posted by "HyukjinKwon (via GitHub)" <gi...@apache.org>.
HyukjinKwon commented on PR #54946:
URL: https://github.com/apache/spark/pull/54946#issuecomment-4887841149

   **Reviewed — 0 blocking, 2 nits.** Solid, well-tested redesign; the placeholder-validation hybrid cleanly resolves the prior round's substitution-ordering finding and the splitter's failure-mode handling is exhaustive. Two comment nits:
   
   - `SqlStatementSplitter.scala:101` — the performance-note Scaladoc says `tryParseSegment`; the method is `tryParseRegion`.
   - `SparkSQLCLIDriver.scala:245` — "This matches the pre-PR behavior" reads relative to this PR's history and loses its meaning once merged; better to state the invariant directly (e.g. "Line-level buffering keeps multi-line input accumulating until the user signals end-of-statement with `;`").
   
   Verification: enumerated `tryParseRegion`'s ANTLR parse state space (SLL success, SLL-bail→LL success, LL-bail-at-EOF vs not-at-EOF, `StackOverflowError` under either stage) — all handled at `SqlStatementSplitter.scala:355-374`, and an unclosed bracketed comment is surfaced via the lexer flag rather than thrown (`:287-290`). So a well-formed `BEGIN..END` block is always confirmed whole and never split at an internal `;`, and malformed input always reaches the backend for a proper error.
   
   <!-- ai-code-review -->
   


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


Re: [PR] [SPARK-56147][SQL] Use parser-based SQL splitter in `spark-sql` CLI [spark]

Posted by "pan3793 (via GitHub)" <gi...@apache.org>.
pan3793 commented on code in PR #54946:
URL: https://github.com/apache/spark/pull/54946#discussion_r3469350800


##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/parser/SqlStatementSplitter.scala:
##########
@@ -0,0 +1,385 @@
+/*
+ * 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
+ *
+ *    http://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.apache.spark.sql.catalyst.parser
+
+import java.util.{ArrayList => JArrayList}
+
+import scala.collection.mutable
+
+import org.antlr.v4.runtime._
+import org.antlr.v4.runtime.atn.PredictionMode
+import org.antlr.v4.runtime.misc.ParseCancellationException
+
+import org.apache.spark.sql.internal.SqlApiConf
+
+/**
+ * Represents a single complete SQL statement together with the delimiter that
+ * terminated it (always `";"` for now).
+ *
+ * @param statement   the SQL statement text, with surrounding whitespace trimmed and
+ *                    without the terminator
+ * @param terminator  the delimiter string that terminated the statement
+ */
+case class SqlStatement(statement: String, terminator: String) {
+  override def toString: String = statement + terminator
+}
+
+/**
+ * Result of splitting a SQL string into individual statements.
+ *
+ * @param completeStatements  statements that are fully terminated by `;`
+ * @param partialStatement    trailing text after the last `;` that has not yet
+ *                            formed a complete statement; an empty string when the
+ *                            input ends with `;` or contains no significant
+ *                            trailing content
+ * @param hasUnclosedComment  true when [[partialStatement]] contains an unclosed
+ *                            bracketed comment (`/* ...` with no matching `*/`).
+ *                            Interactive CLIs may want to flush the partial to the
+ *                            backend in this case (so the user sees a parse error)
+ *                            rather than keep buffering, since the input cannot be
+ *                            completed simply by appending more SQL.
+ */
+case class SqlStatementSplitResult(
+    completeStatements: Seq[SqlStatement],
+    partialStatement: String,
+    hasUnclosedComment: Boolean = false) {
+  def isEmpty: Boolean = completeStatements.isEmpty && partialStatement.isEmpty
+}
+
+/**
+ * A parser-based SQL statement splitter, inspired by Trino's
+ * `io.trino.cli.lexer.StatementSplitter`.
+ *
+ * Each candidate statement is consumed and confirmed by the ANTLR-generated
+ * [[SqlBaseParser]] via the existing `compoundOrSingleStatement` rule (the same
+ * rule that the normal Spark SQL parser uses). The splitter:
+ *
+ *   1. Tokenizes the input once.
+ *   2. Walks through the token stream. At each significant position, the
+ *      splitter asks the parser whether the prefix ending at the next `;` is a
+ *      complete statement; if not, it extends the prefix to the next `;` and
+ *      re-tries. This is how SQL scripting `BEGIN ... END` blocks (whose body
+ *      contains semicolons) end up emitted as a single statement: only the
+ *      prefix that includes a matching `END` is accepted by the parser.
+ *   3. When the parser fails because it reached EOF mid-rule (e.g. an
+ *      un-terminated `BEGIN ... END`, a SELECT with a missing operand), the
+ *      remaining input is treated as a partial statement so an interactive
+ *      caller can keep buffering.
+ *   4. When the parser fails on a non-EOF token (the input is structurally
+ *      invalid), the splitter falls back to splitting at the next `;` so the
+ *      surrounding delimiters still emit chunks and the backend can report
+ *      the error per chunk.
+ *
+ * Quoted strings, single-line and bracketed (nested) comments are honored
+ * throughout. An unterminated bracketed comment is surfaced via
+ * [[SqlStatementSplitResult.hasUnclosedComment]].
+ */
+object SqlStatementSplitter {
+
+  /** Split the given SQL text into individual statements at `;` boundaries. */
+  def split(sqlText: String): SqlStatementSplitResult = {
+    require(sqlText != null, "sqlText must not be null")
+
+    val lexer = new SqlBaseLexer(new UpperCaseCharStream(CharStreams.fromString(sqlText)))
+    lexer.removeErrorListeners()
+    val tokenStream = new CommonTokenStream(lexer)
+    tokenStream.fill()
+
+    val numTokens = tokenStream.size()
+    // Pre-compute the positions of `;` tokens (on the default channel).
+    val delimiterPositions: Array[Int] = {
+      val acc = mutable.ArrayBuffer.empty[Int]
+      var i = 0
+      while (i < numTokens) {
+        if (tokenStream.get(i).getType == SqlBaseLexer.SEMICOLON) acc += i
+        i += 1
+      }
+      acc.toArray
+    }
+
+    val completeStatements = mutable.ArrayBuffer.empty[SqlStatement]
+    val buffer = new StringBuilder()
+    // Whether `buffer` contains any non-hidden token (i.e. any actual SQL content
+    // beyond whitespace and comments). Chunks that only contain whitespace/comments
+    // are dropped, matching the spark-sql CLI's long-standing behavior.
+    var bufferHasContent = false
+    var index = 0
+    var stopOuter = false
+    // The first index in `delimiterPositions` that is still > our cursor.
+    var delimSearchStart = 0
+
+    // Snapshot the session config once -- the splitter is short-lived and the
+    // splitter's parser must agree with the session config on grammar
+    // interpretation (e.g. `double_quoted_identifiers`).
+    val conf = SqlApiConf.get
+
+    while (!stopOuter && index < numTokens) {
+      val startIdx = nextSignificantTokenIndex(tokenStream, index)
+      if (startIdx < 0) {
+        // Just hidden trailing tokens (whitespace / closed comments). Drain
+        // them into the buffer; if any are an unclosed comment, the lexer
+        // flag will surface it as a partial.
+        while (index < numTokens) {
+          val tok = tokenStream.get(index)
+          index += 1
+          if (tok.getType != Token.EOF) buffer.append(tok.getText)
+        }
+        stopOuter = true
+      } else if (tokenStream.get(startIdx).getType == SqlBaseLexer.SEMICOLON) {
+        // The next significant token is itself a `;`. This is an empty
+        // statement (e.g. `;;` or leading `;`); drop everything from the
+        // cursor through this delimiter and continue.
+        index = startIdx + 1
+      } else {
+        // Advance the search for delimiters past our current cursor.
+        while (delimSearchStart < delimiterPositions.length &&
+            delimiterPositions(delimSearchStart) <= startIdx) {
+          delimSearchStart += 1
+        }
+
+        // Try increasingly long prefixes (each ending at a `;`) until the

Review Comment:
   This also seems to be more complex due to the tricky `SET` syntax ...
   
   A non-EOF terminated single-statement rule would drop this to O(n), but Spark's `setResetStatement: SET .*?` / `RESET .*?` wildcards need an EOF anchor to terminate deterministically, so the simple rule rewrite doesn't drop in cleanly. I would like to defer this if non-blocking.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


Re: [PR] [SPARK-56147][SQL] Use parser-based SQL splitter in `spark-sql` CLI [spark]

Posted by "pan3793 (via GitHub)" <gi...@apache.org>.
pan3793 commented on PR #54946:
URL: https://github.com/apache/spark/pull/54946#issuecomment-4923302153

   @HyukjinKwon, thanks for the review. I fixed the comment issues you spotted; in addition, I revised all comments to remove any language that references the PR's history


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


Re: [PR] [SPARK-56147][SQL] `spark-sql` cli correctly handles SQL Scripting compound blocks [spark]

Posted by "miland-db (via GitHub)" <gi...@apache.org>.
miland-db commented on PR #54946:
URL: https://github.com/apache/spark/pull/54946#issuecomment-4206147436

   Can we add some tests that include `SQL Exception Handlers` that are available inside SQL scripts?
   
   ```
   BEGIN
     DECLARE EXIT HANDLER FOR SQLEXCEPTION
     BEGIN
       VALUES('Hello from the exception handler.');
     END;
   
     SELECT * FROM does_not_exist;
   END;
   ```


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


Re: [PR] [SPARK-56147][SQL] `spark-sql` cli correctly handles SQL Scripting compound blocks [spark]

Posted by "cloud-fan (via GitHub)" <gi...@apache.org>.
cloud-fan commented on code in PR #54946:
URL: https://github.com/apache/spark/pull/54946#discussion_r3462721230


##########
sql/hive-thriftserver/src/main/scala/org/apache/spark/sql/hive/thriftserver/SparkSQLCLIDriver.scala:
##########
@@ -255,30 +258,44 @@ private[hive] object SparkSQLCLIDriver extends Logging {
     def continuedPromptWithDBSpaces: String = continuedPrompt + ReflectionUtils.invokeStatic(
       classOf[CliDriver], "spacesForString", classOf[String] -> currentDB)
 
+    val sqlParser = SparkSQLEnv.sparkSession.sessionState.sqlParser
     var currentPrompt = promptWithCurrentDB
     var line = reader.readLine(currentPrompt + "> ")
 
     while (line != null) {
       // SPARK-55198: call line.trim to also skip comment line with leading whitespaces,
       // this keeps the behavior align with HIVE-8396
       if (!line.trim.startsWith("--")) {
-        if (prefix.nonEmpty) {
-          prefix += '\n'
-        }
-
-        if (line.trim().endsWith(";") && !line.trim().endsWith("\\;")) {
-          line = prefix + line
-          ret = cli.processLine(line, true)
-          prefix = ""
-          currentPrompt = promptWithCurrentDB
-        } else {
-          prefix = prefix + line
-          currentPrompt = continuedPromptWithDBSpaces
+        val candidate = if (buffer.isEmpty) line else buffer + "\n" + line

Review Comment:
   The rewritten loop drops the old `!line.trim().endsWith("\\;")` line-continuation special-case. With the new splitter a stray `\` lexes as a default-channel `UNRECOGNIZED` token, while `processCmd` still has the `oneCmd.endsWith("\\")` continuation branch (which only accumulates — never executes — when it's the trailing chunk). Could you confirm the intended `\;` behavior and add a `CliSuite` case for it (or note it's intentionally removed)? It's currently uncovered. Non-blocking.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/parser/ParserInterface.scala:
##########
@@ -80,4 +80,24 @@ trait ParserInterface extends DataTypeParserInterface {
    */
   @throws[ParseException]("Text cannot be parsed to routine parameters")
   def parseRoutineParam(sqlText: String): StructType
+
+  /**
+   * Split a SQL string into individual statements at `;` boundaries.
+   *
+   * Designed for tooling such as the `spark-sql` CLI that needs to feed multiple
+   * statements to the parser one at a time, while correctly handling quoted
+   * strings, single-line and bracketed comments, and SQL scripting compound blocks
+   * (`BEGIN ... END`) so that semicolons inside them do not split the surrounding
+   * statement.
+   *
+   * The method is fault-tolerant: it does not throw on incomplete or malformed
+   * input. Trailing text that does not yet form a complete statement is returned
+   * in [[SqlStatementSplitResult.partialStatement]] so callers can buffer it and
+   * read more input.
+   *
+   * Implementations are expected to apply the same input preprocessing (variable
+   * substitution, etc.) as their `parsePlan` so that the splitter sees the same
+   * stream of tokens the parser would.
+   */
+  def splitStatements(sqlText: String): SqlStatementSplitResult

Review Comment:
   If split-time substitution is dropped (see the `SparkSqlParser` comment), this method has no per-implementation behavior left — the splitter always validates against the vanilla `SqlBaseParser`, so an injected/extension parser can't customize splitting anyway. At that point this new `@DeveloperApi` abstract method (plus the `AbstractSqlParser` default, the `SparkSqlParser` override, and the two test-decorator overrides) could be removed and the CLI could call `SqlStatementSplitter.split` directly. Worth considering to keep the public API surface minimal — non-blocking.



##########
sql/core/src/test/scala/org/apache/spark/sql/execution/SparkSqlParserSuite.scala:
##########
@@ -1206,4 +1206,31 @@ class SparkSqlParserSuite extends AnalysisTest with SharedSparkSession {
     parser.parsePlan(
       "SELECT CAST(null AS STRUCT<>), CAST(null AS MAP<STRING, ARRAY<INT>>), 2 >> 1")
   }
+
+  test("splitStatements applies variable substitution before splitting") {

Review Comment:
   This pins the up-front-substitution behavior but doesn't cover `SET`-then-`${...}` ordering across statements in one batch — the case flagged on `SparkSqlParser.splitStatements`. If that finding is addressed, please add a batch test asserting a later statement sees the value set by an earlier `SET`. Non-blocking.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/parser/SqlStatementSplitter.scala:
##########
@@ -0,0 +1,385 @@
+/*
+ * 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
+ *
+ *    http://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.apache.spark.sql.catalyst.parser
+
+import java.util.{ArrayList => JArrayList}
+
+import scala.collection.mutable
+
+import org.antlr.v4.runtime._
+import org.antlr.v4.runtime.atn.PredictionMode
+import org.antlr.v4.runtime.misc.ParseCancellationException
+
+import org.apache.spark.sql.internal.SqlApiConf
+
+/**
+ * Represents a single complete SQL statement together with the delimiter that
+ * terminated it (always `";"` for now).
+ *
+ * @param statement   the SQL statement text, with surrounding whitespace trimmed and
+ *                    without the terminator
+ * @param terminator  the delimiter string that terminated the statement
+ */
+case class SqlStatement(statement: String, terminator: String) {
+  override def toString: String = statement + terminator
+}
+
+/**
+ * Result of splitting a SQL string into individual statements.
+ *
+ * @param completeStatements  statements that are fully terminated by `;`
+ * @param partialStatement    trailing text after the last `;` that has not yet
+ *                            formed a complete statement; an empty string when the
+ *                            input ends with `;` or contains no significant
+ *                            trailing content
+ * @param hasUnclosedComment  true when [[partialStatement]] contains an unclosed
+ *                            bracketed comment (`/* ...` with no matching `*/`).
+ *                            Interactive CLIs may want to flush the partial to the
+ *                            backend in this case (so the user sees a parse error)
+ *                            rather than keep buffering, since the input cannot be
+ *                            completed simply by appending more SQL.
+ */
+case class SqlStatementSplitResult(
+    completeStatements: Seq[SqlStatement],
+    partialStatement: String,
+    hasUnclosedComment: Boolean = false) {
+  def isEmpty: Boolean = completeStatements.isEmpty && partialStatement.isEmpty
+}
+
+/**
+ * A parser-based SQL statement splitter, inspired by Trino's
+ * `io.trino.cli.lexer.StatementSplitter`.
+ *
+ * Each candidate statement is consumed and confirmed by the ANTLR-generated
+ * [[SqlBaseParser]] via the existing `compoundOrSingleStatement` rule (the same
+ * rule that the normal Spark SQL parser uses). The splitter:
+ *
+ *   1. Tokenizes the input once.
+ *   2. Walks through the token stream. At each significant position, the
+ *      splitter asks the parser whether the prefix ending at the next `;` is a
+ *      complete statement; if not, it extends the prefix to the next `;` and
+ *      re-tries. This is how SQL scripting `BEGIN ... END` blocks (whose body
+ *      contains semicolons) end up emitted as a single statement: only the
+ *      prefix that includes a matching `END` is accepted by the parser.
+ *   3. When the parser fails because it reached EOF mid-rule (e.g. an
+ *      un-terminated `BEGIN ... END`, a SELECT with a missing operand), the
+ *      remaining input is treated as a partial statement so an interactive
+ *      caller can keep buffering.
+ *   4. When the parser fails on a non-EOF token (the input is structurally
+ *      invalid), the splitter falls back to splitting at the next `;` so the
+ *      surrounding delimiters still emit chunks and the backend can report
+ *      the error per chunk.
+ *
+ * Quoted strings, single-line and bracketed (nested) comments are honored
+ * throughout. An unterminated bracketed comment is surfaced via
+ * [[SqlStatementSplitResult.hasUnclosedComment]].
+ */
+object SqlStatementSplitter {
+
+  /** Split the given SQL text into individual statements at `;` boundaries. */
+  def split(sqlText: String): SqlStatementSplitResult = {
+    require(sqlText != null, "sqlText must not be null")
+
+    val lexer = new SqlBaseLexer(new UpperCaseCharStream(CharStreams.fromString(sqlText)))
+    lexer.removeErrorListeners()
+    val tokenStream = new CommonTokenStream(lexer)
+    tokenStream.fill()
+
+    val numTokens = tokenStream.size()
+    // Pre-compute the positions of `;` tokens (on the default channel).
+    val delimiterPositions: Array[Int] = {
+      val acc = mutable.ArrayBuffer.empty[Int]
+      var i = 0
+      while (i < numTokens) {
+        if (tokenStream.get(i).getType == SqlBaseLexer.SEMICOLON) acc += i
+        i += 1
+      }
+      acc.toArray
+    }
+
+    val completeStatements = mutable.ArrayBuffer.empty[SqlStatement]
+    val buffer = new StringBuilder()
+    // Whether `buffer` contains any non-hidden token (i.e. any actual SQL content
+    // beyond whitespace and comments). Chunks that only contain whitespace/comments
+    // are dropped, matching the spark-sql CLI's long-standing behavior.
+    var bufferHasContent = false
+    var index = 0
+    var stopOuter = false
+    // The first index in `delimiterPositions` that is still > our cursor.
+    var delimSearchStart = 0
+
+    // Snapshot the session config once -- the splitter is short-lived and the
+    // splitter's parser must agree with the session config on grammar
+    // interpretation (e.g. `double_quoted_identifiers`).
+    val conf = SqlApiConf.get
+
+    while (!stopOuter && index < numTokens) {
+      val startIdx = nextSignificantTokenIndex(tokenStream, index)
+      if (startIdx < 0) {
+        // Just hidden trailing tokens (whitespace / closed comments). Drain
+        // them into the buffer; if any are an unclosed comment, the lexer
+        // flag will surface it as a partial.
+        while (index < numTokens) {
+          val tok = tokenStream.get(index)
+          index += 1
+          if (tok.getType != Token.EOF) buffer.append(tok.getText)
+        }
+        stopOuter = true
+      } else if (tokenStream.get(startIdx).getType == SqlBaseLexer.SEMICOLON) {
+        // The next significant token is itself a `;`. This is an empty
+        // statement (e.g. `;;` or leading `;`); drop everything from the
+        // cursor through this delimiter and continue.
+        index = startIdx + 1
+      } else {
+        // Advance the search for delimiters past our current cursor.
+        while (delimSearchStart < delimiterPositions.length &&
+            delimiterPositions(delimSearchStart) <= startIdx) {
+          delimSearchStart += 1
+        }
+
+        // Try increasingly long prefixes (each ending at a `;`) until the

Review Comment:
   Boundary detection here re-parses a *growing* prefix from the block start for each internal `;`, because `compoundOrSingleStatement` is `EOF`-terminated and can only answer "is this whole slice one statement?". So a `BEGIN ... END` block with k internal `;` costs ~k re-parses (O(k²)), and an incomplete block re-tries every delimiter on each interactive keystroke. Ordinary non-scripting SQL is linear and the cost is dwarfed by query execution, so this isn't a correctness issue — but an uncommon large/incomplete block is a real latency cliff.
   
   It can be made O(n) without changing the overall approach: parse each region *once* with a single-statement entry that is **not** `EOF`-terminated, then read where it stopped, instead of growing prefixes. The grammar already has the sub-rules — `beginEndCompoundBlock` (no EOF), `statement`, `setResetStatement` — so a small
   
   ```
   parseOneStatement : beginEndCompoundBlock | statement | setResetStatement ;
   ```
   
   lets you parse the remaining token stream once, take `ctx.getStop().getTokenIndex()` as the boundary, consume the trailing `;`, and continue. A top-level `statement` can't consume a `;`, so the parser stops at the boundary deterministically; the incomplete-vs-invalid (`LA(1) == EOF`) classification and the extension/invalid fallback are unchanged. Non-blocking, but worth doing since the worst case is user-visible latency.



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/SparkSqlParser.scala:
##########
@@ -103,6 +103,22 @@ class SparkSqlParser extends AbstractSqlParser {
     parseInternal(command, None)(toResult)
   }
 
+  /**
+   * Split a SQL string into individual statements after expanding any `${...}`
+   * variable references. Variable substitution has to happen *before* splitting
+   * because a substituted value may itself contain `;`, comments, or
+   * `BEGIN ... END` structure that affect statement boundaries.
+   *
+   * Parameter substitution is intentionally NOT applied here: the splitter
+   * runs at the top level of an interactive session / batch input, where there
+   * is no parameter context bound. If a caller does have a parameter context,
+   * they should pre-substitute the input and call this with the result.
+   */
+  override def splitStatements(sqlText: String): SqlStatementSplitResult = {
+    val variableSubstituted = substitutor.substitute(sqlText)

Review Comment:
   Substituting the whole input here and returning statements carved from the *substituted* text means the CLI substitutes the entire `-e`/`-f` batch before any statement executes. Because `ConfigReader` resolves config defaults eagerly, a `${conf}` whose value is changed by an earlier `SET` in the same batch resolves to the pre-`SET` / default value:
   
   ```
   SET spark.sql.shuffle.partitions=99;
   SELECT '${spark.sql.shuffle.partitions}' AS p;   -- yields 200, not 99
   ```
   
   The replaced `splitSemiColon` path substituted per-statement at parse time (`parseInternal`, after the `SET` ran), so this is a regression. Suggest splitting the raw text (i.e. drop this override and use the `AbstractSqlParser` default) and letting each statement substitute at parse — the old path never split on `;` inside a substituted value either, so no capability is lost. Interactive mode is unaffected since statements execute between splits.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org