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
5 changes: 4 additions & 1 deletion fuzz/fuzz_seeds/publication.sql
Original file line number Diff line number Diff line change
@@ -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;
50 changes: 50 additions & 0 deletions src/ast/ddl.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<SqlOption>),
/// `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)
Expand Down
63 changes: 38 additions & 25 deletions src/ast/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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}")
Expand Down Expand Up @@ -12783,6 +12790,12 @@ impl From<AlterCollation> for Statement {
}
}

impl From<AlterPublication> for Statement {
fn from(a: AlterPublication) -> Self {
Self::AlterPublication(a)
}
}

impl From<AlterView> for Statement {
fn from(a: AlterView) -> Self {
Self::AlterView(a)
Expand Down
2 changes: 2 additions & 0 deletions src/ast/spans.rs
Original file line number Diff line number Diff line change
Expand Up @@ -277,6 +277,7 @@ impl Spanned for Values {
/// - [Statement::CreateCollation]
/// - [Statement::AlterCollation]
/// - [Statement::CreatePublication]
/// - [Statement::AlterPublication]
/// - [Statement::Fetch]
/// - [Statement::Flush]
/// - [Statement::Discard]
Expand Down Expand Up @@ -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(),
Expand Down
26 changes: 25 additions & 1 deletion src/parser/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12175,14 +12175,15 @@ 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()
}
Keyword::USER => self.parse_alter_user().map(Into::into),
_ => {
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(),
)
}
Expand Down Expand Up @@ -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<AlterPublication, ParserError> {
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)
Expand Down
2 changes: 1 addition & 1 deletion tests/sqlparser_common.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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"),
Expand Down
57 changes: 57 additions & 0 deletions tests/sqlparser_postgres.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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}"
);
}
}
Loading