From 7835fd805c67e79b34792762c1ae3edcc4e50841 Mon Sep 17 00:00:00 2001 From: LucaCappelletti94 Date: Sun, 15 Nov 2026 11:39:40 +0100 Subject: [PATCH] PostgreSQL: Support `ALTER PUBLICATION` options, owner and rename --- fuzz/fuzz_seeds/publication.sql | 5 ++- src/ast/ddl.rs | 50 ++++++++++++++++++++++++++ src/ast/mod.rs | 63 ++++++++++++++++++++------------- src/ast/spans.rs | 2 ++ src/parser/mod.rs | 26 +++++++++++++- tests/sqlparser_common.rs | 2 +- tests/sqlparser_postgres.rs | 57 +++++++++++++++++++++++++++++ 7 files changed, 177 insertions(+), 28 deletions(-) diff --git a/fuzz/fuzz_seeds/publication.sql b/fuzz/fuzz_seeds/publication.sql index a23ae892a1..44cf427cad 100644 --- a/fuzz/fuzz_seeds/publication.sql +++ b/fuzz/fuzz_seeds/publication.sql @@ -1,3 +1,6 @@ CREATE PUBLICATION p FOR TABLE ONLY public.items (id) WHERE ((id > 0)), other *, TABLES IN SCHEMA feed, CURRENT_SCHEMA, TABLE ONLY (last) WITH (publish = 'insert'); CREATE PUBLICATION a FOR ALL TABLES WITH (publish = 'insert', publish_via_partition_root); -DROP PUBLICATION IF EXISTS p, a CASCADE; +ALTER PUBLICATION p SET (publish_generated_columns = stored); +ALTER PUBLICATION p OWNER TO CURRENT_ROLE; +ALTER PUBLICATION a RENAME TO b; +DROP PUBLICATION IF EXISTS p, b CASCADE; diff --git a/src/ast/ddl.rs b/src/ast/ddl.rs index 05f8fb7086..2f4ad86d83 100644 --- a/src/ast/ddl.rs +++ b/src/ast/ddl.rs @@ -5146,6 +5146,56 @@ fn fmt_publication_relation( } } +/// `ALTER PUBLICATION` statement. +/// +/// See [PostgreSQL](https://www.postgresql.org/docs/current/sql-alterpublication.html) +#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)] +#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] +#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))] +pub struct AlterPublication { + /// Name of the publication. + pub name: Ident, + /// The operation to perform on the publication. + pub operation: AlterPublicationOperation, +} + +impl fmt::Display for AlterPublication { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + write!(f, "ALTER PUBLICATION {} {}", self.name, self.operation) + } +} + +impl Spanned for AlterPublication { + fn span(&self) -> Span { + Span::empty() + } +} + +/// Operations supported by `ALTER PUBLICATION`. +#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)] +#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] +#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))] +pub enum AlterPublicationOperation { + /// `SET ( publication_parameter [= value] [, ...] )` + SetOptions(Vec), + /// `OWNER TO new_owner` + OwnerTo(Owner), + /// `RENAME TO new_name` + RenameTo(Ident), +} + +impl fmt::Display for AlterPublicationOperation { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + match self { + AlterPublicationOperation::SetOptions(options) => { + write!(f, "SET ({})", display_comma_separated(options)) + } + AlterPublicationOperation::OwnerTo(owner) => write!(f, "OWNER TO {owner}"), + AlterPublicationOperation::RenameTo(new_name) => write!(f, "RENAME TO {new_name}"), + } + } +} + /// `ALTER [ MATERIALIZED ] VIEW` statement. /// /// See [PostgreSQL](https://www.postgresql.org/docs/current/sql-altermaterializedview.html) diff --git a/src/ast/mod.rs b/src/ast/mod.rs index 9ee8ded5fc..76f53677c4 100644 --- a/src/ast/mod.rs +++ b/src/ast/mod.rs @@ -69,31 +69,32 @@ pub use self::ddl::{ AlterFunctionOperation, AlterGenericOption, AlterIndexOperation, AlterOperator, AlterOperatorClass, AlterOperatorClassOperation, AlterOperatorFamily, AlterOperatorFamilyOperation, AlterOperatorOperation, AlterPolicy, AlterPolicyOperation, - AlterSchema, AlterSchemaOperation, AlterTable, AlterTableAlgorithm, AlterTableLock, - AlterTableOperation, AlterTableType, AlterTextSearch, AlterTextSearchOperation, - AlterTextSearchOption, AlterTrigger, AlterTriggerOperation, AlterType, AlterTypeAddValue, - AlterTypeAddValuePosition, AlterTypeOperation, AlterTypeRename, AlterTypeRenameValue, - AlterView, AlterViewOperation, ClusteredBy, ColumnDef, ColumnOption, ColumnOptionDef, - ColumnOptions, ColumnPolicy, ColumnPolicyProperty, ConstraintCharacteristics, CreateAggregate, - CreateAggregateArgs, CreateAggregateOption, CreateCollation, CreateCollationDefinition, - CreateConnector, CreateDomain, CreateExtension, CreateForeignDataWrapper, CreateForeignTable, - CreateFunction, CreateIndex, CreateOperator, CreateOperatorClass, CreateOperatorFamily, - CreatePolicy, CreatePolicyCommand, CreatePolicyType, CreatePublication, CreateRule, - CreateRuleAction, CreateRuleDoKind, CreateRuleEvent, CreateTable, CreateTextSearch, - CreateTrigger, CreateUserMapping, CreateView, Deduplicate, DeferrableInitial, - DetachPartitionMode, DistStyle, DropBehavior, DropExtension, DropFunction, DropOperator, - DropOperatorClass, DropOperatorFamily, DropOperatorSignature, DropPolicy, DropRule, - DropTrigger, ForValues, ForeignDataWrapperRoutineClause, FunctionReturnType, GeneratedAs, - GeneratedExpressionMode, IdentityParameters, IdentityProperty, IdentityPropertyFormatKind, - IdentityPropertyKind, IdentityPropertyOrder, IndexColumn, IndexOption, IndexType, - KeyOrIndexDisplay, Msck, NullsDistinctOption, OperatorArgTypes, OperatorClassItem, - OperatorFamilyDropItem, OperatorFamilyItem, OperatorOption, OperatorPurpose, Owner, Partition, - PartitionBoundValue, ProcedureParam, PublicationObject, PublicationSchema, PublicationTable, - PublicationTarget, ReferentialAction, RenameTableNameKind, ReplicaIdentity, SqliteTableOption, - SqliteTableOptions, TagsColumnOption, TextSearchObjectType, TriggerObjectKind, Truncate, - UserDefinedTypeCompositeAttributeDef, UserDefinedTypeInternalLength, - UserDefinedTypeRangeOption, UserDefinedTypeRepresentation, UserDefinedTypeSqlDefinitionOption, - UserDefinedTypeStorage, UserMappingUser, ViewColumnDef, WithData, + AlterPublication, AlterPublicationOperation, AlterSchema, AlterSchemaOperation, AlterTable, + AlterTableAlgorithm, AlterTableLock, AlterTableOperation, AlterTableType, AlterTextSearch, + AlterTextSearchOperation, AlterTextSearchOption, AlterTrigger, AlterTriggerOperation, + AlterType, AlterTypeAddValue, AlterTypeAddValuePosition, AlterTypeOperation, AlterTypeRename, + AlterTypeRenameValue, AlterView, AlterViewOperation, ClusteredBy, ColumnDef, ColumnOption, + ColumnOptionDef, ColumnOptions, ColumnPolicy, ColumnPolicyProperty, ConstraintCharacteristics, + CreateAggregate, CreateAggregateArgs, CreateAggregateOption, CreateCollation, + CreateCollationDefinition, CreateConnector, CreateDomain, CreateExtension, + CreateForeignDataWrapper, CreateForeignTable, CreateFunction, CreateIndex, CreateOperator, + CreateOperatorClass, CreateOperatorFamily, CreatePolicy, CreatePolicyCommand, CreatePolicyType, + CreatePublication, CreateRule, CreateRuleAction, CreateRuleDoKind, CreateRuleEvent, + CreateTable, CreateTextSearch, CreateTrigger, CreateUserMapping, CreateView, Deduplicate, + DeferrableInitial, DetachPartitionMode, DistStyle, DropBehavior, DropExtension, DropFunction, + DropOperator, DropOperatorClass, DropOperatorFamily, DropOperatorSignature, DropPolicy, + DropRule, DropTrigger, ForValues, ForeignDataWrapperRoutineClause, FunctionReturnType, + GeneratedAs, GeneratedExpressionMode, IdentityParameters, IdentityProperty, + IdentityPropertyFormatKind, IdentityPropertyKind, IdentityPropertyOrder, IndexColumn, + IndexOption, IndexType, KeyOrIndexDisplay, Msck, NullsDistinctOption, OperatorArgTypes, + OperatorClassItem, OperatorFamilyDropItem, OperatorFamilyItem, OperatorOption, OperatorPurpose, + Owner, Partition, PartitionBoundValue, ProcedureParam, PublicationObject, PublicationSchema, + PublicationTable, PublicationTarget, ReferentialAction, RenameTableNameKind, ReplicaIdentity, + SqliteTableOption, SqliteTableOptions, TagsColumnOption, TextSearchObjectType, + TriggerObjectKind, Truncate, UserDefinedTypeCompositeAttributeDef, + UserDefinedTypeInternalLength, UserDefinedTypeRangeOption, UserDefinedTypeRepresentation, + UserDefinedTypeSqlDefinitionOption, UserDefinedTypeStorage, UserMappingUser, ViewColumnDef, + WithData, }; pub use self::dml::{ Delete, Insert, InsertOverriding, Merge, MergeAction, MergeClause, MergeClauseKind, @@ -3944,6 +3945,11 @@ pub enum Statement { /// See [PostgreSQL](https://www.postgresql.org/docs/current/sql-altercollation.html) AlterCollation(AlterCollation), /// ```sql + /// ALTER PUBLICATION + /// ``` + /// See [PostgreSQL](https://www.postgresql.org/docs/current/sql-alterpublication.html) + AlterPublication(AlterPublication), + /// ```sql /// ALTER OPERATOR /// ``` /// See [PostgreSQL](https://www.postgresql.org/docs/current/sql-alteroperator.html) @@ -5792,6 +5798,7 @@ impl fmt::Display for Statement { write!(f, "ALTER TYPE {name} {operation}") } Statement::AlterCollation(alter_collation) => write!(f, "{alter_collation}"), + Statement::AlterPublication(alter_publication) => write!(f, "{alter_publication}"), Statement::AlterOperator(alter_operator) => write!(f, "{alter_operator}"), Statement::AlterOperatorFamily(alter_operator_family) => { write!(f, "{alter_operator_family}") @@ -12783,6 +12790,12 @@ impl From for Statement { } } +impl From for Statement { + fn from(a: AlterPublication) -> Self { + Self::AlterPublication(a) + } +} + impl From for Statement { fn from(a: AlterView) -> Self { Self::AlterView(a) diff --git a/src/ast/spans.rs b/src/ast/spans.rs index 9c4409e362..8f7cfca747 100644 --- a/src/ast/spans.rs +++ b/src/ast/spans.rs @@ -277,6 +277,7 @@ impl Spanned for Values { /// - [Statement::CreateCollation] /// - [Statement::AlterCollation] /// - [Statement::CreatePublication] +/// - [Statement::AlterPublication] /// - [Statement::Fetch] /// - [Statement::Flush] /// - [Statement::Discard] @@ -418,6 +419,7 @@ impl Spanned for Statement { Statement::AlterFunction { .. } => Span::empty(), Statement::AlterType { .. } => Span::empty(), Statement::AlterCollation { .. } => Span::empty(), + Statement::AlterPublication(alter_publication) => alter_publication.span(), Statement::AlterOperator { .. } => Span::empty(), Statement::AlterOperatorFamily { .. } => Span::empty(), Statement::AlterOperatorClass { .. } => Span::empty(), diff --git a/src/parser/mod.rs b/src/parser/mod.rs index 6a1245f9a3..4cd33b31eb 100644 --- a/src/parser/mod.rs +++ b/src/parser/mod.rs @@ -12175,6 +12175,7 @@ impl<'a> Parser<'a> { Keyword::POLICY => self.parse_alter_policy().map(Into::into), Keyword::TRIGGER => self.parse_alter_trigger().map(Into::into), Keyword::CONNECTOR => self.parse_alter_connector(), + Keyword::PUBLICATION => self.parse_alter_publication().map(Into::into), Keyword::USER if self.dialect.supports_alter_user_as_alter_role() => { self.parse_alter_role() } @@ -12182,7 +12183,7 @@ impl<'a> Parser<'a> { _ => { self.index = index; self.expected_ref( - "one of VIEW or MATERIALIZED VIEW or TYPE or COLLATION or TABLE or INDEX or FUNCTION or AGGREGATE or ROLE or POLICY or TRIGGER or CONNECTOR or ICEBERG or FOREIGN TABLE or SCHEMA or USER or OPERATOR", + "one of VIEW or MATERIALIZED VIEW or TYPE or COLLATION or TABLE or INDEX or FUNCTION or AGGREGATE or ROLE or POLICY or TRIGGER or CONNECTOR or ICEBERG or FOREIGN TABLE or SCHEMA or USER or OPERATOR or PUBLICATION", self.peek_token_ref(), ) } @@ -12615,6 +12616,29 @@ impl<'a> Parser<'a> { Ok(AlterCollation { name, operation }) } + /// Parse a [Statement::AlterPublication]. + /// + /// [PostgreSQL Documentation](https://www.postgresql.org/docs/current/sql-alterpublication.html) + pub fn parse_alter_publication(&mut self) -> Result { + let name = self.parse_identifier()?; + let operation = if self.parse_keyword(Keyword::SET) { + self.expect_token(&Token::LParen)?; + let options = self.parse_comma_separated(Parser::parse_sql_option)?; + self.expect_token(&Token::RParen)?; + AlterPublicationOperation::SetOptions(options) + } else if self.parse_keywords(&[Keyword::OWNER, Keyword::TO]) { + AlterPublicationOperation::OwnerTo(self.parse_owner()?) + } else if self.parse_keywords(&[Keyword::RENAME, Keyword::TO]) { + AlterPublicationOperation::RenameTo(self.parse_identifier()?) + } else { + return self.expected_ref( + "SET, OWNER TO, or RENAME TO after ALTER PUBLICATION", + self.peek_token_ref(), + ); + }; + Ok(AlterPublication { name, operation }) + } + /// Parse a [Statement::AlterOperator] /// /// [PostgreSQL Documentation](https://www.postgresql.org/docs/current/sql-alteroperator.html) diff --git a/tests/sqlparser_common.rs b/tests/sqlparser_common.rs index 7354199f0d..ab812f9c22 100644 --- a/tests/sqlparser_common.rs +++ b/tests/sqlparser_common.rs @@ -16196,7 +16196,7 @@ fn parse_alter_trigger_spans() { #[test] fn parse_alter_rejects_missing_or_unknown_object_type() { - let objects = "one of VIEW or MATERIALIZED VIEW or TYPE or COLLATION or TABLE or INDEX or FUNCTION or AGGREGATE or ROLE or POLICY or TRIGGER or CONNECTOR or ICEBERG or FOREIGN TABLE or SCHEMA or USER or OPERATOR"; + let objects = "one of VIEW or MATERIALIZED VIEW or TYPE or COLLATION or TABLE or INDEX or FUNCTION or AGGREGATE or ROLE or POLICY or TRIGGER or CONNECTOR or ICEBERG or FOREIGN TABLE or SCHEMA or USER or OPERATOR or PUBLICATION"; for (sql, found) in [ ("ALTER", "EOF"), ("ALTER 1", "1"), diff --git a/tests/sqlparser_postgres.rs b/tests/sqlparser_postgres.rs index 090c0a2298..c2bea62941 100644 --- a/tests/sqlparser_postgres.rs +++ b/tests/sqlparser_postgres.rs @@ -13772,3 +13772,60 @@ fn parse_publication_schemas() { ); } } + +#[test] +fn parse_alter_publication() { + for sql in [ + "ALTER PUBLICATION p SET (publish = 'insert', publish_via_partition_root = true)", + "ALTER PUBLICATION p OWNER TO postgres", + "ALTER PUBLICATION p OWNER TO CURRENT_ROLE", + "ALTER PUBLICATION p OWNER TO CURRENT_USER", + "ALTER PUBLICATION p OWNER TO SESSION_USER", + "ALTER PUBLICATION p RENAME TO renamed", + ] { + pg_and_generic().verified_stmt(sql); + } + + let operation = |sql| match pg_and_generic().verified_stmt(sql) { + Statement::AlterPublication(AlterPublication { name, operation }) => { + assert_eq!(name, Ident::new("p")); + operation + } + _ => unreachable!(), + }; + assert_eq!( + operation("ALTER PUBLICATION p SET (publish_via_partition_root)"), + AlterPublicationOperation::SetOptions(vec![SqlOption::Ident(ObjectName::from(vec![ + Ident::new("publish_via_partition_root") + ]))]) + ); + assert_eq!( + operation("ALTER PUBLICATION p OWNER TO CURRENT_ROLE"), + AlterPublicationOperation::OwnerTo(Owner::CurrentRole) + ); + assert_eq!( + operation(r#"ALTER PUBLICATION p RENAME TO "Renamed""#), + AlterPublicationOperation::RenameTo(Ident::with_quote('"', "Renamed")) + ); + + for (sql, expected) in [ + ( + "ALTER PUBLICATION p SET ()", + "Expected: identifier, found: )", + ), + ( + "ALTER PUBLICATION p RENAME TO s.q", + "Expected: end of statement, found: .", + ), + ( + "ALTER PUBLICATION p REFRESH", + "Expected: SET, OWNER TO, or RENAME TO after ALTER PUBLICATION, found: REFRESH", + ), + ] { + assert_eq!( + pg_and_generic().parse_sql_statements(sql).unwrap_err(), + ParserError::ParserError(expected.to_string()), + "{sql}" + ); + } +}