You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@datafusion.apache.org by gi...@apache.org on 2026/04/09 09:20:36 UTC

(datafusion-sqlparser-rs) 01/01: Fix parsing EXECUTE (...) with a more general string expression (#2295)

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

github-bot pushed a commit to branch gh-readonly-queue/main/pr-2295-3a28ffa4bf973f34d9d68a0718612d9fa460091d
in repository https://gitbox.apache.org/repos/asf/datafusion-sqlparser-rs.git

commit ea9b413c9979badc71559ae6896c6e7aa74a696b
Author: Roman Borschel <ro...@users.noreply.github.com>
AuthorDate: Thu Apr 9 11:20:19 2026 +0200

    Fix parsing EXECUTE (...) with a more general string expression (#2295)
    
    Co-authored-by: Roman Borschel <ro...@cluvio.com>
---
 src/ast/mod.rs            |  5 +++--
 src/parser/mod.rs         | 42 +++++++++++++-----------------------------
 tests/sqlparser_common.rs |  4 ++--
 tests/sqlparser_mssql.rs  | 14 ++++++++++++++
 4 files changed, 32 insertions(+), 33 deletions(-)

diff --git a/src/ast/mod.rs b/src/ast/mod.rs
index d7a3679a..2268ed5e 100644
--- a/src/ast/mod.rs
+++ b/src/ast/mod.rs
@@ -4456,7 +4456,7 @@ pub enum Statement {
         name: Option<ObjectName>,
         /// Parameter expressions passed to execute.
         parameters: Vec<Expr>,
-        /// Whether parentheses were present.
+        /// Whether parentheses were present around `parameters`.
         has_parentheses: bool,
         /// Is this an `EXECUTE IMMEDIATE`.
         immediate: bool,
@@ -5911,7 +5911,8 @@ impl fmt::Display for Statement {
                 default,
             } => {
                 let (open, close) = if *has_parentheses {
-                    ("(", ")")
+                    // Space before `(` only when there is no name directly preceding it.
+                    (if name.is_some() { "(" } else { " (" }, ")")
                 } else {
                     (if parameters.is_empty() { "" } else { " " }, "")
                 };
diff --git a/src/parser/mod.rs b/src/parser/mod.rs
index 8497dc2e..70e8ce28 100644
--- a/src/parser/mod.rs
+++ b/src/parser/mod.rs
@@ -18881,31 +18881,21 @@ impl<'a> Parser<'a> {
 
     /// Parse a SQL `EXECUTE` statement
     pub fn parse_execute(&mut self) -> Result<Statement, ParserError> {
-        // Track whether the procedure/expression name itself was wrapped in parens,
-        // i.e. `EXEC (@sql)` (dynamic string execution) vs `EXEC sp_name`.
-        // When the name has parens there are no additional parameters.
-        let name = if self.dialect.supports_execute_immediate()
-            && self.parse_keyword(Keyword::IMMEDIATE)
-        {
+        let immediate =
+            self.dialect.supports_execute_immediate() && self.parse_keyword(Keyword::IMMEDIATE);
+
+        // When `EXEC` is immediately followed by `(`, the content is a dynamic-SQL
+        // expression — e.g. `EXEC (@sql)`, `EXEC ('SELECT ...')`, or
+        // `EXEC ('SELECT ... FROM ' + @tbl + ' WHERE ...')`.
+        // Skip name parsing; the expression ends up in `parameters` via the
+        // `has_parentheses` path below, consistent with `EXECUTE IMMEDIATE <expr>`.
+        let name = if immediate || matches!(self.peek_token_ref().token, Token::LParen) {
             None
         } else {
-            let has_parentheses = self.consume_token(&Token::LParen);
-            let name = self.parse_object_name(false)?;
-            if has_parentheses {
-                self.expect_token(&Token::RParen)?;
-            }
-            Some((name, has_parentheses))
+            Some(self.parse_object_name(false)?)
         };
 
-        let name_had_parentheses = name.as_ref().map(|(_, p)| *p).unwrap_or(false);
-
-        // Only look for a parameter list when the name was NOT wrapped in parens.
-        // `EXEC (@sql)` is dynamic SQL execution and takes no parameters here.
-        let has_parentheses = if name_had_parentheses {
-            false
-        } else {
-            self.consume_token(&Token::LParen)
-        };
+        let has_parentheses = self.consume_token(&Token::LParen);
 
         let end_kws = &[Keyword::USING, Keyword::OUTPUT, Keyword::DEFAULT];
         let end_token = match (has_parentheses, self.peek_token().token) {
@@ -18915,18 +18905,12 @@ impl<'a> Parser<'a> {
             (false, _) => Token::SemiColon,
         };
 
-        let parameters = if name_had_parentheses {
-            vec![]
-        } else {
-            self.parse_comma_separated0(Parser::parse_expr, end_token)?
-        };
+        let parameters = self.parse_comma_separated0(Parser::parse_expr, end_token)?;
 
         if has_parentheses {
             self.expect_token(&Token::RParen)?;
         }
 
-        let name = name.map(|(n, _)| n);
-
         let into = if self.parse_keyword(Keyword::INTO) {
             self.parse_comma_separated(Self::parse_identifier)?
         } else {
@@ -18944,7 +18928,7 @@ impl<'a> Parser<'a> {
         let default = self.parse_keyword(Keyword::DEFAULT);
 
         Ok(Statement::Execute {
-            immediate: name.is_none(),
+            immediate,
             name,
             parameters,
             has_parentheses,
diff --git a/tests/sqlparser_common.rs b/tests/sqlparser_common.rs
index 5c46f3cf..ad1e521f 100644
--- a/tests/sqlparser_common.rs
+++ b/tests/sqlparser_common.rs
@@ -12294,8 +12294,8 @@ fn parse_execute_stored_procedure() {
         }
         _ => unreachable!(),
     }
-    // Test optional parentheses around procedure name
-    ms_and_generic().one_statement_parses_to("EXEC ('name')", "EXECUTE 'name'");
+    // Parenthesised form is dynamic SQL; the expression ends up in parameters.
+    ms_and_generic().one_statement_parses_to("EXEC ('name')", "EXECUTE ('name')");
 }
 
 #[test]
diff --git a/tests/sqlparser_mssql.rs b/tests/sqlparser_mssql.rs
index 9f7b42eb..98609ae2 100644
--- a/tests/sqlparser_mssql.rs
+++ b/tests/sqlparser_mssql.rs
@@ -2819,6 +2819,20 @@ fn test_exec_dynamic_sql() {
     assert_eq!(stmts.len(), 2);
 }
 
+#[test]
+fn test_exec_dynamic_sql_string_concat() {
+    // EXEC with string concatenation: EXEC ('...' + @var + '...')
+    let stmts = tsql()
+        .parse_sql_statements("EXEC ('SELECT * FROM ' + @TableName + ' WHERE 1=1')")
+        .expect("EXEC with string concatenation should parse");
+    assert_eq!(stmts.len(), 1);
+    assert!(
+        matches!(&stmts[0], Statement::Execute { .. }),
+        "expected Execute, got: {:?}",
+        stmts[0]
+    );
+}
+
 // MSSQL OUTPUT clause on INSERT/UPDATE/DELETE
 // https://learn.microsoft.com/en-us/sql/t-sql/queries/output-clause-transact-sql
 #[test]


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@datafusion.apache.org
For additional commands, e-mail: commits-help@datafusion.apache.org