Skip to content
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

BigQuery: ALTER ... SET OPTIONS #36

Merged
merged 3 commits into from
Mar 26, 2024
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
10 changes: 9 additions & 1 deletion src/ast/ddl.rs
Original file line number Diff line number Diff line change
Expand Up @@ -99,10 +99,15 @@ pub enum AlterTableOperation {
column_name: Ident,
op: AlterColumnOperation,
},
/// 'SWAP WITH <table_name>'
/// `SWAP WITH <table_name>`
///
/// Note: this is Snowflake specific <https://docs.snowflake.com/en/sql-reference/sql/alter-table>
SwapWith { table_name: ObjectName },

/// `SET OPTIONS(table_set_options_list)`
///
/// Note: this is BigQuery specific <https://cloud.google.com/bigquery/docs/reference/standard-sql/data-definition-language#alter_table_set_options_statement>
SetOptions { options: Vec<SqlOption> },
}

#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
Expand Down Expand Up @@ -213,6 +218,9 @@ impl fmt::Display for AlterTableOperation {
AlterTableOperation::SwapWith { table_name } => {
write!(f, "SWAP WITH {table_name}")
}
AlterTableOperation::SetOptions { options } => {
write!(f, "SET OPTIONS({})", display_comma_separated(options))
}
}
}
}
Expand Down
28 changes: 25 additions & 3 deletions src/ast/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1695,14 +1695,22 @@ pub enum Statement {
name: ObjectName,
operation: AlterIndexOperation,
},
/// ALTER VIEW
/// ALTER VIEW AS
AlterView {
/// View name
#[cfg_attr(feature = "visitor", visit(with = "visit_relation"))]
name: ObjectName,
columns: Vec<WithSpan<Ident>>,
query: Box<Query>,
query: Option<Query>,
with_options: Vec<SqlOption>,
set_options: Vec<SqlOption>,
},
/// ALTER SCHEMA
AlterSchema {
/// View name
#[cfg_attr(feature = "visitor", visit(with = "visit_relation"))]
name: ObjectName,
set_options: Vec<SqlOption>,
},
/// ALTER ROLE
AlterRole {
Expand Down Expand Up @@ -3030,6 +3038,7 @@ impl fmt::Display for Statement {
columns,
query,
with_options,
set_options,
} => {
write!(f, "ALTER VIEW {name}")?;
if !with_options.is_empty() {
Expand All @@ -3038,7 +3047,20 @@ impl fmt::Display for Statement {
if !columns.is_empty() {
write!(f, " ({})", display_comma_separated(columns))?;
}
write!(f, " AS {query}")
if let Some(query) = query {
write!(f, " AS {query}")?;
}
if !set_options.is_empty() {
write!(f, " SET OPTIONS ({})", display_comma_separated(set_options))?;
}
Ok(())
}
Statement::AlterSchema { name, set_options } => {
write!(f, "ALTER SCHEMA {name}")?;
if !set_options.is_empty() {
write!(f, " SET OPTIONS ({})", display_comma_separated(set_options))?;
}
Ok(())
}
Statement::AlterRole { name, operation } => {
write!(f, "ALTER ROLE {name} {operation}")
Expand Down
11 changes: 8 additions & 3 deletions src/ast/value.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ use bigdecimal::BigDecimal;
#[cfg(feature = "serde")]
use serde::{Deserialize, Serialize};

use crate::ast::Expr;
use crate::ast::{display_comma_separated, Expr};
#[cfg(feature = "visitor")]
use sqlparser_derive::{Visit, VisitMut};

Expand Down Expand Up @@ -79,6 +79,9 @@ pub enum Value {
/// https://docs.snowflake.com/en/sql-reference/data-types-semistructured#object-constants
ObjectConstant(Vec<ObjectConstantKeyValue>),
Array(Vec<Value>),
/// TUPLE as used by BigQuery
/// ("org_unit", "development")
Tuple(Vec<Value>),
}

impl fmt::Display for Value {
Expand Down Expand Up @@ -116,8 +119,10 @@ impl fmt::Display for Value {
}
}
Value::Array(values) => {
let collected: Vec<String> = values.iter().map(|v| format!("{}", v)).collect();
write!(f, "[{}]", collected.join(", "))
write!(f, "[{}]", display_comma_separated(values))
}
Value::Tuple(values) => {
write!(f, "({})", display_comma_separated(values))
}
}
}
Expand Down
41 changes: 39 additions & 2 deletions src/parser/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4836,6 +4836,11 @@ impl<'a> Parser<'a> {
self.expect_keyword(Keyword::WITH)?;
let table_name = self.parse_object_name()?;
AlterTableOperation::SwapWith { table_name }
} else if self.parse_keyword(Keyword::SET) {
self.expect_keyword(Keyword::OPTIONS)?;
self.prev_token();
let options = self.parse_options(Keyword::OPTIONS)?;
AlterTableOperation::SetOptions { options }
} else {
return self.expected(
"ADD, RENAME, PARTITION, SWAP or DROP after ALTER TABLE",
Expand All @@ -4851,6 +4856,7 @@ impl<'a> Parser<'a> {
Keyword::TABLE,
Keyword::INDEX,
Keyword::ROLE,
Keyword::SCHEMA,
])?;
match object_type {
Keyword::VIEW => self.parse_alter_view(),
Expand Down Expand Up @@ -4885,6 +4891,7 @@ impl<'a> Parser<'a> {
})
}
Keyword::ROLE => self.parse_alter_role(),
Keyword::SCHEMA => self.parse_alter_schema(),
// unreachable because expect_one_of_keywords used above
_ => unreachable!(),
}
Expand All @@ -4896,17 +4903,39 @@ impl<'a> Parser<'a> {

let with_options = self.parse_options(Keyword::WITH)?;

self.expect_keyword(Keyword::AS)?;
let query = Box::new(self.parse_query()?);
let query = if self.parse_keyword(Keyword::AS) {
Some(self.parse_query()?)
} else {
None
};

let set_options = if self.parse_keywords(&[Keyword::SET, Keyword::OPTIONS]) {
self.prev_token();
self.parse_options(Keyword::OPTIONS)?
} else {
vec![]
};

Ok(Statement::AlterView {
name,
columns,
query,
with_options,
set_options,
})
}

pub fn parse_alter_schema(&mut self) -> Result<Statement, ParserError> {
let name = self.parse_object_name()?;

self.expect_keywords(&[Keyword::SET, Keyword::OPTIONS])?;
self.prev_token();

let set_options = self.parse_options(Keyword::OPTIONS)?;

Ok(Statement::AlterSchema { name, set_options })
}

/// Parse a copy statement
pub fn parse_copy(&mut self) -> Result<Statement, ParserError> {
let source;
Expand Down Expand Up @@ -5231,6 +5260,14 @@ impl<'a> Parser<'a> {
self.expect_token(&Token::RBracket)?;
Ok(Value::Array(fields))
}
Token::LParen => {
let values = self.parse_comma_separated(Parser::parse_value)?;
if values.len() == 1 {
Ok(values.into_iter().next().unwrap())
} else {
Ok(Value::Tuple(values))
}
}
unexpected => self.expected(
"a value",
TokenWithLocation {
Expand Down
16 changes: 16 additions & 0 deletions tests/sqlparser_bigquery.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1292,3 +1292,19 @@ fn test_create_view_options() {
"CREATE VIEW `myproject`.`mydataset`.`newview` OPTIONS(friendly_name = \"newview\", description = \"a view that expires in 2 days\") AS SELECT col_1 FROM `myproject`.`mydataset`.`mytable`",
);
}

#[test]
fn test_alter_table_set_options() {
bigquery().verified_stmt("ALTER TABLE tbl SET OPTIONS(description = \"Desc.\")");
}

#[test]
fn test_alter_view_set_options() {
bigquery().verified_stmt("ALTER VIEW tbl SET OPTIONS (description = \"Desc.\")");
}

#[test]
fn test_alter_schema_set_options() {
bigquery()
.verified_stmt("ALTER SCHEMA mydataset SET OPTIONS (default_table_expiration_days = 3.75)");
}
8 changes: 6 additions & 2 deletions tests/sqlparser_common.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3231,11 +3231,13 @@ fn parse_alter_view() {
columns,
query,
with_options,
set_options,
} => {
assert_eq!("myschema.myview", name.to_string());
assert_eq!(Vec::<WithSpan<Ident>>::new(), columns);
assert_eq!("SELECT foo FROM bar", query.to_string());
assert_eq!("SELECT foo FROM bar", query.unwrap().to_string());
assert_eq!(with_options, vec![]);
assert_eq!(set_options, vec![]);
}
_ => unreachable!(),
}
Expand Down Expand Up @@ -3273,6 +3275,7 @@ fn parse_alter_view_with_columns() {
columns,
query,
with_options,
set_options,
} => {
assert_eq!("v", name.to_string());
assert_eq!(
Expand All @@ -3282,8 +3285,9 @@ fn parse_alter_view_with_columns() {
Ident::new("cols").empty_span(),
]
);
assert_eq!("SELECT 1, 2", query.to_string());
assert_eq!("SELECT 1, 2", query.unwrap().to_string());
assert_eq!(with_options, vec![]);
assert_eq!(set_options, vec![]);
}
_ => unreachable!(),
}
Expand Down
Loading