Skip to content

Commit 2a2abc8

Browse files
Added support for DROP OPERATOR syntax (#2102)
Co-authored-by: Ifeanyi Ubah <[email protected]>
1 parent 2ceae00 commit 2a2abc8

File tree

5 files changed

+206
-9
lines changed

5 files changed

+206
-9
lines changed

src/ast/ddl.rs

Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4188,3 +4188,62 @@ impl fmt::Display for OperatorPurpose {
41884188
}
41894189
}
41904190
}
4191+
4192+
/// `DROP OPERATOR` statement
4193+
/// See <https://www.postgresql.org/docs/current/sql-dropoperator.html>
4194+
#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
4195+
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
4196+
#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
4197+
pub struct DropOperator {
4198+
/// `IF EXISTS` clause
4199+
pub if_exists: bool,
4200+
/// One or more operators to drop with their signatures
4201+
pub operators: Vec<DropOperatorSignature>,
4202+
/// `CASCADE or RESTRICT`
4203+
pub drop_behavior: Option<DropBehavior>,
4204+
}
4205+
4206+
/// Operator signature for a `DROP OPERATOR` statement
4207+
#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
4208+
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
4209+
#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
4210+
pub struct DropOperatorSignature {
4211+
/// Operator name
4212+
pub name: ObjectName,
4213+
/// Left operand type
4214+
pub left_type: Option<DataType>,
4215+
/// Right operand type
4216+
pub right_type: DataType,
4217+
}
4218+
4219+
impl fmt::Display for DropOperatorSignature {
4220+
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
4221+
write!(f, "{} (", self.name)?;
4222+
if let Some(left_type) = &self.left_type {
4223+
write!(f, "{}", left_type)?;
4224+
} else {
4225+
write!(f, "NONE")?;
4226+
}
4227+
write!(f, ", {})", self.right_type)
4228+
}
4229+
}
4230+
4231+
impl fmt::Display for DropOperator {
4232+
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
4233+
write!(f, "DROP OPERATOR")?;
4234+
if self.if_exists {
4235+
write!(f, " IF EXISTS")?;
4236+
}
4237+
write!(f, " {}", display_comma_separated(&self.operators))?;
4238+
if let Some(drop_behavior) = &self.drop_behavior {
4239+
write!(f, " {}", drop_behavior)?;
4240+
}
4241+
Ok(())
4242+
}
4243+
}
4244+
4245+
impl Spanned for DropOperator {
4246+
fn span(&self) -> Span {
4247+
Span::empty()
4248+
}
4249+
}

src/ast/mod.rs

Lines changed: 16 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -67,14 +67,15 @@ pub use self::ddl::{
6767
ColumnPolicyProperty, ConstraintCharacteristics, CreateConnector, CreateDomain,
6868
CreateExtension, CreateFunction, CreateIndex, CreateOperator, CreateOperatorClass,
6969
CreateOperatorFamily, CreateTable, CreateTrigger, CreateView, Deduplicate, DeferrableInitial,
70-
DropBehavior, DropExtension, DropFunction, DropTrigger, GeneratedAs, GeneratedExpressionMode,
71-
IdentityParameters, IdentityProperty, IdentityPropertyFormatKind, IdentityPropertyKind,
72-
IdentityPropertyOrder, IndexColumn, IndexOption, IndexType, KeyOrIndexDisplay, Msck,
73-
NullsDistinctOption, OperatorArgTypes, OperatorClassItem, OperatorPurpose, Owner, Partition,
74-
ProcedureParam, ReferentialAction, RenameTableNameKind, ReplicaIdentity, TagsColumnOption,
75-
TriggerObjectKind, Truncate, UserDefinedTypeCompositeAttributeDef,
76-
UserDefinedTypeInternalLength, UserDefinedTypeRangeOption, UserDefinedTypeRepresentation,
77-
UserDefinedTypeSqlDefinitionOption, UserDefinedTypeStorage, ViewColumnDef,
70+
DropBehavior, DropExtension, DropFunction, DropOperator, DropOperatorSignature, DropTrigger,
71+
GeneratedAs, GeneratedExpressionMode, IdentityParameters, IdentityProperty,
72+
IdentityPropertyFormatKind, IdentityPropertyKind, IdentityPropertyOrder, IndexColumn,
73+
IndexOption, IndexType, KeyOrIndexDisplay, Msck, NullsDistinctOption, OperatorArgTypes,
74+
OperatorClassItem, OperatorPurpose, Owner, Partition, ProcedureParam, ReferentialAction,
75+
RenameTableNameKind, ReplicaIdentity, TagsColumnOption, TriggerObjectKind, Truncate,
76+
UserDefinedTypeCompositeAttributeDef, UserDefinedTypeInternalLength,
77+
UserDefinedTypeRangeOption, UserDefinedTypeRepresentation, UserDefinedTypeSqlDefinitionOption,
78+
UserDefinedTypeStorage, ViewColumnDef,
7879
};
7980
pub use self::dml::{Delete, Insert, Update};
8081
pub use self::operator::{BinaryOperator, UnaryOperator};
@@ -3573,6 +3574,12 @@ pub enum Statement {
35733574
/// <https://www.postgresql.org/docs/current/sql-dropextension.html>
35743575
DropExtension(DropExtension),
35753576
/// ```sql
3577+
/// DROP OPERATOR [ IF EXISTS ] name ( { left_type | NONE } , right_type ) [, ...] [ CASCADE | RESTRICT ]
3578+
/// ```
3579+
/// Note: this is a PostgreSQL-specific statement.
3580+
/// <https://www.postgresql.org/docs/current/sql-dropoperator.html>
3581+
DropOperator(DropOperator),
3582+
/// ```sql
35763583
/// FETCH
35773584
/// ```
35783585
/// Retrieve rows from a query using a cursor
@@ -4836,6 +4843,7 @@ impl fmt::Display for Statement {
48364843
Statement::CreateIndex(create_index) => create_index.fmt(f),
48374844
Statement::CreateExtension(create_extension) => write!(f, "{create_extension}"),
48384845
Statement::DropExtension(drop_extension) => write!(f, "{drop_extension}"),
4846+
Statement::DropOperator(drop_operator) => write!(f, "{drop_operator}"),
48394847
Statement::CreateRole(create_role) => write!(f, "{create_role}"),
48404848
Statement::CreateSecret {
48414849
or_replace,

src/ast/spans.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -375,6 +375,7 @@ impl Spanned for Statement {
375375
Statement::CreateRole(create_role) => create_role.span(),
376376
Statement::CreateExtension(create_extension) => create_extension.span(),
377377
Statement::DropExtension(drop_extension) => drop_extension.span(),
378+
Statement::DropOperator(drop_operator) => drop_operator.span(),
378379
Statement::CreateSecret { .. } => Span::empty(),
379380
Statement::CreateServer { .. } => Span::empty(),
380381
Statement::CreateConnector { .. } => Span::empty(),

src/parser/mod.rs

Lines changed: 43 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6767,9 +6767,11 @@ impl<'a> Parser<'a> {
67676767
return self.parse_drop_trigger();
67686768
} else if self.parse_keyword(Keyword::EXTENSION) {
67696769
return self.parse_drop_extension();
6770+
} else if self.parse_keyword(Keyword::OPERATOR) {
6771+
return self.parse_drop_operator();
67706772
} else {
67716773
return self.expected(
6772-
"CONNECTOR, DATABASE, EXTENSION, FUNCTION, INDEX, POLICY, PROCEDURE, ROLE, SCHEMA, SECRET, SEQUENCE, STAGE, TABLE, TRIGGER, TYPE, VIEW, MATERIALIZED VIEW or USER after DROP",
6774+
"CONNECTOR, DATABASE, EXTENSION, FUNCTION, INDEX, OPERATOR, POLICY, PROCEDURE, ROLE, SCHEMA, SECRET, SEQUENCE, STAGE, TABLE, TRIGGER, TYPE, VIEW, MATERIALIZED VIEW or USER after DROP",
67736775
self.peek_token(),
67746776
);
67756777
};
@@ -7525,6 +7527,46 @@ impl<'a> Parser<'a> {
75257527
}))
75267528
}
75277529

7530+
/// Parse a[Statement::DropOperator] statement.
7531+
///
7532+
pub fn parse_drop_operator(&mut self) -> Result<Statement, ParserError> {
7533+
let if_exists = self.parse_keywords(&[Keyword::IF, Keyword::EXISTS]);
7534+
let operators = self.parse_comma_separated(|p| p.parse_drop_operator_signature())?;
7535+
let drop_behavior = self.parse_optional_drop_behavior();
7536+
Ok(Statement::DropOperator(DropOperator {
7537+
if_exists,
7538+
operators,
7539+
drop_behavior,
7540+
}))
7541+
}
7542+
7543+
/// Parse an operator signature for a [Statement::DropOperator]
7544+
/// Format: `name ( { left_type | NONE } , right_type )`
7545+
fn parse_drop_operator_signature(&mut self) -> Result<DropOperatorSignature, ParserError> {
7546+
let name = self.parse_operator_name()?;
7547+
self.expect_token(&Token::LParen)?;
7548+
7549+
// Parse left operand type (or NONE for prefix operators)
7550+
let left_type = if self.parse_keyword(Keyword::NONE) {
7551+
None
7552+
} else {
7553+
Some(self.parse_data_type()?)
7554+
};
7555+
7556+
self.expect_token(&Token::Comma)?;
7557+
7558+
// Parse right operand type (always required)
7559+
let right_type = self.parse_data_type()?;
7560+
7561+
self.expect_token(&Token::RParen)?;
7562+
7563+
Ok(DropOperatorSignature {
7564+
name,
7565+
left_type,
7566+
right_type,
7567+
})
7568+
}
7569+
75287570
//TODO: Implement parsing for Skewed
75297571
pub fn parse_hive_distribution(&mut self) -> Result<HiveDistributionStyle, ParserError> {
75307572
if self.parse_keywords(&[Keyword::PARTITIONED, Keyword::BY]) {

tests/sqlparser_postgres.rs

Lines changed: 87 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,7 @@
2323
mod test_utils;
2424

2525
use helpers::attached_token::AttachedToken;
26+
use sqlparser::ast::{DataType, DropBehavior, DropOperator, DropOperatorSignature};
2627
use sqlparser::tokenizer::Span;
2728
use test_utils::*;
2829

@@ -6763,6 +6764,92 @@ fn parse_create_operator() {
67636764
assert!(pg().parse_sql_statements("CREATE OPERATOR > ())").is_err());
67646765
}
67656766

6767+
#[test]
6768+
fn parse_drop_operator() {
6769+
// Test DROP OPERATOR with NONE for prefix operator
6770+
let sql = "DROP OPERATOR ~ (NONE, BIT)";
6771+
assert_eq!(
6772+
pg_and_generic().verified_stmt(sql),
6773+
Statement::DropOperator(DropOperator {
6774+
if_exists: false,
6775+
operators: vec![DropOperatorSignature {
6776+
name: ObjectName::from(vec![Ident::new("~")]),
6777+
left_type: None,
6778+
right_type: DataType::Bit(None),
6779+
}],
6780+
drop_behavior: None,
6781+
})
6782+
);
6783+
6784+
for if_exist in [true, false] {
6785+
for cascading in [
6786+
None,
6787+
Some(DropBehavior::Cascade),
6788+
Some(DropBehavior::Restrict),
6789+
] {
6790+
for op in &["<", ">", "<=", ">=", "<>", "||", "&&", "<<", ">>"] {
6791+
let sql = format!(
6792+
"DROP OPERATOR{} {op} (INTEGER, INTEGER){}",
6793+
if if_exist { " IF EXISTS" } else { "" },
6794+
match cascading {
6795+
Some(cascading) => format!(" {cascading}"),
6796+
None => String::new(),
6797+
}
6798+
);
6799+
assert_eq!(
6800+
pg_and_generic().verified_stmt(&sql),
6801+
Statement::DropOperator(DropOperator {
6802+
if_exists: if_exist,
6803+
operators: vec![DropOperatorSignature {
6804+
name: ObjectName::from(vec![Ident::new(*op)]),
6805+
left_type: Some(DataType::Integer(None)),
6806+
right_type: DataType::Integer(None),
6807+
}],
6808+
drop_behavior: cascading,
6809+
})
6810+
);
6811+
}
6812+
}
6813+
}
6814+
6815+
// Test DROP OPERATOR with schema-qualified operator name
6816+
let sql = "DROP OPERATOR myschema.@@ (TEXT, TEXT)";
6817+
assert_eq!(
6818+
pg_and_generic().verified_stmt(sql),
6819+
Statement::DropOperator(DropOperator {
6820+
if_exists: false,
6821+
operators: vec![DropOperatorSignature {
6822+
name: ObjectName::from(vec![Ident::new("myschema"), Ident::new("@@")]),
6823+
left_type: Some(DataType::Text),
6824+
right_type: DataType::Text,
6825+
}],
6826+
drop_behavior: None,
6827+
})
6828+
);
6829+
6830+
// Test DROP OPERATOR with multiple operators, IF EXISTS and CASCADE
6831+
let sql = "DROP OPERATOR IF EXISTS + (INTEGER, INTEGER), - (INTEGER, INTEGER) CASCADE";
6832+
assert_eq!(
6833+
pg_and_generic().verified_stmt(sql),
6834+
Statement::DropOperator(DropOperator {
6835+
if_exists: true,
6836+
operators: vec![
6837+
DropOperatorSignature {
6838+
name: ObjectName::from(vec![Ident::new("+")]),
6839+
left_type: Some(DataType::Integer(None)),
6840+
right_type: DataType::Integer(None),
6841+
},
6842+
DropOperatorSignature {
6843+
name: ObjectName::from(vec![Ident::new("-")]),
6844+
left_type: Some(DataType::Integer(None)),
6845+
right_type: DataType::Integer(None),
6846+
}
6847+
],
6848+
drop_behavior: Some(DropBehavior::Cascade),
6849+
})
6850+
);
6851+
}
6852+
67666853
#[test]
67676854
fn parse_create_operator_family() {
67686855
for index_method in &["btree", "hash", "gist", "gin", "spgist", "brin"] {

0 commit comments

Comments
 (0)