Skip to content

Commit a206343

Browse files
committed
Stop losing parens when roundtripping (1/4)
Before this change an expression like `(a+b)-(c+d)` was parsed correctly (as a Minus node with two Plus nodes as children), but when serializing back to an SQL string, it came up as a+b-c+d, since we don't store parens in AST and don't attempt to insert them when necessary during serialization. The latter would be hard, and we already had an SQLNested enum variant, so I changed the code to wrap the AST node for the parenthesized expression in it.
1 parent 14a07a9 commit a206343

File tree

2 files changed

+7
-8
lines changed

2 files changed

+7
-8
lines changed

src/sqlparser.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -194,9 +194,9 @@ impl Parser {
194194
self.parse_sql_value()
195195
}
196196
Token::LParen => {
197-
let expr = self.parse_expr(); // TBD (1)
197+
let expr = self.parse_expr()?;
198198
self.expect_token(&Token::RParen)?;
199-
expr
199+
Ok(ASTNode::SQLNested(Box::new(expr)))
200200
}
201201
_ => parser_err!(format!(
202202
"Prefix parser expected a keyword but found {:?}",

tests/sqlparser_generic.rs

Lines changed: 5 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -420,22 +420,21 @@ fn parse_parens() {
420420
use self::ASTNode::*;
421421
use self::SQLOperator::*;
422422
let sql = "(a + b) - (c + d)";
423-
let ast = parse_sql_expr(&sql);
424423
assert_eq!(
425424
SQLBinaryExpr {
426-
left: Box::new(SQLBinaryExpr {
425+
left: Box::new(SQLNested(Box::new(SQLBinaryExpr {
427426
left: Box::new(SQLIdentifier("a".to_string())),
428427
op: Plus,
429428
right: Box::new(SQLIdentifier("b".to_string()))
430-
}),
429+
}))),
431430
op: Minus,
432-
right: Box::new(SQLBinaryExpr {
431+
right: Box::new(SQLNested(Box::new(SQLBinaryExpr {
433432
left: Box::new(SQLIdentifier("c".to_string())),
434433
op: Plus,
435434
right: Box::new(SQLIdentifier("d".to_string()))
436-
})
435+
})))
437436
},
438-
ast
437+
verified_expr(sql)
439438
);
440439
}
441440

0 commit comments

Comments
 (0)