Skip to content
Merged
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: 1 addition & 1 deletion src/ast/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ pub use self::ddl::{
AlterColumnOperation, AlterTableOperation, ColumnDef, ColumnOption, ColumnOptionDef,
ReferentialAction, TableConstraint,
};
pub use self::operator::{BinaryOperator, PGCustomOperator, UnaryOperator};
pub use self::operator::{BinaryOperator, UnaryOperator};
pub use self::query::{
Cte, Fetch, Join, JoinConstraint, JoinOperator, LateralView, LockType, Offset, OffsetRows,
OrderByExpr, Query, Select, SelectInto, SelectItem, SetExpr, SetOperator, TableAlias,
Expand Down
26 changes: 9 additions & 17 deletions src/ast/operator.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,8 @@ use alloc::string::String;
#[cfg(feature = "serde")]
use serde::{Deserialize, Serialize};

use super::display_separated;

/// Unary operators
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
Expand Down Expand Up @@ -88,17 +90,11 @@ pub enum BinaryOperator {
PGRegexIMatch,
PGRegexNotMatch,
PGRegexNotIMatch,
PGCustomBinaryOperator(PGCustomOperator),
}

/// PostgreSQL-specific custom operator.
///
/// See [CREATE OPERATOR](https://www.postgresql.org/docs/current/sql-createoperator.html) for more information.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct PGCustomOperator {
pub schema: Option<String>,
pub name: String,
/// PostgreSQL-specific custom operator.
///
/// See [CREATE OPERATOR](https://www.postgresql.org/docs/current/sql-createoperator.html)
/// for more information.
PGCustomBinaryOperator(Vec<String>),
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

One downside of this approach that I can think of is that it does not restrict the initial parts of the custom operator to valid tokens

Aka this should probably really be something like

Suggested change
PGCustomBinaryOperator(Vec<String>),
PGCustomBinaryOperator{ ident: Vec<Ident>, op: String),

But I think this may be good enough?

}

impl fmt::Display for BinaryOperator {
Expand Down Expand Up @@ -134,12 +130,8 @@ impl fmt::Display for BinaryOperator {
BinaryOperator::PGRegexIMatch => f.write_str("~*"),
BinaryOperator::PGRegexNotMatch => f.write_str("!~"),
BinaryOperator::PGRegexNotIMatch => f.write_str("!~*"),
BinaryOperator::PGCustomBinaryOperator(ref custom_operator) => {
write!(f, "OPERATOR(")?;
if let Some(ref schema) = custom_operator.schema {
write!(f, "{}.", schema)?;
}
write!(f, "{})", custom_operator.name)
BinaryOperator::PGCustomBinaryOperator(idents) => {
write!(f, "OPERATOR({})", display_separated(idents, "."))
}
}
}
Expand Down
32 changes: 11 additions & 21 deletions src/parser.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1161,29 +1161,19 @@ impl<'a> Parser<'a> {
Keyword::XOR => Some(BinaryOperator::Xor),
Keyword::OPERATOR if dialect_of!(self is PostgreSqlDialect | GenericDialect) => {
self.expect_token(&Token::LParen)?;
let token_1 = self.peek_nth_token(1);

let custom_operator = match token_1 {
Token::Period => {
let schema = self.parse_identifier()?;
self.expect_token(&Token::Period)?;
let operator = self.next_token();
PGCustomOperator {
schema: Some(schema.value),
name: operator.to_string(),
}
}
_ => {
let operator = self.next_token();
PGCustomOperator {
schema: None,
name: operator.to_string(),
}
// there are special rules for operator names in
// postgres so we can not use 'parse_object'
// or similar.
// See https://www.postgresql.org/docs/current/sql-createoperator.html
let mut idents = vec![];
loop {
idents.push(self.next_token().to_string());
if !self.consume_token(&Token::Period) {
break;
}
};

}
self.expect_token(&Token::RParen)?;
Some(BinaryOperator::PGCustomBinaryOperator(custom_operator))
Some(BinaryOperator::PGCustomBinaryOperator(idents))
}
_ => None,
},
Expand Down
29 changes: 21 additions & 8 deletions tests/sqlparser_postgres.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1567,6 +1567,25 @@ fn parse_fetch() {

#[test]
fn parse_custom_operator() {
// operator with a database and schema
let sql = r#"SELECT * FROM events WHERE relname OPERATOR(database.pg_catalog.~) '^(table)$'"#;
let select = pg().verified_only_select(sql);
assert_eq!(
select.selection,
Some(Expr::BinaryOp {
left: Box::new(Expr::Identifier(Ident {
value: "relname".into(),
quote_style: None,
})),
op: BinaryOperator::PGCustomBinaryOperator(vec![
"database".into(),
"pg_catalog".into(),
"~".into()
]),
right: Box::new(Expr::Value(Value::SingleQuotedString("^(table)$".into())))
})
);

// operator with a schema
let sql = r#"SELECT * FROM events WHERE relname OPERATOR(pg_catalog.~) '^(table)$'"#;
let select = pg().verified_only_select(sql);
Expand All @@ -1577,10 +1596,7 @@ fn parse_custom_operator() {
value: "relname".into(),
quote_style: None,
})),
op: BinaryOperator::PGCustomBinaryOperator(PGCustomOperator {
schema: Some("pg_catalog".into()),
name: "~".into(),
}),
op: BinaryOperator::PGCustomBinaryOperator(vec!["pg_catalog".into(), "~".into()]),
right: Box::new(Expr::Value(Value::SingleQuotedString("^(table)$".into())))
})
);
Expand All @@ -1595,10 +1611,7 @@ fn parse_custom_operator() {
value: "relname".into(),
quote_style: None,
})),
op: BinaryOperator::PGCustomBinaryOperator(PGCustomOperator {
schema: None,
name: "~".into(),
}),
op: BinaryOperator::PGCustomBinaryOperator(vec!["~".into()]),
right: Box::new(Expr::Value(Value::SingleQuotedString("^(table)$".into())))
})
);
Expand Down