pypika icon indicating copy to clipboard operation
pypika copied to clipboard

Arithmetic Order of Operations Bug

Open anthonyaag opened this issue 5 years ago • 3 comments

Hi All,

When using parens in statements I would expect them to be carried forward into the generated sql to ensure that my intended order of operations was maintained.

I'd expect that

from pypika.terms import Term

example             = Term.wrap_constant(1.0) /  Term.wrap_constant(2.0) * Term.wrap_constant(3.0)
example_with_parens = Term.wrap_constant(1.0) / (Term.wrap_constant(2.0) * Term.wrap_constant(3.0))

would generate different sql representations 1.0/2.0*3.0 and 1.0/(2.0*3.0) respectively. However, that does not appear to be the case.

It seems that parentheses are being ignored when constructing sql for division and multiplication. I see this is done so explicitly in ArithmeticExpression. I think this causes a correctness issue when parens are used, as the above examples produce identical sql.

print((example.get_sql(),
       example_with_parns.get_sql(),
       example.get_sql() == example_with_parns.get_sql()))
> ('1.0/2.0*3.0', '1.0/2.0*3.0', True)

This results in both example and example_with_parens returning 1.50 when executed, but the example_with_parens should return 0.166.

anthonyaag avatar Oct 22 '20 14:10 anthonyaag

Fair point. Would definitely accept a PR for this.

gl3nn avatar Nov 03 '20 18:11 gl3nn

I can take this. Working on a PR now.

mkbsh avatar Dec 09 '20 06:12 mkbsh

Should this issue be closed now that #532 has been merged?

knowsuchagency avatar Jul 29 '21 03:07 knowsuchagency