Precedence issue
Currently:
from cities
select temp_c = (temp - 32) * 3
compiles to:
SELECT
temp - 32 * 3 AS temp_c
FROM
cities
...which has the wrong precedence — we should have (temp - 32) * 3
This comment has been here from before I started contributing:
https://github.com/prql/prql/blob/be13c12f91bcf3cd147f9bd30098293da3ea5191/prql-compiler/src/sql/translator.rs#L487-L489
and answer is yes, but not in all cases :D
As ever, s-strings are a way of mitigating this until it's fixed:
from n
derive x = s"(y or z) and (a or b)"
is correctly parsed as:
SELECT
n.*,
(
y
or z
)
and (
a
or b
) AS x
FROM
n
I have run into a variant of this bug:
from x
derive [
n = a + b,
r = a/n,
]
translates as
SELECT
x.*,
a + b AS n,
a / a + b AS r
FROM
x
Thanks @mmm444 and sorry for the trouble .
For the next day or two™, you can get around it with an s-string:
from x
derive [
n = s"(a + b)",
r = a/n,
]
SELECT
x.*,
(a + b) AS n,
a / (a + b) AS r
FROM
x
We'll aim to fix this soon though.
I'm not sure of the best way to solve this — we can put parentheses around left and right here: https://github.com/prql/prql/blob/dbbd8ddc9c2a6acb767c6481d88eeb69a431ef55/prql-compiler/src/sql/translator.rs#L493-L512
but it'll generate a lot of parentheses.
While I can imagine writing the code to handle this properly (e.g. "is the current operator higher precedence than any of the operators within `right", assuming operators are left-associative") — there's probably some well-understood technique to this. If anyone is familiar, please comment!
Otherwise I'll ask someone who is more experienced than me to ensure we're not reinventing stuff.
This is the "put parentheses around everything" approach;
diff --git a/prql-compiler/src/sql/snapshots/prql_compiler__sql__translator__test__prql_to_sql_2.snap b/prql-compiler/src/sql/snapshots/prql_compiler__sql__translator__test__prql_to_sql_2.snap
index e3f29634..1ba7e992 100644
--- a/prql-compiler/src/sql/snapshots/prql_compiler__sql__translator__test__prql_to_sql_2.snap
+++ b/prql-compiler/src/sql/snapshots/prql_compiler__sql__translator__test__prql_to_sql_2.snap
@@ -9,14 +9,14 @@ SELECT
SUM(salary),
AVG(salary + payroll_tax),
SUM(salary + payroll_tax),
- AVG(salary + payroll_tax + benefits_cost),
- SUM(salary + payroll_tax + benefits_cost) AS sum_gross_cost,
+ AVG((salary + payroll_tax) + benefits_cost),
+ SUM((salary + payroll_tax) + benefits_cost) AS sum_gross_cost,
COUNT(*) AS ct
FROM
employees
WHERE
- country = 'USA'
- AND salary + payroll_tax + benefits_cost > 0
+ (country = 'USA')
+ AND (((salary + payroll_tax) + benefits_cost) > 0)
GROUP BY
title,
country
diff --git a/prql-compiler/src/sql/translator.rs b/prql-compiler/src/sql/translator.rs
index 038f8578..87819cff 100644
--- a/prql-compiler/src/sql/translator.rs
+++ b/prql-compiler/src/sql/translator.rs
@@ -490,8 +490,20 @@ fn try_from(item: Item) -> Result<Self> {
if let Some(is_null) = try_into_is_null(&op, &left, &right)? {
is_null
} else {
+ let left = match left.item {
+ Item::Binary { .. } => {
+ Box::new(Expr::Nested(Box::new(left.item.try_into()?)))
+ }
+ _ => Box::new(left.item.try_into()?),
+ };
+ let right = match right.item {
+ Item::Binary { .. } => {
+ Box::new(Expr::Nested(Box::new(right.item.try_into()?)))
+ }
+ _ => Box::new(right.item.try_into()?),
+ };
Expr::BinaryOp {
- left: Box::new(left.item.try_into()?),
+ left,
op: match op {
BinOp::Mul => BinaryOperator::Multiply,
BinOp::Div => BinaryOperator::Divide,
@@ -508,7 +520,7 @@ fn try_from(item: Item) -> Result<Self> {
BinOp::Or => BinaryOperator::Or,
BinOp::Coalesce => unreachable!(),
},
- right: Box::new(right.item.try_into()?),
+ right,
}
}
}
@@ -1139,6 +1151,22 @@ fn test_prql_to_sql_1() -> Result<()> {
employees
"###
);
+
+ let query = parse(
+ r#"
+from cities
+select temp_c = (temp - 32) * 3
+ "#,
+ )?;
+ let sql = resolve_and_translate(query)?;
+ assert_display_snapshot!(sql,
+ @r###"
+ SELECT
+ (temp - 32) * 3 AS temp_c
+ FROM
+ cities
+ "###
+ );
Ok(())
}
@@ -1866,8 +1894,8 @@ fn test_filter() {
FROM
employees
WHERE
- age > 25
- AND age < 40
+ (age > 25)
+ AND (age < 40)
"###);
assert_display_snapshot!((resolve_and_translate(parse(r###"
@@ -1881,8 +1909,8 @@ fn test_filter() {
FROM
employees
WHERE
- age > 25
- AND age < 40
+ (age > 25)
+ AND (age < 40)
"###);
}
@@ -1923,8 +1951,8 @@ fn test_nulls() -> Result<()> {
FROM
employees
WHERE
- first_name IS NULL
- AND last_name IS NULL
+ (first_name IS NULL)
+ AND (last_name IS NULL)
"###);
// IS NOT NULL
@@ -1938,8 +1966,8 @@ fn test_nulls() -> Result<()> {
FROM
employees
WHERE
- first_name IS NOT NULL
- AND last_name IS NOT NULL
+ (first_name IS NOT NULL)
+ AND (last_name IS NOT NULL)
"###);
Ok(())
If there were a quick way of not having it quite so ugly as SUM((salary + payroll_tax) + benefits_cost) AS sum_gross_cost, then it would be good to merge something that solved the problem even if not completely / elegantly.
@aljazerzen WDYT about being us adding a type to the AST that represented a parenthesized expression? Then we wouldn't need to estimate how to handle precedence when we did the translation to SQL, because the parentheses would carry over.
This would work, but not for all cases:
func add a b -> a + b
from table
derive [d = c * add a b]
Instead I would propose a precedence check during translation:
fn translate_ast_node(node) -> (sql, binding_strength) {
match(node.item) {
Item::Binary { left, op, right } => {
let (left_sql, left_strength) = translate_ast_node(left);
if left_strength < op.strength {
left_sql = "(" + left_sql + ")"
}
let (right_sql, right_strength) = translate_ast_node(right);
if right_strength < op.strength {
right_sql = "(" + right_sql + ")"
}
return (left_sql + op + right_sql, op.strength)
}
...
}
}
where op.strength is binding strength of the operator in SQL. All other expressions (lists, pipelines, function calls, literals) can have some high value for strength, since they cannot interfere with binary expressions (i.e. 5 + [1, 2, 3] is not [6, 2, 3]).
In effect this would check if context of the expression requires it to be parenthesized.
I think the 'ugly but working solution' is good enough for now, then we can make a new ticket around binding strength or a new AST type for 'parenthesized' ?
I always seem to eventually hit this it's a pretty big issue.
Great. I was working on the quotes issue yesterday. I'll ensure I spend a decent amount of time on both that and this one on Saturday; I expect we can resolve them.
I'm also trying to make the compiler a bit more modular, so it's easier for others to engage — the current throughput of changes is not great. We were basically completely reliant on @aljazerzen spending almost all his time on the compiler! Which is very admirable, but not scalable. And when he takes a break (which is always completely fine to do tbc; that's the nature of open-source), we find ourselves moving very slowly.
Not sure if this should be a separate issue, but I'd also expect repeated filter statements to implicitly throw parentheses around subsequent arguments. Like so:
from table
filter a == True
filter b == 1 or c == 3
Currently produces:
SELECT
table.*
FROM
table
WHERE
a = "True"
AND b = 1
OR c = 3
But I hope it would produce:
SELECT
table.*
FROM
table
WHERE
a = "True"
AND (b = 1
OR c = 3)
@aljazerzen — if you're around — what are you envisaging left_strength represents here?
let (left_sql, left_strength) = translate_ast_node(left);
If we have (3 + 2) * 5 and we're translating the * op, is left_strength the +? What about if we have (3 + 2 - 1) * 5?
Since this is a recursive function, this would mostly be op.strength, which is binding strength of the operator in SQL.
It means how much does this SQL expression sticks together, so it can be compared with strength of the outer operator to see if the outer operator would "overrule" the inner one, in which case we need parentheses.
Yes I think get the concept — it's great.
To confirm on the cases above though, when we're looking at the *:
(3 + 2) * 5would haveleft_strengthas+(3 + 2 - 1) * 5would haveleft_strengthas-I think? Because this is represented in the AST as((3 + 2) - 1)— is that right?
I think the immediate issue is closed by #839.
Does anyone have other cases we should test against? This currently only works for a few operators which I think should be sufficient for most cases — what are the ones we're currently missing?
Sorry this took a while to fix — that's much worse than our cadence needs to be at our current stage — in exchange for the langugage having occasional bugs, we should be fixing them fast.
It was partly a confluence of me traveling / working quite hard, others taking a well-earned break, the number of the people who work on the guts of the compiler being small, and the compiler being a bit difficult to approach for newcomers.
The first two of those won't change, but I'm working on structuring the compiler — actually not that much needs to change — and hopefully that will make it more approachable, and help with the final two items.
Thanks for the understanding from those who waited, and know that I'm invested in making subsequent bugs easier to squash.
Nice! This seems to be solved even for the "hard" cases, where PRQL does not have () but SQL should:
func add a b -> a + b
from numbers
derive [sum_1 = a + b, sum_2 = add a b]
select [result = c * sum_1 * sum_2]
SELECT
c * (a + b) + (a + b) AS result
FROM
numbers
This algorithm I proposed is more general and would currently handle some weird edge cases, but after I've tried to construct an example where current approach would fail, I realized that these edge cases are not possible and that current approach covers all cases.
In short, I was worried that binding strength of an expression cannot be determined by the top-level operator alone, but we must traverse AST and find the lowest binding strength in the whole tree. Fortunately this is not the case, because if any of non-top-level operators would have lower binding strength than the top-level operator, they would be parenthesized and have their strength increased.
In summary, I agree that this issue is closed.
PS: I did a refactor and added () for unary operators and IS NULL expressions
@aljazerzen one thought I had was whether this covers operators like ** which are right-associative. I didn't mention it because we don't have that yet, but if we did, we may have to consider that.
I think we could just branch on this in the code, and look at the right side rather than the left (maybe I need to be more explicit here).
But regardless yes I agree the approach is very elegant, thank you for proposing it!
Associativity comes into play only when there are many operators with same precedence. I think current approach can be extended to take this into account.
I didn't know that SQL had ** operator... Wouldn't it be translated into POW function anyway?
I didn't know that SQL had
**operator... Wouldn't it be translated intoPOWfunction anyway?
Yes but presumably we would need to do that in the correct order; i.e. 2 ** 3 ** 4 would be pow(2, pow(3, 4)), which wouldn't happen atm IIUC?
Definitely agree this is tractable; easy to do when we get there!