Using `sqlalchemy.and_()` and `sqlalchemy.or_()` functions rather than `&` and `|` operators
- Dominant language
- Python
- Stars
- 670
- Forks
- 183
- Avg merge
- 17h 7m
- Merged PRs (30d)
- 358
Description
## Problem
We found cases where Python's boolean operators (`and`, `or`) were incorrectly used instead of SQLAlchemy operators, as seen in PR #2989:
```python
# Incorrect: Using Python's boolean operator
query = sa.select(ImageRow).where(
(ImageRow.name == identifier.canonical)
and (ImageRow.architecture == identifier.architecture)
)
```
This is problematic because Python's boolean operators don't properly translate to SQL conditions. The query will be evaluated differently than intended.
## Proposal
Use `sqlalchemy.and_()` and `sqlalchemy.or_()` functions to make it explicit that we're using SQLAlchemy's SQL generation:
```python
# Correct: Using SQLAlchemy functions
query_stmt = sa.select(ImageRow).where(
sa.and_(
ImageRow.name == identifier.canonical,
ImageRow.architecture == identifier.architecture
)
)
```
While using SQLAlchemy's operators (`&`, `|`) is also correct:
```python
# Also correct: Using SQLAlchemy operators
query = sa.select(ImageRow).where(
(ImageRow.name == identifier.canonical)
& (ImageRow.architecture == identifier.architecture)
)
```
The function-based approach makes it impossible to accidentally use Python's boolean operators, as the syntax is distinctly different from Python's `and`/`or`.
## Related Links
- PR #2989 (fix for incorrect use of Python's `and` operator)
JIRA Issue: BA-45
Contributor guide
Assessment
This issue has not been assessed yet.