Skip to content
Draft
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
18 changes: 18 additions & 0 deletions src/ast/ddl.rs
Original file line number Diff line number Diff line change
Expand Up @@ -579,6 +579,11 @@ pub enum AlterTableOperation {
/// Target schema name.
schema_name: ObjectName,
},
/// `SET ACCESS METHOD { name | DEFAULT }`
SetAccessMethod {
/// Access method name, or `None` for `DEFAULT`.
access_method: Option<Ident>,
},
/// Arbitrary parenthesized `SET` options.
///
/// Example:
Expand Down Expand Up @@ -1186,6 +1191,10 @@ impl fmt::Display for AlterTableOperation {
AlterTableOperation::SetSchema { schema_name } => {
write!(f, "SET SCHEMA {schema_name}")
}
AlterTableOperation::SetAccessMethod { access_method } => match access_method {
Some(name) => write!(f, "SET ACCESS METHOD {name}"),
None => f.write_str("SET ACCESS METHOD DEFAULT"),
},
AlterTableOperation::SetOptionsParens { options } => {
write!(f, "SET ({})", display_comma_separated(options))
}
Expand Down Expand Up @@ -5462,6 +5471,11 @@ pub enum AlterViewOperation {
/// Target schema name.
schema_name: ObjectName,
},
/// `ALTER MATERIALIZED VIEW name SET ACCESS METHOD { name | DEFAULT }`
SetAccessMethod {
/// Access method name, or `None` for `DEFAULT`.
access_method: Option<Ident>,
},
/// ```sql
/// ALTER VIEW name SET ( view_option_name [ = view_option_value ] [, ... ] )
/// ```
Expand Down Expand Up @@ -5506,6 +5520,10 @@ impl fmt::Display for AlterViewOperation {
AlterViewOperation::SetSchema { schema_name } => {
write!(f, "SET SCHEMA {schema_name}")
}
AlterViewOperation::SetAccessMethod { access_method } => match access_method {
Some(name) => write!(f, "SET ACCESS METHOD {name}"),
None => f.write_str("SET ACCESS METHOD DEFAULT"),
},
AlterViewOperation::SetOptions { options } => {
write!(f, "SET ({})", display_comma_separated(options))
}
Expand Down
8 changes: 8 additions & 0 deletions src/ast/spans.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1213,6 +1213,7 @@ impl Spanned for AlterView {
///
/// Missing spans:
/// - [AlterViewOperation::OwnerTo]
/// - [AlterViewOperation::SetAccessMethod] with `DEFAULT`
impl Spanned for AlterViewOperation {
fn span(&self) -> Span {
match self {
Expand All @@ -1237,6 +1238,9 @@ impl Spanned for AlterViewOperation {
} => old_column_name.span.union(&new_column_name.span),
AlterViewOperation::RenameTo { new_name } => new_name.span(),
AlterViewOperation::SetSchema { schema_name } => schema_name.span(),
AlterViewOperation::SetAccessMethod { access_method } => access_method
.as_ref()
.map_or(Span::empty(), |name| name.span),
AlterViewOperation::SetOptions { options } => {
union_spans(options.iter().map(|i| i.span()))
}
Expand All @@ -1251,6 +1255,7 @@ impl Spanned for AlterViewOperation {
///
/// Missing spans:
/// - [AlterTableOperation::OwnerTo]
/// - [AlterTableOperation::SetAccessMethod] with `DEFAULT`
impl Spanned for AlterTableOperation {
fn span(&self) -> Span {
match self {
Expand Down Expand Up @@ -1399,6 +1404,9 @@ impl Spanned for AlterTableOperation {
parent.span()
}
AlterTableOperation::SetSchema { schema_name } => schema_name.span(),
AlterTableOperation::SetAccessMethod { access_method } => access_method
.as_ref()
.map_or(Span::empty(), |name| name.span),
AlterTableOperation::SetOptionsParens { options } => {
union_spans(options.iter().map(|i| i.span()))
}
Expand Down
4 changes: 4 additions & 0 deletions src/dialect/generic.rs
Original file line number Diff line number Diff line change
Expand Up @@ -377,6 +377,10 @@ impl Dialect for GenericDialect {
true
}

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

fn supports_alter_column_position(&self) -> bool {
true
}
Expand Down
6 changes: 6 additions & 0 deletions src/dialect/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,7 @@ pub use self::hive::HiveDialect;
pub use self::mssql::MsSqlDialect;
pub use self::mysql::MySqlDialect;
pub use self::oracle::OracleDialect;
pub(crate) use self::postgresql::is_postgresql_col_id;
pub use self::postgresql::PostgreSqlDialect;
pub use self::redshift::RedshiftSqlDialect;
pub use self::snowflake::parse_snowflake_stage_name;
Expand Down Expand Up @@ -1904,6 +1905,11 @@ pub trait Dialect: Debug + Any {
false
}

/// Returns true if `ALTER TABLE` and `ALTER MATERIALIZED VIEW` support `SET ACCESS METHOD`.
fn supports_alter_set_access_method(&self) -> bool {
false
}

/// Returns true if the dialect supports `ALTER TABLE tbl DROP COLUMN c1, ..., cn`
fn supports_comma_separated_drop_column_list(&self) -> bool {
false
Expand Down
15 changes: 14 additions & 1 deletion src/dialect/postgresql.rs
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ use log::debug;
use crate::dialect::{BindPlaceholderStyle, Dialect, Precedence};
use crate::keywords::Keyword;
use crate::parser::{Parser, ParserError};
use crate::tokenizer::Token;
use crate::tokenizer::{Token, Word};

use super::keywords::{self, RESERVED_FOR_IDENTIFIER};

Expand Down Expand Up @@ -201,6 +201,15 @@ const TYPE_FUNC_NAME_KEYWORDS: &[Keyword] = &[
Keyword::VERBOSE,
];

/// PostgreSQL `ColId` excludes reserved and type/function-name keywords.
pub(crate) fn is_postgresql_col_id(word: &Word) -> bool {
word.quote_style.is_some()
|| (!RESERVED_TYPE_NAME_KEYWORDS.contains(&word.keyword)
&& !TYPE_FUNC_NAME_KEYWORDS.contains(&word.keyword)
// The tokenizer does not classify the reserved spelling `ANALYSE` as a keyword.
&& !word.value.eq_ignore_ascii_case("analyse"))
}

/// A [`Dialect`] for [PostgreSQL](https://www.postgresql.org/)
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
Expand Down Expand Up @@ -541,6 +550,10 @@ impl Dialect for PostgreSqlDialect {
true
}

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

/// PostgreSQL supports right-deep join chains: `t0 JOIN t1 JOIN t2 ON c1 ON c2`
/// See: <https://www.postgresql.org/docs/current/queries-table-expressions.html#QUERIES-JOIN>
fn supports_left_associative_joins_without_parens(&self) -> bool {
Expand Down
24 changes: 24 additions & 0 deletions src/parser/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12123,6 +12123,12 @@ impl<'a> Parser<'a> {
AlterTableOperation::SetSchema {
schema_name: self.parse_object_name(false)?,
}
} else if self.dialect.supports_alter_set_access_method()
&& self.parse_keywords(&[Keyword::SET, Keyword::ACCESS, Keyword::METHOD])
{
AlterTableOperation::SetAccessMethod {
access_method: self.parse_set_access_method_name()?,
}
} else if self.parse_keyword(Keyword::RESET) {
self.expect_token(&Token::LParen)?;
let options = self.parse_comma_separated(|p| p.parse_object_name(false))?;
Expand Down Expand Up @@ -12154,6 +12160,17 @@ impl<'a> Parser<'a> {
Ok(operation)
}

fn parse_set_access_method_name(&mut self) -> Result<Option<Ident>, ParserError> {
let next = self.peek_token_ref();
let access_method = match &next.token {
Token::Word(word) if word.keyword == Keyword::DEFAULT => None,
Token::Word(word) if is_postgresql_col_id(word) => Some(word.to_ident(next.span)),
_ => return self.expected_ref("access method name or DEFAULT", next),
};
self.advance_token();
Ok(access_method)
}

fn parse_set_data_type(&mut self, had_set: bool) -> Result<AlterColumnOperation, ParserError> {
let data_type = self.parse_data_type()?;
let collation = if self.parse_keyword(Keyword::COLLATE) {
Expand Down Expand Up @@ -12554,6 +12571,13 @@ impl<'a> Parser<'a> {
AlterViewOperation::SetSchema {
schema_name: self.parse_object_name(false)?,
}
} else if materialized
&& self.dialect.supports_alter_set_access_method()
&& self.parse_keywords(&[Keyword::SET, Keyword::ACCESS, Keyword::METHOD])
{
AlterViewOperation::SetAccessMethod {
access_method: self.parse_set_access_method_name()?,
}
} else if self.parse_keyword(Keyword::SET) {
self.expect_token(&Token::LParen)?;
let options = self.parse_comma_separated(|parser| {
Expand Down
155 changes: 155 additions & 0 deletions tests/sqlparser_postgres.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14874,3 +14874,158 @@ fn parse_create_function_transform() {
);
}
}

#[test]
fn parse_alter_table_set_access_method() {
let dialects = pg_and_generic();
for (sql, access_method) in [
(
"ALTER TABLE my_table SET ACCESS METHOD heap",
Some(Ident::new("heap")),
),
("ALTER TABLE my_table SET ACCESS METHOD DEFAULT", None),
(
"ALTER TABLE IF EXISTS ONLY my_schema.my_table SET ACCESS METHOD my_access_method",
Some(Ident::new("my_access_method")),
),
(
r#"ALTER TABLE my_table SET ACCESS METHOD "default""#,
Some(Ident::with_quote('"', "default")),
),
] {
let Statement::AlterTable(alter) = dialects.verified_stmt(sql) else {
unreachable!()
};
assert_eq!(
alter.operations,
vec![AlterTableOperation::SetAccessMethod { access_method }],
"{sql}"
);
}

let Statement::AlterTable(alter) =
dialects.verified_stmt("ALTER TABLE my_table SET ACCESS METHOD between, ADD COLUMN c INT")
else {
unreachable!()
};
assert!(matches!(
alter.operations.as_slice(),
[
AlterTableOperation::SetAccessMethod {
access_method: Some(method),
},
AlterTableOperation::AddColumn { column_def, .. },
] if method == &Ident::new("between") && column_def.name == Ident::new("c")
));
}

#[test]
fn parse_alter_materialized_view_set_access_method() {
let dialects = pg_and_generic();
for (sql, access_method) in [
(
"ALTER MATERIALIZED VIEW my_view SET ACCESS METHOD heap",
Some(Ident::new("heap")),
),
(
"ALTER MATERIALIZED VIEW IF EXISTS my_view SET ACCESS METHOD DEFAULT",
None,
),
(
r#"ALTER MATERIALIZED VIEW my_schema.my_view SET ACCESS METHOD "default""#,
Some(Ident::with_quote('"', "default")),
),
] {
let Statement::AlterView(alter) = dialects.verified_stmt(sql) else {
unreachable!()
};
assert_eq!(
alter.operation,
AlterViewOperation::SetAccessMethod { access_method },
"{sql}"
);
}
}

#[test]
fn parse_alter_set_access_method_spans() {
let dialects = pg_and_generic();
for (sql, expected) in [
(
"ALTER TABLE my_table SET ACCESS METHOD heap",
Span::new(Location::new(1, 40), Location::new(1, 44)),
),
(
r#"ALTER MATERIALIZED VIEW my_view SET ACCESS METHOD "default""#,
Span::new(Location::new(1, 51), Location::new(1, 60)),
),
(
"ALTER TABLE my_table SET ACCESS METHOD DEFAULT",
Span::empty(),
),
(
"ALTER MATERIALIZED VIEW my_view SET ACCESS METHOD DEFAULT",
Span::empty(),
),
] {
let span =
dialects.run_parser_method(sql, |parser| match parser.parse_statement().unwrap() {
Statement::AlterTable(alter) => alter.operations[0].span(),
Statement::AlterView(alter) => alter.operation.span(),
statement => {
panic!("expected ALTER TABLE or ALTER MATERIALIZED VIEW, got {statement:?}")
}
});
assert_eq!(span, expected, "{sql}");
}
}

#[test]
fn parse_alter_set_access_method_errors() {
let dialects = pg_and_generic();
let mysql = TestedDialects::new(vec![Box::new(MySqlDialect {})]);
for relation in ["TABLE my_table", "MATERIALIZED VIEW my_view"] {
let sql = format!("ALTER {relation} SET ACCESS METHOD");
for (suffix, found) in [
("", "EOF"),
(" 42", "42"),
(" 'heap'", "'heap'"),
(" SELECT", "SELECT"),
(" LEFT", "LEFT"),
(" ANALYSE", "ANALYSE"),
] {
assert_eq!(
dialects
.parse_sql_statements(&format!("{sql}{suffix}"))
.unwrap_err()
.to_string(),
format!(
"sql parser error: Expected: access method name or DEFAULT, found: {found}"
)
);
}
for (suffix, found) in [("my_schema.heap", "."), ("heap()", "(")] {
assert_eq!(
dialects
.parse_sql_statements(&format!("{sql} {suffix}"))
.unwrap_err()
.to_string(),
format!("sql parser error: Expected: end of statement, found: {found}")
);
}
assert_eq!(
mysql
.parse_sql_statements(&format!("{sql} heap"))
.unwrap_err()
.to_string(),
"sql parser error: Expected: (, found: ACCESS"
);
}
assert_eq!(
dialects
.parse_sql_statements("ALTER VIEW my_view SET ACCESS METHOD heap")
.unwrap_err()
.to_string(),
"sql parser error: Expected: (, found: ACCESS"
);
}
Loading