Skip to content

Commit

Permalink
feat(insights): Support unary minus and plus in formulas (#23119)
Browse files Browse the repository at this point in the history
* feat(insights): Support unary minus and plus in formulas

* Fix variable use issue
  • Loading branch information
Twixes authored Jun 20, 2024
1 parent fcc1884 commit a7b678b
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 1 deletion.
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 @@ def _evaluate(self, node, const_map: dict[str, Any]):
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 {unary_op.__class__.__name__} not supported")

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)

0 comments on commit a7b678b

Please sign in to comment.