:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(hogql): use divideDecimal when dividing two decimal columns (#68728)
posthog[bot]03355dd5d1c2
diff --git a/posthog/hogql/printer/clickhouse.py b/posthog/hogql/printer/clickhouse.pyindex 3f82e227a5cc..c83a23d3807b 100644--- a/posthog/hogql/printer/clickhouse.py+++ b/posthog/hogql/printer/clickhouse.py@@ -780,6 +780,24 @@ class ClickHousePrinter(BasePrinter):else:raise ImpossibleASTError("Impossible")+ def visit_arithmetic_operation(self, node: ast.ArithmeticOperation):+ # ClickHouse's plain divide() derives a decimal result scale of (dividend_scale - divisor_scale).+ # When the divisor's scale exceeds the dividend's — e.g. a Decimal(38, 2) column divided by a+ # Decimal(38, 18) one — that underflows to a negative scale and the query errors out with+ # "Decimal result's scale is less than argument's one". divideDecimal derives a valid result scale+ # (the max of the two operand scales, computed at runtime) instead, mirroring the currency-conversion+ # path in _render_posthog_function_call which uses divideDecimal for the same reason.+ if node.op == ast.ArithmeticOperationOp.Div and self._both_operands_decimal(node):+ return f"divideDecimal({self.visit(node.left)}, {self.visit(node.right)})"+ return super().visit_arithmetic_operation(node)++ def _both_operands_decimal(self, node: ast.ArithmeticOperation) -> bool:+ if node.left.type is None or node.right.type is None:+ return False+ left_type = node.left.type.resolve_constant_type(self.context)+ right_type = node.right.type.resolve_constant_type(self.context)+ return isinstance(left_type, ast.DecimalType) and isinstance(right_type, ast.DecimalType)+def visit_call(self, node: ast.Call):# Property-group call optimizations (isNull/isNotNull/JSONHas over a property-group key) now run in ClickHouse# property resolution, which rewrites them to the keys-index `has(group, key)` form before printing.diff --git a/posthog/hogql/printer/test/test_printer.py b/posthog/hogql/printer/test/test_printer.pyindex 54f2704032d6..6319778f9f41 100644--- a/posthog/hogql/printer/test/test_printer.py+++ b/posthog/hogql/printer/test/test_printer.py@@ -3311,6 +3311,35 @@ class TestPrinter(BaseTest):self.assertIn("toDecimal128(100, 10)", printed)self.assertNotIn("toDecimal64(100", printed)+ def test_decimal_division_uses_divide_decimal(self):+ # Regression guard: dividing two Decimal columns whose scales differ (e.g. a warehouse+ # Decimal(38, 2) column over a Decimal(38, 18) one) makes ClickHouse's plain divide() derive a+ # negative result scale and error with "Decimal result's scale is less than argument's one".+ # divideDecimal derives a valid result scale instead, so the query runs. Non-division decimal+ # arithmetic (and non-decimal division) must stay on the plain operators.+ from posthog.hogql.database.models import DecimalDatabaseField++ context = HogQLContext(team_id=self.team.pk, enable_select_queries=True, database=Database())+ assert context.database is not None+ events = context.database.get_table("events")+ events.fields["wholesale"] = DecimalDatabaseField(name="wholesale", nullable=True)+ events.fields["rate"] = DecimalDatabaseField(name="rate", nullable=True)++ # The reported shape: a decimal column divided by nullIf(decimal_column, 0).+ printed = self._select("SELECT wholesale / nullIf(rate, 0) AS ratio FROM events", context)+ assert "divideDecimal(" in printed, printed+ assert "divide(" not in printed, printed++ # Multiplication of the same decimals is unaffected.+ printed_mult = self._select("SELECT wholesale * rate AS product FROM events", context)+ assert "multiply(" in printed_mult, printed_mult+ assert "divideDecimal" not in printed_mult, printed_mult++ # Non-decimal division still uses plain divide().+ printed_int = self._select("SELECT 10 / 3 AS q FROM events", context)+ assert "divide(10, 3)" in printed_int, printed_int+ assert "divideDecimal" not in printed_int, printed_int+def test_sortable_semver(self):# Also test different capitalizationsprinted = self._print(diff --git a/posthog/hogql/resolver.py b/posthog/hogql/resolver.pyindex 59aecf5eed0e..a2237bd3e69d 100644--- a/posthog/hogql/resolver.py+++ b/posthog/hogql/resolver.py@@ -1528,6 +1528,17 @@ class Resolver(CloningVisitor):node.type = ast.FloatType()elif isinstance(left_type, ast.DateTimeType) or isinstance(right_type, ast.DateTimeType):node.type = ast.DateTimeType()+ elif isinstance(left_type, ast.DecimalType) or isinstance(right_type, ast.DecimalType):+ # ClickHouse widens Decimal combined with a Float to Float; Decimal combined with a+ # Decimal or Integer stays Decimal. Anything else (e.g. Decimal + String) is unknown.+ if isinstance(left_type, ast.FloatType) or isinstance(right_type, ast.FloatType):+ node.type = ast.FloatType()+ elif isinstance(left_type, ast.DecimalType | ast.IntegerType) and isinstance(+ right_type, ast.DecimalType | ast.IntegerType+ ):+ node.type = ast.DecimalType()+ else:+ node.type = ast.UnknownType()elif isinstance(left_type, ast.UnknownType) or isinstance(right_type, ast.UnknownType):node.type = ast.UnknownType()else: