Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(insights): Support unary minus and plus in formulas #23119

Merged
merged 2 commits into from
Jun 20, 2024
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 9 additions & 1 deletion posthog/hogql_queries/utils/formula_ast.py
Original file line number Diff line number Diff line change
Expand Up @@ -49,14 +49,22 @@
left = self._evaluate(node.left, const_map)
op = node.op
right = self._evaluate(node.right, const_map)

try:
return self.op_map[type(op)](left, right)
except ZeroDivisionError:
return 0
except KeyError:
raise ValueError(f"Operator {op.__class__.__name__} not supported")

elif isinstance(node, ast.UnaryOp):
operand = self._evaluate(node.operand, const_map)
unary_op = node.op
if isinstance(unary_op, ast.USub):
return -operand
elif isinstance(unary_op, ast.UAdd):
return operand
raise ValueError(f"Operator {op.__class__.__name__} not supported")

Check failure on line 66 in posthog/hogql_queries/utils/formula_ast.py

View workflow job for this annotation

GitHub Actions / Python code quality checks

Name "op" is used before definition

elif isinstance(node, ast.Num):
return node.n

Expand Down
10 changes: 10 additions & 0 deletions posthog/hogql_queries/utils/test/test_formula_ast.py
Original file line number Diff line number Diff line change
Expand Up @@ -56,3 +56,13 @@ def test_named_values_lower_case(self):
formula = self._get_formula_ast()
response = formula.call("a+b")
self.assertListEqual([2, 4, 6, 8], response)

def test_unary_minus(self):
formula = self._get_formula_ast()
response = formula.call("-A")
self.assertListEqual([-1, -2, -3, -4], response)

def test_unary_plus(self):
formula = self._get_formula_ast()
response = formula.call("+A")
self.assertListEqual([1, 2, 3, 4], response)
Loading