Skip to content

Commit

Permalink
Merge pull request #229 from opensafely/support-arithmetic-operators
Browse files Browse the repository at this point in the history
Allow arithmetic operators in SQL expressions
  • Loading branch information
evansd authored Jul 6, 2020
2 parents 84441f8 + be4ebd9 commit 49aadc2
Show file tree
Hide file tree
Showing 3 changed files with 6 additions and 3 deletions.
2 changes: 1 addition & 1 deletion cohortextractor/VERSION
Original file line number Diff line number Diff line change
@@ -1 +1 @@
0.1.28
0.1.29
5 changes: 4 additions & 1 deletion cohortextractor/expressions.py
Original file line number Diff line number Diff line change
Expand Up @@ -112,6 +112,8 @@ def is_allowed(token):
return value in [">", "<", ">=", "<=", "=", "!="]
if ttype in ttypes.Number.Float or ttype in ttypes.Number.Integer:
return True
if ttype in ttypes.Operator:
return value in ["+", "-", "*", "/"]
return False


Expand All @@ -132,7 +134,8 @@ def insert_implicit_comparisons(tokens, empty_value_map):
is_compared = (
next_ttype is ttypes.Comparison or previous_ttype is ttypes.Comparison
)
if token.ttype is ttypes.Name and not is_compared:
is_combined = next_ttype is ttypes.Operator or previous_ttype is ttypes.Operator
if token.ttype is ttypes.Name and not is_compared and not is_combined:
column_name = str(token)
empty_value = empty_value_map[column_name]
yield sqlparse.sql.Token(ttypes.Punctuation, "(")
Expand Down
2 changes: 1 addition & 1 deletion tests/test_tpp_backend.py
Original file line number Diff line number Diff line change
Expand Up @@ -830,7 +830,7 @@ def test_patients_satisfying():
has_asthma=patients.with_these_clinical_events(
codelist([condition_code], "ctv3")
),
at_risk=patients.satisfying("(age > 70 AND sex = 'M') OR has_asthma"),
at_risk=patients.satisfying("((age + 30) > 100 AND sex = 'M') OR has_asthma"),
)
results = study.to_dicts()
assert [i["at_risk"] for i in results] == ["1", "0", "0", "1"]
Expand Down

0 comments on commit 49aadc2

Please sign in to comment.