Skip to content
Open
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
3 changes: 2 additions & 1 deletion fuzz/fuzz_seeds/alter_database.sql
Original file line number Diff line number Diff line change
Expand Up @@ -5,4 +5,5 @@ ALTER DATABASE d SET XML OPTION DOCUMENT;
ALTER DATABASE d RESET ALL;
ALTER DATABASE d OWNER TO CURRENT_USER;
ALTER DATABASE d SET TABLESPACE pg_default;
ALTER DATABASE d REFRESH COLLATION VERSION
ALTER DATABASE d REFRESH COLLATION VERSION;
ALTER DATABASE d WITH ALLOW_CONNECTIONS true CONNECTION LIMIT -1 IS_TEMPLATE false
65 changes: 64 additions & 1 deletion src/ast/ddl.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5039,6 +5039,19 @@ pub enum AlterDatabaseOperation {
},
/// `REFRESH COLLATION VERSION`
RefreshCollationVersion,
/// `[ WITH ] option [ ... ]`, where the list may be empty.
Options {
/// Whether the `WITH` keyword was present.
with: bool,
/// The options to change.
options: Vec<AlterDatabaseOption>,
},
}

impl AlterDatabaseOperation {
fn is_empty(&self) -> bool {
matches!(self, Self::Options { with: false, options } if options.is_empty())
}
}

impl fmt::Display for AlterDatabaseOperation {
Expand All @@ -5057,13 +5070,22 @@ impl fmt::Display for AlterDatabaseOperation {
AlterDatabaseOperation::RefreshCollationVersion => {
f.write_str("REFRESH COLLATION VERSION")
}
AlterDatabaseOperation::Options { with, options } => match (with, options.is_empty()) {
(false, _) => write!(f, "{}", display_separated(options, " ")),
(true, true) => f.write_str("WITH"),
(true, false) => write!(f, "WITH {}", display_separated(options, " ")),
},
}
}
}

impl fmt::Display for AlterDatabase {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "ALTER DATABASE {} {}", self.name, self.operation)
if self.operation.is_empty() {
write!(f, "ALTER DATABASE {}", self.name)
} else {
write!(f, "ALTER DATABASE {} {}", self.name, self.operation)
}
}
}

Expand All @@ -5073,6 +5095,47 @@ impl Spanned for AlterDatabase {
}
}

/// An option of `ALTER DATABASE ... [ WITH ] option`, such as
/// `ALLOW_CONNECTIONS true`, `CONNECTION LIMIT 5` or `IS_TEMPLATE false`.
///
/// The name is kept as written, since PostgreSQL's grammar accepts any
/// identifier here and only the server checks it.
#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
pub struct AlterDatabaseOption {
/// Option name.
pub name: AlterDatabaseOptionName,
/// Option value.
pub value: Expr,
}

impl fmt::Display for AlterDatabaseOption {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{} {}", self.name, self.value)
}
}

/// Name of an [`AlterDatabaseOption`].
#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
pub enum AlterDatabaseOptionName {
/// `CONNECTION LIMIT`
ConnectionLimit,
/// Any other option name, such as `ALLOW_CONNECTIONS`.
Name(Ident),
}

impl fmt::Display for AlterDatabaseOptionName {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
AlterDatabaseOptionName::ConnectionLimit => f.write_str("CONNECTION LIMIT"),
AlterDatabaseOptionName::Name(name) => write!(f, "{name}"),
}
}
}

/// A `SET` clause that stores a configuration parameter default, as in
/// `ALTER DATABASE ... SET`.
///
Expand Down
7 changes: 4 additions & 3 deletions src/ast/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -65,9 +65,10 @@ pub use self::dcl::{
};
pub use self::ddl::{
AggregateModifyKind, Alignment, AlterCollation, AlterCollationOperation, AlterColumnOperation,
AlterConnectorOwner, AlterDatabase, AlterDatabaseOperation, AlterFunction, AlterFunctionAction,
AlterFunctionKind, AlterFunctionOperation, AlterGenericOption, AlterIndexOperation,
AlterOperator, AlterOperatorClass, AlterOperatorClassOperation, AlterOperatorFamily,
AlterConnectorOwner, AlterDatabase, AlterDatabaseOperation, AlterDatabaseOption,
AlterDatabaseOptionName, AlterFunction, AlterFunctionAction, AlterFunctionKind,
AlterFunctionOperation, AlterGenericOption, AlterIndexOperation, AlterOperator,
AlterOperatorClass, AlterOperatorClassOperation, AlterOperatorFamily,
AlterOperatorFamilyOperation, AlterOperatorOperation, AlterPolicy, AlterPolicyOperation,
AlterSchema, AlterSchemaOperation, AlterTable, AlterTableAlgorithm, AlterTableLock,
AlterTableOperation, AlterTableType, AlterTextSearch, AlterTextSearchOperation,
Expand Down
27 changes: 23 additions & 4 deletions src/parser/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12525,15 +12525,34 @@ impl<'a> Parser<'a> {
} else if self.parse_keywords(&[Keyword::REFRESH, Keyword::COLLATION, Keyword::VERSION]) {
AlterDatabaseOperation::RefreshCollationVersion
} else {
return self.expected_ref(
"RENAME TO, OWNER TO, SET, RESET or REFRESH COLLATION VERSION after ALTER DATABASE",
self.peek_token_ref(),
);
let with = self.parse_keyword(Keyword::WITH);
let mut options = vec![];
while let Some(option) = self.parse_alter_database_option()? {
options.push(option);
}
AlterDatabaseOperation::Options { with, options }
};

Ok(AlterDatabase { name, operation })
}

fn parse_alter_database_option(&mut self) -> Result<Option<AlterDatabaseOption>, ParserError> {
let name = if self.parse_keyword(Keyword::CONNECTION) {
self.expect_keyword_is(Keyword::LIMIT)?;
AlterDatabaseOptionName::ConnectionLimit
} else {
let token = self.next_token();
let Token::Word(word) = token.token else {
self.prev_token();
return Ok(None);
};
AlterDatabaseOptionName::Name(word.into_ident(token.span))
};
let _ = self.consume_token(&Token::Eq);
let value = self.parse_expr()?;
Ok(Some(AlterDatabaseOption { name, value }))
}

/// Parse the clause after `SET` that stores a configuration parameter
/// default, as in `ALTER DATABASE ... SET`.
///
Expand Down
81 changes: 69 additions & 12 deletions tests/sqlparser_postgres.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13547,20 +13547,10 @@ fn parse_alter_database_rename() {
.span(),
Span::new(Location::new(1, 16), Location::new(1, 21))
);
for (sql, error) in [
("ALTER DATABASE", "Expected: identifier, found: EOF"),
(
"ALTER DATABASE d RENAME TO",
"Expected: identifier, found: EOF",
),
(
"ALTER DATABASE d",
"Expected: RENAME TO, OWNER TO, SET, RESET or REFRESH COLLATION VERSION after ALTER DATABASE, found: EOF",
),
] {
for sql in ["ALTER DATABASE", "ALTER DATABASE d RENAME TO"] {
assert_eq!(
dialects.parse_sql_statements(sql).unwrap_err(),
ParserError::ParserError(error.to_string()),
ParserError::ParserError("Expected: identifier, found: EOF".to_string()),
"{sql}"
);
}
Expand Down Expand Up @@ -13782,3 +13772,70 @@ fn parse_alter_database_refresh_collation_version() {
ParserError::ParserError("Expected: end of statement, found: x".to_string())
);
}

#[test]
fn parse_alter_database_options() {
let dialects = pg_and_generic();

assert_eq!(
dialects.verified_stmt(
"ALTER DATABASE d WITH allow_connections true CONNECTION LIMIT -1 \"is_template\" false"
),
Statement::AlterDatabase(AlterDatabase {
name: ObjectName::from(vec![Ident::new("d")]),
operation: AlterDatabaseOperation::Options {
with: true,
options: vec![
AlterDatabaseOption {
name: AlterDatabaseOptionName::Name(Ident::new("allow_connections")),
value: Expr::Value(Value::Boolean(true).with_empty_span()),
},
AlterDatabaseOption {
name: AlterDatabaseOptionName::ConnectionLimit,
value: Expr::UnaryOp {
op: UnaryOperator::Minus,
expr: Box::new(Expr::value(number("1"))),
},
},
AlterDatabaseOption {
name: AlterDatabaseOptionName::Name(Ident::with_quote('"', "is_template")),
value: Expr::Value(Value::Boolean(false).with_empty_span()),
},
],
},
})
);

for sql in [
"ALTER DATABASE d",
"ALTER DATABASE d WITH",
"ALTER DATABASE d ALLOW_CONNECTIONS DEFAULT",
"ALTER DATABASE d TABLESPACE pg_default",
"ALTER DATABASE d OWNER r",
] {
dialects.verified_stmt(sql);
}

dialects.one_statement_parses_to(
"ALTER DATABASE d CONNECTION LIMIT = 5 tablespace = pg_default",
"ALTER DATABASE d CONNECTION LIMIT 5 tablespace pg_default",
);

for (sql, error) in [
("ALTER DATABASE d CONNECTION 5", "Expected: LIMIT, found: 5"),
(
"ALTER DATABASE d IS_TEMPLATE",
"Expected: an expression, found: EOF",
),
(
"ALTER DATABASE d 'x' 1",
"Expected: end of statement, found: 'x'",
),
] {
assert_eq!(
dialects.parse_sql_statements(sql).unwrap_err(),
ParserError::ParserError(error.to_string()),
"{sql}"
);
}
}
Loading