sqlalchemy: SQLite and Postgresql have conflicting operator precedence for the string concat and math operators

Describe the bug SQLAlchemy (on the latest master version) does not place correct parenthesis when using the || operator.

Expected behavior

expr = type_coerce(Author.id + literal(1), types.String)
f = (Author.first_name + expr).label('f')
session.query(f).select_from(Author)

I expect the following query:

SELECT author.first_name || (author.id + ?) AS f
FROM author

Producing:

Name1
Name2
...

Instead SQLAlchemy generate the following query:

SELECT author.first_name || author.id + ? AS f
FROM author

Leading to incorrect results:

1
1
...

Unlike the SQL operator +, the operator || has the highest precedence. Therefore to interpret this query correctly parenthesis are needed. For more details see here

Versions. SQLAlchemy latest master version(commit)

Have a nice day!

About this issue

  • Original URL
  • State: closed
  • Created 4 years ago
  • Comments: 23 (23 by maintainers)

Commits related to this issue

Most upvoted comments

Ι wonder though why sqlalchemy does not explicitly place parenthesis since when I apply the operator || between two expressions e1, e2 (i.e., e1 || e2) I treat e1 and e2 as the operands of ||, with e can be any expression.

So in this case, I find removing parenthesis counter-intuitive. Maybe this contradicts with the semantics of SQLAlchemy sub-expressions. I believe that placing parenthesis should work in any database.