Skip to content

: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.

chore(properties): delete four uncalled property util helpers (#69721)

Andy Zhao88b245d78716
diff --git a/ee/clickhouse/models/test/test_property.py b/ee/clickhouse/models/test/test_property.py
index dc5a4fbd1834..502c28a6db90 100644
--- a/ee/clickhouse/models/test/test_property.py
+++ b/ee/clickhouse/models/test/test_property.py
@@ -1,5 +1,5 @@
from datetime import datetime
-from typing import Any, Literal, Union, cast
+from typing import Any, cast
from uuid import UUID
import pytest
@@ -21,11 +21,10 @@ from posthog.models.element import Element
from posthog.models.filters import Filter
from posthog.models.instance_setting import get_instance_setting
from posthog.models.organization import Organization
-from posthog.models.property import Property, TableWithProperties
+from posthog.models.property import Property
from posthog.models.property.util import (
PropertyGroup,
get_property_string_expr,
- get_single_or_multi_property_string_expr,
parse_prop_grouped_clauses,
prop_filter_json_extract,
)
@@ -1186,112 +1185,6 @@ def test_parse_groups_persons_edge_case_with_single_filter(snapshot):
)
-TEST_BREAKDOWN_PROCESSING = [
- (
- "$browser",
- "events",
- "prop",
- "properties",
- (
- "replaceRegexpAll(JSONExtractRaw(properties, %(breakdown_param_1)s), '^\"|\"$', '') AS prop",
- {"breakdown_param_1": "$browser"},
- ),
- ),
- (
- ["$browser"],
- "events",
- "value",
- "properties",
- (
- "array(replaceRegexpAll(JSONExtractRaw(properties, %(breakdown_param_1)s), '^\"|\"$', '')) AS value",
- {"breakdown_param_1": "$browser"},
- ),
- ),
- (
- ["$browser", "$browser_version"],
- "events",
- "prop",
- "properties",
- (
- "array(replaceRegexpAll(JSONExtractRaw(properties, %(breakdown_param_1)s), '^\"|\"$', ''),replaceRegexpAll(JSONExtractRaw(properties, %(breakdown_param_2)s), '^\"|\"$', '')) AS prop",
- {"breakdown_param_1": "$browser", "breakdown_param_2": "$browser_version"},
- ),
- ),
-]
-
-
[email protected]("breakdown, table, query_alias, column, expected", TEST_BREAKDOWN_PROCESSING)
-def test_breakdown_query_expression(
- clean_up_materialised_columns,
- breakdown: Union[str, list[str]],
- table: TableWithProperties,
- query_alias: Literal["prop", "value"],
- column: str,
- expected: tuple[str, dict[str, Any]],
-):
- actual = get_single_or_multi_property_string_expr(breakdown, table, query_alias, column)
-
- assert actual == expected
-
-
-TEST_BREAKDOWN_PROCESSING_MATERIALIZED = [
- (
- ["$browser"],
- "events",
- "value",
- "properties",
- "person_properties",
- (
- "array(replaceRegexpAll(JSONExtractRaw(properties, %(breakdown_param_1)s), '^\"|\"$', '')) AS value",
- {"breakdown_param_1": "$browser"},
- ),
- ('array("mat_pp_$browser") AS value', {"breakdown_param_1": "$browser"}),
- )
-]
-
-
- "breakdown, table, query_alias, column, materialise_column, expected_with, expected_without",
- TEST_BREAKDOWN_PROCESSING_MATERIALIZED,
-)
-def test_breakdown_query_expression_materialised(
- clean_up_materialised_columns,
- breakdown: Union[str, list[str]],
- table: TableWithProperties,
- query_alias: Literal["prop", "value"],
- column: str,
- materialise_column: str,
- expected_with: tuple[str, dict[str, Any]],
- expected_without: tuple[str, dict[str, Any]],
-):
- from posthog.models.team import util
-
- util.can_enable_actor_on_events = True # ty: ignore[invalid-assignment]
-
- materialize(table, breakdown[0], table_column="properties")
- actual = get_single_or_multi_property_string_expr(
- breakdown,
- table,
- query_alias,
- column,
- materialised_table_column=materialise_column,
- )
- assert actual == expected_with
-
- materialize(table, breakdown[0], table_column=cast(Any, materialise_column))
- actual = get_single_or_multi_property_string_expr(
- breakdown,
- table,
- query_alias,
- column,
- materialised_table_column=materialise_column,
- )
-
- assert actual == expected_without
-
-
@pytest.fixture
def test_events(db, team) -> list[UUID]:
return [
diff --git a/posthog/models/property/test/test_property_util.py b/posthog/models/property/test/test_property_util.py
deleted file mode 100644
index bbe4586193dc..000000000000
--- a/posthog/models/property/test/test_property_util.py
+++ /dev/null
@@ -1,81 +0,0 @@
-import pytest
-from posthog.test.base import BaseTest
-from unittest.mock import MagicMock
-
-from posthog.schema import ErrorTrackingIssueFilter, PropertyOperator
-
-from posthog.models.property.util import property_to_django_filter
-
-
-class TestPropertyUtil(BaseTest):
- def test_property_to_django_filtering(self):
- qs = MagicMock()
- qs.filter = MagicMock()
- qs.exclude = MagicMock()
-
- # does not filter falsey exact matches
- property_to_django_filter(qs, ErrorTrackingIssueFilter(key="name", value=None, operator=PropertyOperator.EXACT))
- qs.filter.assert_not_called()
- property_to_django_filter(qs, ErrorTrackingIssueFilter(key="name", value=[], operator=PropertyOperator.EXACT))
- qs.filter.assert_not_called()
-
- # array based options
- property_to_django_filter(
- qs, ErrorTrackingIssueFilter(key="name", value=["value"], operator=PropertyOperator.EXACT)
- )
- qs.filter.assert_called_once_with(name__in=["value"])
- qs.filter.reset_mock()
-
- # default options
- property_to_django_filter(
- qs, ErrorTrackingIssueFilter(key="name", value="value", operator=PropertyOperator.ICONTAINS)
- )
- qs.filter.assert_called_once_with(name__icontains="value")
- qs.filter.reset_mock()
-
- # negated filtering
- property_to_django_filter(
- qs, ErrorTrackingIssueFilter(key="name", value=["value"], operator=PropertyOperator.IS_NOT)
- )
- qs.exclude.assert_called_once_with(name__in=["value"])
-
- def test_issue_description_mapping(self):
- qs = MagicMock()
- qs.filter = MagicMock()
-
- property_to_django_filter(
- qs,
- ErrorTrackingIssueFilter(key="issue_description", value=["description"], operator=PropertyOperator.EXACT),
- )
- qs.filter.assert_called_once_with(description__in=["description"])
- qs.filter.reset_mock()
-
- def test_rejects_orm_traversal_keys(self):
- qs = MagicMock()
-
- with pytest.raises(ValueError, match="Unsupported error tracking filter key"):
- property_to_django_filter(
- qs,
- ErrorTrackingIssueFilter(
- key="assignment__user__password", value="x", operator=PropertyOperator.ICONTAINS
- ),
- )
-
- with pytest.raises(ValueError, match="Unsupported error tracking filter key"):
- property_to_django_filter(
- qs,
- ErrorTrackingIssueFilter(key="team__api_token", value="x", operator=PropertyOperator.ICONTAINS),
- )
-
- qs.filter.assert_not_called()
-
- def test_unimplemented_filter_types_raise(self):
- qs = MagicMock()
-
- with pytest.raises(NotImplementedError):
- property_to_django_filter(
- qs,
- ErrorTrackingIssueFilter(
- key="issue_description", value=["description"], operator=PropertyOperator.BETWEEN
- ),
- )
diff --git a/posthog/models/property/util.py b/posthog/models/property/util.py
index c1e43a47777e..391d8bd0fb3f 100644
--- a/posthog/models/property/util.py
+++ b/posthog/models/property/util.py
@@ -6,8 +6,6 @@ from collections import (
from collections.abc import Callable, Iterable
from typing import Any, Literal, Optional, Union, cast
-from django.db.models import QuerySet
-
from rest_framework import exceptions
from posthog.hogql import ast
@@ -34,9 +32,7 @@ from posthog.models.property.property import ValueT
from posthog.models.team import Team
from posthog.queries.person_distinct_id_query import get_team_distinct_ids_query
from posthog.queries.util import PersonPropertiesMode
-from posthog.schema_enums import PropertyOperator
from posthog.session_recordings.queries.session_query import SessionQuery
-from posthog.types import ErrorTrackingIssueFilter
from posthog.utils import is_json, is_valid_regex
from products.actions.backend.models.action import Action
@@ -134,13 +130,6 @@ def parse_prop_grouped_clauses(
return final, final_params
-def is_property_group(group: Union[Property, "PropertyGroup"]):
- if isinstance(group, PropertyGroup):
- return True
- else:
- return False
-
-
def parse_prop_clauses(
team_id: int,
filters: list[Property],
@@ -623,76 +612,6 @@ def property_table(property: Property) -> TableWithProperties:
raise ValueError(f"Property type does not have a table: {property.type}")
-def get_single_or_multi_property_string_expr(
- breakdown,
- table: TableWithProperties,
- query_alias: Literal["prop", "value", "prop_basic", None],
- column: str,
- allow_denormalized_props=True,
- materialised_table_column: str = "properties",
- normalize_url: bool = False,
-) -> tuple[str, dict[str, Any]]:
- """
- When querying for breakdown properties:
- * If the breakdown provided is a string, we extract the JSON from the properties object stored in the DB
- * If it is an array of strings, we extract each of those properties and concatenate them into a single value
- clickhouse parameterizes into a query template from a flat list using % string formatting
- values are escaped and inserted in the query here instead of adding new items to the flat list of values
-
- :param query_alias:
-
- Specifies the SQL query alias to add to the expression e.g. `AS prop`. If this is specified as None, then
- no alias will be appended.
-
- """
- breakdown_params: dict[str, Any] = {}
- if isinstance(breakdown, str) or isinstance(breakdown, int):
- breakdown_key = f"breakdown_param_{len(breakdown_params) + 1}"
- breakdown_key = f"breakdown_param_{len(breakdown_params) + 1}"
- breakdown_params[breakdown_key] = breakdown
-
- expression, _ = get_property_string_expr(
- table,
- str(breakdown),
- f"%({breakdown_key})s",
- column,
- allow_denormalized_props,
- materialised_table_column=materialised_table_column,
- )
-
- expression = normalize_url_breakdown(expression, normalize_url)
- else:
- expressions = []
- for b in breakdown:
- breakdown_key = f"breakdown_param_{len(breakdown_params) + 1}"
- breakdown_params[breakdown_key] = b
- expr, _ = get_property_string_expr(
- table,
- b,
- f"%({breakdown_key})s",
- column,
- allow_denormalized_props,
- materialised_table_column=materialised_table_column,
- )
- expressions.append(normalize_url_breakdown(expr, normalize_url))
-
- expression = f"array({','.join(expressions)})"
-
- if query_alias is None:
- return expression, breakdown_params
-
- return f"{expression} AS {query_alias}", breakdown_params
-
-
-def normalize_url_breakdown(breakdown_value, breakdown_normalize_url: bool = True):
- if breakdown_normalize_url:
- return (
- f"if( empty(trim(TRAILING '/?#' from {breakdown_value})), '/', trim(TRAILING '/?#' from {breakdown_value}))"
- )
-
- return breakdown_value
-
-
def get_property_string_expr(
table: TableWithProperties,
property_name: PropertyName,
@@ -978,71 +897,6 @@ def clear_excess_levels(prop: Union["PropertyGroup", "Property"], skip=False):
return prop
-_ALLOWED_ISSUE_FILTER_KEYS = {"name", "status", "issue_description", "first_seen"}
-
-
-def property_to_django_filter(queryset: QuerySet, property: ErrorTrackingIssueFilter):
- # Allowlist prevents ORM relationship traversal via Django's __ notation
- if property.key not in _ALLOWED_ISSUE_FILTER_KEYS:
- raise ValueError(f"Unsupported error tracking filter key: {property.key}")
-
- operator = property.operator
- value = property.value
- field = property.key
-
- if property.type == "error_tracking_issue" and property.key == "issue_description":
- field = "description"
-
- array_based = (
- operator == PropertyOperator.EXACT or operator == PropertyOperator.IS_NOT or operator == PropertyOperator.NOT_IN
- )
- negated = (
- True
- if operator
- in [
- PropertyOperator.IS_NOT,
- PropertyOperator.NOT_ICONTAINS,
- PropertyOperator.NOT_ICONTAINS_MULTI,
- PropertyOperator.NOT_REGEX,
- PropertyOperator.IS_SET,
- PropertyOperator.NOT_IN,
- ]
- else False
- )
- query = f"{field}"
-
- if array_based and not value:
- return queryset
-
- if array_based:
- query += "__in"
- elif operator == PropertyOperator.IS_SET or operator == PropertyOperator.IS_NOT_SET:
- query += "__isnull"
- value = True
- elif operator == PropertyOperator.ICONTAINS or operator == PropertyOperator.NOT_ICONTAINS:
- query += "__icontains"
- elif operator == PropertyOperator.ICONTAINS_MULTI or operator == PropertyOperator.NOT_ICONTAINS_MULTI:
- query += "__icontains"
- elif operator == PropertyOperator.REGEX:
- query += "__regex"
- elif operator == PropertyOperator.IS_DATE_EXACT:
- query += "__date"
- elif operator == PropertyOperator.GT or operator == PropertyOperator.IS_DATE_AFTER:
- query += "__gt"
- elif operator == PropertyOperator.GTE:
- query += "__gte"
- elif operator == PropertyOperator.LT or operator == PropertyOperator.IS_DATE_BEFORE:
- query += "__lt"
- elif operator == PropertyOperator.LTE:
- query += "__lte"
- else:
- raise NotImplementedError(f"PropertyOperator {operator} not implemented")
-
- filter = {f"{query}": value}
-
- return queryset.exclude(**filter) if negated else queryset.filter(**filter)
-
-
class S3TableVisitor(TraversingVisitor):
def __init__(self):
super().__init__()