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
2 changes: 2 additions & 0 deletions fuzz/fuzz_seeds/publication.sql
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
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);
ALTER PUBLICATION p ADD TABLE t (id) WHERE (id > 0), TABLES IN SCHEMA s;
ALTER PUBLICATION p DROP TABLE ONLY (items), TABLES IN SCHEMA feed;
ALTER PUBLICATION p SET (publish_generated_columns = stored);
ALTER PUBLICATION p OWNER TO CURRENT_ROLE;
ALTER PUBLICATION a RENAME TO b;
Expand Down
57 changes: 57 additions & 0 deletions src/ast/ddl.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5176,6 +5176,12 @@ impl Spanned for AlterPublication {
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
pub enum AlterPublicationOperation {
/// `ADD publication_object [, ...]`
Add(Vec<PublicationObject>),
/// `SET publication_object [, ...]`, replacing all members.
Set(Vec<PublicationObject>),
/// `DROP publication_drop_object [, ...]`
Drop(Vec<PublicationDropObject>),
/// `SET ( publication_parameter [= value] [, ...] )`
SetOptions(Vec<SqlOption>),
/// `OWNER TO new_owner`
Expand All @@ -5187,6 +5193,15 @@ pub enum AlterPublicationOperation {
impl fmt::Display for AlterPublicationOperation {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
AlterPublicationOperation::Add(objects) => {
write!(f, "ADD {}", display_comma_separated(objects))
}
AlterPublicationOperation::Set(objects) => {
write!(f, "SET {}", display_comma_separated(objects))
}
AlterPublicationOperation::Drop(objects) => {
write!(f, "DROP {}", display_comma_separated(objects))
}
AlterPublicationOperation::SetOptions(options) => {
write!(f, "SET ({})", display_comma_separated(options))
}
Expand All @@ -5196,6 +5211,48 @@ impl fmt::Display for AlterPublicationOperation {
}
}

/// A group of members removed by `ALTER PUBLICATION ... DROP`.
#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
pub enum PublicationDropObject {
/// `TABLE [ ONLY ] table_name [ * ] [, ...]`
Tables(Vec<PublicationDropTable>),
/// `TABLES IN SCHEMA { schema_name | CURRENT_SCHEMA } [, ...]`
Schemas(Vec<PublicationSchema>),
}

impl fmt::Display for PublicationDropObject {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
PublicationDropObject::Tables(tables) => {
write!(f, "TABLE {}", display_comma_separated(tables))
}
PublicationDropObject::Schemas(schemas) => {
write!(f, "TABLES IN SCHEMA {}", display_comma_separated(schemas))
}
}
}
}

/// A table removed from a publication.
#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
pub struct PublicationDropTable {
/// Name of the table.
#[cfg_attr(feature = "visitor", visit(with = "visit_relation"))]
pub name: ObjectName,
/// `ONLY` or `*` marker.
pub inheritance: Option<TableInheritance>,
}

impl fmt::Display for PublicationDropTable {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
fmt_publication_relation(f, &self.name, self.inheritance)
}
}

/// `ALTER [ MATERIALIZED ] VIEW` statement.
///
/// See [PostgreSQL](https://www.postgresql.org/docs/current/sql-altermaterializedview.html)
Expand Down
14 changes: 7 additions & 7 deletions src/ast/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -88,13 +88,13 @@ pub use self::ddl::{
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,
Owner, Partition, PartitionBoundValue, ProcedureParam, PublicationDropObject,
PublicationDropTable, 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
59 changes: 43 additions & 16 deletions src/parser/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9126,22 +9126,33 @@ impl<'a> Parser<'a> {
}

fn parse_publication_objects(&mut self) -> Result<Vec<PublicationObject>, ParserError> {
let mut objects = vec![];
self.parse_publication_object_groups(
Parser::parse_publication_table,
PublicationObject::Tables,
PublicationObject::Schemas,
)
}

/// Parses `TABLE ...` and `TABLES IN SCHEMA ...` groups, building table
/// members with `parse_table`.
fn parse_publication_object_groups<Table, Group>(
&mut self,
parse_table: fn(&mut Self) -> Result<Table, ParserError>,
tables: fn(Vec<Table>) -> Group,
schemas: fn(Vec<PublicationSchema>) -> Group,
) -> Result<Vec<Group>, ParserError> {
let mut groups = vec![];
loop {
let object = if self.parse_keyword(Keyword::TABLE) {
PublicationObject::Tables(
self.parse_publication_group_members(Parser::parse_publication_table)?,
)
let group = if self.parse_keyword(Keyword::TABLE) {
tables(self.parse_publication_group_members(parse_table)?)
} else if self.parse_keywords(&[Keyword::TABLES, Keyword::IN, Keyword::SCHEMA]) {
PublicationObject::Schemas(
self.parse_publication_group_members(Parser::parse_publication_schema)?,
)
schemas(self.parse_publication_group_members(Parser::parse_publication_schema)?)
} else {
return self.expected_ref("TABLE or TABLES IN SCHEMA", self.peek_token_ref());
};
objects.push(object);
groups.push(group);
if !self.consume_token(&Token::Comma) {
return Ok(objects);
return Ok(groups);
}
}
}
Expand Down Expand Up @@ -9211,6 +9222,11 @@ impl<'a> Parser<'a> {
}
}

fn parse_publication_drop_table(&mut self) -> Result<PublicationDropTable, ParserError> {
let (name, inheritance) = self.parse_publication_relation()?;
Ok(PublicationDropTable { name, inheritance })
}

/// Parse a PostgreSQL-specific [Statement::DropExtension] statement.
pub fn parse_drop_extension(&mut self) -> Result<Statement, ParserError> {
let if_exists = self.parse_keywords(&[Keyword::IF, Keyword::EXISTS]);
Expand Down Expand Up @@ -12621,18 +12637,29 @@ impl<'a> Parser<'a> {
/// [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)
let operation = if self.parse_keyword(Keyword::ADD) {
AlterPublicationOperation::Add(self.parse_publication_objects()?)
} else if self.parse_keyword(Keyword::SET) {
if self.consume_token(&Token::LParen) {
let options = self.parse_comma_separated(Parser::parse_sql_option)?;
self.expect_token(&Token::RParen)?;
AlterPublicationOperation::SetOptions(options)
} else {
AlterPublicationOperation::Set(self.parse_publication_objects()?)
}
} else if self.parse_keyword(Keyword::DROP) {
AlterPublicationOperation::Drop(self.parse_publication_object_groups(
Parser::parse_publication_drop_table,
PublicationDropObject::Tables,
PublicationDropObject::Schemas,
)?)
} 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",
"ADD, SET, DROP, OWNER TO, or RENAME TO after ALTER PUBLICATION",
self.peek_token_ref(),
);
};
Expand Down
69 changes: 68 additions & 1 deletion tests/sqlparser_postgres.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13819,7 +13819,74 @@ fn parse_alter_publication() {
),
(
"ALTER PUBLICATION p REFRESH",
"Expected: SET, OWNER TO, or RENAME TO after ALTER PUBLICATION, found: REFRESH",
"Expected: ADD, SET, DROP, 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}"
);
}
}

#[test]
fn parse_alter_publication_members() {
for sql in [
"ALTER PUBLICATION p ADD TABLE ONLY public.items (id) WHERE ((id > 0))",
"ALTER PUBLICATION p ADD TABLES IN SCHEMA feed",
"ALTER PUBLICATION p SET TABLE public.items (id) WHERE (id > 0)",
"ALTER PUBLICATION p SET TABLES IN SCHEMA feed, TABLE t",
"ALTER PUBLICATION p DROP TABLE ONLY public.items",
"ALTER PUBLICATION p DROP TABLE ONLY (a), b *, TABLES IN SCHEMA feed",
] {
pg_and_generic().verified_stmt(sql);
}

let operation = |sql| match pg_and_generic().verified_stmt(sql) {
Statement::AlterPublication(AlterPublication { operation, .. }) => operation,
_ => unreachable!(),
};
assert_eq!(
operation("ALTER PUBLICATION p DROP TABLE ONLY (a), TABLES IN SCHEMA CURRENT_SCHEMA"),
AlterPublicationOperation::Drop(vec![
PublicationDropObject::Tables(vec![PublicationDropTable {
name: ObjectName::from(vec![Ident::new("a")]),
inheritance: Some(TableInheritance::Only {
parenthesized: true
}),
}]),
PublicationDropObject::Schemas(vec![PublicationSchema::CurrentSchema]),
])
);
assert_eq!(
operation("ALTER PUBLICATION p SET TABLES IN SCHEMA feed"),
AlterPublicationOperation::Set(vec![PublicationObject::Schemas(vec![
PublicationSchema::Name(Ident::new("feed"))
])])
);
assert_eq!(
operation("ALTER PUBLICATION p ADD TABLE t"),
AlterPublicationOperation::Add(vec![PublicationObject::Tables(vec![PublicationTable {
name: ObjectName::from(vec![Ident::new("t")]),
inheritance: None,
columns: vec![],
filter: None,
}])])
);

for (sql, expected) in [
(
"ALTER PUBLICATION p DROP TABLE t (id)",
"Expected: end of statement, found: (",
),
(
"ALTER PUBLICATION p DROP TABLE t WHERE (id > 0)",
"Expected: end of statement, found: WHERE",
),
(
"ALTER PUBLICATION p ADD t",
"Expected: TABLE or TABLES IN SCHEMA, found: t",
),
] {
assert_eq!(
Expand Down
Loading