From ab5bf964678ff6244f40c8d3b78e4a30e6065330 Mon Sep 17 00:00:00 2001 From: LucaCappelletti94 Date: Sat, 7 Nov 2026 16:34:10 +0100 Subject: [PATCH] PostgreSQL: Support `ALTER DATABASE` options --- fuzz/fuzz_seeds/alter_database.sql | 3 +- src/ast/ddl.rs | 65 +++++++++++++++++++++++- src/ast/mod.rs | 7 +-- src/parser/mod.rs | 27 ++++++++-- tests/sqlparser_postgres.rs | 81 +++++++++++++++++++++++++----- 5 files changed, 162 insertions(+), 21 deletions(-) diff --git a/fuzz/fuzz_seeds/alter_database.sql b/fuzz/fuzz_seeds/alter_database.sql index 7b69441391..d32550cdce 100644 --- a/fuzz/fuzz_seeds/alter_database.sql +++ b/fuzz/fuzz_seeds/alter_database.sql @@ -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 diff --git a/src/ast/ddl.rs b/src/ast/ddl.rs index bc31ad9a43..c23ec35105 100644 --- a/src/ast/ddl.rs +++ b/src/ast/ddl.rs @@ -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, + }, +} + +impl AlterDatabaseOperation { + fn is_empty(&self) -> bool { + matches!(self, Self::Options { with: false, options } if options.is_empty()) + } } impl fmt::Display for AlterDatabaseOperation { @@ -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) + } } } @@ -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`. /// diff --git a/src/ast/mod.rs b/src/ast/mod.rs index dd5642f623..02ee872030 100644 --- a/src/ast/mod.rs +++ b/src/ast/mod.rs @@ -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, diff --git a/src/parser/mod.rs b/src/parser/mod.rs index fa727c2fe6..61c106b6c5 100644 --- a/src/parser/mod.rs +++ b/src/parser/mod.rs @@ -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, 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`. /// diff --git a/tests/sqlparser_postgres.rs b/tests/sqlparser_postgres.rs index 3b8b8fc2c7..e42ad548c2 100644 --- a/tests/sqlparser_postgres.rs +++ b/tests/sqlparser_postgres.rs @@ -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}" ); } @@ -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}" + ); + } +}