Skip to content

Commit 7aa9f73

Browse files
committed
MySQL: Add support for casting using the BINARY keyword
1 parent ee3b622 commit 7aa9f73

File tree

4 files changed

+27
-0
lines changed

4 files changed

+27
-0
lines changed

src/dialect/mod.rs

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1237,6 +1237,12 @@ pub trait Dialect: Debug + Any {
12371237
fn supports_double_ampersand_operator(&self) -> bool {
12381238
false
12391239
}
1240+
1241+
/// Returns true if the dialect supports casting an expression to a binary type
1242+
/// using the `BINARY <expr>` syntax.
1243+
fn supports_binary_kw_as_cast(&self) -> bool {
1244+
false
1245+
}
12401246
}
12411247

12421248
/// Operators for which precedence must be defined.

src/dialect/mysql.rs

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -176,6 +176,12 @@ impl Dialect for MySqlDialect {
176176
fn supports_double_ampersand_operator(&self) -> bool {
177177
true
178178
}
179+
180+
/// Deprecated functionality by MySQL but still supported
181+
/// See: <https://dev.mysql.com/doc/refman/8.4/en/cast-functions.html#operator_binary>
182+
fn supports_binary_kw_as_cast(&self) -> bool {
183+
true
184+
}
179185
}
180186

181187
/// `LOCK TABLES`

src/parser/mod.rs

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1641,6 +1641,15 @@ impl<'a> Parser<'a> {
16411641
// an unary negation `NOT ('a' LIKE 'b')`. To solve this, we don't accept the
16421642
// `type 'string'` syntax for the custom data types at all.
16431643
DataType::Custom(..) => parser_err!("dummy", loc),
1644+
// MySQL supports using the `BINARY` keyword as a cast to binary type.
1645+
DataType::Binary(..) if self.dialect.supports_binary_kw_as_cast() => {
1646+
Ok(Expr::Cast {
1647+
kind: CastKind::Cast,
1648+
expr: Box::new(parser.parse_expr()?),
1649+
data_type: DataType::Binary(None),
1650+
format: None,
1651+
})
1652+
}
16441653
data_type => Ok(Expr::TypedString(TypedString {
16451654
data_type,
16461655
value: parser.parse_value()?,

tests/sqlparser_common.rs

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18060,3 +18060,9 @@ fn test_parse_key_value_options_trailing_semicolon() {
1806018060
"CREATE USER u1 option1='value1' option2='value2'",
1806118061
);
1806218062
}
18063+
18064+
#[test]
18065+
fn test_binary_kw_as_cast() {
18066+
all_dialects_where(|d| d.supports_binary_kw_as_cast())
18067+
.one_statement_parses_to("SELECT BINARY 1+1", "SELECT CAST(1 + 1 AS BINARY)");
18068+
}

0 commit comments

Comments
 (0)