Skip to content

Add support for EXECUTE IMMEDIATE #1717

New issue

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

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

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Feb 19, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 21 additions & 10 deletions src/ast/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3288,18 +3288,21 @@ pub enum Statement {
/// Note: this is a PostgreSQL-specific statement.
Deallocate { name: Ident, prepare: bool },
/// ```sql
/// EXECUTE name [ ( parameter [, ...] ) ] [USING <expr>]
/// An `EXECUTE` statement
/// ```
///
/// Note: this statement is supported by Postgres and MSSQL, with slight differences in syntax.
///
/// Postgres: <https://www.postgresql.org/docs/current/sql-execute.html>
/// MSSQL: <https://learn.microsoft.com/en-us/sql/relational-databases/stored-procedures/execute-a-stored-procedure>
/// BigQuery: <https://cloud.google.com/bigquery/docs/reference/standard-sql/procedural-language#execute_immediate>
/// Snowflake: <https://docs.snowflake.com/en/sql-reference/sql/execute-immediate>
Execute {
name: ObjectName,
name: Option<ObjectName>,
parameters: Vec<Expr>,
has_parentheses: bool,
using: Vec<Expr>,
/// Is this an `EXECUTE IMMEDIATE`
immediate: bool,
into: Vec<Ident>,
using: Vec<ExprWithAlias>,
},
/// ```sql
/// PREPARE name [ ( data_type [, ...] ) ] AS statement
Expand Down Expand Up @@ -4905,18 +4908,26 @@ impl fmt::Display for Statement {
name,
parameters,
has_parentheses,
immediate,
into,
using,
} => {
let (open, close) = if *has_parentheses {
("(", ")")
} else {
(if parameters.is_empty() { "" } else { " " }, "")
};
write!(
f,
"EXECUTE {name}{open}{}{close}",
display_comma_separated(parameters),
)?;
write!(f, "EXECUTE")?;
if *immediate {
write!(f, " IMMEDIATE")?;
}
if let Some(name) = name {
write!(f, " {name}")?;
}
write!(f, "{open}{}{close}", display_comma_separated(parameters),)?;
if !into.is_empty() {
write!(f, " INTO {}", display_comma_separated(into))?;
}
if !using.is_empty() {
write!(f, " USING {}", display_comma_separated(using))?;
};
Expand Down
5 changes: 5 additions & 0 deletions src/dialect/bigquery.rs
Original file line number Diff line number Diff line change
Expand Up @@ -110,6 +110,11 @@ impl Dialect for BigQueryDialect {
true
}

/// See <https://cloud.google.com/bigquery/docs/reference/standard-sql/procedural-language#execute_immediate>
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

i like how we are settling on using methods in Dialect to support the various options

fn supports_execute_immediate(&self) -> bool {
true
}

// See <https://cloud.google.com/bigquery/docs/access-historical-data>
fn supports_timestamp_versioning(&self) -> bool {
true
Expand Down
5 changes: 5 additions & 0 deletions src/dialect/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -250,6 +250,11 @@ pub trait Dialect: Debug + Any {
false
}

/// Returns true if the dialect supports `EXECUTE IMMEDIATE` statements.
fn supports_execute_immediate(&self) -> bool {
false
}

/// Returns true if the dialect supports the MATCH_RECOGNIZE operation.
fn supports_match_recognize(&self) -> bool {
false
Expand Down
5 changes: 5 additions & 0 deletions src/dialect/snowflake.rs
Original file line number Diff line number Diff line change
Expand Up @@ -91,6 +91,11 @@ impl Dialect for SnowflakeDialect {
true
}

/// See <https://docs.snowflake.com/en/sql-reference/sql/execute-immediate>
fn supports_execute_immediate(&self) -> bool {
true
}

fn supports_match_recognize(&self) -> bool {
true
}
Expand Down
26 changes: 19 additions & 7 deletions src/parser/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13695,7 +13695,14 @@ impl<'a> Parser<'a> {
}

pub fn parse_execute(&mut self) -> Result<Statement, ParserError> {
let name = self.parse_object_name(false)?;
let name = if self.dialect.supports_execute_immediate()
&& self.parse_keyword(Keyword::IMMEDIATE)
{
None
} else {
let name = self.parse_object_name(false)?;
Some(name)
};

let has_parentheses = self.consume_token(&Token::LParen);

Expand All @@ -13712,19 +13719,24 @@ impl<'a> Parser<'a> {
self.expect_token(&Token::RParen)?;
}

let mut using = vec![];
if self.parse_keyword(Keyword::USING) {
using.push(self.parse_expr()?);
let into = if self.parse_keyword(Keyword::INTO) {
self.parse_comma_separated(Self::parse_identifier)?
} else {
vec![]
};

while self.consume_token(&Token::Comma) {
using.push(self.parse_expr()?);
}
let using = if self.parse_keyword(Keyword::USING) {
self.parse_comma_separated(Self::parse_expr_with_alias)?
} else {
vec![]
};

Ok(Statement::Execute {
immediate: name.is_none(),
name,
parameters,
has_parentheses,
into,
using,
})
}
Expand Down
41 changes: 39 additions & 2 deletions tests/sqlparser_common.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10575,7 +10575,7 @@ fn parse_call() {
#[test]
fn parse_execute_stored_procedure() {
let expected = Statement::Execute {
name: ObjectName::from(vec![
name: Some(ObjectName::from(vec![
Ident {
value: "my_schema".to_string(),
quote_style: None,
Expand All @@ -10586,13 +10586,15 @@ fn parse_execute_stored_procedure() {
quote_style: None,
span: Span::empty(),
},
]),
])),
parameters: vec![
Expr::Value(Value::NationalStringLiteral("param1".to_string())),
Expr::Value(Value::NationalStringLiteral("param2".to_string())),
],
has_parentheses: false,
immediate: false,
using: vec![],
into: vec![],
};
assert_eq!(
// Microsoft SQL Server does not use parentheses around arguments for EXECUTE
Expand All @@ -10609,6 +10611,41 @@ fn parse_execute_stored_procedure() {
);
}

#[test]
fn parse_execute_immediate() {
let dialects = all_dialects_where(|d| d.supports_execute_immediate());

let expected = Statement::Execute {
parameters: vec![Expr::Value(Value::SingleQuotedString(
"SELECT 1".to_string(),
))],
immediate: true,
using: vec![ExprWithAlias {
expr: Expr::Value(number("1")),
alias: Some(Ident::new("b")),
}],
into: vec![Ident::new("a")],
name: None,
has_parentheses: false,
};

let stmt = dialects.verified_stmt("EXECUTE IMMEDIATE 'SELECT 1' INTO a USING 1 AS b");
assert_eq!(expected, stmt);

dialects.verified_stmt("EXECUTE IMMEDIATE 'SELECT 1' INTO a, b USING 1 AS x, y");
dialects.verified_stmt("EXECUTE IMMEDIATE 'SELECT 1' USING 1 AS x, y");
dialects.verified_stmt("EXECUTE IMMEDIATE 'SELECT 1' INTO a, b");
dialects.verified_stmt("EXECUTE IMMEDIATE 'SELECT 1'");
dialects.verified_stmt("EXECUTE 'SELECT 1'");

assert_eq!(
ParserError::ParserError("Expected: identifier, found: ,".to_string()),
dialects
.parse_sql_statements("EXECUTE IMMEDIATE 'SELECT 1' USING 1 AS, y")
.unwrap_err()
);
}

#[test]
fn parse_create_table_collate() {
pg_and_generic().verified_stmt("CREATE TABLE tbl (foo INT, bar TEXT COLLATE \"de_DE\")");
Expand Down
44 changes: 28 additions & 16 deletions tests/sqlparser_postgres.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1658,24 +1658,28 @@ fn parse_execute() {
assert_eq!(
stmt,
Statement::Execute {
name: ObjectName::from(vec!["a".into()]),
name: Some(ObjectName::from(vec!["a".into()])),
parameters: vec![],
has_parentheses: false,
using: vec![]
using: vec![],
immediate: false,
into: vec![]
}
);

let stmt = pg_and_generic().verified_stmt("EXECUTE a(1, 't')");
assert_eq!(
stmt,
Statement::Execute {
name: ObjectName::from(vec!["a".into()]),
name: Some(ObjectName::from(vec!["a".into()])),
parameters: vec![
Expr::Value(number("1")),
Expr::Value(Value::SingleQuotedString("t".to_string()))
],
has_parentheses: true,
using: vec![]
using: vec![],
immediate: false,
into: vec![]
}
);

Expand All @@ -1684,23 +1688,31 @@ fn parse_execute() {
assert_eq!(
stmt,
Statement::Execute {
name: ObjectName::from(vec!["a".into()]),
name: Some(ObjectName::from(vec!["a".into()])),
parameters: vec![],
has_parentheses: false,
using: vec![
Expr::Cast {
kind: CastKind::Cast,
expr: Box::new(Expr::Value(Value::Number("1337".parse().unwrap(), false))),
data_type: DataType::SmallInt(None),
format: None
ExprWithAlias {
expr: Expr::Cast {
kind: CastKind::Cast,
expr: Box::new(Expr::Value(Value::Number("1337".parse().unwrap(), false))),
data_type: DataType::SmallInt(None),
format: None
},
alias: None
},
Expr::Cast {
kind: CastKind::Cast,
expr: Box::new(Expr::Value(Value::Number("7331".parse().unwrap(), false))),
data_type: DataType::SmallInt(None),
format: None
ExprWithAlias {
expr: Expr::Cast {
kind: CastKind::Cast,
expr: Box::new(Expr::Value(Value::Number("7331".parse().unwrap(), false))),
data_type: DataType::SmallInt(None),
format: None
},
alias: None
},
]
],
immediate: false,
into: vec![]
}
);
}
Expand Down