From 257a9da2211108b1a43984ef12e78ecf6fed5087 Mon Sep 17 00:00:00 2001 From: Marius Andra Date: Tue, 27 Feb 2024 18:02:58 +0100 Subject: [PATCH] feat(trends): division by zero is zero (#20579) --- posthog/hogql_queries/utils/formula_ast.py | 2 ++ posthog/hogql_queries/utils/test/test_formula_ast.py | 5 +++++ 2 files changed, 7 insertions(+) diff --git a/posthog/hogql_queries/utils/formula_ast.py b/posthog/hogql_queries/utils/formula_ast.py index 95fa476d6fcee..28e705827b7f8 100644 --- a/posthog/hogql_queries/utils/formula_ast.py +++ b/posthog/hogql_queries/utils/formula_ast.py @@ -52,6 +52,8 @@ def _evaluate(self, node, const_map: Dict[str, Any]): try: return self.op_map[type(op)](left, right) + except ZeroDivisionError: + return 0 except KeyError: raise ValueError(f"Operator {op.__class__.__name__} not supported") diff --git a/posthog/hogql_queries/utils/test/test_formula_ast.py b/posthog/hogql_queries/utils/test/test_formula_ast.py index a10a54f71ca29..3f065bf516cbc 100644 --- a/posthog/hogql_queries/utils/test/test_formula_ast.py +++ b/posthog/hogql_queries/utils/test/test_formula_ast.py @@ -27,6 +27,11 @@ def test_division(self): response = formula.call("A/2") self.assertListEqual([0.5, 1, 1.5, 2], response) + def test_division_zero(self): + formula = self._get_formula_ast() + response = formula.call("A/0") + self.assertListEqual([0, 0, 0, 0], response) + def test_modulo(self): formula = self._get_formula_ast() response = formula.call("A%2")