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
17 changes: 14 additions & 3 deletions src/ast/ddl.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1468,6 +1468,13 @@ pub enum AlterColumnOperation {
/// The type of storage.
storage: UserDefinedTypeStorage,
},
/// `SET STATISTICS { <integer> | DEFAULT }`
///
/// [PostgreSQL](https://www.postgresql.org/docs/current/sql-altertable.html)
SetStatistics {
/// The statistics target, or `None` for `DEFAULT`.
target: Option<i64>,
},
/// `OPTIONS ( [ ADD | SET | DROP ] option ['value'] [, ...] )`, changing the
/// options of a foreign table column.
///
Expand Down Expand Up @@ -1539,6 +1546,10 @@ impl fmt::Display for AlterColumnOperation {
AlterColumnOperation::SetStorage { storage } => {
write!(f, "SET STORAGE {storage}")
}
AlterColumnOperation::SetStatistics { target } => match target {
Some(target) => write!(f, "SET STATISTICS {target}"),
None => write!(f, "SET STATISTICS DEFAULT"),
},
AlterColumnOperation::GenericOptions { options } => {
write!(f, "OPTIONS ({})", display_comma_separated(options))
}
Expand Down Expand Up @@ -5392,8 +5403,7 @@ impl Spanned for AlterCollation {
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
pub struct AlterView {
/// Whether `MATERIALIZED` was specified. A materialized view's operation is never
/// [`AlterViewOperation::As`] or [`AlterViewOperation::AlterColumn`].
/// Whether `MATERIALIZED` was specified.
pub materialized: bool,
/// View name being altered.
#[cfg_attr(feature = "visitor", visit(with = "visit_relation"))]
Expand Down Expand Up @@ -5428,11 +5438,12 @@ pub enum AlterViewOperation {
},
/// ```sql
/// ALTER VIEW name ALTER [ COLUMN ] column_name { SET DEFAULT expression | DROP DEFAULT }
/// ALTER MATERIALIZED VIEW name ALTER [ COLUMN ] column_name SET STATISTICS { <integer> | DEFAULT }
/// ```
AlterColumn {
/// The column to alter.
column_name: Ident,
/// Either [`AlterColumnOperation::SetDefault`] or [`AlterColumnOperation::DropDefault`].
/// A column default operation, or [`AlterColumnOperation::SetStatistics`] for a materialized view.
op: AlterColumnOperation,
},
/// ```sql
Expand Down
2 changes: 2 additions & 0 deletions src/ast/spans.rs
Original file line number Diff line number Diff line change
Expand Up @@ -974,6 +974,7 @@ impl Spanned for RefreshMaterializedView {
/// - [AlterColumnOperation::DropDefault]
/// - [AlterColumnOperation::AddGenerated]
/// - [AlterColumnOperation::SetStorage]
/// - [AlterColumnOperation::SetStatistics]
impl Spanned for AlterColumnOperation {
fn span(&self) -> Span {
match self {
Expand All @@ -995,6 +996,7 @@ impl Spanned for AlterColumnOperation {
AlterColumnOperation::AddGenerated { .. } => Span::empty(),
AlterColumnOperation::DropExpression { .. } => Span::empty(),
AlterColumnOperation::SetStorage { .. } => Span::empty(),
AlterColumnOperation::SetStatistics { .. } => Span::empty(),
AlterColumnOperation::GenericOptions { options } => {
union_spans(options.iter().map(|option| option.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 @@ -384,4 +384,8 @@ impl Dialect for GenericDialect {
fn supports_add_column_if_not_exists(&self) -> bool {
true
}

fn supports_alter_column_set_statistics(&self) -> bool {
true
}
}
10 changes: 10 additions & 0 deletions src/dialect/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1904,6 +1904,16 @@ pub trait Dialect: Debug + Any {
false
}

/// Returns true if the dialect supports the `SET STATISTICS` operation in an
/// `ALTER [ COLUMN ]` clause.
/// Example:
/// ```sql
/// ALTER TABLE tbl ALTER COLUMN col SET STATISTICS 100
/// ```
fn supports_alter_column_set_statistics(&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
4 changes: 4 additions & 0 deletions src/dialect/postgresql.rs
Original file line number Diff line number Diff line change
Expand Up @@ -541,6 +541,10 @@ impl Dialect for PostgreSqlDialect {
true
}

fn supports_alter_column_set_statistics(&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
20 changes: 19 additions & 1 deletion src/parser/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11960,6 +11960,10 @@ impl<'a> Parser<'a> {
AlterColumnOperation::SetStorage {
storage: self.parse_user_defined_type_storage()?,
}
} else if self.dialect.supports_alter_column_set_statistics()
&& self.parse_keywords(&[Keyword::SET, Keyword::STATISTICS])
{
self.parse_set_statistics()?
} else {
let message = if is_postgresql {
"SET/DROP NOT NULL, SET DEFAULT, SET DATA TYPE, ADD GENERATED, or OPTIONS after ALTER COLUMN"
Expand Down Expand Up @@ -12543,6 +12547,15 @@ impl<'a> Parser<'a> {
.into())
}

fn parse_set_statistics(&mut self) -> Result<AlterColumnOperation, ParserError> {
let target = if self.parse_keyword(Keyword::DEFAULT) {
None
} else {
Some(self.parse_signed_integer()?)
};
Ok(AlterColumnOperation::SetStatistics { target })
}

/// Parse an `ALTER [ MATERIALIZED ] VIEW` statement.
pub fn parse_alter_view(&mut self, materialized: bool) -> Result<Statement, ParserError> {
let if_exists = self.parse_keywords(&[Keyword::IF, Keyword::EXISTS]);
Expand Down Expand Up @@ -12589,7 +12602,12 @@ impl<'a> Parser<'a> {
} else if self.parse_keyword(Keyword::ALTER) {
let _ = self.parse_keyword(Keyword::COLUMN);
let column_name = self.parse_identifier()?;
let op = if self.parse_keywords(&[Keyword::SET, Keyword::DEFAULT]) {
let op = if materialized
&& self.dialect.supports_alter_column_set_statistics()
&& self.parse_keywords(&[Keyword::SET, Keyword::STATISTICS])
{
self.parse_set_statistics()?
} else if self.parse_keywords(&[Keyword::SET, Keyword::DEFAULT]) {
AlterColumnOperation::SetDefault {
value: self.parse_expr()?,
}
Expand Down
119 changes: 119 additions & 0 deletions tests/sqlparser_postgres.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14874,3 +14874,122 @@ fn parse_create_function_transform() {
);
}
}

#[test]
fn parse_alter_column_set_statistics() {
for (sql, canonical, target) in [
(
"ALTER TABLE t ALTER COLUMN c SET STATISTICS 100",
"ALTER TABLE t ALTER COLUMN c SET STATISTICS 100",
Some(100),
),
(
"ALTER TABLE t ALTER COLUMN c SET STATISTICS -1",
"ALTER TABLE t ALTER COLUMN c SET STATISTICS -1",
Some(-1),
),
(
"ALTER TABLE t ALTER COLUMN c SET STATISTICS DEFAULT",
"ALTER TABLE t ALTER COLUMN c SET STATISTICS DEFAULT",
None,
),
(
"ALTER TABLE t ALTER COLUMN c SET STATISTICS +5",
"ALTER TABLE t ALTER COLUMN c SET STATISTICS 5",
Some(5),
),
] {
let statement = pg_and_generic().one_statement_parses_to(sql, canonical);
let Statement::AlterTable(AlterTable { operations, .. }) = statement else {
panic!("expected ALTER TABLE, got {statement:?}")
};
assert_eq!(
operations,
vec![AlterTableOperation::AlterColumn {
column_name: Ident::new("c"),
op: AlterColumnOperation::SetStatistics { target },
}]
);
}

for (sql, expected) in [
(
"ALTER TABLE t ALTER COLUMN c SET STATISTICS",
"Expected: number, found: EOF",
),
(
"ALTER TABLE t ALTER COLUMN c SET STATISTICS c",
"Expected: number, found: c",
),
(
"ALTER TABLE t ALTER COLUMN c SET STATISTICS 1.5",
"Could not parse '1.5' as i64: invalid digit found in string",
),
(
"ALTER TABLE t ALTER COLUMN c SET STATISTICS '5'",
"Expected: number, found: '5'",
),
(
"ALTER TABLE t ALTER COLUMN c SET STATISTICS 1 + 2",
"Expected: end of statement, found: +",
),
] {
assert_eq!(
pg_and_generic().parse_sql_statements(sql).unwrap_err(),
ParserError::ParserError(expected.to_string()),
"{sql}"
);
}

assert_eq!(
TestedDialects::new(vec![Box::new(MySqlDialect {})])
.parse_sql_statements("ALTER TABLE t ALTER COLUMN c SET STATISTICS 1")
.unwrap_err(),
ParserError::ParserError(
"Expected: SET/DROP NOT NULL, SET DEFAULT, SET DATA TYPE, or OPTIONS after ALTER COLUMN, found: SET"
.to_string()
)
);
}

#[test]
fn parse_alter_materialized_view_column_set_statistics() {
let statement = pg_and_generic().one_statement_parses_to(
"ALTER MATERIALIZED VIEW m ALTER c SET STATISTICS 10",
"ALTER MATERIALIZED VIEW m ALTER COLUMN c SET STATISTICS 10",
);
assert_eq!(
statement,
Statement::AlterView(AlterView {
materialized: true,
name: ObjectName::from(vec![Ident::new("m")]),
if_exists: false,
operation: AlterViewOperation::AlterColumn {
column_name: Ident::new("c"),
op: AlterColumnOperation::SetStatistics { target: Some(10) },
},
})
);

let Statement::AlterView(AlterView { operation, .. }) = pg_and_generic().verified_stmt(
"ALTER MATERIALIZED VIEW IF EXISTS s.m ALTER COLUMN c SET STATISTICS DEFAULT",
) else {
unreachable!()
};
assert_eq!(
operation,
AlterViewOperation::AlterColumn {
column_name: Ident::new("c"),
op: AlterColumnOperation::SetStatistics { target: None },
}
);

assert_eq!(
pg_and_generic()
.parse_sql_statements("ALTER VIEW v ALTER COLUMN c SET STATISTICS 1")
.unwrap_err(),
ParserError::ParserError(
"Expected: SET DEFAULT or DROP DEFAULT after ALTER COLUMN, found: SET".to_string()
)
);
}
Loading