Skip to content

Commit 066f27f

Browse files
Added support for DROP OPERATOR syntax
1 parent 1114d6a commit 066f27f

File tree

5 files changed

+212
-9
lines changed

5 files changed

+212
-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<OperatorSignature>,
4202+
/// CASCADE or RESTRICT
4203+
pub drop_behavior: Option<DropBehavior>,
4204+
}
4205+
4206+
/// Operator signature for DROP OPERATOR
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 OperatorSignature {
4211+
/// Operator name (can be schema-qualified)
4212+
pub name: ObjectName,
4213+
/// Left operand type (None for prefix operators)
4214+
pub left_type: Option<DataType>,
4215+
/// Right operand type (always required)
4216+
pub right_type: DataType,
4217+
}
4218+
4219+
impl fmt::Display for OperatorSignature {
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, DropTrigger, GeneratedAs,
71+
GeneratedExpressionMode, IdentityParameters, IdentityProperty, IdentityPropertyFormatKind,
72+
IdentityPropertyKind, IdentityPropertyOrder, IndexColumn, IndexOption, IndexType,
73+
KeyOrIndexDisplay, Msck, NullsDistinctOption, OperatorArgTypes, OperatorClassItem,
74+
OperatorPurpose, OperatorSignature, 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
@@ -4835,6 +4842,7 @@ impl fmt::Display for Statement {
48354842
Statement::CreateIndex(create_index) => create_index.fmt(f),
48364843
Statement::CreateExtension(create_extension) => write!(f, "{create_extension}"),
48374844
Statement::DropExtension(drop_extension) => write!(f, "{drop_extension}"),
4845+
Statement::DropOperator(drop_operator) => write!(f, "{drop_operator}"),
48384846
Statement::CreateRole(create_role) => write!(f, "{create_role}"),
48394847
Statement::CreateSecret {
48404848
or_replace,

src/ast/spans.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -366,6 +366,7 @@ impl Spanned for Statement {
366366
Statement::CreateRole(create_role) => create_role.span(),
367367
Statement::CreateExtension(create_extension) => create_extension.span(),
368368
Statement::DropExtension(drop_extension) => drop_extension.span(),
369+
Statement::DropOperator(drop_operator) => drop_operator.span(),
369370
Statement::CreateSecret { .. } => Span::empty(),
370371
Statement::CreateServer { .. } => Span::empty(),
371372
Statement::CreateConnector { .. } => Span::empty(),

src/parser/mod.rs

Lines changed: 48 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,51 @@ impl<'a> Parser<'a> {
75257527
}))
75267528
}
75277529

7530+
/// Parse a PostgreSQL-specific [Statement::DropOperator] statement.
7531+
///
7532+
/// ```sql
7533+
/// DROP OPERATOR [ IF EXISTS ] name ( { left_type | NONE } , right_type ) [, ...] [ CASCADE | RESTRICT ]
7534+
/// ```
7535+
///
7536+
/// [PostgreSQL Documentation](https://www.postgresql.org/docs/current/sql-dropoperator.html)
7537+
pub fn parse_drop_operator(&mut self) -> Result<Statement, ParserError> {
7538+
let if_exists = self.parse_keywords(&[Keyword::IF, Keyword::EXISTS]);
7539+
let operators = self.parse_comma_separated(|p| p.parse_operator_signature())?;
7540+
let drop_behavior = self.parse_optional_drop_behavior();
7541+
Ok(Statement::DropOperator(DropOperator {
7542+
if_exists,
7543+
operators,
7544+
drop_behavior,
7545+
}))
7546+
}
7547+
7548+
/// Parse an operator signature for DROP OPERATOR
7549+
/// Format: name ( { left_type | NONE } , right_type )
7550+
fn parse_operator_signature(&mut self) -> Result<OperatorSignature, ParserError> {
7551+
let name = self.parse_operator_name()?;
7552+
self.expect_token(&Token::LParen)?;
7553+
7554+
// Parse left operand type (or NONE for prefix operators)
7555+
let left_type = if self.parse_keyword(Keyword::NONE) {
7556+
None
7557+
} else {
7558+
Some(self.parse_data_type()?)
7559+
};
7560+
7561+
self.expect_token(&Token::Comma)?;
7562+
7563+
// Parse right operand type (always required)
7564+
let right_type = self.parse_data_type()?;
7565+
7566+
self.expect_token(&Token::RParen)?;
7567+
7568+
Ok(OperatorSignature {
7569+
name,
7570+
left_type,
7571+
right_type,
7572+
})
7573+
}
7574+
75287575
//TODO: Implement parsing for Skewed
75297576
pub fn parse_hive_distribution(&mut self) -> Result<HiveDistributionStyle, ParserError> {
75307577
if self.parse_keywords(&[Keyword::PARTITIONED, Keyword::BY]) {

tests/sqlparser_postgres.rs

Lines changed: 88 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6763,6 +6763,94 @@ fn parse_create_operator() {
67636763
assert!(pg().parse_sql_statements("CREATE OPERATOR > ())").is_err());
67646764
}
67656765

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

0 commit comments

Comments
 (0)